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): integrate state machine a (#1564)
Sean Ayec36d9a3a3161
diff --git a/.github/workflows/code-check-cloud-storage.yml b/.github/workflows/code-check-cloud-storage.ymlindex 4edbe775ca..5f5623fbc3 100644--- a/.github/workflows/code-check-cloud-storage.yml+++ b/.github/workflows/code-check-cloud-storage.yml@@ -59,6 +59,11 @@ jobs:- 5432:5432# needed because the postgres container does not provide a healthcheckoptions: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5+ redis:+ image: redis:7+ ports:+ - 6379:6379+ options: --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5steps:- uses: actions/checkout@v4- uses: ./.github/actions/setup-rustdiff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 41e483f5da..6a6535584b 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -528,6 +528,7 @@ dependencies = ["futures","http-body-util","jsonwebtoken",+ "last_online_tracker","macro_auth","macro_aws_config","macro_cache_client",@@ -552,6 +553,7 @@ dependencies = ["notification_service_client","openssl","rand 0.9.0",+ "redis","remote_env_var","reqwest","roles_and_permissions",@@ -1915,6 +1917,7 @@ dependencies = ["futures","http-body-util","jsonwebtoken",+ "last_online_tracker","macro_auth","macro_aws_config","macro_axum_utils",@@ -2789,6 +2792,7 @@ dependencies = ["hex","http-body-util","jsonwebtoken",+ "last_online_tracker","lazy_static","macro_auth","macro_aws_config",@@ -3267,6 +3271,7 @@ dependencies = ["html-escape","http-body-util","infer 0.19.0",+ "last_online_tracker","lol_html","macro_auth","macro_aws_config",@@ -6049,8 +6054,10 @@ dependencies = ["chrono","cowlike","either",+ "futures","hex","itertools 0.14.0",+ "last_online_tracker","macro_db_migrator","macro_user_id","model-entity",@@ -6967,6 +6974,7 @@ dependencies = ["chrono","email_db_client","http-body-util",+ "last_online_tracker","macro_auth","macro_aws_config","macro_cors",diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.tomlindex 2acd8d372a..08ab053545 100644--- a/rust/cloud-storage/authentication_service/Cargo.toml+++ b/rust/cloud-storage/authentication_service/Cargo.toml@@ -58,6 +58,7 @@ macro_db_client = { path = "../macro_db_client", default-features = false, featu"account_merge_request","team",] }+last_online_tracker = { path = "../last_online_tracker" }macro_entrypoint = { path = "../macro_entrypoint" }macro_env = { path = "../macro_env", features = ["frontend_url"] }macro_env_var = { path = "../macro_env_var" }@@ -81,6 +82,7 @@ notification = { path = "../notification" }notification_service_client = { path = "../notification_service_client" }openssl = { workspace = true }rand = { workspace = true }+redis = { workspace = true }remote_env_var = { path = "../remote_env_var" }reqwest = { workspace = true }roles_and_permissions = { path = "../roles_and_permissions" }diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex 3914214889..e6a64ffcc1 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -7,8 +7,13 @@ use macro_env::Environment;use macro_env_var::env_var;use macro_middleware::auth::internal_access::InternalApiSecretKey;use native_app_service::{domain::service::NativeAppServiceImpl, outbound::DefaultBundleFetcher};+use notification::domain::models::email_notification_digest::StateMachineDriverA;use notification::domain::service::NotificationIngressService;-use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};+use notification::outbound::{+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,+};use remote_env_var::LocalOrRemoteSecret;use roles_and_permissions::{domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,@@ -19,6 +24,22 @@ use teams::{outbound::team_repo::TeamRepositoryImpl,};+type StateMachine = StateMachineDriverA<+ DbUserExistenceChecker,+ PushNotificationCheckerImpl<DbNotificationRepository<PgPool>>,+ LastOnlineCheckerImpl<+ last_online_tracker::outbound::time::DefaultTime,+ last_online_tracker::outbound::redis::RedisLastOnlineRepo,+ >,+ RedisDigestBatcher,+>;++pub(crate) type NotificationIngressType = NotificationIngressService<+ DbNotificationRepository<PgPool>,+ SqsNotificationQueue,+ StateMachine,+>;+#[derive(Clone, FromRef)]pub(crate) struct ApiContext {pub db: PgPool,@@ -29,8 +50,7 @@ pub(crate) struct ApiContext {Arc<document_storage_service_client::DocumentStorageServiceClient>,pub notification_service_client: Arc<notification_service_client::NotificationServiceClient>,pub ses_client: Arc<ses_client::Ses>,- pub notification_ingress_service:- Arc<NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>>,+ pub notification_ingress_service: Arc<NotificationIngressType>,pub sqs_client: Arc<sqs_client::SQS>,pub environment: Environment,pub jwt_args: JwtValidationArgs,diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex 8b8f8ce261..b092ecd6e6 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -8,9 +8,15 @@ use native_app_service::{domain::{models::PlatformData, service::NativeAppServiceImpl},outbound::DefaultBundleFetcher,};+use notification::domain::models::email_notification_digest::{+ EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder, StateMachineDriverA,+};use notification::domain::service::NotificationIngressService;-use notification::outbound::queue::SqsNotificationQueue;-use notification::outbound::repository::DbNotificationRepository;+use notification::outbound::{+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,+};use notification_service_client::NotificationServiceClient;use roles_and_permissions::{domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,@@ -163,13 +169,40 @@ async fn main() -> anyhow::Result<()> {JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client).await?;+ let redis_state_machine_client = redis::Client::open(config.redis_uri.as_str())+ .context("failed to create redis client for state machine")?;+ let redis_multiplexed_conn = redis_state_machine_client+ .get_multiplexed_async_connection()+ .await+ .context("failed to get multiplexed redis connection for state machine")?;+let notification_repository = DbNotificationRepository::new(db.clone());let notification_queue = SqsNotificationQueue::new(aws_sdk_sqs::Client::new(¯o_aws_config::get_macro_aws_config().await),config.notification_queue.clone(),);+ let state_machine = StateMachineDriverA {+ user_checker: DbUserExistenceChecker::new(db.clone()),+ notification_checker: PushNotificationCheckerImpl::new(DbNotificationRepository::new(+ db.clone(),+ )),+ online_checker: LastOnlineCheckerImpl::new(+ last_online_tracker::domain::services::LastOnlineService::new(+ last_online_tracker::outbound::time::DefaultTime,+ last_online_tracker::outbound::redis::RedisLastOnlineRepo::new(+ redis_multiplexed_conn.clone(),+ ),+ ),+ ),+ digest_batcher: RedisDigestBatcher::new(redis_multiplexed_conn),+ block_list: EmailBlockList::new::<model_notifications::NewEmailMetadata>(),+ invite_list: ExplicitInviteAllowList::new::<model_notifications::InviteToTeamMetadata>()+ .append::<model_notifications::ChannelInviteMetadata>(),+ digest_window: std::time::Duration::from_secs(30 * 60),+ online_duration_threshold: std::time::Duration::from_secs(60 * 60),+ };let notification_ingress_service =- NotificationIngressService::new(notification_repository, notification_queue);+ NotificationIngressService::new(notification_repository, notification_queue, state_machine);tracing::trace!("initialized notification ingress service");let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(diff --git a/rust/cloud-storage/comms_service/Cargo.toml b/rust/cloud-storage/comms_service/Cargo.tomlindex 09ae25ce6c..8d09fe6f88 100644--- a/rust/cloud-storage/comms_service/Cargo.toml+++ b/rust/cloud-storage/comms_service/Cargo.toml@@ -61,6 +61,7 @@ model_notifications = { path = "../model_notifications" }models_comms = { path = "../models_comms" }models_opensearch = { path = "../models_opensearch" }models_permissions = { path = "../models_permissions" }+last_online_tracker = { path = "../last_online_tracker" }notification_hex = { path = "../notification", package = "notification" }reqwest.workspace = truesecretsmanager_client = { path = "../secretsmanager_client" }diff --git a/rust/cloud-storage/comms_service/src/api/context.rs b/rust/cloud-storage/comms_service/src/api/context.rsindex 62d8cfa61e..b3800f79cb 100644--- a/rust/cloud-storage/comms_service/src/api/context.rs+++ b/rust/cloud-storage/comms_service/src/api/context.rs@@ -8,16 +8,32 @@ use connection_gateway_client::client::ConnectionGatewayClient;use frecency::outbound::postgres::FrecencyPgStorage;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_env_var::env_var;+use notification_hex::domain::models::email_notification_digest::StateMachineDriverA;use notification_hex::domain::service::NotificationIngressService;use notification_hex::outbound::{- queue::SqsNotificationQueue, repository::DbNotificationRepository,+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,};use secretsmanager_client::LocalOrRemoteSecret;use sqlx::PgPool;use std::sync::Arc;-pub type NotificationIngressType =- NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>;+type StateMachine = StateMachineDriverA<+ DbUserExistenceChecker,+ PushNotificationCheckerImpl<DbNotificationRepository<PgPool>>,+ LastOnlineCheckerImpl<+ last_online_tracker::outbound::time::DefaultTime,+ last_online_tracker::outbound::redis::RedisLastOnlineRepo,+ >,+ RedisDigestBatcher,+>;++pub type NotificationIngressType = NotificationIngressService<+ DbNotificationRepository<PgPool>,+ SqsNotificationQueue,+ StateMachine,+>;env_var! {#[derive(Clone)]diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex fb42ebd48a..24dc38435d 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -72,6 +72,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"cloud_storage","user_permissions",] }+last_online_tracker = { path = "../last_online_tracker" }notification = { path = "../notification" }macro_project_utils = { path = "../macro_project_utils" }macro_sha_count_client = { path = "../macro_sha_count_client" }diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rsindex 59aad260e5..61582e605b 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs@@ -21,8 +21,7 @@ use model::{response::ErrorResponse,user::UserContext,};-use notification::domain::service::{NotificationIngress, NotificationIngressService};-use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};+use notification::domain::service::NotificationIngress;use sqlx::PgPool;use super::comment_error_response;@@ -50,9 +49,7 @@ pub struct Params {)]#[axum::debug_handler(state = ApiContext)]pub async fn create_comment_handler(- State(notification_ingress_service): State<- Arc<NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>>,- >,+ State(notification_ingress_service): State<Arc<crate::api::context::NotificationIngressType>>,State(db): State<PgPool>,State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,Extension(UserContext { user_id, .. }): Extension<UserContext>,diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rsindex a08053b412..5c0cf9ce2c 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs@@ -19,8 +19,7 @@ use model::{response::ErrorResponse,user::UserContext,};-use notification::domain::service::{NotificationIngress, NotificationIngressService};-use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};+use notification::domain::service::NotificationIngress;use sqlx::PgPool;use super::comment_error_response;@@ -47,9 +46,7 @@ pub struct Params {)]pub async fn edit_comment_handler(State(db): State<PgPool>,- State(notification_ingress_service): State<- Arc<NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>>,- >,+ State(notification_ingress_service): State<Arc<crate::api::context::NotificationIngressType>>,State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,Extension(UserContext { user_id, .. }): Extension<UserContext>,Path(Params { comment_id }): Path<Params>,diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 504337fa6c..07707c9b87 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -22,8 +22,13 @@ use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::Fuse macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_env_var::env_var;use macro_sha_count_client::Redis;+use notification::domain::models::email_notification_digest::StateMachineDriverA;use notification::domain::service::NotificationIngressService;-use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};+use notification::outbound::{+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,+};use opensearch_client::OpensearchClient;use properties::{NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,@@ -56,8 +61,20 @@ type DssSoupState = SoupRouterState<>;type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;-type NotificationIngressType =- NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>;+type StateMachine = StateMachineDriverA<+ DbUserExistenceChecker,+ PushNotificationCheckerImpl<DbNotificationRepository<PgPool>>,+ LastOnlineCheckerImpl<+ last_online_tracker::outbound::time::DefaultTime,+ last_online_tracker::outbound::redis::RedisLastOnlineRepo,+ >,+ RedisDigestBatcher,+>;+pub(crate) type NotificationIngressType = NotificationIngressService<+ DbNotificationRepository<PgPool>,+ SqsNotificationQueue,+ StateMachine,+>;type PropertiesService = PropertiesServiceImpl<PropertiesPgRepo,PermissionServiceImpl,diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 106b0c6415..fa282a08e2 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -29,8 +29,15 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_entrypoint::MacroEntrypoint;use macro_middleware::auth::internal_access::InternalApiSecretKey;use macro_sha_count_client::Redis;+use notification::domain::models::email_notification_digest::{+ EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder, StateMachineDriverA,+};use notification::domain::service::NotificationIngressService;-use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};+use notification::outbound::{+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,+};use opensearch_client::OpensearchClient;use properties::{NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,@@ -209,13 +216,39 @@ async fn main() -> anyhow::Result<()> {EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());let system_properties_service =SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()));+ let redis_multiplexed_conn = redis_client+ .get_multiplexed_async_connection()+ .await+ .context("failed to get multiplexed redis connection for state machine")?;+let make_notification_ingress = || {let notification_repository = DbNotificationRepository::new(db.clone());let notification_queue = SqsNotificationQueue::new(aws_sdk_sqs::Client::new(&aws_config),config.vars.notification_queue.as_ref().to_string(),);- NotificationIngressService::new(notification_repository, notification_queue)+ let state_machine = StateMachineDriverA {+ user_checker: DbUserExistenceChecker::new(db.clone()),+ notification_checker: PushNotificationCheckerImpl::new(DbNotificationRepository::new(+ db.clone(),+ )),+ online_checker: LastOnlineCheckerImpl::new(+ last_online_tracker::domain::services::LastOnlineService::new(+ last_online_tracker::outbound::time::DefaultTime,+ last_online_tracker::outbound::redis::RedisLastOnlineRepo::new(+ redis_multiplexed_conn.clone(),+ ),+ ),+ ),+ digest_batcher: RedisDigestBatcher::new(redis_multiplexed_conn.clone()),+ block_list: EmailBlockList::new::<model_notifications::NewEmailMetadata>(),+ invite_list: ExplicitInviteAllowList::new::<model_notifications::InviteToTeamMetadata>(+ )+ .append::<model_notifications::ChannelInviteMetadata>(),+ digest_window: std::time::Duration::from_secs(30 * 60),+ online_duration_threshold: std::time::Duration::from_secs(60 * 60),+ };+ NotificationIngressService::new(notification_repository, notification_queue, state_machine)};let notification_ingress_service = Arc::new(make_notification_ingress());tracing::trace!("initialized notification ingress service");diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex 0ab3019fb1..a76f4f3dc4 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -100,6 +100,7 @@ macro_env_var = { path = "../macro_env_var" }macro_middleware = { path = "../macro_middleware", default-features = false, features = ["auth",] }+last_online_tracker = { path = "../last_online_tracker" }notification = { path = "../notification" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rsindex e413cb1c45..51b0c74544 100644--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs@@ -4,8 +4,15 @@ use email_service::config::{Config, EmailServiceCloudfrontSignerPrivateKey};use macro_entrypoint::MacroEntrypoint;use macro_env::Environment;use macro_middleware::auth::internal_access::InternalApiSecretKey;+use notification::domain::models::email_notification_digest::{+ EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder, StateMachineDriverA,+};use notification::domain::service::NotificationIngressService;-use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};+use notification::outbound::{+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,+};use secretsmanager_client::SecretManager;use sqlx::postgres::PgPoolOptions;use static_file_service_client::StaticFileServiceClient;@@ -84,14 +91,6 @@ async fn main() -> anyhow::Result<()> {.contacts_queue(&config.contacts_queue).email_link_manager_queue(&config.link_manager_queue);- let notification_ingress_service = Arc::new(NotificationIngressService::new(- DbNotificationRepository::new(db.clone()),- SqsNotificationQueue::new(- aws_sdk_sqs::Client::new(&aws_config),- config.notification_queue.clone(),- ),- ));-let link_manager_worker = sqs_worker::SQSWorker::new(aws_sdk_sqs::Client::new(&gmail_queue_aws_config),config.link_manager_queue.clone(),@@ -176,6 +175,41 @@ async fn main() -> anyhow::Result<()> {}).context("failed to connect to redis")?;+ let redis_multiplexed_conn = redis_inner_client+ .get_multiplexed_async_connection()+ .await+ .context("failed to get multiplexed redis connection for state machine")?;++ let state_machine = StateMachineDriverA {+ user_checker: DbUserExistenceChecker::new(db.clone()),+ notification_checker: PushNotificationCheckerImpl::new(DbNotificationRepository::new(+ db.clone(),+ )),+ online_checker: LastOnlineCheckerImpl::new(+ last_online_tracker::domain::services::LastOnlineService::new(+ last_online_tracker::outbound::time::DefaultTime,+ last_online_tracker::outbound::redis::RedisLastOnlineRepo::new(+ redis_multiplexed_conn.clone(),+ ),+ ),+ ),+ digest_batcher: RedisDigestBatcher::new(redis_multiplexed_conn),+ block_list: EmailBlockList::new::<model_notifications::NewEmailMetadata>(),+ invite_list: ExplicitInviteAllowList::new::<model_notifications::InviteToTeamMetadata>()+ .append::<model_notifications::ChannelInviteMetadata>(),+ digest_window: std::time::Duration::from_secs(30 * 60),+ online_duration_threshold: std::time::Duration::from_secs(60 * 60),+ };++ let notification_ingress_service = Arc::new(NotificationIngressService::new(+ DbNotificationRepository::new(db.clone()),+ SqsNotificationQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ config.notification_queue.clone(),+ ),+ state_machine,+ ));+let redis_client = email_service::util::redis::RedisClient::new(redis_inner_client,config.redis_rate_limit_reqs,diff --git a/rust/cloud-storage/email_service/src/pubsub/context.rs b/rust/cloud-storage/email_service/src/pubsub/context.rsindex 364d63feeb..a38d559d1f 100644--- a/rust/cloud-storage/email_service/src/pubsub/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/context.rs@@ -3,16 +3,34 @@ use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;use document_storage_service_client::DocumentStorageServiceClient;use gmail_client::GmailClient;+use notification::domain::models::email_notification_digest::StateMachineDriverA;use notification::domain::service::NotificationIngressService;-use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};+use notification::outbound::{+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,+};use sqlx::PgPool;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};+type StateMachine = StateMachineDriverA<+ DbUserExistenceChecker,+ PushNotificationCheckerImpl<DbNotificationRepository<PgPool>>,+ LastOnlineCheckerImpl<+ last_online_tracker::outbound::time::DefaultTime,+ last_online_tracker::outbound::redis::RedisLastOnlineRepo,+ >,+ RedisDigestBatcher,+>;+/// The concrete notification ingress service type.-pub type NotificationIngressType =- NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>;+pub type NotificationIngressType = NotificationIngressService<+ DbNotificationRepository<PgPool>,+ SqsNotificationQueue,+ StateMachine,+>;#[derive(Clone)]pub struct PubSubContext {diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.tomlindex bb2770fd0d..3ef9f18dcb 100644--- a/rust/cloud-storage/notification/Cargo.toml+++ b/rust/cloud-storage/notification/Cargo.toml@@ -30,8 +30,10 @@ axum = { workspace = true, optional = true }chrono = { workspace = true }cowlike = { path = "../cowlike" }either = { workspace = true }+futures = { workspace = true }hex = { workspace = true }itertools = { workspace = true }+last_online_tracker = { path = "../last_online_tracker" }macro_user_id = { path = "../macro_user_id" }model-entity = { path = "../model-entity" }model-error-response = { path = "../model-error-response", optional = true }diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rsindex e17dc1c38e..1f3ac9dfc6 100644--- a/rust/cloud-storage/notification/src/domain/models.rs+++ b/rust/cloud-storage/notification/src/domain/models.rs@@ -1,5 +1,7 @@//! Domain models for the notification service.+use std::sync::Arc;+use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize, de::DeserializeOwned};@@ -113,97 +115,43 @@ pub struct TaggedContent<T> {content: T,}-impl<T: Notification> TaggedContent<T> {+impl<T: Notification> TaggedContent<Arc<T>> {/// create a new value from a notification T- pub fn new(val: T) -> Self {+ pub fn new_arc(val: Arc<T>) -> Self {TaggedContent {tag: T::TYPE_NAME.to_string(),content: val,}}+}- /// convert the inner to a type erased json value- pub fn serialize(self) -> TaggedContent<serde_json::Value> {- let TaggedContent { tag, content } = self;+impl<T: Notification> TaggedContent<T> {+ /// create a new value from a notification T+ pub fn new(val: T) -> Self {TaggedContent {- tag,- content: serde_json::to_value(&content).expect("serde json serialize cant fail"),+ tag: T::TYPE_NAME.to_string(),+ content: val,}}}-impl<T> UserNotificationRow<T> {- /// Wrap the metadata in a [`TaggedContent`] using the notification event type as the tag.- pub fn into_tagged(self) -> UserNotificationRow<TaggedContent<T>> {- let UserNotificationRow {- owner_id,- notification_id,- notification_event_type,- entity,- sent,- done,- created_at,- viewed_at,- updated_at,- deleted_at,- notification_metadata,- sender_id,- } = self;-- UserNotificationRow {- owner_id,- notification_id,- entity,- sent,- done,- created_at,- viewed_at,- updated_at,- deleted_at,- notification_metadata: TaggedContent {- tag: notification_event_type.clone(),- content: notification_metadata,- },- notification_event_type,- sender_id,- }+impl UserNotificationRow<serde_json::Value> {+ /// Wrap the raw JSON metadata in a [`TaggedContent`] using the row's+ /// `notification_event_type` as the tag. This produces the adjacently-tagged+ /// shape produced by [`UserNotificationRow::into_tagged`] ++ /// [`UserNotificationRow::into_json`].+ pub fn into_tagged(self) -> UserNotificationRow<TaggedContent<serde_json::Value>> {+ let tag = self.notification_event_type.clone();+ self.map(|v| TaggedContent { tag, content: v })}}-impl<T: Serialize> UserNotificationRow<T> {- /// Serialize the metadata into a [`serde_json::Value`].+impl<T: Serialize> UserNotificationRow<TaggedContent<T>> {+ /// Serialize the [`TaggedContent`] wrapper back into a single JSON value,+ /// producing `{ "tag": "...", "content": ... }`.pub fn into_json(self) -> Result<UserNotificationRow<serde_json::Value>, serde_json::Error> {- let UserNotificationRow {- owner_id,- notification_id,- notification_event_type,- entity,- sent,- done,- created_at,- viewed_at,- updated_at,- deleted_at,- notification_metadata,- sender_id,- } = self;-- let val = serde_json::to_value(notification_metadata)?;-- Ok(UserNotificationRow {- owner_id,- notification_id,- notification_event_type,- entity,- sent,- done,- created_at,- viewed_at,- updated_at,- deleted_at,- notification_metadata: val,- sender_id,- })+ let val = serde_json::to_value(&self.notification_metadata)?;+ Ok(self.map(|_| val))}}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 02ccbf7190..4ac841dc31 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@@ -9,7 +9,7 @@use crate::domain::{models::{- Notification, TaggedContent, UserNotificationRow,+ Notification, UserNotificationRow,email_notification_digest::ports::{DigestBatcher, LastOnlineChecker, MessageId, MessageReceiptRepo,NotificationSendChecker, PushNotificationChecker, UserExistenceChecker,@@ -19,9 +19,10 @@ use crate::domain::{};use either::Either;use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;use rootcause::{Report, report};use serde::{Deserialize, Serialize};-use std::{collections::HashSet, time::Duration};+use std::{collections::HashSet, sync::Arc, time::Duration};/// Port traits for external dependencies (user existence, push notification checks).pub mod ports;@@ -34,12 +35,35 @@ mod test;#[serde(transparent)]pub struct BatchSend<T>(T);+impl<T> BatchSend<T> {+ /// Borrow the inner value.+ pub(crate) fn inner(&self) -> &T {+ &self.0+ }+}++#[cfg(test)]+impl<T> BatchSend<T> {+ /// Wrap an inner value.+ pub(crate) fn from_inner(inner: T) -> Self {+ Self(inner)+ }+}+/// Send immediately as a single notification email.pub struct SingleSend<T>(T);/// Do not send an email for this notification.pub struct DontSend(());+#[cfg(test)]+impl DontSend {+ /// Create a new `DontSend` value (test-only).+ pub(crate) fn new() -> Self {+ Self(())+ }+}+struct NotificationSet(HashSet<&'static str>);/// trait used to create a set of notifications.@@ -137,7 +161,7 @@ impl EmailBlockList {/// or [`Decision::Next`] with an [`AllowedNotification`] to continue the flow.pub fn notification_is_allowed<T: Notification>(&self,- notif: UserNotificationRow<T>,+ notif: UserNotificationRow<Arc<T>>,) -> Either<AllowedNotification<T>, DontSend> {match self.0.is_member::<T>() {true => Either::Right(DontSend(())),@@ -148,7 +172,7 @@ impl EmailBlockList {/// represents a notification that is allowed to be sent as part of a [EmailSendDecision]pub struct AllowedNotification<T> {- inner: UserNotificationRow<T>,+ inner: UserNotificationRow<Arc<T>>,}/// State indicating the notification recipient has a Macro account.@@ -209,7 +233,7 @@ impl<T: Notification> AccountDoesNotExist<T> {pub fn batch_or_single_send(self,invite_list: &ExplicitInviteAllowList,- ) -> EmailSendDecision<UserNotificationRow<T>> {+ ) -> EmailSendDecision<UserNotificationRow<Arc<T>>> {match invite_list.0.is_member::<T>() {true => EmailSendDecision::Left(SingleSend(self.prev.inner)),false => EmailSendDecision::Right(BatchSend(self.prev.inner)),@@ -220,20 +244,25 @@ 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(Debug, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct PushNotificationsEnabled {/// the inner value which has become adjacently tagged/// We lose the compiler typing here because we need to store this value/// to be retrieved during the SNS event handling./// The deserialization cannot handle some specific T it needs to handle the general case/// of some json value- inner: UserNotificationRow<TaggedContent<serde_json::Value>>,+ inner: UserNotificationRow<serde_json::Value>,}impl PushNotificationsEnabled {+ /// Get the owner (user) ID of this notification.+ pub(crate) fn owner_id(&self) -> &MacroUserIdStr<'static> {+ &self.inner.owner_id+ }+/// 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>>> {+ fn assert_failed(self) -> BatchSend<UserNotificationRow<serde_json::Value>> {BatchSend(self.inner)}}@@ -262,8 +291,7 @@ impl<T: Notification> AccountExists<T> {inner: self.prev.inner- .map(TaggedContent::new)- .map(TaggedContent::serialize),+ .map(|v| serde_json::to_value(&*v).expect("serialization cannot fail")),})),Ok(false) => Ok(Either::Right(PushNotificationsDisabled { prev: self })),Err(e) => Err(e),@@ -279,7 +307,7 @@ impl<T: Notification> PushNotificationsDisabled<T> {self,checker: &impl LastOnlineChecker,threshold: Duration,- ) -> Result<Either<BatchSend<UserNotificationRow<T>>, DontSend>, Report> {+ ) -> Result<Either<BatchSend<UserNotificationRow<Arc<T>>>, DontSend>, Report> {let last_online = checker.last_online_checker(self.prev.prev.inner.owner_id.copied()).await?;@@ -290,6 +318,20 @@ impl<T: Notification> PushNotificationsDisabled<T> {}}+/// Port for driving the bulk-digest state machine to an initial decision.+///+/// This abstracts the concrete [`StateMachineDriverA`] so callers only depend on the capability,+/// not the specific implementation or its generic adapter parameters.+pub trait BulkDigestStateMachine: Send + Sync + 'static {+ /// Given an input notification, drive the state machine to an initial decision.+ ///+ /// See [`StateMachineDecisionA`] for the possible outcomes.+ fn ingest<T: Notification + 'static>(+ &self,+ notif: UserNotificationRow<Arc<T>>,+ ) -> impl Future<Output = Result<StateMachineDecisionA<T>, Report>> + Send;+}+/// 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.@@ -329,7 +371,7 @@ pub enum StateMachineDecisionA<T> {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>>),+ SendImmediate(SingleSend<UserNotificationRow<Arc<T>>>),}impl<U, N, O, B> StateMachineDriverA<U, N, O, B>@@ -344,7 +386,7 @@ where/// See [StateMachineInitialDecision] for more info.pub async fn ingest<T: Notification>(&self,- notif: UserNotificationRow<T>,+ notif: UserNotificationRow<Arc<T>>,) -> Result<StateMachineDecisionA<T>, Report> {let allowed = match self.block_list.notification_is_allowed(notif) {Either::Left(l) => l,@@ -389,9 +431,11 @@ whereasync fn inner_store_batch<T: Notification>(&self,- batch: BatchSend<UserNotificationRow<T>>,+ batch: BatchSend<UserNotificationRow<Arc<T>>>,) -> Result<BatchSend<()>, Report> {- let notif = batch.0.into_tagged().map(TaggedContent::serialize);+ let notif = batch+ .0+ .map(|v| serde_json::to_value(&*v).expect("serialize cannot fail"));let () = self.digest_batcher.add_to_digest(¬if, self.digest_window)@@ -400,6 +444,21 @@ where}}+impl<U, N, O, B> BulkDigestStateMachine for StateMachineDriverA<U, N, O, B>+where+ U: UserExistenceChecker,+ N: PushNotificationChecker,+ O: LastOnlineChecker,+ B: DigestBatcher,+{+ fn ingest<T: Notification + 'static>(+ &self,+ notif: UserNotificationRow<Arc<T>>,+ ) -> impl Future<Output = Result<StateMachineDecisionA<T>, Report>> + Send {+ self.ingest(notif)+ }+}+/// 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 ispub struct StateMachineDriverB<B, R> {@@ -415,9 +474,8 @@ pub struct StateMachineDriverB<B, R> {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,+ /// all endpoint send checkers for this user — implements [NotificationSendChecker]+ pub send_notifs: Vec<N>,}impl<B, R> StateMachineDriverB<B, R>@@ -426,46 +484,103 @@ whereR: 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+ /// We call this when its time to send the notification, on the egress side of the queue.+ ///+ /// Tries all endpoints for the user. Records message IDs for successes.+ /// Only queues a batch email digest if ALL endpoints fail.+ ///+ /// Returns a tuple of:+ /// - Per-endpoint results (for delivery status tracking)+ /// - `Left(DontSend)` if any succeeded, `Right(batch_result)` if all failed+ #[allow(clippy::type_complexity)]pub async fn continue_machine<N: NotificationSendChecker>(&self,req: ResumeMachineBRequest<N>,- ) -> Result<(N::Ok, DontSend), (N::Err, Result<BatchSend<()>, Report>)> {+ ) -> (+ Vec<Result<N::Ok, N::Err>>,+ Either<DontSend, Result<BatchSend<()>, Report>>,+ ) {let ResumeMachineBRequest {notification_enabled,- send_notif,+ send_notifs,} = 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))++ let mut results = Vec::with_capacity(send_notifs.len());+ let mut any_succeeded = false;++ for send_notif in send_notifs {+ match send_notif.send_notification().await {+ Ok(r) => {+ 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.copied(),+ notification_enabled.inner.notification_id,+ )+ .await;+ results.push(Ok(r));+ any_succeeded = true;+ }+ Err(e) => {+ results.push(Err(e));+ }}}++ if any_succeeded {+ (results, Either::Left(DontSend(())))+ } else {+ let next = notification_enabled.assert_failed();+ let batch_result = self+ .digest_batcher+ .add_to_digest(&next.0, self.digest_window)+ .await+ .map(BatchSend);+ (results, Either::Right(batch_result))+ }+ }+}++/// Port for continuing the bulk-digest state machine on the egress side.+///+/// This abstracts [`StateMachineDriverB`] so callers only depend on the capability,+/// not the specific implementation or its generic adapter parameters.+pub trait BulkDigestEgressStateMachine: Send + Sync + 'static {+ /// Try all endpoints for a user. Records message IDs for successes.+ /// Only queues a batch email digest if ALL endpoints fail.+ ///+ /// Returns per-endpoint results and either `DontSend` (any succeeded)+ /// or the batch result (all failed).+ #[allow(clippy::type_complexity)]+ fn continue_machine<N: NotificationSendChecker>(+ &self,+ req: ResumeMachineBRequest<N>,+ ) -> impl Future<+ Output = (+ Vec<Result<N::Ok, N::Err>>,+ Either<DontSend, Result<BatchSend<()>, Report>>,+ ),+ > + Send;+}++impl<B, R> BulkDigestEgressStateMachine for StateMachineDriverB<B, R>+where+ B: DigestBatcher,+ R: MessageReceiptRepo,+{+ fn continue_machine<N: NotificationSendChecker>(+ &self,+ req: ResumeMachineBRequest<N>,+ ) -> impl Future<+ Output = (+ Vec<Result<N::Ok, N::Err>>,+ Either<DontSend, Result<BatchSend<()>, Report>>,+ ),+ > + Send {+ self.continue_machine(req)}}@@ -526,7 +641,6 @@ wherenotif_id));};- let notif = notif.into_tagged();let () = self.digest_batcherdiff --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 8403612627..bf1f2e7f07 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@@ -46,7 +46,7 @@ pub trait DigestBatcher: Send + Sync + 'static {/// to be sent after `send_after` duration.fn add_to_digest(&self,- notification: &UserNotificationRow<TaggedContent<serde_json::Value>>,+ notification: &UserNotificationRow<serde_json::Value>,send_after: Duration,) -> impl Future<Output = Result<(), Report>> + Send;@@ -81,11 +81,12 @@ pub trait LastOnlineChecker: Send + Sync + 'static {}/// The id of a message that was send as a push notification to SNS+#[derive(Debug)]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 {+pub trait MessageReceiptRepo: Send + Sync + 'static {/// 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,@@ -109,11 +110,11 @@ pub trait MessageReceiptRepo {}/// trait which abstracts away the sending of a notification-pub trait NotificationSendChecker {+pub trait NotificationSendChecker: Send {/// the type returned when the notification was sent successfully- type Ok;+ type Ok: Send;/// the error type of the request- type Err;+ type Err: Send;/// try to send the notificationfn send_notification(self) -> impl Future<Output = Result<Self::Ok, Self::Err>> + Send;diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rsindex b3bf36ed19..0f49ee29b5 100644--- a/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs+++ b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs@@ -7,6 +7,7 @@ use model_entity::EntityType;use rootcause::Report;use serde::{Deserialize, Serialize};use std::future::Future;+use std::sync::Arc;use std::time::Duration;// ============================================================================@@ -224,7 +225,7 @@ fn test_user_id() -> MacroUserIdStr<'static> {MacroUserIdStr::try_from_email("[email protected]").unwrap()}-fn create_test_notification_row<T>(metadata: T) -> UserNotificationRow<T> {+fn create_test_notification_row<T>(metadata: T) -> UserNotificationRow<Arc<T>> {UserNotificationRow {owner_id: test_user_id(),notification_id: uuid::Uuid::now_v7(),@@ -236,7 +237,7 @@ fn create_test_notification_row<T>(metadata: T) -> UserNotificationRow<T> {viewed_at: None,updated_at: None,deleted_at: None,- notification_metadata: metadata,+ notification_metadata: Arc::new(metadata),sender_id: None,}}diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rsindex 15784acc74..e9e13520c6 100644--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs@@ -3,20 +3,32 @@use crate::domain::models::{Notification, RateLimitConfig, RateLimitKey, SendNotificationRequest, TaggedContent,apple::APNSPushNotification,- email_notification_digest::{BatchSend, PushNotificationsEnabled},+ email_notification_digest::{BatchSend, PushNotificationsEnabled, StateMachineDecisionA},mobile::MessageAttributes,};use chrono::{DateTime, Utc};use cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use model_entity::Entity;+use rootcause::Report;use serde::{Deserialize, Serialize};+use std::collections::HashMap;use thiserror::Error;use uuid::Uuid;#[cfg(test)]mod test;+/// Per-user iOS push delivery targets.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct UserApnsEndpoints {+ /// The iOS device endpoint ARNs for this user.+ pub endpoints: Vec<String>,+ /// State machine data if the ingress decision was indeterminate for this user.+ #[serde(default)]+ pub digest_state: Option<BatchSend<PushNotificationsEnabled>>,+}+/// APNS push notification targets.#[derive(Debug, Serialize, Deserialize)]pub struct APNSTargets<T> {@@ -24,13 +36,8 @@ pub struct APNSTargets<T> {pub notif: APNSPushNotification<T>,/// The APNS message attributes.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>>,+ /// Per-user iOS device endpoints and optional state machine data.+ pub ios_device_endpoints: HashMap<MacroUserIdStr<'static>, UserApnsEndpoints>,}/// Email notification payload.@@ -165,15 +172,6 @@ pub enum NotificationChannel<'a, T, U> {ConnGateway(ConnGatewayNotification<'a, T>),}-/// A delivery node with optional fallback on failure.-#[derive(Debug, Serialize, Deserialize)]-pub struct Node<'a, T, U> {- /// The channel of notification we are delivering on.- pub notif: NotificationChannel<'a, T, U>,- /// The optional next channel we will attempt to deliver on if this method fails.- pub on_failure: Option<Box<Node<'a, T, U>>>,-}-/// Message published to SQS after DB persistence./// Contains everything needed for delivery.#[derive(Debug, Serialize, Deserialize)]@@ -185,7 +183,68 @@ pub struct QueueMessage<'a, T, U> {pub rate_limit: Option<(RateLimitKey, RateLimitConfig)>,/// The methods on which we will attempt to deliver./// This is an ALL relationship.- pub content: Node<'a, T, U>,+ pub content: NotificationChannel<'a, T, U>,+}++/// a wrapper type over [QueueMessage] which can only be opened by providing the decision from the bulk digest state machine+pub(crate) struct QueueMessageNeedsStateMachine<'a, T, U>(Vec<QueueMessage<'a, T, U>>);++impl<'a, T, U> QueueMessageNeedsStateMachine<'a, T, U> {+ pub fn new(messages: Vec<QueueMessage<'a, T, U>>) -> Self {+ Self(messages)+ }++ /// open the inner container by applying the state machine output to the necessary fields+ pub fn with_state_decisions(+ self,+ states: Vec<Result<StateMachineDecisionA<T>, Report>>,+ ) -> impl Iterator<Item = QueueMessage<'a, T, U>> {+ // Collect indeterminate decisions keyed by owner_id+ let indeterminates: HashMap<MacroUserIdStr<'static>, BatchSend<PushNotificationsEnabled>> =+ states+ .into_iter()+ .filter_map(|v| match v {+ Ok(StateMachineDecisionA::Indeterminate(indeterminate)) => Some(indeterminate),+ Err(_)+ | Ok(StateMachineDecisionA::DontSend(_))+ | Ok(StateMachineDecisionA::BatchWasQueued(_))+ | Ok(StateMachineDecisionA::SendImmediate(_)) => None,+ })+ .map(|batch| {+ let owner = batch.inner().owner_id().clone();+ (owner, batch)+ })+ .collect();++ let mut indeterminates = Some(indeterminates);++ let map_msg = move |msg: QueueMessage<'a, T, U>| {+ let QueueMessage {+ message_type,+ rate_limit,+ mut content,+ } = msg;++ if let NotificationChannel::Ios(ios) = &mut content {+ if let Some(ref mut lookup) = indeterminates {+ for (user_id, user_endpoints) in &mut ios.ios_device_endpoints {+ if let Some(entry) = lookup.remove(user_id) {+ user_endpoints.digest_state = Some(entry);+ }+ }+ }+ indeterminates = None;+ }++ QueueMessage {+ message_type,+ rate_limit,+ content,+ }+ };++ self.0.into_iter().map(map_msg)+ }}/// Custom data payload for a silent background push that clears a previouslydiff --git a/rust/cloud-storage/notification/src/domain/models/queue_message/test.rs b/rust/cloud-storage/notification/src/domain/models/queue_message/test.rsindex 6d229f2f28..5c8f42fefa 100644--- a/rust/cloud-storage/notification/src/domain/models/queue_message/test.rs+++ b/rust/cloud-storage/notification/src/domain/models/queue_message/test.rs@@ -1,9 +1,8 @@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#"{+fn test_apns_targets_deserializes_with_per_user_endpoints() {+ let json = r#"{"notif": {"aps": {"alert": {@@ -18,19 +17,36 @@ fn test_apns_targets_deserializes_old_format_without_bulk_digest_state_machine()"push_type": "Alert","collapse_key": "test-collapse-key"},- "ios_device_endpoints": ["endpoint1", "endpoint2"]+ "ios_device_endpoints": {+ "macro|[email protected]": {+ "endpoints": ["endpoint1", "endpoint2"]+ },+ "macro|[email protected]": {+ "endpoints": ["endpoint3"]+ }+ }}"#;- let result: Result<APNSTargets<serde_json::Value>, _> = serde_json::from_str(old_json);+ let result: Result<APNSTargets<serde_json::Value>, _> = serde_json::from_str(json);assert!(result.is_ok(),- "Old JSON format without bulk_digest_state_machine should deserialize successfully: {:?}",+ "Per-user endpoint format 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);+ let total_endpoints: usize = targets+ .ios_device_endpoints+ .values()+ .map(|u| u.endpoints.len())+ .sum();+ assert_eq!(total_endpoints, 3);assert_eq!(targets.attributes.collapse_key, "test-collapse-key");++ // Verify digest_state defaults to None when not present+ for user_endpoints in targets.ios_device_endpoints.values() {+ assert!(user_endpoints.digest_state.is_none());+ }}diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rsindex 04a3150f4e..1150bd504a 100644--- a/rust/cloud-storage/notification/src/domain/ports.rs+++ b/rust/cloud-storage/notification/src/domain/ports.rs@@ -5,6 +5,7 @@use std::collections::{HashMap, HashSet};use std::future::Future;+use std::sync::Arc;use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;@@ -23,20 +24,24 @@ use crate::domain::models::{/// Port for sending mobile push notifications (iOS/Android via SNS).pub trait NotificationSender: Send + Sync + 'static {/// Send an iOS push notification via APNS.+ ///+ /// Returns the SNS message ID on success (used for delivery failure tracking).fn send_ios_push_notification<T: Serialize + Send + Sync>(&self,endpoint_arn: &str,notification: &APNSPushNotification<T>,attributes: &MessageAttributes,- ) -> impl Future<Output = Result<(), Report>> + Send;+ ) -> impl Future<Output = Result<String, Report>> + Send;/// Send an Android push notification via FCM.+ ///+ /// Returns the SNS message ID on success (used for delivery failure tracking).fn send_android_push_notification<T: Serialize + Send + Sync>(&self,endpoint_arn: &str,notification: &FCMMessage<T>,attributes: &MessageAttributes,- ) -> impl Future<Output = Result<(), Report>> + Send;+ ) -> impl Future<Output = Result<String, Report>> + Send;}/// Port for rate limiting operations.@@ -73,11 +78,11 @@ pub trait NotificationRepository: Send + Sync + 'static {/// (idempotent operation).fn create_notification<'a, T: Notification + Send + Sync>(&self,- request: &SendNotificationRequestBuilder<'a, T>,+ request: SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,service_sender: &str,apns_collapse_key: Option<&str>,- ) -> impl Future<Output = Result<Option<Uuid>, Report>> + Send;+ ) -> impl Future<Output = Result<Option<Vec<UserNotificationRow<Arc<T>>>>, Report>> + Send;/// Update the sent status for users who received the notification.fn update_sent_status<'a>(@@ -189,9 +194,9 @@ use crate::domain::models::queue_message::{DeliverySuccess, QueueMessage, RawQue/// Port for publishing notifications to delivery queue and receiving them.pub trait NotificationQueue: Send + Sync + 'static {/// Publish notifications for async delivery (after DB persistence).- fn publish<T: Serialize + Send + Sync, U: Serialize + Send + Sync>(+ fn publish<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(&self,- messages: &[QueueMessage<'_, T, U>],+ messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,) -> impl Future<Output = Result<(), Report>> + Send;/// Receive messages from the queue (for worker).diff --git a/rust/cloud-storage/notification/src/domain/service.rs b/rust/cloud-storage/notification/src/domain/service.rsindex e4fd29096d..e7c7846eed 100644--- a/rust/cloud-storage/notification/src/domain/service.rs+++ b/rust/cloud-storage/notification/src/domain/service.rs@@ -14,6 +14,8 @@ use thiserror::Error;pub use egress::NotificationEgressService;pub use ingress::NotificationIngress;pub use ingress::NotificationIngressService;+pub use ingress::NotificationReader;+pub use ingress::NotificationReaderService;/// Error returned when sending a notification fails.#[derive(Debug, Error)]diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rsindex 07a4ff687b..f68543c500 100644--- a/rust/cloud-storage/notification/src/domain/service/egress.rs+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs@@ -4,8 +4,14 @@//! consuming from the queue and delivering via WebSocket, push, and email.use crate::domain::models::RateLimitResult;+use crate::domain::models::apple::APNSPushNotification;+use crate::domain::models::email_notification_digest::ports::{MessageId, NotificationSendChecker};+use crate::domain::models::email_notification_digest::{+ BulkDigestEgressStateMachine, ResumeMachineBRequest,+};+use crate::domain::models::mobile::MessageAttributes;use crate::domain::models::queue_message::{- ConnGatewayNotification, DeliveryFailure, DeliverySuccess, EmailNotification, Node,+ APNSTargets, ConnGatewayNotification, DeliveryFailure, DeliverySuccess, EmailNotification,NotificationChannel, QueueMessage,};use crate::domain::ports::{@@ -16,10 +22,36 @@ use either::Either;use rootcause::prelude::ResultExt;use rootcause::{Report, report};+/// Wraps a single iOS push notification send for the bulk-digest state machine.+///+/// The state machine calls [`NotificationSendChecker::send_notification`] to perform the actual+/// push delivery, then records the SNS message ID or queues for batch email on failure.+struct IosPushSend<'a, M> {+ mobile: &'a M,+ endpoint_arn: &'a str,+ notif: &'a APNSPushNotification<serde_json::Value>,+ attributes: &'a MessageAttributes,+}++impl<M: NotificationSender> NotificationSendChecker for IosPushSend<'_, M> {+ type Ok = String;+ type Err = Report;++ async fn send_notification(self) -> Result<String, Report> {+ self.mobile+ .send_ios_push_notification(self.endpoint_arn, self.notif, self.attributes)+ .await+ }++ fn extract_message_id(res: &String) -> MessageId {+ MessageId(res.clone())+ }+}+/// Service for delivering notifications (egress side).////// Handles consuming from queue and delivering via WebSocket, push, and email.-pub struct NotificationEgressService<Q, N, W, M, E, R> {+pub struct NotificationEgressService<Q, N, W, M, E, R, S> {queue: Q,#[allow(dead_code)]repository: N,@@ -27,9 +59,10 @@ pub struct NotificationEgressService<Q, N, W, M, E, R> {mobile: M,email: E,rate_limiter: R,+ state_machine: S,}-impl<Q, N, W, M, E, R> NotificationEgressService<Q, N, W, M, E, R>+impl<Q, N, W, M, E, R, S> NotificationEgressService<Q, N, W, M, E, R, S>whereQ: NotificationQueue,N: NotificationRepository,@@ -37,6 +70,7 @@ whereM: NotificationSender,E: EmailSender,R: RateLimitPort,+ S: BulkDigestEgressStateMachine,{/// Create a new egress service.pub fn new(@@ -46,6 +80,7 @@ wheremobile: M,email: E,rate_limiter: R,+ state_machine: S,) -> Self {Self {queue,@@ -54,6 +89,7 @@ wheremobile,email,rate_limiter,+ state_machine,}}@@ -80,37 +116,20 @@ where}}- self.deliver_notification_inner(&message.message_type, message.content, Vec::new())- .await- .into_iter()- .map(|r| r.context(DeliveryFailure::Other))- .collect()- }-- /// Deliver a single node, with fallback on failure.- async fn deliver_notification_inner(- &self,- message_type: &str,- node: Node<'static, serde_json::Value, serde_json::Value>,- mut recursion_tail: Vec<Result<DeliverySuccess, Report>>,- ) -> Vec<Result<DeliverySuccess, Report>> {- let result = match &node.notif {- NotificationChannel::ConnGateway(conn) => {+ let results = match message.content {+ NotificationChannel::ConnGateway(ref conn) => {Either::Left([self.deliver_conn_gateway(conn).await])}- NotificationChannel::Email(email) => Either::Left([self.deliver_email(email).await]),- NotificationChannel::Ios(apns) => Either::Right(self.deliver_ios(apns).await),- };- let all_failed = result.iter().all(Result::is_err);- recursion_tail.extend(result.into_iter());-- match (all_failed, node.on_failure) {- (false, _) | (true, None) => recursion_tail,- (true, Some(fallback)) => {- Box::pin(self.deliver_notification_inner(message_type, *fallback, recursion_tail))- .await+ NotificationChannel::Email(ref email) => {+ Either::Left([self.deliver_email(email).await])}- }+ NotificationChannel::Ios(apns) => Either::Right(self.deliver_ios(&apns).await),+ };++ results+ .into_iter()+ .map(|r| r.context(DeliveryFailure::Other))+ .collect()}/// Deliver via connection gateway (WebSocket).@@ -125,19 +144,64 @@ where}/// Deliver via iOS push (APNS).+ ///+ /// Iterates per-user. If a user has a digest state machine entry, all+ /// endpoints are passed to [`BulkDigestEgressStateMachine::continue_machine`]+ /// in a single call. The state machine records SNS message IDs for successes+ /// and only queues a batch email if ALL endpoints fail.+ /// Users without a state machine entry are sent directly.async fn deliver_ios(&self,- apns: &crate::domain::models::queue_message::APNSTargets<serde_json::Value>,+ apns: &APNSTargets<serde_json::Value>,) -> Vec<Result<DeliverySuccess, Report>> {- let mut out = Vec::with_capacity(apns.ios_device_endpoints.len());- for endpoint in &apns.ios_device_endpoints {- let res = self- .mobile- .send_ios_push_notification(endpoint, &apns.notif, &apns.attributes)- .await- .map(|()| DeliverySuccess::Ios);- out.push(res)+ let total: usize = apns+ .ios_device_endpoints+ .values()+ .map(|u| u.endpoints.len())+ .sum();+ let mut out = Vec::with_capacity(total);++ for user_apns in apns.ios_device_endpoints.values() {+ if let Some(ref entry) = user_apns.digest_state {+ // Build all send checkers for this user's endpoints+ let checkers: Vec<_> = user_apns+ .endpoints+ .iter()+ .map(|endpoint| IosPushSend {+ mobile: &self.mobile,+ endpoint_arn: endpoint,+ notif: &apns.notif,+ attributes: &apns.attributes,+ })+ .collect();++ let req = ResumeMachineBRequest {+ notification_enabled: entry.inner().clone(),+ send_notifs: checkers,+ };++ let (results, batch_decision) = self.state_machine.continue_machine(req).await;++ if let Either::Right(Err(ref batch_err)) = batch_decision {+ tracing::error!(error=?batch_err, "failed to queue digest batch after all pushes failed");+ }++ for result in results {+ out.push(result.map(|_| DeliverySuccess::Ios));+ }+ } else {+ // No state machine entry — send directly+ for endpoint in &user_apns.endpoints {+ let res = self+ .mobile+ .send_ios_push_notification(endpoint, &apns.notif, &apns.attributes)+ .await+ .map(|_| DeliverySuccess::Ios);+ out.push(res);+ }+ }}+out}@@ -153,7 +217,7 @@ where}}-impl<Q, N, W, M, E, R> NotificationEgress for NotificationEgressService<Q, N, W, M, E, R>+impl<Q, N, W, M, E, R, S> NotificationEgress for NotificationEgressService<Q, N, W, M, E, R, S>whereQ: NotificationQueue,N: NotificationRepository,@@ -161,6 +225,7 @@ whereM: NotificationSender,E: EmailSender,R: RateLimitPort,+ S: BulkDigestEgressStateMachine,{#[tracing::instrument(ret, skip(self))]async fn poll_and_deliver(&self) -> Vec<Result<DeliverySuccess, Report>> {diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rsindex 4b956e8904..22732842fb 100644--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs@@ -4,10 +4,11 @@//! filtering recipients, persisting to DB, and publishing to the queue.use crate::domain::models::apple::{APNSPushNotification, Aps};+use crate::domain::models::email_notification_digest::BulkDigestStateMachine;use crate::domain::models::mobile::{MessageAttributes, PushType};use crate::domain::models::queue_message::{- APNSTargets, ClearPushIdentifier, ConnGatewayNotification, EmailNotification, Node,- NotificationChannel, QueueMessage,+ APNSTargets, ClearPushIdentifier, ConnGatewayNotification, EmailNotification,+ NotificationChannel, QueueMessage, QueueMessageNeedsStateMachine, UserApnsEndpoints,};use crate::domain::models::request::{GetNotificationsByEventItemIdsRequest, NotificationStatus, UpdateNotificationsRequest,@@ -17,6 +18,7 @@ use crate::domain::models::{};use crate::domain::ports::{NotificationQueue, NotificationRepository};use crate::domain::service::SendNotificationError;+use ::futures::future::join_all;use macro_user_id::cowlike::CowLike;use models_pagination::{CreatedAt, PaginateOn, Paginated, Query, TypeEraseCursor};use rootcause::Report;@@ -29,11 +31,21 @@ use uuid::Uuid;/// Trait for sending notifications through the ingress service.pub trait NotificationIngress: Send + Sync + 'static {/// Send a notification to the specified recipients.- fn send_notification<'a, T: Notification + Clone, U: Serialize + Send + Sync>(- &self,+ fn send_notification<+ 'a,+ T: Notification + Clone + 'static,+ U: Serialize + Send + Sync + 'static,+ >(+ &'a self,req: SendNotificationRequest<'a, T, U>,) -> impl Future<Output = Result<Option<NotificationResult<'a>>, Report<SendNotificationError>>> + Send;+}+/// Trait for reading and updating notifications.+///+/// This is separated from [`NotificationIngress`] because these operations+/// do not require the bulk-digest state machine.+pub trait NotificationReader: Send + Sync + 'static {/// Mark notifications as seen for a user and enqueue push notification clearing.fn update_notifications(&self,@@ -83,17 +95,259 @@ pub trait NotificationIngress: Send + Sync + 'static {////// Handles recipient filtering, DB persistence, and queue publishing./// Does NOT handle delivery - that's done by [`super::NotificationEgressService`].-pub struct NotificationIngressService<N, Q> {+pub struct NotificationIngressService<N, Q, S> {repository: N,queue: Q,+ state_machine_driver: S,service_name: &'static str,}-impl<N, Q> NotificationIngress for NotificationIngressService<N, Q>+impl<N, Q, S> NotificationIngress for NotificationIngressService<N, Q, S>+where+ N: NotificationRepository,+ Q: NotificationQueue,+ S: BulkDigestStateMachine,+{+ fn send_notification<+ 'a,+ T: Notification + Clone + 'static,+ U: Serialize + Send + Sync + 'static,+ >(+ &'a self,+ request: SendNotificationRequest<'a, T, U>,+ ) -> impl Future<Output = Result<Option<NotificationResult<'a>>, Report<SendNotificationError>>> + Send+ {+ self.send_notification_impl(request)+ }+}++impl<N, Q, S> NotificationIngressService<N, Q, S>+where+ N: NotificationRepository,+ Q: NotificationQueue,+ S: BulkDigestStateMachine,+{+ /// Create a new ingress service.+ pub fn new(repository: N, queue: Q, state_machine_driver: S) -> Self {+ Self {+ repository,+ queue,+ state_machine_driver,+ service_name: std::env!("CARGO_PKG_NAME"),+ }+ }++ /// Send a notification to the specified recipients.+ ///+ /// This method performs the following steps:+ /// 1. Filter recipients (remove sender, muted users, unsubscribed users)+ /// 2. Create notification in the database+ /// 3. Build and publish QueueMessage to SQS+ /// 4. Return result (delivery happens async via worker)+ async fn send_notification_impl<+ 'a,+ T: Notification + Clone + 'static,+ U: Serialize + Send + Sync + 'static,+ >(+ &'a self,+ request: SendNotificationRequest<'a, T, U>,+ ) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {+ let mut request = self+ .filter_recipients(request)+ .await+ .context(SendNotificationError::Other)?;++ if request.req.recipient_ids.is_empty() {+ return Ok(None);+ }++ let notification_id = Uuid::now_v7();+ let (queue_messages, apns_collapse_key) = self+ .build_queue_message(notification_id, &mut request)+ .await?;++ let notified_recipients = request.req.recipient_ids.clone();++ // Create notification in DB (with collapse key if APNS was built)+ let created = self+ .repository+ .create_notification(+ request.req,+ notification_id,+ self.service_name,+ apns_collapse_key.as_deref(),+ )+ .await+ .context(SendNotificationError::Other)?;++ // If notification already exists (idempotent), return early+ let Some(n) = created else {+ return Ok(Some(NotificationResult {+ notification_id,+ notified_recipients: HashSet::new(),+ }));+ };++ let results = join_all(+ n.into_iter()+ .map(|user_notif| self.state_machine_driver.ingest(user_notif)),+ )+ .await;++ self.queue+ .publish(queue_messages.with_state_decisions(results))+ .await+ .context(SendNotificationError::Other)?;++ // Return result (delivery happens async)+ Ok(Some(NotificationResult {+ notification_id,+ notified_recipients,+ }))+ }++ /// Filter recipients based on:+ /// - Sender (sender cannot receive their own notification)+ /// - Muted notifications+ /// - Unsubscribed from item+ async fn filter_recipients<'a, T, U>(+ &self,+ req: SendNotificationRequest<'a, T, U>,+ ) -> Result<SendNotificationRequest<'a, T, U>, Report> {+ let recipient_ids: Vec<_> = req.req.recipient_ids.iter().map(CowLike::copied).collect();++ // Fetch all filter data upfront+ let (muted_users, unsubscribed_users) = tokio::try_join!(+ self.repository.get_muted_users(&recipient_ids),+ self.repository+ .get_unsubscribed_users(&req.req.notification_entity.entity_id, &recipient_ids),+ )?;++ let (out, _excluded) = req.update_recipients(muted_users, unsubscribed_users);+ Ok(out)+ }++ /// Build queue messages for each delivery channel.+ ///+ /// - `send_conn_gateway`: Creates a single message for all recipients (1:M)+ /// - `build_apns`: Creates one message per recipient with their device endpoints (1:1)+ /// - `build_email`: Creates one message per recipient (1:1)+ /// Returns `(queue_messages, apns_collapse_key)`.+ async fn build_queue_message<'a, T: Notification + Clone, U: Serialize + Send + Sync>(+ &self,+ notification_id: Uuid,+ notification: &mut SendNotificationRequest<'a, T, U>,+ ) -> Result<+ (QueueMessageNeedsStateMachine<'a, T, U>, Option<String>),+ Report<SendNotificationError>,+ > {+ let rate_limit = notification.req.get_rate_limit()?;+ let message_type = T::TYPE_NAME.to_string();+ let mut messages = Vec::new();+ let mut apns_collapse_key = None;++ // Connection gateway: 1:M (single message for all recipients)+ if notification.send_conn_gateway {+ messages.push(QueueMessage {+ message_type: message_type.clone(),+ rate_limit: rate_limit.clone(),+ content: NotificationChannel::ConnGateway(+ ConnGatewayNotification::clone_from_request(notification_id, notification),+ ),+ });+ }++ // APNS (iOS push): 1:M (single message for all recipients' device endpoints)+ if let Some(ref mut build_apns) = notification.build_apns {+ let recipients_vec: Vec<_> = notification.req.recipient_ids.iter().cloned().collect();+ let device_endpoints = self+ .repository+ .get_device_endpoints(&recipients_vec)+ .await+ .context(SendNotificationError::Other)?;++ let ios_endpoints: std::collections::HashMap<_, _> = device_endpoints+ .into_iter()+ .filter_map(|(user_id, endpoints)| {+ let ios: Vec<String> = endpoints+ .into_iter()+ .filter_map(|e| match e {+ DeviceEndpoint::Ios(arn) => Some(arn),+ DeviceEndpoint::Android(_) => None,+ })+ .collect();+ if ios.is_empty() {+ None+ } else {+ Some((+ user_id,+ UserApnsEndpoints {+ endpoints: ios,+ digest_state: None,+ },+ ))+ }+ })+ .collect();++ if !ios_endpoints.is_empty()+ && let Some((apns_notif, attributes)) =+ build_apns(notification.req.notification.clone(), notification_id)+ {+ apns_collapse_key = Some(attributes.collapse_key.clone());+ messages.push(QueueMessage {+ message_type: message_type.clone(),+ rate_limit: rate_limit.clone(),+ content: NotificationChannel::Ios(Box::new(APNSTargets {+ notif: apns_notif,+ attributes,+ ios_device_endpoints: ios_endpoints,+ })),+ });+ }+ }++ // Email: 1:1 (one message per recipient)+ if let Some(ref mut build_email) = notification.build_email {+ for recipient in ¬ification.req.recipient_ids {+ let email_content = build_email(notification.req.notification.clone());+ messages.push(QueueMessage {+ message_type: message_type.clone(),+ rate_limit: rate_limit.clone(),+ content: NotificationChannel::Email(EmailNotification {+ to: recipient.clone(),+ content: email_content,+ }),+ });+ }+ }++ Ok((+ QueueMessageNeedsStateMachine::new(messages),+ apns_collapse_key,+ ))+ }+}++/// Service for reading and updating notifications.+///+/// Handles notification queries, status updates, and deletion.+/// Does not require a bulk-digest state machine.+pub struct NotificationReaderService<N, Q> {+ repository: N,+ queue: Q,+}++impl<N, Q> NotificationReaderService<N, Q>whereN: NotificationRepository,Q: NotificationQueue,{+ /// Create a new reader service.+ pub fn new(repository: N, queue: Q) -> Self {+ Self { repository, queue }+ }+/// Update notification status for a user and optionally enqueue push notification clearing.////// This method performs the following steps:@@ -103,7 +357,7 @@ where/// b. Look up the user's iOS device endpoints/// c. Publish silent background push messages to clear badges on devices#[tracing::instrument(err, skip(self))]- async fn update_notifications(+ async fn update_notifications_impl(&self,req: UpdateNotificationsRequest<'_>,) -> Result<(), Report> {@@ -138,12 +392,27 @@ where.get_device_endpoints(&[req.user_id.copied()]).await?;- let ios_endpoints: Vec<String> = device_endpoints- .values()- .flatten()- .filter_map(|e| match e {- DeviceEndpoint::Ios(arn) => Some(arn.clone()),- DeviceEndpoint::Android(_) => None,+ let ios_endpoints: std::collections::HashMap<_, _> = device_endpoints+ .into_iter()+ .filter_map(|(user_id, endpoints)| {+ let ios: Vec<String> = endpoints+ .into_iter()+ .filter_map(|e| match e {+ DeviceEndpoint::Ios(arn) => Some(arn),+ DeviceEndpoint::Android(_) => None,+ })+ .collect();+ if ios.is_empty() {+ None+ } else {+ Some((+ user_id,+ UserApnsEndpoints {+ endpoints: ios,+ digest_state: None,+ },+ ))+ }}).collect();@@ -159,91 +428,43 @@ whereQueueMessage {message_type: "clear_push_notification".to_string(),rate_limit: None,- content: Node {- notif: NotificationChannel::Ios(Box::new(APNSTargets {- notif: APNSPushNotification {- aps: Aps {- content_available: Some(1),- sound: None,- ..Default::default()- },- push_notification_data: ClearPushIdentifier {- identifier: collapse_key.clone(),- },+ content: NotificationChannel::Ios(Box::new(APNSTargets {+ notif: APNSPushNotification {+ aps: Aps {+ content_available: Some(1),+ sound: None,+ ..Default::default()},- attributes: MessageAttributes {- push_type: PushType::Background,- collapse_key,+ push_notification_data: ClearPushIdentifier {+ identifier: collapse_key.clone(),},- ios_device_endpoints: ios_endpoints.clone(),- bulk_digest_state_machine: None,- })),- on_failure: None,- },+ },+ attributes: MessageAttributes {+ push_type: PushType::Background,+ collapse_key,+ },+ ios_device_endpoints: ios_endpoints.clone(),+ })),}}).collect();- self.queue.publish(&messages).await?;+ self.queue.publish(messages.into_iter()).await?;Ok(())}+}- /// Send a notification to the specified recipients.- ///- /// This method performs the following steps:- /// 1. Filter recipients (remove sender, muted users, unsubscribed users)- /// 2. Create notification in the database- /// 3. Build and publish QueueMessage to SQS- /// 4. Return result (delivery happens async via worker)- async fn send_notification<'a, T: Notification + Clone, U: Serialize + Send + Sync>(+impl<N, Q> NotificationReader for NotificationReaderService<N, Q>+where+ N: NotificationRepository,+ Q: NotificationQueue,+{+ fn update_notifications(&self,- request: SendNotificationRequest<'a, T, U>,- ) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {- let mut request = self- .filter_recipients(request)- .await- .context(SendNotificationError::Other)?;-- if request.req.recipient_ids.is_empty() {- return Ok(None);- }-- let notification_id = Uuid::now_v7();- let (queue_messages, apns_collapse_key) = self- .build_queue_message(notification_id, &mut request)- .await?;-- // Create notification in DB (with collapse key if APNS was built)- let created = self- .repository- .create_notification(- &request.req,- notification_id,- self.service_name,- apns_collapse_key.as_deref(),- )- .await- .context(SendNotificationError::Other)?;-- // If notification already exists (idempotent), return early- let Some(notification_id) = created else {- return Ok(Some(NotificationResult {- notification_id,- notified_recipients: HashSet::new(),- }));- };-- self.queue- .publish(&queue_messages)- .await- .context(SendNotificationError::Other)?;-- // Return result (delivery happens async)- Ok(Some(NotificationResult {- notification_id,- notified_recipients: request.req.recipient_ids,- }))+ req: UpdateNotificationsRequest<'_>,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ self.update_notifications_impl(req)}#[tracing::instrument(err, skip(self))]@@ -328,129 +549,3 @@ where.await}}--impl<N, Q> NotificationIngressService<N, Q>-where- N: NotificationRepository,- Q: NotificationQueue,-{- /// Create a new ingress service.- pub fn new(repository: N, queue: Q) -> Self {- Self {- repository,- queue,- service_name: std::env!("CARGO_PKG_NAME"),- }- }-- /// Filter recipients based on:- /// - Sender (sender cannot receive their own notification)- /// - Muted notifications- /// - Unsubscribed from item- async fn filter_recipients<'a, T, U>(- &self,- req: SendNotificationRequest<'a, T, U>,- ) -> Result<SendNotificationRequest<'a, T, U>, Report> {- let recipient_ids: Vec<_> = req.req.recipient_ids.iter().map(CowLike::copied).collect();-- // Fetch all filter data upfront- let (muted_users, unsubscribed_users) = tokio::try_join!(- self.repository.get_muted_users(&recipient_ids),- self.repository- .get_unsubscribed_users(&req.req.notification_entity.entity_id, &recipient_ids),- )?;-- let (out, _excluded) = req.update_recipients(muted_users, unsubscribed_users);- Ok(out)- }-- /// Build queue messages for each delivery channel.- ///- /// - `send_conn_gateway`: Creates a single message for all recipients (1:M)- /// - `build_apns`: Creates one message per recipient with their device endpoints (1:1)- /// - `build_email`: Creates one message per recipient (1:1)- /// Returns `(queue_messages, apns_collapse_key)`.- async fn build_queue_message<'a, T: Notification + Clone, U: Serialize + Send + Sync>(- &self,- notification_id: Uuid,- notification: &mut SendNotificationRequest<'a, T, U>,- ) -> Result<(Vec<QueueMessage<'a, T, U>>, Option<String>), Report<SendNotificationError>> {- let rate_limit = notification.req.get_rate_limit()?;- let message_type = T::TYPE_NAME.to_string();- let mut messages = Vec::new();- let mut apns_collapse_key = None;-- // Connection gateway: 1:M (single message for all recipients)- if notification.send_conn_gateway {- messages.push(QueueMessage {- message_type: message_type.clone(),- rate_limit: rate_limit.clone(),- content: Node {- notif: NotificationChannel::ConnGateway(- ConnGatewayNotification::clone_from_request(notification_id, notification),- ),- on_failure: None,- },- });- }-- // APNS (iOS push): 1:M (single message for all recipients' device endpoints)- if let Some(ref mut build_apns) = notification.build_apns {- let recipients_vec: Vec<_> = notification.req.recipient_ids.iter().cloned().collect();- let device_endpoints = self- .repository- .get_device_endpoints(&recipients_vec)- .await- .context(SendNotificationError::Other)?;-- let ios_endpoints: Vec<String> = device_endpoints- .values()- .flatten()- .filter_map(|e| match e {- DeviceEndpoint::Ios(arn) => Some(arn.clone()),- DeviceEndpoint::Android(_) => None,- })- .collect();-- if !ios_endpoints.is_empty()- && let Some((apns_notif, attributes)) =- build_apns(notification.req.notification.clone(), notification_id)- {- apns_collapse_key = Some(attributes.collapse_key.clone());- messages.push(QueueMessage {- message_type: message_type.clone(),- rate_limit: rate_limit.clone(),- content: Node {- notif: NotificationChannel::Ios(Box::new(APNSTargets {- notif: apns_notif,- attributes,- ios_device_endpoints: ios_endpoints,- bulk_digest_state_machine: None,- })),- on_failure: None,- },- });- }- }-- // Email: 1:1 (one message per recipient)- if let Some(ref mut build_email) = notification.build_email {- for recipient in ¬ification.req.recipient_ids {- let email_content = build_email(notification.req.notification.clone());- messages.push(QueueMessage {- message_type: message_type.clone(),- rate_limit: rate_limit.clone(),- content: Node {- notif: NotificationChannel::Email(EmailNotification {- to: recipient.clone(),- content: email_content,- }),- on_failure: None,- },- });- }- }-- Ok((messages, apns_collapse_key))- }-}diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex 6cd6acb4d9..9a623fd83c 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -1,9 +1,10 @@//! Unit tests for the notification services.use crate::domain::models::apple::APNSPushNotification;+use crate::domain::models::email_notification_digest::BulkDigestStateMachine;use crate::domain::models::mobile::NotifCollapseKey;use crate::domain::models::queue_message::{- ConnGatewayInnerNotif, ConnGatewayNotification, EmailContent, Node, NotificationChannel,+ ConnGatewayInnerNotif, ConnGatewayNotification, EmailContent, NotificationChannel,QueueMessage, RawQueueMessage,};use crate::domain::models::request::{NotificationStatus, UpdateNotificationsRequest};@@ -17,16 +18,18 @@ use crate::domain::ports::{WebSocketSender,};use crate::domain::service::{- NotificationEgressService, NotificationIngress, NotificationIngressService,+ NotificationEgressService, NotificationIngress, NotificationIngressService, NotificationReader,+ NotificationReaderService,};+use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;-use rootcause::Report;+use rootcause::{Report, report};use serde::de::DeserializeOwned;use serde::{Deserialize, Serialize};use serde_json::json;use std::collections::{HashMap, HashSet};-use std::sync::Mutex;+use std::sync::{Arc, Mutex};use std::time::Duration;use uuid::Uuid;@@ -139,6 +142,18 @@ impl MockRepository {}}+struct MockStateMachine;++impl BulkDigestStateMachine for MockStateMachine {+ async fn ingest<T: Notification + 'static>(+ &self,+ _notif: UserNotificationRow<Arc<T>>,+ ) -> Result<crate::domain::models::email_notification_digest::StateMachineDecisionA<T>, Report>+ {+ Err(report!("not implemented"))+ }+}+impl NotificationRepository for MockRepository {async fn get_muted_users<'a>(&self,@@ -157,11 +172,11 @@ impl NotificationRepository for MockRepository {async fn create_notification<'a, T: Notification + Send + Sync>(&self,- _request: &SendNotificationRequestBuilder<'a, T>,+ request: SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,_service_sender: &str,apns_collapse_key: Option<&str>,- ) -> Result<Option<Uuid>, Report> {+ ) -> Result<Option<Vec<UserNotificationRow<Arc<T>>>>, Report> {self.created_notifications.lock().unwrap()@@ -170,7 +185,28 @@ impl NotificationRepository for MockRepository {.lock().unwrap().push((notification_id, apns_collapse_key.map(String::from)));- Ok(Some(notification_id))+ let entity = request.notification_entity.clone().into_owned();+ let sender_id = request.sender_id.as_ref().map(|id| id.clone().into_owned());+ let notification_metadata = Arc::new(request.notification);+ let rows = request+ .recipient_ids+ .iter()+ .map(|recipient| UserNotificationRow {+ owner_id: recipient.clone().into_owned(),+ notification_id,+ notification_event_type: T::TYPE_NAME.to_string(),+ entity: entity.clone(),+ sent: false,+ done: false,+ created_at: None,+ viewed_at: None,+ updated_at: None,+ deleted_at: None,+ notification_metadata: notification_metadata.clone(),+ sender_id: sender_id.clone(),+ })+ .collect();+ Ok(Some(rows))}async fn update_sent_status<'a>(@@ -283,11 +319,11 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {async fn create_notification<'a, T: Notification + Send + Sync>(&self,- request: &SendNotificationRequestBuilder<'a, T>,+ request: SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,service_sender: &str,apns_collapse_key: Option<&str>,- ) -> Result<Option<Uuid>, Report> {+ ) -> Result<Option<Vec<UserNotificationRow<Arc<T>>>>, Report> {(**self).create_notification(request, notification_id, service_sender, apns_collapse_key).await@@ -409,13 +445,13 @@ impl MockQueue {}impl NotificationQueue for MockQueue {- async fn publish<T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(+ async fn publish<'a, T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(&self,- messages: &[QueueMessage<'_, T, U>],+ messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,) -> Result<(), Report> {let mut published = self.published.lock().unwrap();for message in messages {- let json = serde_json::to_value(message).unwrap();+ let json = serde_json::to_value(&message).unwrap();published.push(json);}Ok(())@@ -431,9 +467,9 @@ impl NotificationQueue for MockQueue {}impl NotificationQueue for std::sync::Arc<MockQueue> {- async fn publish<T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(+ async fn publish<'a, T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(&self,- messages: &[QueueMessage<'_, T, U>],+ messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,) -> Result<(), Report> {(**self).publish(messages).await}@@ -447,17 +483,10 @@ impl NotificationQueue for std::sync::Arc<MockQueue> {}}-fn create_service<N, Q>(repository: N, queue: Q) -> NotificationIngressService<N, Q>-where- N: NotificationRepository,- Q: NotificationQueue,-{- NotificationIngressService::new(repository, queue)-}-#[tokio::test]async fn test_send_notification_success() {- let service = create_service(MockRepository::new(), MockQueue::new());+ let service =+ NotificationIngressService::new(MockRepository::new(), MockQueue::new(), MockStateMachine);let recipient = test_user_id("[email protected]");let request = SendNotificationRequestBuilder {@@ -477,7 +506,8 @@ async fn test_send_notification_success() {#[tokio::test]async fn test_sender_excluded_from_recipients() {- let service = create_service(MockRepository::new(), MockQueue::new());+ let service =+ NotificationIngressService::new(MockRepository::new(), MockQueue::new(), MockStateMachine);let sender = test_user_id("[email protected]");let request = SendNotificationRequestBuilder {@@ -499,9 +529,10 @@ async fn test_sender_excluded_from_recipients() {#[tokio::test]async fn test_muted_user_excluded() {let muted_user = test_user_id("[email protected]");- let service = create_service(+ let service = NotificationIngressService::new(MockRepository::new().with_muted_user(muted_user.clone()),MockQueue::new(),+ MockStateMachine,);let request = SendNotificationRequestBuilder {@@ -523,9 +554,10 @@ async fn test_muted_user_excluded() {#[tokio::test]async fn test_unsubscribed_user_excluded() {let unsubscribed_user = test_user_id("[email protected]");- let service = create_service(+ let service = NotificationIngressService::new(MockRepository::new().with_unsubscribed_user(unsubscribed_user.clone()),MockQueue::new(),+ MockStateMachine,);let request = SendNotificationRequestBuilder {@@ -549,7 +581,8 @@ async fn test_queue_message_conn_gateway_only() {use std::sync::Arc;let queue = Arc::new(MockQueue::new());- let service = NotificationIngressService::new(MockRepository::new(), queue.clone());+ let service =+ NotificationIngressService::new(MockRepository::new(), queue.clone(), MockStateMachine);let recipient = test_user_id("[email protected]");let request = SendNotificationRequestBuilder {@@ -570,7 +603,7 @@ async fn test_queue_message_conn_gateway_only() {let msg = &published[0];assert_eq!(msg["message_type"], "test_notification");- assert!(msg["content"]["notif"]["ConnGateway"].is_object());+ assert!(msg["content"]["ConnGateway"].is_object());}#[tokio::test]@@ -578,7 +611,8 @@ async fn test_queue_message_email_per_recipient() {use std::sync::Arc;let queue = Arc::new(MockQueue::new());- let service = NotificationIngressService::new(MockRepository::new(), queue.clone());+ let service =+ NotificationIngressService::new(MockRepository::new(), queue.clone(), MockStateMachine);let recipient1 = test_user_id("[email protected]");let recipient2 = test_user_id("[email protected]");@@ -601,7 +635,7 @@ async fn test_queue_message_email_per_recipient() {for msg in &published {assert_eq!(msg["message_type"], "test_notification");- assert!(msg["content"]["notif"]["Email"].is_object());+ assert!(msg["content"]["Email"].is_object());}}@@ -615,7 +649,7 @@ async fn test_queue_message_multiple_channels() {recipient.clone(),DeviceEndpoint::Ios("arn:aws:sns:test".to_string()),);- let service = NotificationIngressService::new(repo, queue.clone());+ let service = NotificationIngressService::new(repo, queue.clone(), MockStateMachine);let request = SendNotificationRequestBuilder {notification_entity: EntityType::Document.with_entity_str("entity_1"),@@ -638,13 +672,9 @@ async fn test_queue_message_multiple_channels() {let has_conn_gateway = published.iter()- .any(|m| m["content"]["notif"]["ConnGateway"].is_object());- let has_ios = published- .iter()- .any(|m| m["content"]["notif"]["Ios"].is_object());- let has_email = published- .iter()- .any(|m| m["content"]["notif"]["Email"].is_object());+ .any(|m| m["content"]["ConnGateway"].is_object());+ let has_ios = published.iter().any(|m| m["content"]["Ios"].is_object());+ let has_email = published.iter().any(|m| m["content"]["Email"].is_object());assert!(has_conn_gateway, "Should have ConnGateway message");assert!(has_ios, "Should have iOS message");@@ -686,7 +716,7 @@ async fn test_apns_enqueues_correct_data_for_multiple_users() {),);- let service = NotificationIngressService::new(repo, queue.clone());+ let service = NotificationIngressService::new(repo, queue.clone(), MockStateMachine);let request = SendNotificationRequestBuilder {notification_entity: EntityType::Document.with_entity_str("doc_123"),@@ -712,7 +742,7 @@ async fn test_apns_enqueues_correct_data_for_multiple_users() {assert_eq!(msg["message_type"], "test_notification");// The message should be an Ios variant- let ios = &msg["content"]["notif"]["Ios"];+ let ios = &msg["content"]["Ios"];assert!(ios.is_object(), "Expected Ios notification channel");// Verify the APNS notification payload contains the notification data@@ -729,33 +759,42 @@ async fn test_apns_enqueues_correct_data_for_multiple_users() {let expected_key = NotifCollapseKey::new("test").into_hashed().into_inner();assert_eq!(attrs["collapse_key"], expected_key);- // Verify all device endpoints from all users are included- let endpoints: Vec<&str> = ios["ios_device_endpoints"]- .as_array()- .expect("iosDeviceEndpoints should be an array")- .iter()- .map(|v| v.as_str().unwrap())+ // Verify all device endpoints from all users are included (now keyed by user)+ let endpoints_map = ios["ios_device_endpoints"]+ .as_object()+ .expect("ios_device_endpoints should be an object keyed by user ID");++ // Collect all endpoints across all users+ let all_endpoints: Vec<&str> = endpoints_map+ .values()+ .flat_map(|user| {+ user["endpoints"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap())+ }).collect();assert_eq!(- endpoints.len(),+ all_endpoints.len(),4,"Should include all 4 device endpoints across 3 users");assert!(- endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice-device"),+ all_endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice-device"),"Should include alice's device");assert!(- endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob-device"),+ all_endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob-device"),"Should include bob's first device");assert!(- endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob-device-2"),+ all_endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob-device-2"),"Should include bob's second device");assert!(- endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/charlie-device"),+ all_endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/charlie-device"),"Should include charlie's device");}@@ -771,7 +810,7 @@ async fn test_apns_collapse_key_stored_on_create() {DeviceEndpoint::Ios("arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice".to_string()),));let queue = Arc::new(MockQueue::new());- let service = NotificationIngressService::new(repo.clone(), queue);+ let service = NotificationIngressService::new(repo.clone(), queue, MockStateMachine);let request = SendNotificationRequestBuilder {notification_entity: EntityType::Document.with_entity_str("doc_1"),@@ -803,7 +842,7 @@ async fn test_no_apns_collapse_key_when_apns_not_enabled() {let repo = Arc::new(MockRepository::new());let queue = Arc::new(MockQueue::new());- let service = NotificationIngressService::new(repo.clone(), queue);+ let service = NotificationIngressService::new(repo.clone(), queue, MockStateMachine);let request = SendNotificationRequestBuilder {notification_entity: EntityType::Document.with_entity_str("doc_1"),@@ -852,8 +891,8 @@ impl NotificationSender for MockMobileSender {_endpoint_arn: &str,_notification: &crate::domain::models::apple::APNSPushNotification<T>,_attributes: &crate::domain::models::mobile::MessageAttributes,- ) -> Result<(), Report> {- Ok(())+ ) -> Result<String, Report> {+ Ok("mock-message-id".to_string())}async fn send_android_push_notification<T: Serialize + Send + Sync>(@@ -861,8 +900,8 @@ impl NotificationSender for MockMobileSender {_endpoint_arn: &str,_notification: &crate::domain::models::android::FCMMessage<T>,_attributes: &crate::domain::models::mobile::MessageAttributes,- ) -> Result<(), Report> {- Ok(())+ ) -> Result<String, Report> {+ Ok("mock-message-id".to_string())}}@@ -916,6 +955,51 @@ impl RateLimitPort for MockRateLimiter {}}+/// Mock egress state machine that forwards sends without recording message IDs or batching.+struct MockEgressStateMachine;++impl crate::domain::models::email_notification_digest::BulkDigestEgressStateMachine+ for MockEgressStateMachine+{+ async fn continue_machine<+ N: crate::domain::models::email_notification_digest::ports::NotificationSendChecker,+ >(+ &self,+ req: crate::domain::models::email_notification_digest::ResumeMachineBRequest<N>,+ ) -> (+ Vec<Result<N::Ok, N::Err>>,+ either::Either<+ crate::domain::models::email_notification_digest::DontSend,+ Result<crate::domain::models::email_notification_digest::BatchSend<()>, Report>,+ >,+ ) {+ let mut results = Vec::with_capacity(req.send_notifs.len());+ let mut any_succeeded = false;++ for send_notif in req.send_notifs {+ match send_notif.send_notification().await {+ Ok(ok) => {+ results.push(Ok(ok));+ any_succeeded = true;+ }+ Err(err) => {+ results.push(Err(err));+ }+ }+ }++ let decision = if any_succeeded {+ either::Either::Left(crate::domain::models::email_notification_digest::DontSend::new())+ } else {+ either::Either::Right(Ok(+ crate::domain::models::email_notification_digest::BatchSend::from_inner(()),+ ))+ };++ (results, decision)+ }+}+fn create_egress_service<R: RateLimitPort>(rate_limiter: R,) -> NotificationEgressService<@@ -925,6 +1009,7 @@ fn create_egress_service<R: RateLimitPort>(MockMobileSender,MockEmailSender,R,+ MockEgressStateMachine,> {NotificationEgressService::new(MockQueue::new(),@@ -933,6 +1018,7 @@ fn create_egress_service<R: RateLimitPort>(MockMobileSender,MockEmailSender,rate_limiter,+ MockEgressStateMachine,)}@@ -963,18 +1049,15 @@ async fn test_egress_rate_limit_exceeded() {RateLimitKey::from_str_hashed("test"),RateLimitConfig::new(10, Duration::from_secs(3600)),)),- content: Node {- notif: NotificationChannel::ConnGateway(- ConnGatewayNotification {- notif: create_mock_notif(TestNotification {- message: "Hello".to_string(),- }),- recipients: vec![recipient],- }- .testing_to_value(),- ),- on_failure: None,- },+ content: NotificationChannel::ConnGateway(+ ConnGatewayNotification {+ notif: create_mock_notif(TestNotification {+ message: "Hello".to_string(),+ }),+ recipients: vec![recipient],+ }+ .testing_to_value(),+ ),};let results = service.deliver_notification(message).await;@@ -1002,19 +1085,16 @@ async fn test_egress_rate_limit_allowed() {RateLimitKey::from_str_hashed("test"),RateLimitConfig::new(10, Duration::from_secs(3600)),)),- content: Node {- notif: NotificationChannel::ConnGateway(- ConnGatewayNotification {- notif: create_mock_notif(TestNotification {- message: "Hello".to_string(),- }),-- recipients: vec![recipient],- }- .testing_to_value(),- ),- on_failure: None,- },+ content: NotificationChannel::ConnGateway(+ ConnGatewayNotification {+ notif: create_mock_notif(TestNotification {+ message: "Hello".to_string(),+ }),++ recipients: vec![recipient],+ }+ .testing_to_value(),+ ),};let results = service.deliver_notification(message).await;@@ -1032,18 +1112,15 @@ async fn test_egress_no_rate_limit_configured() {let message = QueueMessage {message_type: "test_notification".to_string(),rate_limit: None, // No rate limit configured- content: Node {- notif: NotificationChannel::ConnGateway(- ConnGatewayNotification {- notif: create_mock_notif(TestNotification {- message: "Hello".to_string(),- }),- recipients: vec![recipient],- }- .testing_to_value(),- ),- on_failure: None,- },+ content: NotificationChannel::ConnGateway(+ ConnGatewayNotification {+ notif: create_mock_notif(TestNotification {+ message: "Hello".to_string(),+ }),+ recipients: vec![recipient],+ }+ .testing_to_value(),+ ),};let results = service.deliver_notification(message).await;@@ -1075,7 +1152,7 @@ async fn test_mark_seen_publishes_ios_clear_message() {),);let queue = Arc::new(MockQueue::new());- let service = NotificationIngressService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(repo.clone(), queue.clone());let notification_ids = [notif_id];service@@ -1100,7 +1177,7 @@ async fn test_mark_seen_publishes_ios_clear_message() {assert_eq!(msg["message_type"], "clear_push_notification");// Should be an Ios variant with background push- let ios = &msg["content"]["notif"]["Ios"];+ let ios = &msg["content"]["Ios"];assert!(ios.is_object(), "Expected Ios notification channel");// Verify silent background push payload@@ -1116,11 +1193,21 @@ async fn test_mark_seen_publishes_ios_clear_message() {// Verify identifier in custom dataassert_eq!(ios["notif"]["identifier"], "collapse_key_1");- // Verify device endpoint- let endpoints = ios["ios_device_endpoints"].as_array().unwrap();- assert_eq!(endpoints.len(), 1);+ // Verify device endpoint (now keyed by user)+ let endpoints_map = ios["ios_device_endpoints"].as_object().unwrap();+ let all_endpoints: Vec<&str> = endpoints_map+ .values()+ .flat_map(|user| {+ user["endpoints"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap())+ })+ .collect();+ assert_eq!(all_endpoints.len(), 1);assert_eq!(- endpoints[0],+ all_endpoints[0],"arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice");}@@ -1138,7 +1225,7 @@ async fn test_mark_seen_skips_push_when_no_collapse_key() {DeviceEndpoint::Ios("arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob".to_string()),));let queue = Arc::new(MockQueue::new());- let service = NotificationIngressService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(repo.clone(), queue.clone());let notification_ids = [notif_id];service@@ -1174,7 +1261,7 @@ async fn test_mark_seen_skips_push_when_no_device_endpoints() {// No device endpoints registered);let queue = Arc::new(MockQueue::new());- let service = NotificationIngressService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(repo.clone(), queue.clone());let notification_ids = [notif_id];service@@ -1216,7 +1303,7 @@ async fn test_mark_done_updates_db_and_clears_push() {),);let queue = Arc::new(MockQueue::new());- let service = NotificationIngressService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(repo.clone(), queue.clone());let notification_ids = [notif_id];service@@ -1261,7 +1348,7 @@ async fn test_mark_undone_updates_db_no_push_clear() {),);let queue = Arc::new(MockQueue::new());- let service = NotificationIngressService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(repo.clone(), queue.clone());let notification_ids = [notif_id];service@@ -1313,7 +1400,7 @@ impl NotificationSender for TrackingMobileSender {endpoint_arn: &str,_notification: &crate::domain::models::apple::APNSPushNotification<T>,_attributes: &crate::domain::models::mobile::MessageAttributes,- ) -> Result<(), Report> {+ ) -> Result<String, Report> {// Track that this endpoint was attemptedself.attempted_endpoints.lock()@@ -1325,7 +1412,7 @@ impl NotificationSender for TrackingMobileSender {rootcause::bail!("Simulated APNS failure for endpoint: {}", endpoint_arn);}- Ok(())+ Ok(format!("msg-id-{endpoint_arn}"))}async fn send_android_push_notification<T: Serialize + Send + Sync>(@@ -1333,8 +1420,8 @@ impl NotificationSender for TrackingMobileSender {_endpoint_arn: &str,_notification: &crate::domain::models::android::FCMMessage<T>,_attributes: &crate::domain::models::mobile::MessageAttributes,- ) -> Result<(), Report> {- Ok(())+ ) -> Result<String, Report> {+ Ok("mock-android-msg-id".to_string())}}@@ -1342,7 +1429,7 @@ impl NotificationSender for TrackingMobileSender {async fn test_egress_ios_attempts_all_endpoints_even_if_some_fail() {use crate::domain::models::apple::{APNSPushNotification, Aps};use crate::domain::models::mobile::{MessageAttributes, PushType};- use crate::domain::models::queue_message::APNSTargets;+ use crate::domain::models::queue_message::{APNSTargets, UserApnsEndpoints};let endpoint1 = "arn:aws:sns:us-east-1:111:endpoint/APNS/app/device1";let endpoint2 = "arn:aws:sns:us-east-1:111:endpoint/APNS/app/device2";@@ -1360,31 +1447,40 @@ async fn test_egress_ios_attempts_all_endpoints_even_if_some_fail() {mobile_sender.clone(),MockEmailSender,MockRateLimiter::allowing(),+ MockEgressStateMachine,);+ let user1 = test_user_id("[email protected]");+ let user2 = test_user_id("[email protected]");let message = QueueMessage {message_type: "test_notification".to_string(),rate_limit: None,- content: Node {- notif: NotificationChannel::Ios(Box::new(APNSTargets {- notif: APNSPushNotification {- aps: Aps::default(),- push_notification_data: json!({"message": "Hello"}),- },- attributes: MessageAttributes {- push_type: PushType::Alert,- collapse_key: "test_collapse".to_string(),- },- ios_device_endpoints: vec![- endpoint1.to_string(),- endpoint2.to_string(),- endpoint3.to_string(),- endpoint4.to_string(),- ],- bulk_digest_state_machine: None,- })),- on_failure: None,- },+ content: NotificationChannel::Ios(Box::new(APNSTargets {+ notif: APNSPushNotification {+ aps: Aps::default(),+ push_notification_data: json!({"message": "Hello"}),+ },+ attributes: MessageAttributes {+ push_type: PushType::Alert,+ collapse_key: "test_collapse".to_string(),+ },+ ios_device_endpoints: HashMap::from([+ (+ user1,+ UserApnsEndpoints {+ endpoints: vec![endpoint1.to_string(), endpoint2.to_string()],+ digest_state: None,+ },+ ),+ (+ user2,+ UserApnsEndpoints {+ endpoints: vec![endpoint3.to_string(), endpoint4.to_string()],+ digest_state: None,+ },+ ),+ ]),+ })),};let results = service.deliver_notification(message).await;@@ -1430,7 +1526,7 @@ impl NotificationSender for std::sync::Arc<TrackingMobileSender> {endpoint_arn: &str,notification: &crate::domain::models::apple::APNSPushNotification<T>,attributes: &crate::domain::models::mobile::MessageAttributes,- ) -> Result<(), Report> {+ ) -> Result<String, Report> {(**self).send_ios_push_notification(endpoint_arn, notification, attributes).await@@ -1441,7 +1537,7 @@ impl NotificationSender for std::sync::Arc<TrackingMobileSender> {endpoint_arn: &str,notification: &crate::domain::models::android::FCMMessage<T>,attributes: &crate::domain::models::mobile::MessageAttributes,- ) -> Result<(), Report> {+ ) -> Result<String, Report> {(**self).send_android_push_notification(endpoint_arn, notification, attributes).awaitdiff --git a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rsindex 89a9fe2d90..7aa0119183 100644--- a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs+++ b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs@@ -8,7 +8,7 @@ use crate::domain::{UserNotificationRow,request::{NotificationStatus, UpdateNotificationsRequest},},- service::NotificationIngress,+ service::NotificationReader,};use ai::tool::{AsyncTool, AsyncToolSet, RequestContext, ServiceContext, ToolCallError, ToolResult,@@ -22,12 +22,12 @@ use std::sync::Arc;use uuid::Uuid;/// Service context for notification AI tools-pub struct NotificationToolContext<T: NotificationIngress> {+pub struct NotificationToolContext<T> {/// The notification service instancepub service: Arc<T>,}-impl<T: NotificationIngress> Clone for NotificationToolContext<T> {+impl<T> Clone for NotificationToolContext<T> {fn clone(&self) -> Self {Self {service: self.service.clone(),@@ -35,7 +35,7 @@ impl<T: NotificationIngress> Clone for NotificationToolContext<T> {}}-impl<T: NotificationIngress> NotificationToolContext<T> {+impl<T: NotificationReader> NotificationToolContext<T> {/// Create a new notification tool contextpub fn new(service: T) -> Self {Self {@@ -47,7 +47,7 @@ impl<T: NotificationIngress> NotificationToolContext<T> {/// Create a notification toolset for AI agentspub fn notification_toolset<T>() -> AsyncToolSet<NotificationToolContext<T>>where- T: NotificationIngress,+ T: NotificationReader,{AsyncToolSet::new().add_tool::<ListNotifications, NotificationToolContext<T>>()@@ -124,7 +124,7 @@ pub struct ListNotificationsResponse {#[async_trait]impl<T> AsyncTool<NotificationToolContext<T>> for ListNotificationswhere- T: NotificationIngress,+ T: NotificationReader,{type Output = ListNotificationsResponse;@@ -191,7 +191,7 @@ pub struct MarkNotificationsSeen {#[async_trait]impl<T> AsyncTool<NotificationToolContext<T>> for MarkNotificationsSeenwhere- T: NotificationIngress,+ T: NotificationReader,{type Output = MarkNotificationsResponse;@@ -245,7 +245,7 @@ pub struct MarkNotificationsDone {#[async_trait]impl<T> AsyncTool<NotificationToolContext<T>> for MarkNotificationsDonewhere- T: NotificationIngress,+ T: NotificationReader,{type Output = MarkNotificationsResponse;diff --git a/rust/cloud-storage/notification/src/inbound/http.rs b/rust/cloud-storage/notification/src/inbound/http.rsindex 8dbc6e8c41..7405300363 100644--- a/rust/cloud-storage/notification/src/inbound/http.rs+++ b/rust/cloud-storage/notification/src/inbound/http.rs@@ -21,7 +21,7 @@ use crate::domain::{GetNotificationsByEventItemIdsRequest, NotificationStatus, UpdateNotificationsRequest,},},- service::NotificationIngress,+ service::NotificationReader,};/// Path parameter for a single event item ID.@@ -51,7 +51,7 @@ impl<S> Clone for NotificationRouterState<S> {}}-impl<S: NotificationIngress> NotificationRouterState<S> {+impl<S: NotificationReader> NotificationRouterState<S> {/// create a new instance of selfpub fn new(val: S) -> Self {NotificationRouterState {@@ -61,7 +61,7 @@ impl<S: NotificationIngress> NotificationRouterState<S> {}/// construct the router-pub fn router<S: NotificationIngress, T: Serialize + DeserializeOwned + Send + 'static>()+pub fn router<S: NotificationReader, T: Serialize + DeserializeOwned + Send + 'static>()-> Router<NotificationRouterState<S>> {Router::new().route("/bulk/seen", patch(bulk_mark_seen))@@ -87,7 +87,7 @@ pub struct GetAllUserNotificationsResponse<T> {/// List user notifications with generic metadata type `T`.pub async fn list_user_notifications<- S: NotificationIngress,+ S: NotificationReader,T: Serialize + DeserializeOwned + Send,>(State(service): State<NotificationRouterState<S>>,@@ -142,7 +142,7 @@ pub struct BulkGetByEventItemIdsRequest {))]pub async fn bulk_get_by_event_item_ids<- S: NotificationIngress,+ S: NotificationReader,T: Serialize + DeserializeOwned + Send,>(State(service): State<NotificationRouterState<S>>,@@ -197,7 +197,7 @@ pub struct NotificationBulkRequest {(status = 500, body = ErrorResponse),))]-pub async fn bulk_mark_seen<S: NotificationIngress>(+pub async fn bulk_mark_seen<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,macro_user: MacroUserExtractor,Json(req): Json<NotificationBulkRequest>,@@ -218,7 +218,7 @@ pub async fn bulk_mark_seen<S: NotificationIngress>((status = 500, body = ErrorResponse),))]-pub async fn bulk_mark_done<S: NotificationIngress>(+pub async fn bulk_mark_done<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,macro_user: MacroUserExtractor,Json(req): Json<NotificationBulkRequest>,@@ -239,7 +239,7 @@ pub async fn bulk_mark_done<S: NotificationIngress>((status = 500, body = ErrorResponse),))]-pub async fn bulk_mark_undone<S: NotificationIngress>(+pub async fn bulk_mark_undone<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,macro_user: MacroUserExtractor,Json(req): Json<NotificationBulkRequest>,@@ -247,7 +247,7 @@ pub async fn bulk_mark_undone<S: NotificationIngress>(bulk_update(&service, ¯o_user, &req, NotificationStatus::Done(false)).await}-async fn bulk_update<S: NotificationIngress>(+async fn bulk_update<S: NotificationReader>(service: &NotificationRouterState<S>,macro_user: &MacroUserExtractor,req: &NotificationBulkRequest,@@ -291,10 +291,7 @@ async fn bulk_update<S: NotificationIngress>((status = 500, body = ErrorResponse),))]-pub async fn get_by_event_item_id<- S: NotificationIngress,- T: Serialize + DeserializeOwned + Send,->(+pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + DeserializeOwned + Send>(State(service): State<NotificationRouterState<S>>,macro_user: MacroUserExtractor,Path(EventItemIdPath { event_item_id }): Path<EventItemIdPath>,@@ -343,7 +340,7 @@ pub async fn get_by_event_item_id<))]pub async fn get_notification_by_id<- S: NotificationIngress,+ S: NotificationReader,T: Serialize + DeserializeOwned + Send,>(State(service): State<NotificationRouterState<S>>,@@ -391,7 +388,7 @@ pub async fn get_notification_by_id<(status = 500, body = ErrorResponse),))]-pub async fn delete_notification<S: NotificationIngress>(+pub async fn delete_notification<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,macro_user: MacroUserExtractor,Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,@@ -426,7 +423,7 @@ pub async fn delete_notification<S: NotificationIngress>((status = 500, body = ErrorResponse),))]-pub async fn bulk_delete_notifications<S: NotificationIngress>(+pub async fn bulk_delete_notifications<S: NotificationReader>(State(service): State<NotificationRouterState<S>>,macro_user: MacroUserExtractor,Json(req): Json<NotificationBulkRequest>,diff --git a/rust/cloud-storage/notification/src/outbound.rs b/rust/cloud-storage/notification/src/outbound.rsindex e0b739e977..e984f4d1b2 100644--- a/rust/cloud-storage/notification/src/outbound.rs+++ b/rust/cloud-storage/notification/src/outbound.rs@@ -5,6 +5,7 @@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;diff --git a/rust/cloud-storage/notification/src/outbound/digest_batcher.rs b/rust/cloud-storage/notification/src/outbound/digest_batcher.rsindex d52b877c3e..0a76c41441 100644--- a/rust/cloud-storage/notification/src/outbound/digest_batcher.rs+++ b/rust/cloud-storage/notification/src/outbound/digest_batcher.rs@@ -3,10 +3,10 @@#[cfg(all(test, feature = "redis-tests"))]mod test;+use crate::domain::models::UserNotificationRow;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;@@ -33,32 +33,62 @@ use std::time::Duration;/// This ensures no notifications are lost even if new ones arrive during processing.pub struct RedisDigestBatcher {conn: MultiplexedConnection,+ key_prefix: String,}impl RedisDigestBatcher {/// Create a new [RedisDigestBatcher] with the given Redis connection.pub fn new(conn: MultiplexedConnection) -> Self {- Self { conn }+ Self {+ conn,+ key_prefix: String::new(),+ }}- fn digest_key(user_id: &str) -> String {- format!("digest:{user_id}")+ /// Create a new [RedisDigestBatcher] with a key prefix for namespace isolation.+ #[cfg(test)]+ pub(crate) fn with_key_prefix(conn: MultiplexedConnection, prefix: impl Into<String>) -> Self {+ Self {+ conn,+ key_prefix: prefix.into(),+ }+ }++ fn digest_key(&self, user_id: &str) -> String {+ if self.key_prefix.is_empty() {+ format!("digest:{user_id}")+ } else {+ format!("{}:digest:{user_id}", self.key_prefix)+ }}- fn processing_key(user_id: &str) -> String {- format!("digest_processing:{user_id}")+ fn processing_key(&self, user_id: &str) -> String {+ if self.key_prefix.is_empty() {+ format!("digest_processing:{user_id}")+ } else {+ format!("{}:digest_processing:{user_id}", self.key_prefix)+ }+ }++ fn pending_users_key(&self) -> String {+ if self.key_prefix.is_empty() {+ "digest_pending_users".to_string()+ } else {+ format!("{}:digest_pending_users", self.key_prefix)+ }}}impl DigestBatcher for RedisDigestBatcher {async fn add_to_digest(&self,- notification: &UserNotificationRow<TaggedContent<serde_json::Value>>,+ notification: &UserNotificationRow<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 digest_key = self.digest_key(user_id_str);+ let pending_users_key = self.pending_users_key();let serialized = serde_json::to_string(notification)?;@@ -69,7 +99,7 @@ impl DigestBatcher for RedisDigestBatcher {// subsequent notifications don't push back the send timelet send_at = Utc::now().timestamp() + send_after.as_secs() as i64;conn.zadd_options::<_, _, _, ()>(- "digest_pending_users",+ &pending_users_key,user_id_str,send_at,&SortedSetAddOptions::add_only(),@@ -82,10 +112,11 @@ impl DigestBatcher for RedisDigestBatcher {async fn claim_ready_digest(&self) -> Result<ClaimResult, Report> {let mut conn = self.conn.clone();let now = Utc::now().timestamp();+ let pending_users_key = self.pending_users_key();// 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 result: Vec<(String, f64)> = conn.zpopmin(&pending_users_key, 1).await?;let Some((user_id_str, score)) = result.into_iter().next() else {return Ok(ClaimResult::Empty);@@ -94,7 +125,7 @@ impl DigestBatcher for RedisDigestBatcher {// Check if this digest is actually ready to sendif score > now as f64 {// Not ready yet, put it back- conn.zadd::<_, _, _, ()>("digest_pending_users", &user_id_str, score)+ conn.zadd::<_, _, _, ()>(&pending_users_key, &user_id_str, score).await?;// Return how long to wait until this digest is ready@@ -102,8 +133,8 @@ impl DigestBatcher for RedisDigestBatcher {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);+ 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}diff --git a/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs b/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rsindex 19f4c01988..788376de46 100644--- a/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs+++ b/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs@@ -1,5 +1,5 @@use super::*;-use crate::domain::models::{Notification, RateLimitConfig, RateLimitKey};+use crate::domain::models::{Notification, RateLimitConfig, RateLimitKey, TaggedContent};use model_entity::EntityType;use redis::AsyncCommands;use serde::{Deserialize, Serialize};@@ -31,9 +31,15 @@ async fn get_redis_connection() -> MultiplexedConnection {.expect("Failed to connect to Redis")}-async fn cleanup_redis(conn: &mut MultiplexedConnection, prefix: &str) {+/// Each test gets a unique key prefix so tests can run in parallel across+/// nextest processes without interfering with each other's Redis state.+fn test_prefix(name: &str) -> String {+ format!("test_{name}_{}", Uuid::new_v4().as_simple())+}++async fn cleanup_prefix(conn: &mut MultiplexedConnection, prefix: &str) {let keys: Vec<String> = redis::cmd("KEYS")- .arg(format!("{}*", prefix))+ .arg(format!("{prefix}:*")).query_async(conn).await.unwrap_or_default();@@ -41,10 +47,6 @@ async fn cleanup_redis(conn: &mut MultiplexedConnection, prefix: &str) {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> {@@ -54,7 +56,7 @@ fn test_user(suffix: &str) -> MacroUserIdStr<'static> {fn create_test_notification(user_id: MacroUserIdStr<'static>,message: &str,-) -> UserNotificationRow<TaggedContent<serde_json::Value>> {+) -> UserNotificationRow<serde_json::Value> {let notification = TestNotification {message: message.to_string(),};@@ -70,17 +72,17 @@ fn create_test_notification(viewed_at: None,updated_at: Some(Utc::now()),deleted_at: None,- notification_metadata: TaggedContent::new(notification).serialize(),+ notification_metadata: serde_json::to_value(TaggedContent::new(notification))+ .expect("serialize cannot fail"),sender_id: None,}}-// #[tokio::test]+#[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 prefix = test_prefix("add_creates_entry");+ let batcher = RedisDigestBatcher::with_key_prefix(conn.clone(), &prefix);let user = test_user("add_creates_entry");let notification = create_test_notification(user.clone(), "test message");@@ -90,26 +92,23 @@ async fn test_add_to_digest_creates_pending_entry() {.expect("Failed to add to digest");// Verify the notification was added to the list- let digest_key = format!("digest:{}", user.as_ref());+ let digest_key = format!("{prefix}: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();+ let pending_key = format!("{prefix}:digest_pending_users");+ let score: Option<f64> = conn.zscore(&pending_key, user.as_ref()).await.unwrap();assert!(score.is_some());- cleanup_redis(&mut conn, "digest:").await;+ cleanup_prefix(&mut conn, &prefix).await;}-// #[tokio::test]+#[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 prefix = test_prefix("multiple_same_user");+ let batcher = RedisDigestBatcher::with_key_prefix(conn.clone(), &prefix);let user = test_user("multiple_same_user");let notif1 = create_test_notification(user.clone(), "message 1");@@ -130,36 +129,33 @@ async fn test_add_multiple_notifications_same_user() {.unwrap();// Verify all notifications were added- let digest_key = format!("digest:{}", user.as_ref());+ let digest_key = format!("{prefix}: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();+ let pending_key = format!("{prefix}:digest_pending_users");+ let count: usize = conn.zcard(&pending_key).await.unwrap();assert_eq!(count, 1);- cleanup_redis(&mut conn, "digest:").await;+ cleanup_prefix(&mut conn, &prefix).await;}-// #[tokio::test]+#[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 conn = get_redis_connection().await;+ let prefix = test_prefix("empty_when_none");+ let batcher = RedisDigestBatcher::with_key_prefix(conn.clone(), &prefix);let result = batcher.claim_ready_digest().await.unwrap();assert!(matches!(result, ClaimResult::Empty));-- cleanup_redis(&mut conn, "digest:").await;}-// #[tokio::test]+#[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 prefix = test_prefix("wait_not_ready");+ let batcher = RedisDigestBatcher::with_key_prefix(conn.clone(), &prefix);let user = test_user("not_ready");let notification = create_test_notification(user.clone(), "test");@@ -179,15 +175,14 @@ async fn test_claim_ready_digest_returns_wait_when_not_ready() {other => panic!("Expected ClaimResult::Wait, got {:?}", other),}- cleanup_redis(&mut conn, "digest:").await;+ cleanup_prefix(&mut conn, &prefix).await;}-// #[tokio::test]+#[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 prefix = test_prefix("batch_when_ready");+ let batcher = RedisDigestBatcher::with_key_prefix(conn.clone(), &prefix);let user = test_user("ready_batch");let notification = create_test_notification(user.clone(), "ready message");@@ -211,26 +206,23 @@ async fn test_claim_ready_digest_returns_batch_when_ready() {}// Verify the digest was cleaned up- let digest_key = format!("digest:{}", user.as_ref());+ let digest_key = format!("{prefix}: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();+ let pending_key = format!("{prefix}:digest_pending_users");+ let score: Option<f64> = conn.zscore(&pending_key, user.as_ref()).await.unwrap();assert!(score.is_none());- cleanup_redis(&mut conn, "digest:").await;+ cleanup_prefix(&mut conn, &prefix).await;}-// #[tokio::test]+#[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 prefix = test_prefix("during_processing");+ let batcher = RedisDigestBatcher::with_key_prefix(conn.clone(), &prefix);let user = test_user("during_processing");// Add first notification (immediately ready)@@ -264,15 +256,14 @@ async fn test_new_notifications_during_processing_not_lost() {other => panic!("Expected second batch to be ready, got {:?}", other),}- cleanup_redis(&mut conn, "digest:").await;+ cleanup_prefix(&mut conn, &prefix).await;}-// #[tokio::test]+#[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 prefix = test_prefix("multi_user");+ let batcher = RedisDigestBatcher::with_key_prefix(conn.clone(), &prefix);let user1 = test_user("multi_user_1");let user2 = test_user("multi_user_2");@@ -303,5 +294,5 @@ async fn test_multiple_users_independent() {let result3 = batcher.claim_ready_digest().await.unwrap();assert!(matches!(result3, ClaimResult::Empty));- cleanup_redis(&mut conn, "digest:").await;+ cleanup_prefix(&mut conn, &prefix).await;}diff --git a/rust/cloud-storage/notification/src/outbound/last_online_checker.rs b/rust/cloud-storage/notification/src/outbound/last_online_checker.rsnew file mode 100644index 0000000000..ebdff5e9d5--- /dev/null+++ b/rust/cloud-storage/notification/src/outbound/last_online_checker.rs@@ -0,0 +1,34 @@+//! Implementation of [LastOnlineChecker] that delegates to [LastOnlineService].++use crate::domain::models::email_notification_digest::ports::LastOnlineChecker;+use last_online_tracker::domain::{ports::LastOnlineRepo, services::LastOnlineService};+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use std::time::Duration;++/// Adapter that implements [LastOnlineChecker] by delegating to [LastOnlineService].+///+/// When a user has never been tracked (i.e., `time_since_last_online` returns `None`),+/// this adapter returns [Duration::MAX] to indicate the user has been offline "forever",+/// which ensures they qualify for batch email digest delivery.+pub struct LastOnlineCheckerImpl<T, R> {+ service: LastOnlineService<T, R>,+}++impl<T, R> LastOnlineCheckerImpl<T, R> {+ /// Create a new [LastOnlineCheckerImpl] wrapping the given [LastOnlineService].+ pub fn new(service: LastOnlineService<T, R>) -> Self {+ Self { service }+ }+}++impl<T, R> LastOnlineChecker for LastOnlineCheckerImpl<T, R>+where+ T: last_online_tracker::domain::ports::SystemTime,+ R: LastOnlineRepo,+{+ async fn last_online_checker<'a>(&self, user: MacroUserIdStr<'a>) -> Result<Duration, Report> {+ let duration = self.service.time_since_last_online(user).await?;+ Ok(duration.unwrap_or(Duration::MAX))+ }+}diff --git a/rust/cloud-storage/notification/src/outbound/message_receipt_repository.rs b/rust/cloud-storage/notification/src/outbound/message_receipt_repository.rsindex 0962e5448b..0c71d907a5 100644--- a/rust/cloud-storage/notification/src/outbound/message_receipt_repository.rs+++ b/rust/cloud-storage/notification/src/outbound/message_receipt_repository.rs@@ -30,6 +30,7 @@ impl DbMessageReceiptRepository {}impl MessageReceiptRepo for DbMessageReceiptRepository {+ #[tracing::instrument(err, skip(self))]async fn record_message_id(&self,message_id: MessageId,diff --git a/rust/cloud-storage/notification/src/outbound/mobile.rs b/rust/cloud-storage/notification/src/outbound/mobile.rsindex 64274ae178..8f17ed83fc 100644--- a/rust/cloud-storage/notification/src/outbound/mobile.rs+++ b/rust/cloud-storage/notification/src/outbound/mobile.rs@@ -34,12 +34,14 @@ impl<P> MobilePushAdapter<P> {/// This allows the adapter to work with different SNS client implementations.pub trait MobilePushOps {/// Send a push notification to the specified endpoint ARN.+ ///+ /// Returns the SNS message ID on success.fn push_notification<T: Serialize + Send + Sync>(&self,endpoint_arn: &str,message: &SnsTarget<'_, T>,attributes: HashMap<String, MessageAttributeValue>,- ) -> impl std::future::Future<Output = Result<(), Report>> + Send;+ ) -> impl std::future::Future<Output = Result<String, Report>> + Send;}impl MobilePushOps for aws_sdk_sns::Client {@@ -48,10 +50,11 @@ impl MobilePushOps for aws_sdk_sns::Client {endpoint_arn: &str,message: &SnsTarget<'_, T>,attributes: HashMap<String, MessageAttributeValue>,- ) -> Result<(), Report> {+ ) -> Result<String, Report> {let payload = message.as_json()?;- self.publish()+ let output = self+ .publish().target_arn(endpoint_arn).message_structure("json").message(payload)@@ -59,7 +62,7 @@ impl MobilePushOps for aws_sdk_sns::Client {.send().await?;- Ok(())+ Ok(output.message_id.unwrap_or_default())}}@@ -69,7 +72,7 @@ impl<P: MobilePushOps + Send + Sync + 'static> NotificationSender for MobilePushendpoint_arn: &str,notification: &APNSPushNotification<T>,attributes: &MessageAttributes,- ) -> Result<(), Report> {+ ) -> Result<String, Report> {let target = SnsTarget::Ios(notification);let sns_attributes = build_sns_attributes(&self.apns_bundle_id, attributes);self.push_service@@ -82,7 +85,7 @@ impl<P: MobilePushOps + Send + Sync + 'static> NotificationSender for MobilePushendpoint_arn: &str,notification: &FCMMessage<T>,attributes: &MessageAttributes,- ) -> Result<(), Report> {+ ) -> Result<String, Report> {let target = SnsTarget::Android(notification);let sns_attributes = build_sns_attributes(&self.apns_bundle_id, attributes);self.push_servicediff --git a/rust/cloud-storage/notification/src/outbound/queue.rs b/rust/cloud-storage/notification/src/outbound/queue.rsindex fa0e3f1d83..fddc1d0a33 100644--- a/rust/cloud-storage/notification/src/outbound/queue.rs+++ b/rust/cloud-storage/notification/src/outbound/queue.rs@@ -22,12 +22,12 @@ impl SqsNotificationQueue {}impl NotificationQueue for SqsNotificationQueue {- async fn publish<T: Serialize + Send + Sync, U: Serialize + Send + Sync>(+ async fn publish<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(&self,- messages: &[QueueMessage<'_, T, U>],+ messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,) -> Result<(), Report> {for message in messages {- let body = serde_json::to_string(message)?;+ let body = serde_json::to_string(&message)?;self.client.send_message().queue_url(&self.queue_url)@@ -100,15 +100,15 @@ impl FileQueue {}impl NotificationQueue for FileQueue {- async fn publish<T: Serialize + Send + Sync, U: Serialize + Send + Sync>(+ async fn publish<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(&self,- messages: &[QueueMessage<'_, T, U>],+ messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,) -> Result<(), Report> {for message in messages {let id = uuid::Uuid::new_v4();let filename = format!("{}.json", id);let path = self.dir.join(&filename);- let content = serde_json::to_string_pretty(message)?;+ let content = serde_json::to_string_pretty(&message)?;tokio::fs::write(&path, content).await?;}Ok(())diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rsindex b24f0eeafe..7fe35fb6f0 100644--- a/rust/cloud-storage/notification/src/outbound/repository.rs+++ b/rust/cloud-storage/notification/src/outbound/repository.rs@@ -17,6 +17,7 @@ use serde::de::DeserializeOwned;use sqlx::PgPool;use std::collections::{HashMap, HashSet};use std::str::FromStr;+use std::sync::Arc;use uuid::Uuid;/// Local representation of the `notification_device_type_option` Postgres enum@@ -76,11 +77,11 @@ pub trait NotificationDbOps: Send + Sync + 'static {/// Returns `Some(notification_id)` if created, `None` if it already exists (idempotent).fn create_notification<'a, T: Notification + Send + Sync>(&self,- request: &SendNotificationRequestBuilder<'a, T>,+ request: SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,service_name: &str,apns_collapse_key: Option<&str>,- ) -> impl std::future::Future<Output = Result<Option<Uuid>, Report>> + Send;+ ) -> impl std::future::Future<Output = Result<Option<Vec<UserNotificationRow<Arc<T>>>>, Report>> + Send;/// Update the sent status for recipients who received the notification.fn update_sent_status<'a>(@@ -252,13 +253,13 @@ impl NotificationDbOps for PgPool {async fn create_notification<'a, T: Notification + Send + Sync>(&self,- request: &SendNotificationRequestBuilder<'a, T>,+ request: SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,service_name: &str,apns_collapse_key: Option<&str>,- ) -> Result<Option<Uuid>, Report> {+ ) -> Result<Option<Vec<UserNotificationRow<Arc<T>>>>, Report> {let entity_type: &str = request.notification_entity.entity_type.into();- let metadata = serde_json::to_value(&request.notification).ok();+ let metadata = serde_json::to_value(&request.notification)?;let mut tx = self.begin().await?;@@ -276,7 +277,7 @@ impl NotificationDbOps for PgPool {request.notification_entity.entity_id.as_ref(),entity_type,service_name,- metadata as Option<serde_json::Value>,+ metadata as serde_json::Value,sender_id,apns_collapse_key)@@ -309,7 +310,31 @@ impl NotificationDbOps for PgPool {tx.commit().await?;- Ok(Some(notification_id))+ let entity = request.notification_entity.clone().into_owned();+ let sender_id = request.sender_id.as_ref().map(|id| id.clone().into_owned());++ let n = Arc::new(request.notification);++ let rows = request+ .recipient_ids+ .iter()+ .map(|recipient| UserNotificationRow {+ owner_id: recipient.clone().into_owned(),+ notification_id,+ notification_event_type: T::TYPE_NAME.to_string(),+ entity: entity.clone(),+ sent: false,+ done: false,+ created_at: None,+ viewed_at: None,+ updated_at: None,+ deleted_at: None,+ notification_metadata: n.clone(),+ sender_id: sender_id.clone(),+ })+ .collect();++ Ok(Some(rows))}async fn update_sent_status<'a>(@@ -706,11 +731,11 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificatiasync fn create_notification<'a, T: Notification + Send + Sync>(&self,- request: &SendNotificationRequestBuilder<'a, T>,+ request: SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,service_name: &str,apns_collapse_key: Option<&str>,- ) -> Result<Option<Uuid>, Report> {+ ) -> Result<Option<Vec<UserNotificationRow<Arc<T>>>>, Report> {self.db.create_notification(request, notification_id, service_name, apns_collapse_key).awaitdiff --git a/rust/cloud-storage/notification/src/outbound/repository/test.rs b/rust/cloud-storage/notification/src/outbound/repository/test.rsindex c92e4dd0e0..2fc6e6cb8d 100644--- a/rust/cloud-storage/notification/src/outbound/repository/test.rs+++ b/rust/cloud-storage/notification/src/outbound/repository/test.rs@@ -92,7 +92,10 @@ async fn test_get_unsubscribed_users_different_item(pool: Pool<Postgres>) {async fn test_get_device_endpoints(pool: Pool<Postgres>) {let user = test_user("[email protected]");- let result = pool.get_device_endpoints(&[user.clone()]).await.unwrap();+ let result = pool+ .get_device_endpoints(std::slice::from_ref(&user))+ .await+ .unwrap();let endpoints = result.get(&user).expect("user should have endpoints");assert_eq!(endpoints.len(), 2);@@ -132,11 +135,11 @@ async fn test_create_notification(pool: Pool<Postgres>) {};let result = pool- .create_notification(&request, notification_id, "test_service", None)+ .create_notification(request, notification_id, "test_service", None).await.unwrap();- assert_eq!(result, Some(notification_id));+ assert!(result.is_some());// Verify notification was insertedlet row = sqlx::query!("SELECT id FROM notification WHERE id = $1", notification_id)@@ -328,18 +331,27 @@ async fn test_create_notification_returns_none_on_conflict(pool: Pool<Postgres>)};// First creation should succeed+ let request2 = SendNotificationRequestBuilder {+ notification_entity: EntityType::Document.with_entity_str("doc-1"),+ notification: TestNotification {+ message: "hello".to_string(),+ },+ sender_id: None,+ recipient_ids: std::collections::HashSet::from([recipient.clone()]),+ };+let result = pool- .create_notification(&request, notification_id, "test_service", None)+ .create_notification(request, notification_id, "test_service", None).await.unwrap();- assert_eq!(result, Some(notification_id));+ assert!(result.is_some());// Second creation with same ID should return Nonelet result = pool- .create_notification(&request, notification_id, "test_service", None)+ .create_notification(request2, notification_id, "test_service", None).await.unwrap();- assert_eq!(result, None);+ assert!(result.is_none());// Verify only one notification existslet count: i64 = sqlx::query_scalar!(diff --git a/rust/cloud-storage/notification_service/src/api/mod.rs b/rust/cloud-storage/notification_service/src/api/mod.rsindex 93f22a51e6..442d1ad53d 100644--- a/rust/cloud-storage/notification_service/src/api/mod.rs+++ b/rust/cloud-storage/notification_service/src/api/mod.rs@@ -21,7 +21,7 @@ pub(crate) mod user_notification;pub(crate) mod swagger;-pub async fn setup_and_serve<S: ::notification::domain::service::NotificationIngress>(+pub async fn setup_and_serve<S: ::notification::domain::service::NotificationReader>(state: ApiContext,ingress_state: NotificationRouterState<S>,) -> anyhow::Result<()> {@@ -58,7 +58,7 @@ pub async fn setup_and_serve<S: ::notification::domain::service::NotificationIng.context("error starting service")}-fn api_router<S: ::notification::domain::service::NotificationIngress>(+fn api_router<S: ::notification::domain::service::NotificationReader>(state: ApiContext,ingress_state: NotificationRouterState<S>,) -> Router<ApiContext> {diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rsindex d5c0f3df03..214bbc2c63 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs@@ -100,7 +100,7 @@ pub fn to_typed_row(/// Instantiates the notification crate's generic router, then overwrites the/// GET `/` route with a wrapper that deserializes each row into [`NotifEvent`].pub fn router<- S: ::notification::domain::service::NotificationIngress,+ S: ::notification::domain::service::NotificationReader,O: Clone + Send + Sync + 'static,>(state: ::notification::inbound::http::NotificationRouterState<S>,@@ -146,7 +146,7 @@ pub fn router<(status = 500, body = ErrorResponse),))]-async fn list_typed_notifications<S: ::notification::domain::service::NotificationIngress>(+async fn list_typed_notifications<S: ::notification::domain::service::NotificationReader>(state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,macro_user: model_user::axum_extractor::MacroUserExtractor,query: axum::extract::Query<::notification::inbound::http::Params>,@@ -202,7 +202,7 @@ async fn list_typed_notifications<S: ::notification::domain::service::Notificati))]async fn bulk_get_typed_notifications_by_event_item_ids<- S: ::notification::domain::service::NotificationIngress,+ S: ::notification::domain::service::NotificationReader,>(state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,macro_user: model_user::axum_extractor::MacroUserExtractor,@@ -256,7 +256,7 @@ async fn bulk_get_typed_notifications_by_event_item_ids<(status = 500, body = ErrorResponse),))]-async fn get_typed_by_event_item_id<S: ::notification::domain::service::NotificationIngress>(+async fn get_typed_by_event_item_id<S: ::notification::domain::service::NotificationReader>(state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,macro_user: model_user::axum_extractor::MacroUserExtractor,path: axum::extract::Path<::notification::inbound::http::EventItemIdPath>,@@ -308,7 +308,7 @@ async fn get_typed_by_event_item_id<S: ::notification::domain::service::Notifica(status = 500, body = ErrorResponse),))]-async fn get_typed_notification_by_id<S: ::notification::domain::service::NotificationIngress>(+async fn get_typed_notification_by_id<S: ::notification::domain::service::NotificationReader>(state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,macro_user: model_user::axum_extractor::MacroUserExtractor,path: axum::extract::Path<::notification::inbound::http::NotificationIdPath>,diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rsindex 32c59649a3..7249f2acb2 100644--- a/rust/cloud-storage/notification_service/src/main.rs+++ b/rust/cloud-storage/notification_service/src/main.rs@@ -100,12 +100,11 @@ pub async fn main() -> anyhow::Result<()> {aws_sdk_sqs::Client::new(&aws_config),vars.notification_queue.as_ref().to_string(),);- let ingress_service = ::notification::domain::service::NotificationIngressService::new(+ let reader_service = ::notification::domain::service::NotificationReaderService::new(notification_repository,notification_queue.clone(),);- let ingress_state =- ::notification::inbound::http::NotificationRouterState::new(ingress_service);+ let ingress_state = ::notification::inbound::http::NotificationRouterState::new(reader_service);// Set up egress worker for delivering notifications from the queuelet egress_repository =@@ -126,8 +125,24 @@ pub async fn main() -> anyhow::Result<()> {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+ .context("failed to get multiplexed redis connection for egress state machine")?;let rate_limit_adapter = RedisRateLimitAdapter::new(redis_client);+ let egress_state_machine =+ ::notification::domain::models::email_notification_digest::StateMachineDriverB {+ message_receipt_repo:+ ::notification::outbound::message_receipt_repository::DbMessageReceiptRepository::new(+ db.clone(),+ ),+ digest_batcher: ::notification::outbound::digest_batcher::RedisDigestBatcher::new(+ redis_multiplexed_conn,+ ),+ digest_window: std::time::Duration::from_secs(30 * 60),+ };+let egress_service = NotificationEgressService::new(notification_queue,egress_repository,@@ -135,6 +150,7 @@ pub async fn main() -> anyhow::Result<()> {mobile_adapter,email_adapter,rate_limit_adapter,+ egress_state_machine,);let worker = NotificationWorker::new(egress_service);diff --git a/rust/cloud-storage/properties_service/Cargo.toml b/rust/cloud-storage/properties_service/Cargo.tomlindex e2f5a19ff6..3890a982c4 100644--- a/rust/cloud-storage/properties_service/Cargo.toml+++ b/rust/cloud-storage/properties_service/Cargo.toml@@ -29,6 +29,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"auth","cloud_storage",] }+last_online_tracker = { path = "../last_online_tracker" }notification = { path = "../notification" }aws-sdk-sqs = { workspace = true }macro_uuid = { path = "../macro_uuid" }diff --git a/rust/cloud-storage/properties_service/src/api/context.rs b/rust/cloud-storage/properties_service/src/api/context.rsindex df1a4b34f1..2cd9db8fb7 100644--- a/rust/cloud-storage/properties_service/src/api/context.rs+++ b/rust/cloud-storage/properties_service/src/api/context.rs@@ -1,15 +1,32 @@use axum::extract::FromRef;+use notification::domain::models::email_notification_digest::StateMachineDriverA;use notification::domain::service::NotificationIngressService;-use notification::outbound::queue::SqsNotificationQueue;-use notification::outbound::repository::DbNotificationRepository;+use notification::outbound::{+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,+};use sqlx::PgPool;use std::sync::Arc;use properties::PropertiesServiceImpl;+type StateMachine = StateMachineDriverA<+ DbUserExistenceChecker,+ PushNotificationCheckerImpl<DbNotificationRepository<PgPool>>,+ LastOnlineCheckerImpl<+ last_online_tracker::outbound::time::DefaultTime,+ last_online_tracker::outbound::redis::RedisLastOnlineRepo,+ >,+ RedisDigestBatcher,+>;+/// The concrete notification ingress service type.-type NotificationIngressType =- NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>;+type NotificationIngressType = NotificationIngressService<+ DbNotificationRepository<PgPool>,+ SqsNotificationQueue,+ StateMachine,+>;/// Type alias for the properties service implementation used throughout the service.pub type PropertiesService = PropertiesServiceImpl<diff --git a/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zipdeleted file mode 100644index 03345db145..0000000000Binary files a/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zipdeleted file mode 100644index 83b1a14112..0000000000Binary files a/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip b/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zipdeleted file mode 100644index a1bf4cfb97..0000000000Binary files a/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zip b/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zipdeleted file mode 100644index a44d65f3b9..0000000000Binary files a/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zipdeleted file mode 100644index cbab506c8d..0000000000Binary files a/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zipdeleted file mode 100644index eb5186f513..0000000000Binary files a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zipdeleted file mode 100644index fd09d4e79f..0000000000Binary files a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/email_sfs_delete_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_sfs_delete_handler/bootstrap.zipdeleted file mode 100644index d6835a8f31..0000000000Binary files a/rust/cloud-storage/target/lambda/email_sfs_delete_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zipdeleted file mode 100644index b309e9cf41..0000000000Binary files a/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zipdeleted file mode 100644index 674e5a70c6..0000000000Binary files a/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zipdeleted file mode 100644index 2f061def13..0000000000Binary files a/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zipdeleted file mode 100644index 9d06895c91..0000000000Binary files a/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zipdeleted file mode 100644index f4b54ae261..0000000000Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zipdeleted file mode 100644index cdb584e0cd..0000000000Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zipdeleted file mode 100644index 48c18ed74b..0000000000Binary files a/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zip and /dev/null differdiff --git a/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zipdeleted file mode 100644index 8bcbc6790f..0000000000Binary files a/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zip and /dev/null differdiff --git a/rust/rust-toolchain.toml b/rust/rust-toolchain.tomlindex 8cf9c1875a..cb0a8a14ef 100644--- a/rust/rust-toolchain.toml+++ b/rust/rust-toolchain.toml@@ -1,3 +1,3 @@[toolchain]-channel = "1.90"-components = ["rustfmt", "clippy"]+channel = "1.93.1"+components = ["clippy", "rustfmt"]