Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(notif): enable email digest (#1921)

Sean Ayecdf689ef35c0
diff --git a/infra/packages/shared/src/macro_notify.ts b/infra/packages/shared/src/macro_notify.ts
index 615940c88d..5be9b0321b 100644
--- a/infra/packages/shared/src/macro_notify.ts
+++ b/infra/packages/shared/src/macro_notify.ts
@@ -2,8 +2,8 @@ import * as pulumi from '@pulumi/pulumi';
import { stack } from '../../shared';
export function getMacroNotify(): {
- notificationQueueName: pulumi.Output<string>;
- notificationQueueArn: pulumi.Output<string>;
+ notificationIngressQueueName: pulumi.Output<string>;
+ notificationIngressQueueArn: pulumi.Output<string>;
} {
const notificationServiceStack = new pulumi.StackReference(
'notification-service-stack',
@@ -12,16 +12,18 @@ export function getMacroNotify(): {
}
);
- const notificationQueueArn: pulumi.Output<string> = notificationServiceStack
- .getOutput('notificationQueueArn')
- .apply((arn) => arn as string);
+ const notificationIngressQueueArn: pulumi.Output<string> =
+ notificationServiceStack
+ .getOutput('notificationIngressQueueArn')
+ .apply((arn) => arn as string);
- const notificationQueueName: pulumi.Output<string> = notificationServiceStack
- .getOutput('notificationQueueName')
- .apply((arn) => arn as string);
+ const notificationIngressQueueName: pulumi.Output<string> =
+ notificationServiceStack
+ .getOutput('notificationIngressQueueName')
+ .apply((name) => name as string);
return {
- notificationQueueName,
- notificationQueueArn,
+ notificationIngressQueueName,
+ notificationIngressQueueArn,
};
}
diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.ts
index 9e12a15945..18239587a9 100644
--- a/infra/stacks/authentication-service/index.ts
+++ b/infra/stacks/authentication-service/index.ts
@@ -170,7 +170,8 @@ const fusionAuthClusterName: pulumi.Output<string> = fusionAuthStack
.getOutput('fusionAuthClusterName')
.apply((fusionAuthClusterName) => fusionAuthClusterName as string);
-const { notificationQueueName, notificationQueueArn } = getMacroNotify();
+const { notificationIngressQueueName, notificationIngressQueueArn } =
+ getMacroNotify();
const { searchEventQueueName, searchEventQueueArn } = getSearchEventQueue();
@@ -187,7 +188,7 @@ const service = new AuthenticationService('authentication-service', {
isPrivate: false,
healthCheckPath: '/health',
tags,
- queueArns: [notificationQueueArn, searchEventQueueArn],
+ queueArns: [notificationIngressQueueArn, searchEventQueueArn],
containerEnvVars: [
{ name: 'ENVIRONMENT', value: stack },
{
@@ -265,7 +266,7 @@ const service = new AuthenticationService('authentication-service', {
},
{
name: 'NOTIFICATION_QUEUE',
- value: pulumi.interpolate`${notificationQueueName}`,
+ value: pulumi.interpolate`${notificationIngressQueueName}`,
},
{
name: 'SEARCH_EVENT_QUEUE',
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index 3d3560fb58..10ad65bd7d 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -175,7 +175,8 @@ const contactsQueueArn: pulumi.Output<string> = contactsServiceStack
.getOutput('contactsQueueArn')
.apply((arn) => arn as string);
-const { notificationQueueName, notificationQueueArn } = getMacroNotify();
+const { notificationIngressQueueName, notificationIngressQueueArn } =
+ getMacroNotify();
// To re-use this secret name after a destroy, you will need to delete the secret without recovery to prevent conflict:
// aws secretsmanager delete-secret --secret-id ${CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME} --force-delete-without-recovery
@@ -266,7 +267,7 @@ const cloudStorageService = new CloudStorageService(
queueArns: [
searchEventQueueArn,
deleteDocumentHandler.queue.arn,
- notificationQueueArn,
+ notificationIngressQueueArn,
contactsQueueArn,
],
vpc: coparse_api_vpc,
@@ -370,7 +371,7 @@ const cloudStorageService = new CloudStorageService(
},
{
name: 'NOTIFICATION_QUEUE',
- value: pulumi.interpolate`${notificationQueueName}`,
+ value: pulumi.interpolate`${notificationIngressQueueName}`,
},
{
name: 'SEARCH_EVENT_QUEUE',
diff --git a/infra/stacks/document-cognition-service/index.ts b/infra/stacks/document-cognition-service/index.ts
index aac6e035a0..99d713c688 100644
--- a/infra/stacks/document-cognition-service/index.ts
+++ b/infra/stacks/document-cognition-service/index.ts
@@ -207,7 +207,8 @@ export const deleteChatQueueName: pulumi.Output<string> =
.getOutput('deleteChatQueueName')
.apply((name) => name as string);
-const { notificationQueueName, notificationQueueArn } = getMacroNotify();
+const { notificationIngressQueueName, notificationIngressQueueArn } =
+ getMacroNotify();
const { searchEventQueueName, searchEventQueueArn } = getSearchEventQueue();
@@ -238,7 +239,7 @@ const documentCognitionService = new DocumentCognitionService(
documentTextExtractorQueueArn,
deleteChatQueueArn,
searchEventQueueArn,
- notificationQueueArn,
+ notificationIngressQueueArn,
],
connectionTablePolicyArn: connectionGatewayTablePolicyArn,
containerEnvVars: [
@@ -305,7 +306,7 @@ const documentCognitionService = new DocumentCognitionService(
},
{
name: 'NOTIFICATION_QUEUE',
- value: pulumi.interpolate`${notificationQueueName}`,
+ value: pulumi.interpolate`${notificationIngressQueueName}`,
},
{
name: 'STATIC_FILE_SERVICE_URL',
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.ts
index e5bd486786..500c4d18aa 100644
--- a/infra/stacks/email-service/index.ts
+++ b/infra/stacks/email-service/index.ts
@@ -125,7 +125,8 @@ const sfsDeleteQueueName: pulumi.Output<string> = sfsDeleteLambdaStack
.getOutput('sfsDeleteQueueName')
.apply((name) => name as string);
-const { notificationQueueName, notificationQueueArn } = getMacroNotify();
+const { notificationIngressQueueName, notificationIngressQueueArn } =
+ getMacroNotify();
const emailServiceRedis = new Redis('email-service-redis', {
vpc: coparse_api_vpc,
@@ -245,7 +246,7 @@ const secretKeyArns = [
];
const queueArns = [
- notificationQueueArn,
+ notificationIngressQueueArn,
inboxSyncQueueArn,
inboxSyncRetryQueueArn,
linkManagerQueueArn,
@@ -392,7 +393,7 @@ const containerEnvVars = [
},
{
name: 'NOTIFICATION_QUEUE',
- value: pulumi.interpolate`${notificationQueueName}`,
+ value: pulumi.interpolate`${notificationIngressQueueName}`,
},
{
name: 'JWT_SECRET_KEY',
diff --git a/infra/stacks/notification-service/index.ts b/infra/stacks/notification-service/index.ts
index f6a4fab56e..a4a03d90a3 100644
--- a/infra/stacks/notification-service/index.ts
+++ b/infra/stacks/notification-service/index.ts
@@ -93,6 +93,10 @@ const notificationQueue = new Queue('notification', {
tags,
});
+const notificationIngressQueue = new Queue('notification-ingress', {
+ tags,
+});
+
const pushNotificationEventHandler = new PushNotificationEventHandler(
'push-notification-event-handler',
{
@@ -133,8 +137,10 @@ const notificationFcmPlatform = new aws.sns.PlatformApplication(
}
);
-export const notificationQueueArn = notificationQueue.queue.arn;
-export const notificationQueueName = notificationQueue.queue.name;
+const notificationQueueArn = notificationQueue.queue.arn;
+const notificationQueueName = notificationQueue.queue.name;
+export const notificationIngressQueueArn = notificationIngressQueue.queue.arn;
+export const notificationIngressQueueName = notificationIngressQueue.queue.name;
export const notificationSnsPlatformArns = [
notificationApnsPlatform.arn,
notificationFcmPlatform.arn,
@@ -153,7 +159,11 @@ const notificationService = new NotificationService('notification-service', {
MACRO_API_TOKENS.macroApiTokenPublicKeyArn,
authenticationServiceInternalApiKeyArn,
],
- queueArns: [pushNotificationEventHandlerQueueArn, notificationQueueArn],
+ queueArns: [
+ pushNotificationEventHandlerQueueArn,
+ notificationQueueArn,
+ notificationIngressQueueArn,
+ ],
snsPlatformArns: notificationSnsPlatformArns,
serviceContainerPort: 8080,
isPrivate: false,
@@ -192,6 +202,10 @@ const notificationService = new NotificationService('notification-service', {
name: 'NOTIFICATION_QUEUE',
value: pulumi.interpolate`${notificationQueueName}`,
},
+ {
+ name: 'NOTIFICATION_INGRESS_QUEUE',
+ value: pulumi.interpolate`${notificationIngressQueueName}`,
+ },
{
name: 'PUSH_NOTIFICATION_EVENT_HANDLER_QUEUE',
value: pulumi.interpolate`${pushNotificationEventHandlerQueueName}`,
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index d9c459c3e7..bea2d2bfa9 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3409,6 +3409,7 @@ version = "0.1.0"
dependencies = [
"askama",
"chrono",
+ "macro_user_id",
"model_notifications",
"notification",
"rootcause",
@@ -6159,6 +6160,7 @@ dependencies = [
"models_pagination",
"notification",
"paste",
+ "rootcause",
"serde",
"serde_json",
"sqlx",
@@ -6610,9 +6612,11 @@ dependencies = [
"aws-sdk-sqs",
"axum",
"chrono",
+ "email_formatting",
"email_validator",
"http-body-util",
"itertools 0.14.0",
+ "last_online_tracker",
"macro_auth",
"macro_aws_config",
"macro_cors",
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index 41ff6508bf..96b744f605 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -11,13 +11,8 @@ 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::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsIngressQueue;
use remote_env_var::LocalOrRemoteSecret;
use roles_and_permissions::{
domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,
@@ -28,21 +23,7 @@ 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,
->;
+pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsIngressQueue>;
#[expect(dead_code, reason = "used by utoipa in swagger.rs")]
pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 4342c0a7d9..102d197822 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -16,15 +16,8 @@ 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::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsIngressQueue;
use roles_and_permissions::{
domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,
};
@@ -171,40 +164,18 @@ 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
+ let redis_client_for_github =
+ redis::Client::open(config.redis_uri.as_str()).context("failed to create redis client")?;
+ let redis_multiplexed_conn = redis_client_for_github
.get_multiplexed_async_connection()
.await
- .context("failed to get multiplexed redis connection for state machine")?;
+ .context("failed to get multiplexed redis connection")?;
- let notification_repository = DbNotificationRepository::new(db.clone());
- let notification_queue = SqsNotificationQueue::new(
+ let ingress_queue = SqsIngressQueue::new(
aws_sdk_sqs::Client::new(&macro_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.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),
- };
- let notification_ingress_service =
- NotificationIngressService::new(notification_repository, notification_queue, state_machine);
+ let notification_ingress_service = SqsNotificationIngress::new(ingress_queue);
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/src/api/context.rs b/rust/cloud-storage/comms_service/src/api/context.rs
index 9312a98af2..3bcd7f7e52 100644
--- a/rust/cloud-storage/comms_service/src/api/context.rs
+++ b/rust/cloud-storage/comms_service/src/api/context.rs
@@ -8,32 +8,13 @@ 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::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification_hex::domain::service::SqsNotificationIngress;
+use notification_hex::outbound::queue::SqsIngressQueue;
use secretsmanager_client::LocalOrRemoteSecret;
use sqlx::PgPool;
use std::sync::Arc;
-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,
->;
+pub type NotificationIngressType = SqsNotificationIngress<SqsIngressQueue>;
env_var! {
#[derive(Clone)]
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
index 5d3e331cba..8d4c6c1d79 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
@@ -5,13 +5,8 @@ use connection_gateway::service::connection::ConnectionRepo;
use document_storage_service_client::DocumentStorageServiceClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
-use notification::domain::models::email_notification_digest::StateMachineDriverA;
-use notification::domain::service::NotificationIngressService;
-use notification::outbound::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsIngressQueue;
use scribe::{
ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,
email::EmailClient, static_file::StaticFileClient,
@@ -30,20 +25,7 @@ pub use test::*;
pub type DcsScribe =
ScribeClient<DocumentClient, ChannelClient, DcsClient, EmailClient, StaticFileClient>;
-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,
->;
+pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsIngressQueue>;
#[derive(Clone, FromRef)]
pub struct ApiContext {
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 64d262e4b5..438edb258c 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -120,15 +120,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
use lexical_client::LexicalClient;
- use notification::domain::models::email_notification_digest::{
- EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder, StateMachineDriverA,
- };
- use notification::domain::service::NotificationIngressService;
- use notification::outbound::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
- };
+ use notification::domain::service::SqsNotificationIngress;
+ use notification::outbound::queue::SqsIngressQueue;
use scribe::ScribeClient;
use search_service_client::SearchServiceClient;
use soup::domain::service::SoupImpl;
@@ -212,41 +205,11 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
channels_service,
));
- let redis_client = redis::Client::open("redis://localhost:6379").unwrap();
- let redis_multiplexed_conn = redis_client
- .get_multiplexed_async_connection()
- .await
- .unwrap();
-
- let notification_ingress_service = Arc::new({
- let notification_repository = DbNotificationRepository::new(pool.clone());
- let notification_queue = SqsNotificationQueue::new(
- aws_sdk_sqs::Client::from_conf(sqs_config),
- "test-notification-queue".to_string(),
- );
- let state_machine = StateMachineDriverA {
- user_checker: DbUserExistenceChecker::new(pool.clone()),
- notification_checker: PushNotificationCheckerImpl::new(DbNotificationRepository::new(
- pool.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),
- };
- NotificationIngressService::new(notification_repository, notification_queue, state_machine)
- });
+ let ingress_queue = SqsIngressQueue::new(
+ aws_sdk_sqs::Client::from_conf(sqs_config),
+ "test-notification-ingress-queue".to_string(),
+ );
+ let notification_ingress_service = Arc::new(SqsNotificationIngress::new(ingress_queue));
// Build document tool context for AI tools
let s3_config = aws_sdk_s3::Config::builder()
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index 4aa7228125..34ebb1dc70 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -23,15 +23,8 @@ use frecency::outbound::postgres::FrecencyPgStorage;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
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::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsIngressQueue;
use scribe::{ScribeClient, document::DocumentClient};
use search_service_client::SearchServiceClient;
use secretsmanager_client::SecretManager;
@@ -204,40 +197,11 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized connection repo");
- let redis_multiplexed_conn = redis_client
- .get_multiplexed_async_connection()
- .await
- .context("failed to get multiplexed redis connection for notification state machine")?;
-
- let notification_ingress_service = Arc::new({
- let notification_repository = DbNotificationRepository::new(db.clone());
- let notification_queue = SqsNotificationQueue::new(
- aws_sdk_sqs::Client::new(&aws_config),
- 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.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 ingress_queue = SqsIngressQueue::new(
+ aws_sdk_sqs::Client::new(&aws_config),
+ config.notification_queue.clone(),
+ );
+ let notification_ingress_service = Arc::new(SqsNotificationIngress::new(ingress_queue));
tracing::info!("initialized notification ingress service");
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index f98d4d93b7..cf6441ee05 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -30,13 +30,8 @@ use github::outbound::pg_github_sync_repo::PgGithubSyncRepo;
use 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::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsIngressQueue;
use opensearch_client::OpensearchClient;
use properties::{
NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,
@@ -82,20 +77,7 @@ type DssSoupState = SoupRouterState<
>;
type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;
-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,
->;
+pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsIngressQueue>;
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.rs
index 5b5de914b9..7eeab4a6fd 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -38,15 +38,8 @@ 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::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsIngressQueue;
use opensearch_client::OpensearchClient;
use properties::{
NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,
@@ -217,45 +210,16 @@ async fn main() -> anyhow::Result<()> {
);
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(),
- );
- 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());
+ let ingress_queue = SqsIngressQueue::new(
+ aws_sdk_sqs::Client::new(&aws_config),
+ config.vars.notification_queue.as_ref().to_string(),
+ );
+ let notification_ingress_service = Arc::new(SqsNotificationIngress::new(ingress_queue.clone()));
tracing::trace!("initialized notification ingress service");
let permission_checker = PermissionServiceImpl::new(db.clone());
- let notification_service = NotificationServiceImpl::new(make_notification_ingress());
+ let notification_service =
+ NotificationServiceImpl::new(SqsNotificationIngress::new(ingress_queue));
let properties_service = Arc::new(PropertiesServiceImpl::new(
PropertiesPgRepo::new(db.clone()),
Some(permission_checker),
diff --git a/rust/cloud-storage/email_formatting/Cargo.toml b/rust/cloud-storage/email_formatting/Cargo.toml
index bcb7b72923..864c77170b 100644
--- a/rust/cloud-storage/email_formatting/Cargo.toml
+++ b/rust/cloud-storage/email_formatting/Cargo.toml
@@ -7,6 +7,7 @@ version = "0.1.0"
[dependencies]
askama = "0.14"
chrono = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
model_notifications = { path = "../model_notifications" }
notification = { path = "../notification" }
rootcause = { workspace = true }
diff --git a/rust/cloud-storage/email_formatting/src/lib.rs b/rust/cloud-storage/email_formatting/src/lib.rs
index 871136e8b5..57db6c08d6 100644
--- a/rust/cloud-storage/email_formatting/src/lib.rs
+++ b/rust/cloud-storage/email_formatting/src/lib.rs
@@ -1,14 +1,14 @@
-use std::time::Duration;
-
use askama::Template;
use chrono::{DateTime, Utc};
-use model_notifications::NotifEvent;
+use macro_user_id::cowlike::CowLike;
+use model_notifications::{NotifEvent, NotificationTitle};
use notification::domain::models::{
Notification, NotificationExtEmail, RateLimitConfig, RateLimitKey, UserNotificationRow,
email_notification_digest::ports::DigestBatch, queue_message::EmailContent,
};
use rootcause::Report;
use serde::{Deserialize, Serialize};
+use std::time::Duration;
#[derive(Template)]
#[template(path = "digest.html")]
@@ -22,13 +22,15 @@ struct NotifPreview {
}
impl NotifPreview {
- fn new(v: UserNotificationRow<NotifEvent>) -> Option<Self> {
- Some(NotifPreview {
+ #[tracing::instrument(err)]
+ fn new(v: UserNotificationRow<NotifEvent>) -> Result<Self, Report> {
+ let title = v
+ .notification_metadata
+ .format_title(v.sender_id.as_ref().map(CowLike::copied))?;
+ let body = v.notification_metadata.format_body(v.sender_id)?;
+ Ok(NotifPreview {
created_at: v.created_at.unwrap_or(Utc::now()),
- message: format!(
- "PLACEHOLDER: you received a notification with typename {}",
- v.notification_event_type
- ),
+ message: format!("{title} - {body}"),
})
}
}
@@ -57,14 +59,13 @@ impl EmailDigestNotification {
.into_iter()
.map(|v| v.deserialize_metadata::<NotifEvent>())
.filter_map(|res| res.inspect_err(log_err).ok())
- .filter_map(NotifPreview::new)
+ .map(NotifPreview::new)
+ .filter_map(Result::ok)
.collect();
let templated_len = notifs.len();
- let template = DigestTemplate { notifs };
-
- let inner_html_string = template.render()?;
+ let inner_html_string = DigestTemplate { notifs }.render()?;
Ok(EmailDigestNotification {
inner_html_string,
@@ -87,7 +88,7 @@ impl NotificationExtEmail for EmailDigestNotification {
fn rate_limit_config() -> RateLimitConfig {
RateLimitConfig {
- max_count: 60,
+ max_count: 600,
window: Duration::from_hours(1),
}
}
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.rs
index ddc5e4bc2a..59f6b18210 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
@@ -5,15 +5,8 @@ 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::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsIngressQueue;
use secretsmanager_client::SecretManager;
use sqlx::postgres::PgPoolOptions;
use static_file_service_client::StaticFileServiceClient;
@@ -176,40 +169,11 @@ 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 ingress_queue = SqsIngressQueue::new(
+ aws_sdk_sqs::Client::new(&aws_config),
+ config.notification_queue.clone(),
+ );
+ let notification_ingress_service = Arc::new(SqsNotificationIngress::new(ingress_queue));
let redis_client = email_service::util::redis::RedisClient::new(
redis_inner_client,
diff --git a/rust/cloud-storage/email_service/src/pubsub/context.rs b/rust/cloud-storage/email_service/src/pubsub/context.rs
index a38d559d1f..e213c9aead 100644
--- a/rust/cloud-storage/email_service/src/pubsub/context.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/context.rs
@@ -3,34 +3,15 @@ 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::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsIngressQueue;
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,
- StateMachine,
->;
+pub type NotificationIngressType = SqsNotificationIngress<SqsIngressQueue>;
#[derive(Clone)]
pub struct PubSubContext {
diff --git a/rust/cloud-storage/model_notifications/Cargo.toml b/rust/cloud-storage/model_notifications/Cargo.toml
index 039c05ef96..6ce7af0086 100644
--- a/rust/cloud-storage/model_notifications/Cargo.toml
+++ b/rust/cloud-storage/model_notifications/Cargo.toml
@@ -15,6 +15,7 @@ models_comms = { path = "../models_comms" }
models_pagination = { path = "../models_pagination" }
notification = { path = "../notification" }
paste = { workspace = true }
+rootcause = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/rust/cloud-storage/model_notifications/src/digest_state.rs b/rust/cloud-storage/model_notifications/src/digest_state.rs
new file mode 100644
index 0000000000..b55fa1be1e
--- /dev/null
+++ b/rust/cloud-storage/model_notifications/src/digest_state.rs
@@ -0,0 +1,12 @@
+use crate::{InviteToTeamMetadata, NewEmailMetadata};
+use notification::domain::models::email_notification_digest::{
+ EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder,
+};
+
+pub fn common_email_block_list() -> EmailBlockList {
+ EmailBlockList::new::<NewEmailMetadata>()
+}
+
+pub fn common_explicit_invite_allow_list() -> ExplicitInviteAllowList {
+ ExplicitInviteAllowList::new::<InviteToTeamMetadata>()
+}
diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rs
index 49ea67e86a..67b493eb32 100644
--- a/rust/cloud-storage/model_notifications/src/lib.rs
+++ b/rust/cloud-storage/model_notifications/src/lib.rs
@@ -1,8 +1,10 @@
use chrono::DateTime;
+use macro_user_id::user_id::MacroUserIdStr;
use serde::{Deserialize, Serialize};
use std::hash::{DefaultHasher, Hasher};
use utoipa::ToSchema;
mod device;
+pub mod digest_state;
mod metadata;
mod unsubscribe;
pub use device::*;
@@ -188,3 +190,77 @@ define_notif_event!(
AiResponse(AiResponseMetadata),
}
);
+
+impl NotificationTitle for NotifEvent {
+ fn format_title(
+ &self,
+ sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ match self {
+ NotifEvent::ChannelMention(channel_mention_metadata) => {
+ channel_mention_metadata.format_title(sender_id)
+ }
+ NotifEvent::DocumentMention(document_mention_metadata) => {
+ document_mention_metadata.format_title(sender_id)
+ }
+ NotifEvent::MentionedInDocumentComment(mentioned_in_document_comment_metadata) => {
+ mentioned_in_document_comment_metadata.format_title(sender_id)
+ }
+ NotifEvent::ChannelInvite(channel_invite_metadata) => {
+ channel_invite_metadata.format_title(sender_id)
+ }
+ NotifEvent::ChannelMessageSend(channel_message_send_metadata) => {
+ channel_message_send_metadata.format_title(sender_id)
+ }
+ NotifEvent::ChannelMessageReply(channel_reply_metadata) => {
+ channel_reply_metadata.format_title(sender_id)
+ }
+ NotifEvent::NewEmail(new_email_metadata) => new_email_metadata.format_title(sender_id),
+ NotifEvent::InviteToTeam(invite_to_team_metadata) => {
+ invite_to_team_metadata.format_title(sender_id)
+ }
+ NotifEvent::TaskAssigned(task_assigned_metadata) => {
+ task_assigned_metadata.format_title(sender_id)
+ }
+ NotifEvent::AiResponse(ai_response_metadata) => {
+ ai_response_metadata.format_title(sender_id)
+ }
+ }
+ }
+
+ fn format_body(
+ &self,
+ sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ match self {
+ NotifEvent::ChannelMention(channel_mention_metadata) => {
+ channel_mention_metadata.format_body(sender_id)
+ }
+ NotifEvent::DocumentMention(document_mention_metadata) => {
+ document_mention_metadata.format_body(sender_id)
+ }
+ NotifEvent::MentionedInDocumentComment(mentioned_in_document_comment_metadata) => {
+ mentioned_in_document_comment_metadata.format_body(sender_id)
+ }
+ NotifEvent::ChannelInvite(channel_invite_metadata) => {
+ channel_invite_metadata.format_body(sender_id)
+ }
+ NotifEvent::ChannelMessageSend(channel_message_send_metadata) => {
+ channel_message_send_metadata.format_body(sender_id)
+ }
+ NotifEvent::ChannelMessageReply(channel_reply_metadata) => {
+ channel_reply_metadata.format_body(sender_id)
+ }
+ NotifEvent::NewEmail(new_email_metadata) => new_email_metadata.format_body(sender_id),
+ NotifEvent::InviteToTeam(invite_to_team_metadata) => {
+ invite_to_team_metadata.format_body(sender_id)
+ }
+ NotifEvent::TaskAssigned(task_assigned_metadata) => {
+ task_assigned_metadata.format_body(sender_id)
+ }
+ NotifEvent::AiResponse(ai_response_metadata) => {
+ ai_response_metadata.format_body(sender_id)
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rs
index 517a67ffc8..f2fe5bfcf2 100644
--- a/rust/cloud-storage/model_notifications/src/metadata.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata.rs
@@ -1,4 +1,5 @@
use doppleganger::Doppleganger;
+use macro_user_id::cowlike::CowLike;
use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};
use mention_utils::parse::{ParsedXmlText, XmlFormatter};
use model_entity::Entity;
@@ -8,6 +9,8 @@ use notification::domain::models::{
NotifCollapseKey, NotificationExtIos,
apple::{APNSPushNotification, AlertDictionary, Aps, PushNotificationData},
};
+use rootcause::Report;
+use rootcause::report;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
@@ -217,6 +220,22 @@ impl notification::domain::models::Notification for NewEmailMetadata {
const TYPE_NAME: &'static str = "new_email";
}
+impl NotificationTitle for NewEmailMetadata {
+ fn format_title(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ Ok(self.subject.clone())
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ Ok(self.snippet.clone())
+ }
+}
+
impl notification::domain::models::Notification for ChannelInviteMetadata {
const TYPE_NAME: &'static str = "channel_invite";
}
@@ -245,6 +264,175 @@ impl notification::domain::models::Notification for InviteToTeamMetadata {
const TYPE_NAME: &'static str = "invite_to_team";
}
+pub trait NotificationTitle {
+ /// format the notification into a user facing title
+ fn format_title(
+ &self,
+ sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report>;
+
+ fn format_body(
+ &self,
+ sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report>;
+}
+
+impl NotificationTitle for ChannelMentionMetadata {
+ fn format_title(
+ &self,
+ sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let sender =
+ sender_id.ok_or_else(|| report!("Expected sender id to exist for {:?}", &self))?;
+ Ok(match self.common.channel_type {
+ ChannelType::DirectMessage => {
+ format!("{} mentioned you", sender.email_part().local_part())
+ }
+ _ => format!(
+ "{} mentioned you in #{}",
+ sender.email_part().local_part(),
+ self.common.channel_name
+ ),
+ })
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ parse_message_plain_text(&self.message_content)
+ }
+}
+
+impl NotificationTitle for DocumentMentionMetadata {
+ fn format_title(
+ &self,
+ sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let sender =
+ sender_id.ok_or_else(|| report!("Expected sender id to exist for {:?}", &self))?;
+ let sender = sender.0.email_part().email_str().to_string();
+ Ok(format!("{sender} sent a document",))
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let file_type_str = self.file_type.as_deref().unwrap_or("");
+ Ok(format!("{}.{}", self.document_name, file_type_str))
+ }
+}
+
+impl NotificationTitle for ChannelMessageSendMetadata {
+ fn format_title(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let title = match self.common.channel_type {
+ ChannelType::DirectMessage => self.sender.email_part().local_part().to_string(),
+ _ => format!(
+ "{} <{}>",
+ self.sender.email_part().local_part(),
+ self.common.channel_name
+ ),
+ };
+ Ok(title)
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ parse_message_plain_text(&self.message_content)
+ }
+}
+
+impl NotificationTitle for MentionedInDocumentCommentMetadata {
+ fn format_title(
+ &self,
+ sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let sender =
+ sender_id.ok_or_else(|| report!("Expected sender id to exist for {:?}", &self))?;
+ let file_type_str = self
+ .file_type
+ .as_ref()
+ .ok_or_else(|| report!("Expected the file type to exist"))?;
+ let email = sender.0.email_part();
+ let sender = email.email_str();
+ let title = format!(
+ "{sender} mentioned you in {}.{}",
+ self.document_name, file_type_str
+ );
+ Ok(title)
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ parse_message_plain_text(&self.text)
+ }
+}
+
+impl NotificationTitle for ChannelReplyMetadata {
+ fn format_title(
+ &self,
+ sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let sender =
+ sender_id.ok_or_else(|| report!("Expected sender id to exist for {:?}", &self))?;
+
+ Ok(format!("Reply from {}", sender.0.email_part().email_str()))
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ parse_message_plain_text(&self.message_content)
+ }
+}
+
+impl NotificationTitle for ChannelInviteMetadata {
+ fn format_title(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let email = self.invited_by.email_part();
+ let sender = email.email_str();
+ let channel = &self.common.channel_name;
+ Ok(format!("{sender} invited you to join #{channel}"))
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ Ok("Open macro to continue".to_string())
+ }
+}
+
+impl NotificationTitle for InviteToTeamMetadata {
+ fn format_title(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let email = self.invited_by.email_part();
+ let sender = email.email_str();
+
+ Ok(format!("{sender} invited you to join a team"))
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ Ok(self.team_name.clone())
+ }
+}
+
/// Metadata for when a user is assigned to a task
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
@@ -275,7 +463,7 @@ impl XmlFormatter for PlainTextFormatter {
link: &mention_utils::parse::ParsedLink<'_>,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
- write!(f, "{}", link.text)
+ write!(f, "{}", link.url)
}
fn format_doc(
@@ -315,24 +503,27 @@ impl XmlFormatter for PlainTextFormatter {
}
/// Helper to parse XML message content to plain text, returning None on failure.
-fn parse_message_plain_text(content: &str) -> Option<String> {
- let parsed = ParsedXmlText::parse(content).ok()?;
- Some(PlainTextFormatter::format_xml_text(parsed).0)
+fn parse_message_plain_text(content: &str) -> Result<String, Report> {
+ let parsed = ParsedXmlText::parse(content)?;
+ Ok(PlainTextFormatter::format_xml_text(parsed).0)
}
/// Helper to create an alert-style APNS notification with title and body.
-fn alert_apns(
- title: String,
- body: String,
+fn alert_apns<T: NotificationTitle>(
+ notif: &T,
+ sender_id: Option<MacroUserIdStr<'_>>,
notification_id: Uuid,
sender_profile_picture_url: Option<String>,
-) -> APNSPushNotification<PushNotificationData> {
+) -> Result<APNSPushNotification<PushNotificationData>, Report> {
+ let title = notif.format_title(sender_id.as_ref().map(CowLike::copied))?;
+ let body = notif.format_body(sender_id)?;
+
let mutable_content = if sender_profile_picture_url.is_some() {
Some(1)
} else {
None
};
- APNSPushNotification {
+ Ok(APNSPushNotification {
aps: Aps {
alert: Some(notification::domain::models::apple::Alert::Dictionary(
AlertDictionary {
@@ -348,7 +539,7 @@ fn alert_apns(
notification_id,
sender_profile_picture_url,
},
- }
+ })
}
impl NotificationExtIos for ChannelInviteMetadata {
@@ -359,18 +550,30 @@ impl NotificationExtIos for ChannelInviteMetadata {
NotifCollapseKey::new(entity_type).append(&entity.entity_id)
}
- fn into_apns<'a>(
- self,
- _sender_id: Option<MacroUserIdStr<'a>>,
+ fn as_apns<'a>(
+ &self,
+ sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
- Some(alert_apns(
- format!("{} Invite", self.common.channel_name),
- format!("{} invited you to join the channel", self.invited_by),
- notification_id,
- self.sender_profile_picture_url,
- ))
+ let profile_pic = self.sender_profile_picture_url.clone();
+ alert_apns(self, sender_id, notification_id, profile_pic).ok()
+ }
+}
+
+impl NotificationTitle for AiResponseMetadata {
+ fn format_title(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ Ok("AI Response".to_string())
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ Ok(self.summary.clone())
}
}
@@ -380,18 +583,13 @@ impl NotificationExtIos for AiResponseMetadata {
NotifCollapseKey::new(&self.message_id)
}
- fn into_apns<'a>(
- self,
- _sender_id: Option<MacroUserIdStr<'a>>,
+ fn as_apns<'a>(
+ &self,
+ sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
- Some(alert_apns(
- "Ai Response".into(),
- self.summary,
- notification_id,
- None,
- ))
+ alert_apns(self, sender_id, notification_id, None).ok()
}
}
@@ -402,27 +600,14 @@ impl NotificationExtIos for ChannelMessageSendMetadata {
NotifCollapseKey::new(&self.message_id)
}
- fn into_apns<'a>(
- self,
- _sender_id: Option<MacroUserIdStr<'a>>,
+ fn as_apns<'a>(
+ &self,
+ sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
- let title = match self.common.channel_type {
- ChannelType::DirectMessage => self.sender.email_part().local_part().to_string(),
- _ => format!(
- "{} <{}>",
- self.sender.email_part().local_part(),
- self.common.channel_name
- ),
- };
- let body = parse_message_plain_text(&self.message_content)?;
- Some(alert_apns(
- title,
- body,
- notification_id,
- self.sender_profile_picture_url,
- ))
+ let profile_pic = self.sender_profile_picture_url.clone();
+ alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
@@ -433,30 +618,14 @@ impl NotificationExtIos for ChannelMentionMetadata {
NotifCollapseKey::new(&self.message_id)
}
- fn into_apns<'a>(
- self,
+ fn as_apns<'a>(
+ &self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
- let sender = sender_id?;
- let title = match self.common.channel_type {
- ChannelType::DirectMessage => {
- format!("{} mentioned you", sender.email_part().local_part())
- }
- _ => format!(
- "{} mentioned you in #{}",
- sender.email_part().local_part(),
- self.common.channel_name
- ),
- };
- let body = parse_message_plain_text(&self.message_content)?;
- Some(alert_apns(
- title,
- body,
- notification_id,
- self.sender_profile_picture_url,
- ))
+ let profile_pic = self.sender_profile_picture_url.clone();
+ alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
@@ -467,21 +636,14 @@ impl NotificationExtIos for ChannelReplyMetadata {
NotifCollapseKey::new(&self.message_id)
}
- fn into_apns<'a>(
- self,
+ fn as_apns<'a>(
+ &self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
- let sender = sender_id?;
- let title = format!("{} Replied", sender.0.email_part().email_str());
- let body = parse_message_plain_text(&self.message_content)?;
- Some(alert_apns(
- title,
- body,
- notification_id,
- self.sender_profile_picture_url,
- ))
+ let profile_pic = self.sender_profile_picture_url.clone();
+ alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
@@ -493,25 +655,14 @@ impl NotificationExtIos for DocumentMentionMetadata {
NotifCollapseKey::new(entity_type).append(&entity.entity_id)
}
- fn into_apns<'a>(
- self,
+ fn as_apns<'a>(
+ &self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
- let sender = sender_id?;
- let file_type_str = self.file_type.as_ref()?;
- let title = sender.0.email_part().email_str().to_string();
- let body = format!(
- "You were mentioned in {}.{}",
- self.document_name, file_type_str
- );
- Some(alert_apns(
- title,
- body,
- notification_id,
- self.sender_profile_picture_url,
- ))
+ let profile_pic = self.sender_profile_picture_url.clone();
+ alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
@@ -519,6 +670,29 @@ impl notification::domain::models::Notification for TaskAssignedMetadata {
const TYPE_NAME: &'static str = "task_assigned";
}
+impl NotificationTitle for TaskAssignedMetadata {
+ fn format_title(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let email = self.assigned_by.email_part();
+ let sender = email.email_str();
+ Ok(format!("Task assigned by {sender}"))
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let body = if let Some(ref task_name) = self.task_name {
+ format!("assigned you to {}", task_name)
+ } else {
+ "New Task".to_string()
+ };
+ Ok(body)
+ }
+}
+
impl NotificationExtIos for TaskAssignedMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
@@ -527,24 +701,14 @@ impl NotificationExtIos for TaskAssignedMetadata {
NotifCollapseKey::new(entity_type).append(&entity.entity_id)
}
- fn into_apns<'a>(
- self,
- _sender_id: Option<MacroUserIdStr<'a>>,
+ fn as_apns<'a>(
+ &self,
+ sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
- let title = self.assigned_by.email_part().email_str().to_string();
- let body = if let Some(ref task_name) = self.task_name {
- format!("assigned you to {}", task_name)
- } else {
- "assigned you a task".to_string()
- };
- Some(alert_apns(
- title,
- body,
- notification_id,
- self.sender_profile_picture_url,
- ))
+ let profile_pic = self.sender_profile_picture_url.clone();
+ alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
@@ -583,25 +747,13 @@ impl NotificationExtIos for MentionedInDocumentCommentMetadata {
NotifCollapseKey::new(entity_type).append(&entity.entity_id)
}
- fn into_apns<'a>(
- self,
+ fn as_apns<'a>(
+ &self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
- let sender = sender_id?;
- let file_type_str = self.file_type.as_ref()?;
- let title = sender.0.email_part().email_str().to_string();
- let body = format!(
- "You were mentioned in {}.{}",
- self.document_name, file_type_str
- );
-
- Some(alert_apns(
- title,
- body,
- notification_id,
- self.sender_profile_picture_url,
- ))
+ let profile_pic = self.sender_profile_picture_url.clone();
+ alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rs
index 717214e9df..3b187bc56b 100644
--- a/rust/cloud-storage/notification/src/domain/models.rs
+++ b/rust/cloud-storage/notification/src/domain/models.rs
@@ -21,7 +21,7 @@ pub use rate_limit::{RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimit
pub use recipient::{ExclusionReason, FilteredRecipient, RecipientExclusion};
pub use request::{NotificationResult, SendNotificationRequest, SendNotificationRequestBuilder};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
-use std::sync::Arc;
+use std::{borrow::Cow, sync::Arc};
/// Notification ID paired with its APNS collapse key, for push clearing.
#[derive(Debug, Clone)]
@@ -139,20 +139,43 @@ impl<T> UserNotificationRow<T> {
sender_id,
})
}
+
+ /// create a notification typename from this row.
+ /// This is dangerous because the compiler cannot assert that the T: Notification
+ pub(crate) fn dangerous_get_typename(&self) -> NotificationTypeName {
+ NotificationTypeName(Cow::Owned(self.notification_event_type.clone()))
+ }
+}
+
+/// newtype wrapper for the the typename of a Notification
+#[derive(Debug, Serialize, Deserialize, Clone)]
+#[serde(transparent)]
+pub(crate) struct NotificationTypeName(Cow<'static, str>);
+
+impl NotificationTypeName {
+ pub(crate) fn new_from_notif<T: Notification>(_v: &T) -> Self {
+ NotificationTypeName(Cow::Borrowed(T::TYPE_NAME))
+ }
+}
+
+impl AsRef<str> for NotificationTypeName {
+ fn as_ref(&self) -> &str {
+ self.0.as_ref()
+ }
}
/// A notification metadata value tagged with the notification event type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaggedContent<T> {
- tag: String,
- content: T,
+ pub(crate) tag: NotificationTypeName,
+ pub(crate) content: T,
}
impl<T: Notification> TaggedContent<Arc<T>> {
/// create a new value from a notification T
pub fn new_arc(val: Arc<T>) -> Self {
TaggedContent {
- tag: T::TYPE_NAME.to_string(),
+ tag: NotificationTypeName::new_from_notif(&*val),
content: val,
}
}
@@ -162,7 +185,7 @@ impl<T: Notification> TaggedContent<T> {
/// create a new value from a notification T
pub fn new(val: T) -> Self {
TaggedContent {
- tag: T::TYPE_NAME.to_string(),
+ tag: NotificationTypeName::new_from_notif(&val),
content: val,
}
}
@@ -175,7 +198,10 @@ impl UserNotificationRow<serde_json::Value> {
/// [`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 })
+ self.map(|v| TaggedContent {
+ tag: NotificationTypeName(Cow::Owned(tag)),
+ content: v,
+ })
}
}
@@ -220,7 +246,7 @@ impl<T> SortOn<CreatedAt> for UserNotificationRow<T> {
}
/// Trait that all notification types must implement.
-pub trait Notification: Serialize + DeserializeOwned + Send + Sync {
+pub trait Notification: Serialize + DeserializeOwned + Send + Sync + 'static {
/// The type name of this notification.
const TYPE_NAME: &'static str;
}
@@ -243,8 +269,8 @@ pub trait NotificationExtIos: Notification {
/// Build the collapse key for this push notification.
fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey;
/// Convert this notification into an APNS push notification.
- fn into_apns<'a>(
- self,
+ fn as_apns<'a>(
+ &self,
sender_id: Option<MacroUserIdStr<'a>>,
entity: &Entity<'_>,
notification_id: uuid::Uuid,
diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
index f74dbe9aef..3e565aed10 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, UserNotificationRow,
+ Notification, NotificationTypeName, UserNotificationRow,
email_notification_digest::ports::{
DigestBatcher, LastOnlineChecker, MessageId, MessageReceiptRepo,
NotificationSendChecker, PushNotificationChecker, UserExistenceChecker,
@@ -97,8 +97,8 @@ impl NotificationSetBuilder for NotificationSet {
}
impl NotificationSet {
- fn is_member<T: Notification>(&self) -> bool {
- self.0.contains(&T::TYPE_NAME)
+ fn is_member(&self, typename: &NotificationTypeName) -> bool {
+ self.0.contains(typename.as_ref())
}
}
@@ -164,11 +164,11 @@ impl EmailBlockList {
///
/// Returns [`Decision::DontSend`] if the notification type is blocked,
/// or [`Decision::Next`] with an [`AllowedNotification`] to continue the flow.
- pub fn notification_is_allowed<T: Notification>(
+ pub fn notification_is_allowed<T>(
&self,
notif: UserNotificationRow<Arc<T>>,
) -> Either<AllowedNotification<T>, DontSend> {
- match self.0.is_member::<T>() {
+ match self.0.is_member(&notif.dangerous_get_typename()) {
true => Either::Right(DontSend(())),
false => Either::Left(AllowedNotification { inner: notif }),
}
@@ -194,7 +194,7 @@ pub struct AccountDoesNotExist<T> {
prev: AllowedNotification<T>,
}
-impl<T: Notification> AllowedNotification<T> {
+impl<T> AllowedNotification<T> {
/// Check if the notification recipient has a Macro account.
///
/// Returns [`AccountExists`] if the user has an account (check push settings next),
@@ -230,7 +230,7 @@ impl NotificationSetBuilder for ExplicitInviteAllowList {
/// type alias for the data returned from [AccountDoesNotExist::batch_or_single_send]
pub type EmailSendDecision<T> = Either<SingleSend<T>, BatchSend<T>>;
-impl<T: Notification> AccountDoesNotExist<T> {
+impl<T> AccountDoesNotExist<T> {
/// Decide whether to send immediately or batch for digest.
///
/// Returns [`EmailSendDecision::SingleSend`] for explicit invite notifications,
@@ -239,7 +239,10 @@ impl<T: Notification> AccountDoesNotExist<T> {
self,
invite_list: &ExplicitInviteAllowList,
) -> EmailSendDecision<UserNotificationRow<Arc<T>>> {
- match invite_list.0.is_member::<T>() {
+ match invite_list
+ .0
+ .is_member(&self.prev.inner.dangerous_get_typename())
+ {
true => EmailSendDecision::Left(SingleSend(self.prev.inner)),
false => EmailSendDecision::Right(BatchSend(self.prev.inner)),
}
@@ -279,7 +282,7 @@ pub struct PushNotificationsDisabled<T> {
prev: AccountExists<T>,
}
-impl<T: Notification> AccountExists<T> {
+impl<T: Serialize> AccountExists<T> {
/// Check if the user has push notifications enabled.
///
/// Returns [`PushNotificationsEnabled`] to check if push was delivered,
@@ -304,7 +307,7 @@ impl<T: Notification> AccountExists<T> {
}
}
-impl<T: Notification> PushNotificationsDisabled<T> {
+impl<T> PushNotificationsDisabled<T> {
/// check if the user has been logged in more recently than the threshold for notifications
/// If the user has been online within the time window then we do not send email notifications.
/// If the user has not been online within the threshold then we queue the notification for batch delivery
@@ -331,7 +334,7 @@ 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>(
+ fn ingest<T: Serialize + Send + Sync + 'static>(
&self,
notif: UserNotificationRow<Arc<T>>,
) -> impl Future<Output = Result<StateMachineDecisionA<T>, Report>> + Send;
@@ -341,27 +344,49 @@ pub trait BulkDigestStateMachine: Send + Sync + 'static {
/// This state machine does not model the entire decision tree because it runs at a place in the program
/// where not all actions have been taken yet.
pub struct StateMachineDriverA<U, N, O, B> {
- /// adapter which implements [UserExistenceChecker]
+ /// Adapter which implements [UserExistenceChecker].
pub user_checker: U,
- /// adapter which implements [PushNotificationChecker]
+ /// Adapter which implements [PushNotificationChecker].
pub notification_checker: N,
- /// adapter which implements [LastOnlineChecker]
+ /// Adapter which implements [LastOnlineChecker].
pub online_checker: O,
- /// adapter which allows inserting a notification for bulk digest email
- /// implements [DigestBatcher]
+ /// Adapter which allows inserting a notification for bulk digest email.
+ /// Implements [DigestBatcher].
pub digest_batcher: B,
- /// the blocklist for notifications which are never forwarded to bulk
+ /// The blocklist for notifications which are never forwarded to bulk.
pub block_list: EmailBlockList,
- /// the allow list for checking if a notification is analagous to an "invite to macro" notification
+ /// The allow list for checking if a notification is analogous to an "invite to macro" notification.
pub invite_list: ExplicitInviteAllowList,
- /// the window of time in which the digest emails are collected for before sending
+ /// The window of time in which the digest emails are collected for before sending.
pub digest_window: Duration,
- /// the duration for how recently a user has been online
- /// used to abort sending a bulk email if the user is below the
- /// threshold
+ /// The duration for how recently a user has been online.
+ /// Used to abort sending a bulk email if the user is below the threshold.
pub online_duration_threshold: Duration,
}
+impl<U, N, O, B> StateMachineDriverA<U, N, O, B> {
+ /// Create a new instance with the default time windows (30 min digest, 60 min online).
+ pub fn new_with_defaults(
+ user_checker: U,
+ notification_checker: N,
+ online_checker: O,
+ digest_batcher: B,
+ block_list: EmailBlockList,
+ invite_list: ExplicitInviteAllowList,
+ ) -> Self {
+ Self {
+ user_checker,
+ notification_checker,
+ online_checker,
+ digest_batcher,
+ block_list,
+ invite_list,
+ digest_window: std::time::Duration::from_mins(30),
+ online_duration_threshold: std::time::Duration::from_mins(60),
+ }
+ }
+}
+
/// the initial decision created during notification ingress
pub enum StateMachineDecisionA<T> {
/// we will not send a batch email
@@ -389,7 +414,7 @@ where
/// given an input notification, drive the state machine to an initial decision about the notification.
/// This attempts to handle as many cases internally as possible although the caller is responsible for picking up certain decisions.
/// See [StateMachineInitialDecision] for more info.
- pub async fn ingest<T: Notification>(
+ pub async fn ingest<T: Serialize>(
&self,
notif: UserNotificationRow<Arc<T>>,
) -> Result<StateMachineDecisionA<T>, Report> {
@@ -434,7 +459,7 @@ where
})
}
- async fn inner_store_batch<T: Notification>(
+ async fn inner_store_batch<T: Serialize>(
&self,
batch: BatchSend<UserNotificationRow<Arc<T>>>,
) -> Result<BatchSend<()>, Report> {
@@ -456,7 +481,7 @@ where
O: LastOnlineChecker,
B: DigestBatcher,
{
- fn ingest<T: Notification + 'static>(
+ fn ingest<T: Serialize + Send + Sync + 'static>(
&self,
notif: UserNotificationRow<Arc<T>>,
) -> impl Future<Output = Result<StateMachineDecisionA<T>, Report>> + 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.rs
index f70a3ee2e1..2b7bd11903 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
@@ -193,11 +193,11 @@ fn test_user_id() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").unwrap()
}
-fn create_test_notification_row<T>(metadata: T) -> UserNotificationRow<Arc<T>> {
+fn create_test_notification_row<T: Notification>(metadata: T) -> UserNotificationRow<Arc<T>> {
UserNotificationRow {
owner_id: test_user_id(),
notification_id: uuid::Uuid::now_v7(),
- notification_event_type: "test".to_string(),
+ notification_event_type: T::TYPE_NAME.to_string(),
entity: EntityType::Document.with_entity_str("doc_123"),
sent: false,
done: false,
diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
index 88fb45d028..e0a9559b68 100644
--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs
+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
@@ -1,11 +1,12 @@
//! Queue message models for notification delivery via SQS.
use crate::domain::models::{
- Notification, NotificationExtEmail, RateLimitConfig, RateLimitKey, SendNotificationRequest,
+ Notification, NotificationExtEmail, NotificationTypeName, RateLimitConfig, RateLimitKey,
TaggedContent,
apple::APNSPushNotification,
email_notification_digest::{BatchSend, PushNotificationsEnabled, StateMachineDecisionA},
mobile::MessageAttributes,
+ request::SendNotificationRequest,
};
use chrono::{DateTime, Utc};
use cowlike::CowLike;
@@ -42,7 +43,7 @@ pub struct APNSTargets<T> {
}
/// Email notification payload.
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EmailContent {
/// The email subject line.
pub subject: String,
@@ -63,6 +64,7 @@ pub struct EmailNotification<'a> {
rate_limit_key: RateLimitKey,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct EmailCreateBundle {
/// The email content (subject and body).
content: EmailContent,
@@ -151,12 +153,12 @@ pub(crate) struct ConnGatewayNotification<'a, T> {
pub(crate) recipients: Vec<MacroUserIdStr<'a>>,
}
-impl<'a, T: Notification + Clone> ConnGatewayNotification<'a, T> {
+impl<'a, T: Clone> ConnGatewayNotification<'a, T> {
pub(crate) fn clone_from_request<U>(id: Uuid, req: &SendNotificationRequest<'a, T, U>) -> Self {
ConnGatewayNotification {
notif: ConnGatewayInnerNotif {
notification_id: id,
- notification_event_type: T::TYPE_NAME.to_string(),
+ notification_event_type: req.req.notification.tag.as_ref().to_string(),
entity: req.req.notification_entity.clone().into_owned(),
sent: true,
done: false,
@@ -164,7 +166,7 @@ impl<'a, T: Notification + Clone> ConnGatewayNotification<'a, T> {
viewed_at: None,
updated_at: None,
deleted_at: None,
- notification_metadata: TaggedContent::new(req.req.notification.clone()),
+ notification_metadata: req.req.notification.clone(),
sender_id: req.req.sender_id.as_ref().map(|x| x.clone().into_owned()),
},
recipients: req.req.recipient_ids.iter().cloned().collect(),
@@ -237,14 +239,29 @@ pub struct QueueMessage<'a, T, U> {
content: NotificationChannel<'a, T, U>,
}
-impl<'a, T: Notification, U> QueueMessage<'a, T, U> {
+impl<'a, T, U> QueueMessage<'a, T, U> {
/// Create a new queue message. Only valid notification types can be published.
- ///
- /// The `message_type` is derived from [`Notification::TYPE_NAME`].
- pub(crate) fn new(content: NotificationChannel<'a, T, U>) -> Self {
+ pub(crate) fn new_from_conn_gateway(content: ConnGatewayNotification<'a, T>) -> Self {
Self {
- message_type: T::TYPE_NAME.to_string(),
- content,
+ message_type: content.notif.notification_metadata.tag.as_ref().to_string(),
+ content: NotificationChannel::ConnGateway(content),
+ }
+ }
+
+ pub(crate) fn new_from_email(
+ content: EmailNotification<'a>,
+ typename: &NotificationTypeName,
+ ) -> Self {
+ Self {
+ message_type: typename.as_ref().to_string(),
+ content: NotificationChannel::Email(content),
+ }
+ }
+
+ pub(crate) fn new_from_apns(content: APNSTargets<U>, typename: &NotificationTypeName) -> Self {
+ Self {
+ message_type: typename.as_ref().to_string(),
+ content: NotificationChannel::Ios(Box::new(content)),
}
}
}
@@ -374,3 +391,34 @@ pub enum DeliveryFailure {
#[error("A delivery error occured")]
Other,
}
+
+/// Message published to the ingress SQS queue.
+///
+/// Wraps a type-erased [`SendNotificationRequest`] so callers can push
+/// notification requests to a queue without needing database or state-machine
+/// dependencies. A worker in `notification_service` picks up these messages
+/// and processes them through [`crate::domain::service::NotificationIngressService`].
+#[derive(Serialize, Deserialize)]
+pub struct IngressQueueMessage {
+ /// The type-erased notification request.
+ pub request: SendNotificationRequest<'static, serde_json::Value, serde_json::Value>,
+}
+
+impl IngressQueueMessage {
+ /// Type-erase a typed request via serde round-trip.
+ pub fn from_request<T: Serialize, U: Serialize>(
+ req: &SendNotificationRequest<'_, T, U>,
+ ) -> Result<Self, serde_json::Error> {
+ let value = serde_json::to_value(req)?;
+ let request = serde_json::from_value(value)?;
+ Ok(Self { request })
+ }
+}
+
+/// Raw message received from the ingress SQS queue.
+pub struct RawIngressQueueMessage {
+ /// The deserialized ingress queue message body.
+ pub body: IngressQueueMessage,
+ /// The receipt handle for deleting the message after processing.
+ pub receipt_handle: String,
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message/test.rs b/rust/cloud-storage/notification/src/domain/models/queue_message/test.rs
index 5c8f42fefa..e191d2601f 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
@@ -50,3 +50,51 @@ fn test_apns_targets_deserializes_with_per_user_endpoints() {
assert!(user_endpoints.digest_state.is_none());
}
}
+
+#[test]
+fn test_ingress_queue_message_round_trip() {
+ use crate::domain::models::{SendNotificationRequestBuilder, TaggedContent};
+ use model_entity::EntityType;
+ use std::collections::HashSet;
+
+ #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+ struct MyNotif {
+ msg: String,
+ }
+ impl crate::domain::models::Notification for MyNotif {
+ const TYPE_NAME: &'static str = "my_notif";
+ }
+
+ let recipient =
+ macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").unwrap();
+
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("doc_1"),
+ notification: MyNotif {
+ msg: "hello".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([recipient]),
+ }
+ .into_request()
+ .with_conn_gateway();
+
+ // Type-erase into IngressQueueMessage
+ let ingress_msg = IngressQueueMessage::from_request(&request).unwrap();
+
+ // Serialize to JSON and back
+ let json = serde_json::to_string(&ingress_msg).unwrap();
+ let deserialized: IngressQueueMessage = serde_json::from_str(&json).unwrap();
+
+ // Verify key fields survived the round-trip
+ assert_eq!(
+ deserialized.request.req.notification.tag.as_ref(),
+ "my_notif"
+ );
+ assert!(deserialized.request.send_conn_gateway);
+ assert_eq!(deserialized.request.req.recipient_ids.len(), 1);
+ assert_eq!(
+ deserialized.request.req.notification.content["msg"],
+ "hello"
+ );
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rs
index 8a384e936b..7270a7b201 100644
--- a/rust/cloud-storage/notification/src/domain/models/request.rs
+++ b/rust/cloud-storage/notification/src/domain/models/request.rs
@@ -2,7 +2,7 @@
use crate::domain::models::{
ExclusionReason, FilteredRecipient, Notification, NotificationExtEmail, NotificationExtIos,
- RecipientExclusion,
+ RecipientExclusion, TaggedContent,
apple::APNSPushNotification,
mobile::{self, MessageAttributes},
queue_message::EmailCreateBundle,
@@ -20,7 +20,6 @@ use uuid::Uuid;
/// Generic over the notification payload type `T`, which must implement
/// the `Notification` trait. The event type is derived from `T::TYPE_NAME`.
#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(bound = "T: Notification")]
pub struct SendNotificationRequestBuilder<'a, T> {
/// The entity associated with this notification (e.g., Channel, Team, Document).
pub notification_entity: Entity<'a>,
@@ -32,11 +31,26 @@ pub struct SendNotificationRequestBuilder<'a, T> {
pub recipient_ids: HashSet<MacroUserIdStr<'a>>,
}
-impl<'a, T> SendNotificationRequestBuilder<'a, T> {
+impl<'a, T> SendNotificationRequestBuilder<'a, T>
+where
+ T: Notification,
+{
/// Convert this builder into a full request with optional delivery customizers.
pub fn into_request(self) -> SendNotificationRequest<'a, T, ()> {
+ let SendNotificationRequestBuilder {
+ notification_entity,
+ notification,
+ sender_id,
+ recipient_ids,
+ } = self;
SendNotificationRequest {
- req: self,
+ uuid_to_write: Uuid::now_v7(),
+ req: SendNotificationRequestBuilder {
+ notification_entity,
+ notification: TaggedContent::new(notification),
+ sender_id,
+ recipient_ids,
+ },
build_apns: None,
build_email: None,
send_conn_gateway: false,
@@ -44,21 +58,25 @@ impl<'a, T> SendNotificationRequestBuilder<'a, T> {
}
}
-type BuildApns<T, U> =
- Box<dyn FnMut(T, uuid::Uuid) -> Option<(APNSPushNotification<U>, MessageAttributes)> + Send>;
-
-type BuildEmail<T> = Box<dyn FnMut(&T) -> EmailCreateBundle + Send>;
+#[derive(Debug, Serialize, Deserialize)]
+pub(crate) struct BuildApnsOutput<U> {
+ pub(crate) notif: APNSPushNotification<U>,
+ pub(crate) attr: MessageAttributes,
+}
/// Full notification request with optional delivery channel builders.
///
/// Created from [`SendNotificationRequestBuilder::into_request`] and can be
/// customized with APNS and email builders.
+#[derive(Serialize, Deserialize)]
pub struct SendNotificationRequest<'a, T, U> {
- pub(crate) req: SendNotificationRequestBuilder<'a, T>,
+ pub(crate) req: SendNotificationRequestBuilder<'a, TaggedContent<T>>,
+ /// the uuid that will be written to db as PK
+ pub(crate) uuid_to_write: Uuid,
/// define how to turn t into an APNSPushNotitication T to be sent to ios
- pub(crate) build_apns: Option<BuildApns<T, U>>,
+ pub(crate) build_apns: Option<BuildApnsOutput<U>>,
/// define how to turn T into an email content to be sent as an email
- pub(crate) build_email: Option<BuildEmail<T>>,
+ pub(crate) build_email: Option<EmailCreateBundle>,
/// connection gateway accepts arbitrary json so we just ask if its enabled or not
pub(crate) send_conn_gateway: bool,
}
@@ -70,24 +88,36 @@ impl<'a, T: NotificationExtIos, U> SendNotificationRequest<'a, T, U> {
req,
build_apns: _,
build_email,
+ uuid_to_write,
send_conn_gateway,
} = self;
let sender = req.sender_id.clone().map(CowLike::into_owned);
let entity = req.notification_entity.clone().into_owned();
+ let collapse_key = req
+ .notification
+ .content
+ .collapse_key(&entity)
+ .into_hashed()
+ .into_inner();
+ let attrs = MessageAttributes {
+ push_type: mobile::PushType::Alert,
+ collapse_key,
+ };
+ let build_apns = req
+ .notification
+ .content
+ .as_apns(sender.clone(), &entity, uuid_to_write)
+ .map(|apns| BuildApnsOutput {
+ notif: apns,
+ attr: attrs,
+ });
+
SendNotificationRequest {
req,
- build_apns: Some(Box::new(move |notif: T, notification_id: uuid::Uuid| {
- let collapse_key = notif.collapse_key(&entity).into_hashed().into_inner();
- let attrs = MessageAttributes {
- push_type: mobile::PushType::Alert,
- collapse_key,
- };
- let apns = notif.into_apns(sender.clone(), &entity, notification_id)?;
-
- Some((apns, attrs))
- })),
+ uuid_to_write,
+ build_apns,
build_email,
send_conn_gateway,
}
@@ -97,7 +127,7 @@ impl<'a, T: NotificationExtIos, U> SendNotificationRequest<'a, T, U> {
impl<'a, T: NotificationExtEmail, U> SendNotificationRequest<'a, T, U> {
/// Add a custom email content builder.
pub fn with_email(mut self) -> Self {
- self.build_email = Some(Box::new(|notif: &T| EmailCreateBundle::new(notif)));
+ self.build_email = Some(EmailCreateBundle::new(&self.req.notification.content));
self
}
}
diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rs
index 203aead32e..dae4d034bc 100644
--- a/rust/cloud-storage/notification/src/domain/ports.rs
+++ b/rust/cloud-storage/notification/src/domain/ports.rs
@@ -15,14 +15,14 @@ use uuid::Uuid;
use models_pagination::{CreatedAt, Query};
+use crate::domain::models::TaggedContent;
use crate::domain::models::device::DeviceType;
use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};
use crate::domain::models::{
- DeviceEndpoint, Notification, NotificationExtEmail, NotificationIdAndCollapseKey,
- RateLimitConfig, RateLimitKey, RateLimitResult, SendNotificationRequestBuilder,
- UserNotificationRow, android::FCMMessage, apple::APNSPushNotification,
- mobile::MessageAttributes,
+ DeviceEndpoint, NotificationExtEmail, NotificationIdAndCollapseKey, RateLimitConfig,
+ RateLimitKey, RateLimitResult, SendNotificationRequestBuilder, UserNotificationRow,
+ android::FCMMessage, apple::APNSPushNotification, mobile::MessageAttributes,
};
/// Port for sending mobile push notifications (iOS/Android via SNS).
@@ -80,9 +80,9 @@ pub trait NotificationRepository: Send + Sync + 'static {
///
/// Returns the notification ID if successful, or None if it already exists
/// (idempotent operation).
- fn create_notification<'a, T: Notification + Send + Sync>(
+ fn create_notification<'a, T: Serialize + Send + Sync>(
&self,
- request: SendNotificationRequestBuilder<'a, T>,
+ request: SendNotificationRequestBuilder<'a, TaggedContent<T>>,
notification_id: Uuid,
service_sender: &str,
apns_collapse_key: Option<&str>,
@@ -233,14 +233,16 @@ pub trait EmailSender: Send + Sync + 'static {
}
use crate::domain::models::push_notification_event::RawPushNotificationEventMessage;
-use crate::domain::models::queue_message::{DeliverySuccess, QueueMessage, RawQueueMessage};
+use crate::domain::models::queue_message::{
+ DeliverySuccess, IngressQueueMessage, QueueMessage, RawIngressQueueMessage, RawQueueMessage,
+};
/// 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<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(
&self,
- messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,
+ messages: Vec<QueueMessage<'a, T, U>>,
) -> impl Future<Output = Result<(), Report>> + Send;
/// Receive messages from the queue (for worker).
@@ -267,10 +269,10 @@ pub trait NotificationEgress: Send + Sync + 'static {
-> impl Future<Output = Vec<Result<DeliverySuccess, Report>>> + Send;
/// Poll for ready digest batches, template them as emails, and send.
- fn poll_email_digests<T: NotificationExtEmail>(
- &self,
+ fn poll_email_digests<'a, T: NotificationExtEmail>(
+ &'a self,
f: fn(DigestBatch) -> Result<T, Report>,
- ) -> impl Future<Output = Result<ClaimResult<()>, Report>> + Send;
+ ) -> impl Future<Output = Result<ClaimResult<()>, Report>> + Send + 'a;
}
/// Port for SNS platform endpoint management (create, get/set attributes).
@@ -317,3 +319,27 @@ pub trait PushNotificationEventQueue: Send + Sync + 'static {
receipt_handle: &str,
) -> impl Future<Output = Result<(), Report>> + Send;
}
+
+/// Port for publishing and consuming notification requests on the ingress queue.
+///
+/// This is separate from [`NotificationQueue`] (the delivery queue).
+/// The ingress queue carries type-erased [`IngressQueueMessage`] payloads
+/// that are processed by the ingress worker inside `notification_service`.
+pub trait NotificationIngressQueue: Send + Sync + 'static {
+ /// Publish a notification request to the ingress queue.
+ fn publish(
+ &self,
+ message: IngressQueueMessage,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+
+ /// Receive messages from the ingress queue.
+ fn receive_messages(
+ &self,
+ ) -> impl Future<Output = Result<Vec<RawIngressQueueMessage>, Report>> + Send;
+
+ /// Delete a message from the ingress queue after successful processing.
+ fn delete_message(
+ &self,
+ receipt_handle: &str,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+}
diff --git a/rust/cloud-storage/notification/src/domain/service.rs b/rust/cloud-storage/notification/src/domain/service.rs
index 4bea539efd..f0c6a9cdf1 100644
--- a/rust/cloud-storage/notification/src/domain/service.rs
+++ b/rust/cloud-storage/notification/src/domain/service.rs
@@ -19,6 +19,7 @@ pub use ingress::NotificationIngressService;
pub use ingress::NotificationReader;
pub use ingress::NotificationReaderService;
pub use ingress::PlatformArnConfig;
+pub use ingress::SqsNotificationIngress;
pub use push_notification_event::PushNotificationEventHandler;
pub use push_notification_event::PushNotificationEventService;
diff --git a/rust/cloud-storage/notification/src/domain/service/device/test.rs b/rust/cloud-storage/notification/src/domain/service/device/test.rs
index 84f635fd88..a3f98ec59e 100644
--- a/rust/cloud-storage/notification/src/domain/service/device/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/device/test.rs
@@ -1,9 +1,11 @@
use crate::domain::models::device::DeviceType;
+use crate::domain::models::queue_message::QueueMessage;
use crate::domain::ports::{NotificationQueue, NotificationRepository, SnsEndpointManager};
use crate::domain::service::NotificationReader;
use crate::domain::service::ingress::{NotificationReaderService, PlatformArnConfig};
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::Report;
+use serde::Serialize;
use std::collections::HashMap;
use std::sync::Mutex;
@@ -94,9 +96,12 @@ impl NotificationRepository for MockNotifRepo {
{
unimplemented!()
}
- async fn create_notification<'a, T: crate::domain::models::Notification + Send + Sync>(
+ async fn create_notification<'a, T: Serialize + Send + Sync>(
&self,
- _: crate::domain::models::SendNotificationRequestBuilder<'a, T>,
+ _: crate::domain::models::SendNotificationRequestBuilder<
+ 'a,
+ crate::domain::models::TaggedContent<T>,
+ >,
_: uuid::Uuid,
_: &str,
_: Option<&str>,
@@ -271,7 +276,7 @@ struct MockQueue;
impl NotificationQueue for MockQueue {
async fn publish<'a, T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(
&self,
- _: impl Iterator<Item = crate::domain::models::queue_message::QueueMessage<'a, T, U>> + Send,
+ _: Vec<QueueMessage<'a, T, U>>,
) -> Result<(), Report> {
Ok(())
}
diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rs
index 71e08efe9c..342da52297 100644
--- a/rust/cloud-storage/notification/src/domain/service/egress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs
@@ -17,15 +17,18 @@ use crate::domain::models::queue_message::{
APNSTargets, ConnGatewayNotification, DeliveryFailure, DeliverySuccess, EmailCreateBundle,
EmailNotification, NotificationChannel, QueueMessage,
};
-use crate::domain::models::{NotificationExtEmail, RateLimitResult};
+use crate::domain::models::{NotificationExtEmail, NotificationTypeName, RateLimitResult};
use crate::domain::ports::{
EmailSender, NotificationEgress, NotificationQueue, NotificationRepository, NotificationSender,
RateLimitPort, WebSocketSender,
};
use either::Either;
use futures::stream::{FuturesUnordered, StreamExt};
+use macro_user_id::email::ReadEmailParts;
+use macro_user_id::user_id::MacroUserIdStr;
use rootcause::prelude::ResultExt;
use rootcause::{Report, report};
+use tracing::Level;
/// Maximum time to wait for a single notification delivery before timing out.
pub(crate) const DELIVERY_TIMEOUT: Duration = Duration::from_secs(15);
@@ -95,6 +98,7 @@ where
/// on failure. Returns a list of results for each delivery attempt.
///
/// If a rate limit is configured and exceeded, returns an empty list (no delivery).
+ #[tracing::instrument(ret, level = Level::INFO, skip(self))]
pub async fn deliver_notification(
&self,
message: QueueMessage<'static, serde_json::Value, serde_json::Value>,
@@ -286,29 +290,36 @@ where
results
}
- #[tracing::instrument(err, skip(self))]
+ // #[tracing::instrument(err, skip(self))]
async fn poll_email_digests<T: NotificationExtEmail>(
&self,
f: fn(DigestBatch) -> Result<T, Report>,
) -> Result<ClaimResult<()>, Report> {
- let batch = match self.digest_batcher.claim_ready_digest().await? {
- ClaimResult::Ready(batch) => batch,
- v @ ClaimResult::Empty | v @ ClaimResult::Wait(_) => return Ok(v.map(|_| ())),
- };
+ let batch =
+ match tokio::time::timeout(DELIVERY_TIMEOUT, self.digest_batcher.claim_ready_digest())
+ .await
+ .context("Dequeing redis batch exceeded timeout")??
+ {
+ ClaimResult::Ready(batch) => batch,
+ v @ ClaimResult::Empty | v @ ClaimResult::Wait(_) => return Ok(v.map(|_| ())),
+ };
+
+ if batch.user_id.email_part().domain_part() != "macro.com" {
+ return Err(report!(
+ "Sending digest for non-macro user is currently disabled"
+ ));
+ }
- let recipient = batch.user_id.clone();
- let email_notif: T = f(batch)?;
+ let recipient: MacroUserIdStr<'static> = batch.user_id.clone();
+ let email_notif = f(batch)?;
let email_content = EmailCreateBundle::new(&email_notif).with_recipient(recipient);
- let message: QueueMessage<'_, T, ()> =
- QueueMessage::new(NotificationChannel::Email(email_content));
+ let typename = NotificationTypeName::new_from_notif(&email_notif);
- self.queue
- .publish(std::iter::once(message))
- .await
- .inspect_err(|e| {
- tracing::error!(error=?e, "failed to queue digest email");
- })?;
+ let message: QueueMessage<'static, T, ()> =
+ QueueMessage::new_from_email(email_content, &typename);
+
+ self.queue.publish(vec![message]).await?;
Ok(ClaimResult::Ready(()))
}
diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rs
index c1f1f3aa58..912462967b 100644
--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs
@@ -7,17 +7,21 @@ use crate::domain::models::apple::{APNSPushNotification, Aps};
use crate::domain::models::device::DeviceType;
use crate::domain::models::email_notification_digest::BulkDigestStateMachine;
use crate::domain::models::mobile::{MessageAttributes, PushType};
+use crate::domain::models::queue_message::IngressQueueMessage;
use crate::domain::models::queue_message::{
- APNSTargets, ClearPushIdentifier, ConnGatewayNotification, NotificationChannel, QueueMessage,
+ APNSTargets, ClearPushIdentifier, ConnGatewayNotification, QueueMessage,
QueueMessageNeedsStateMachine, UserApnsEndpoints,
};
use crate::domain::models::request::{
- GetNotificationsByEventItemIdsRequest, NotificationStatus, UpdateNotificationsRequest,
+ BuildApnsOutput, GetNotificationsByEventItemIdsRequest, NotificationStatus,
+ SendNotificationRequest, UpdateNotificationsRequest,
};
use crate::domain::models::{
- DeviceEndpoint, Notification, NotificationResult, SendNotificationRequest, UserNotificationRow,
+ DeviceEndpoint, Notification, NotificationResult, NotificationTypeName, UserNotificationRow,
+};
+use crate::domain::ports::{
+ NotificationIngressQueue, NotificationQueue, NotificationRepository, SnsEndpointManager,
};
-use crate::domain::ports::{NotificationQueue, NotificationRepository, SnsEndpointManager};
use crate::domain::service::SendNotificationError;
use ::futures::future::join_all;
use macro_user_id::cowlike::CowLike;
@@ -169,12 +173,13 @@ where
/// 4. Return result (delivery happens async via worker)
async fn send_notification_impl<
'a,
- T: Notification + Clone + 'static,
+ T: Clone + Serialize + Send + Sync + 'static,
U: Serialize + Send + Sync + 'static,
>(
&'a self,
request: SendNotificationRequest<'a, T, U>,
) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {
+ let notification_id = request.uuid_to_write;
let mut request = self
.filter_recipients(request)
.await
@@ -184,7 +189,6 @@ where
return Ok(None);
}
- let notification_id = Uuid::now_v7();
let (queue_messages, apns_collapse_key) = self
.build_queue_message(notification_id, &mut request)
.await?;
@@ -218,7 +222,7 @@ where
.await;
self.queue
- .publish(queue_messages.with_state_decisions(results))
+ .publish(queue_messages.with_state_decisions(results).collect())
.await
.context(SendNotificationError::Other)?;
@@ -256,7 +260,11 @@ where
/// - `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>(
+ async fn build_queue_message<
+ 'a,
+ T: Clone + Serialize + Send + Sync,
+ U: Serialize + Send + Sync,
+ >(
&self,
notification_id: Uuid,
notification: &mut SendNotificationRequest<'a, T, U>,
@@ -266,16 +274,17 @@ where
> {
let mut messages = Vec::new();
let mut apns_collapse_key = None;
+ let typename = &notification.req.notification.tag;
// Connection gateway: 1:M (single message for all recipients)
if notification.send_conn_gateway {
- messages.push(QueueMessage::new(NotificationChannel::ConnGateway(
+ messages.push(QueueMessage::new_from_conn_gateway(
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 {
+ if let Some(build_apns) = notification.build_apns.take() {
let recipients_vec: Vec<_> = notification.req.recipient_ids.iter().cloned().collect();
let device_endpoints = self
.repository
@@ -307,28 +316,28 @@ where
})
.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::new(NotificationChannel::Ios(Box::new(
+ if !ios_endpoints.is_empty() {
+ let BuildApnsOutput { notif, attr } = build_apns;
+ apns_collapse_key = Some(attr.collapse_key.clone());
+ messages.push(QueueMessage::new_from_apns(
APNSTargets {
- notif: apns_notif,
- attributes,
+ notif,
+ attributes: attr,
ios_device_endpoints: ios_endpoints,
},
- ))));
+ typename,
+ ));
}
}
// Email: 1:1 (one message per recipient)
- if let Some(ref mut build_email) = notification.build_email {
+ if let Some(ref build_email) = notification.build_email {
for recipient in &notification.req.recipient_ids {
- let email_content = build_email(&notification.req.notification);
- messages.push(QueueMessage::new(NotificationChannel::Email(
+ let email_content = build_email.clone();
+ messages.push(QueueMessage::new_from_email(
email_content.with_recipient(recipient.clone()),
- )));
+ typename,
+ ));
}
}
@@ -337,6 +346,57 @@ where
apns_collapse_key,
))
}
+
+ /// Process a type-erased notification request from the ingress queue.
+ ///
+ /// This accepts `serde_json::Value` types (deserialized from the ingress
+ /// queue) and calls `send_notification_impl` directly, bypassing the
+ /// `T: Notification` trait bound on the public trait method.
+ pub async fn process_from_queue<'a>(
+ &'a self,
+ request: SendNotificationRequest<'a, serde_json::Value, serde_json::Value>,
+ ) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {
+ self.send_notification_impl(request).await
+ }
+}
+
+/// A lightweight [`NotificationIngress`] implementation that serializes
+/// the request and publishes to an ingress queue.
+///
+/// Callers only need a queue client — no database, Redis, or state-machine
+/// dependencies. A worker in `notification_service` picks up messages from
+/// this queue and processes them through [`NotificationIngressService`].
+///
+/// `send_notification` always returns `Ok(None)` because the actual
+/// processing is deferred to the worker.
+pub struct SqsNotificationIngress<Q> {
+ queue: Q,
+}
+
+impl<Q> SqsNotificationIngress<Q> {
+ /// Create a new queue-backed notification ingress.
+ pub fn new(queue: Q) -> Self {
+ Self { queue }
+ }
+}
+
+impl<Q: NotificationIngressQueue> NotificationIngress for SqsNotificationIngress<Q> {
+ async fn send_notification<
+ 'a,
+ T: Notification + Clone + 'static,
+ U: Serialize + Send + Sync + 'static,
+ >(
+ &'a self,
+ req: SendNotificationRequest<'a, T, U>,
+ ) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {
+ let message =
+ IngressQueueMessage::from_request(&req).context(SendNotificationError::Other)?;
+ self.queue
+ .publish(message)
+ .await
+ .context(SendNotificationError::Other)?;
+ Ok(None)
+ }
}
/// Configuration for SNS platform ARNs.
@@ -456,27 +516,35 @@ where
.into_iter()
.map(|n| {
let collapse_key = n.apns_collapse_key;
- QueueMessage::new(NotificationChannel::Ios(Box::new(APNSTargets {
- notif: APNSPushNotification {
- aps: Aps {
- content_available: Some(1),
- sound: None,
- ..Default::default()
+
+ let notif = ClearPushIdentifier {
+ identifier: collapse_key.clone(),
+ };
+
+ let typename = NotificationTypeName::new_from_notif(&notif);
+
+ QueueMessage::new_from_apns(
+ APNSTargets {
+ notif: APNSPushNotification {
+ aps: Aps {
+ content_available: Some(1),
+ sound: None,
+ ..Default::default()
+ },
+ push_notification_data: notif.clone(),
},
- push_notification_data: ClearPushIdentifier {
- identifier: collapse_key.clone(),
+ attributes: MessageAttributes {
+ push_type: PushType::Background,
+ collapse_key,
},
+ ios_device_endpoints: ios_endpoints.clone(),
},
- attributes: MessageAttributes {
- push_type: PushType::Background,
- collapse_key,
- },
- ios_device_endpoints: ios_endpoints.clone(),
- })))
+ &typename,
+ )
})
.collect();
- self.queue.publish(messages.into_iter()).await?;
+ self.queue.publish(messages).await?;
Ok(())
}
diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
index eab3b61108..918c3a84bb 100644
--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
@@ -6,6 +6,7 @@ use crate::domain::models::email_notification_digest::{
use crate::domain::models::push_notification_event::{EventType, SnsPushNotificationEvent};
use crate::domain::ports::{NotificationRepository, SnsEndpointManager};
use rootcause::Report;
+use serde::Serialize;
use std::collections::HashMap;
use std::sync::Mutex;
@@ -62,9 +63,12 @@ impl NotificationRepository for MockNotifRepo {
{
unimplemented!()
}
- async fn create_notification<'a, T: crate::domain::models::Notification + Send + Sync>(
+ async fn create_notification<'a, T: Serialize + Send + Sync>(
&self,
- _: crate::domain::models::SendNotificationRequestBuilder<'a, T>,
+ _: crate::domain::models::SendNotificationRequestBuilder<
+ 'a,
+ crate::domain::models::TaggedContent<T>,
+ >,
_: uuid::Uuid,
_: &str,
_: Option<&str>,
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
index d62ec9f8fa..9fdcb8145a 100644
--- a/rust/cloud-storage/notification/src/domain/service/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -53,15 +53,15 @@ impl NotificationExtIos for TestNotification {
NotifCollapseKey::new("test")
}
- fn into_apns<'a>(
- self,
+ fn as_apns<'a>(
+ &self,
_sender: Option<MacroUserIdStr<'a>>,
_entity: &model_entity::Entity<'_>,
_notification_id: uuid::Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
Some(APNSPushNotification {
aps: Default::default(),
- push_notification_data: self,
+ push_notification_data: self.clone(),
})
}
}
@@ -151,7 +151,7 @@ impl MockRepository {
struct MockStateMachine;
impl BulkDigestStateMachine for MockStateMachine {
- async fn ingest<T: Notification + 'static>(
+ async fn ingest<T: Serialize + Send + Sync + 'static>(
&self,
_notif: UserNotificationRow<Arc<T>>,
) -> Result<crate::domain::models::email_notification_digest::StateMachineDecisionA<T>, Report>
@@ -176,9 +176,9 @@ impl NotificationRepository for MockRepository {
Ok(self.unsubscribed_users.clone())
}
- async fn create_notification<'a, T: Notification + Send + Sync>(
+ async fn create_notification<'a, T: Serialize + Send + Sync>(
&self,
- request: SendNotificationRequestBuilder<'a, T>,
+ request: SendNotificationRequestBuilder<'a, TaggedContent<T>>,
notification_id: Uuid,
_service_sender: &str,
apns_collapse_key: Option<&str>,
@@ -193,14 +193,14 @@ impl NotificationRepository for MockRepository {
.push((notification_id, apns_collapse_key.map(String::from)));
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 notification_metadata = Arc::new(request.notification.content);
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(),
+ notification_event_type: request.notification.tag.as_ref().to_string(),
entity: entity.clone(),
sent: false,
done: false,
@@ -356,9 +356,9 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
(**self).get_unsubscribed_users(item_id, user_ids).await
}
- async fn create_notification<'a, T: Notification + Send + Sync>(
+ async fn create_notification<'a, T: Serialize + Send + Sync>(
&self,
- request: SendNotificationRequestBuilder<'a, T>,
+ request: SendNotificationRequestBuilder<'a, TaggedContent<T>>,
notification_id: Uuid,
service_sender: &str,
apns_collapse_key: Option<&str>,
@@ -523,7 +523,7 @@ impl MockQueue {
impl NotificationQueue for MockQueue {
async fn publish<'a, T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(
&self,
- messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,
+ messages: Vec<QueueMessage<'a, T, U>>,
) -> Result<(), Report> {
let mut published = self.published.lock().unwrap();
for message in messages {
@@ -545,7 +545,7 @@ impl NotificationQueue for MockQueue {
impl NotificationQueue for std::sync::Arc<MockQueue> {
async fn publish<'a, T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(
&self,
- messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,
+ messages: Vec<QueueMessage<'a, T, U>>,
) -> Result<(), Report> {
(**self).publish(messages).await
}
@@ -1687,7 +1687,7 @@ impl DigestBatcher for ReadyDigestBatcher {
async fn test_poll_email_digests_sends_email_for_ready_batch() {
use std::sync::Arc;
- let user = test_user_id("[email protected]");
+ let user = test_user_id("[email protected]");
let notif = UserNotificationRow {
owner_id: user.clone(),
notification_id: Uuid::nil(),
@@ -1740,6 +1740,64 @@ async fn test_poll_email_digests_sends_email_for_ready_batch() {
assert!(published[0]["content"]["Email"].is_object());
}
+/// temporary test which asserts we can't send to external users
+/// This test should be removed in the future
+#[tokio::test]
+async fn it_fails_to_send_to_non_macro_users() {
+ use std::sync::Arc;
+
+ let user = test_user_id("[email protected]");
+ let notif = UserNotificationRow {
+ owner_id: user.clone(),
+ notification_id: Uuid::nil(),
+ notification_event_type: "test_notification".to_string(),
+ entity: EntityType::Document.with_entity_str("doc-1"),
+ sent: false,
+ done: false,
+ created_at: None,
+ viewed_at: None,
+ updated_at: None,
+ deleted_at: None,
+ notification_metadata: serde_json::to_value(TestNotification {
+ message: "hello from digest".to_string(),
+ })
+ .unwrap(),
+ sender_id: None,
+ };
+
+ let batch = DigestBatch {
+ user_id: user.clone(),
+ notifications: vec![notif.into_tagged()],
+ };
+
+ let batcher = ReadyDigestBatcher {
+ batch: Mutex::new(Some(batch)),
+ };
+
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationEgressService {
+ queue: queue.clone(),
+ repository: MockRepository::new(),
+ websocket: MockWebSocketSender,
+ mobile: MockMobileSender,
+ email: MockEmailSender,
+ rate_limiter: MockRateLimiter::allowing(),
+ state_machine: MockEgressStateMachine,
+ digest_batcher: batcher,
+ };
+
+ fn digest_to_notif(batch: DigestBatch) -> Result<TestNotification, Report> {
+ Ok(TestNotification {
+ message: format!("You have {} notification(s)", batch.notifications.len()),
+ })
+ }
+
+ service
+ .poll_email_digests(digest_to_notif)
+ .await
+ .unwrap_err();
+}
+
#[tokio::test]
async fn test_poll_email_digests_noop_when_empty() {
let service = create_egress_service(MockRateLimiter::allowing());
@@ -1778,7 +1836,7 @@ impl EgressTestQueue {
impl NotificationQueue for EgressTestQueue {
async fn publish<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(
&self,
- _messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,
+ _messages: Vec<QueueMessage<'a, T, U>>,
) -> Result<(), Report> {
Ok(())
}
@@ -1951,6 +2009,133 @@ async fn test_poll_and_deliver_deletes_message_when_all_ios_failures() {
);
}
+// ============================================================================
+// Ingress Queue Tests (SqsNotificationIngress + process_from_queue)
+// ============================================================================
+
+/// Mock ingress queue that tracks published messages.
+struct MockIngressQueue {
+ published: Mutex<Vec<crate::domain::models::queue_message::IngressQueueMessage>>,
+}
+
+impl MockIngressQueue {
+ fn new() -> Self {
+ Self {
+ published: Mutex::new(Vec::new()),
+ }
+ }
+
+ fn get_published_count(&self) -> usize {
+ self.published.lock().unwrap().len()
+ }
+}
+
+impl crate::domain::ports::NotificationIngressQueue for MockIngressQueue {
+ async fn publish(
+ &self,
+ message: crate::domain::models::queue_message::IngressQueueMessage,
+ ) -> Result<(), Report> {
+ self.published.lock().unwrap().push(message);
+ Ok(())
+ }
+
+ async fn receive_messages(
+ &self,
+ ) -> Result<Vec<crate::domain::models::queue_message::RawIngressQueueMessage>, Report> {
+ Ok(Vec::new())
+ }
+
+ async fn delete_message(&self, _receipt_handle: &str) -> Result<(), Report> {
+ Ok(())
+ }
+}
+
+impl crate::domain::ports::NotificationIngressQueue for Arc<MockIngressQueue> {
+ async fn publish(
+ &self,
+ message: crate::domain::models::queue_message::IngressQueueMessage,
+ ) -> Result<(), Report> {
+ (**self).publish(message).await
+ }
+
+ async fn receive_messages(
+ &self,
+ ) -> Result<Vec<crate::domain::models::queue_message::RawIngressQueueMessage>, Report> {
+ (**self).receive_messages().await
+ }
+
+ async fn delete_message(&self, receipt_handle: &str) -> Result<(), Report> {
+ (**self).delete_message(receipt_handle).await
+ }
+}
+
+#[tokio::test]
+async fn test_sqs_notification_ingress_publishes_to_queue() {
+ use crate::domain::service::SqsNotificationIngress;
+
+ let queue = Arc::new(MockIngressQueue::new());
+ let ingress = SqsNotificationIngress::new(queue.clone());
+
+ let recipient = test_user_id("[email protected]");
+ let request = SendNotificationRequestBuilder {
+ notification_entity: model_entity::EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello via queue".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([recipient]),
+ }
+ .into_request()
+ .with_conn_gateway();
+
+ let result = ingress.send_notification(request).await.unwrap();
+
+ // SqsNotificationIngress always returns Ok(None)
+ assert!(result.is_none());
+
+ // Verify message was published to the queue
+ assert_eq!(queue.get_published_count(), 1);
+}
+
+#[tokio::test]
+async fn test_process_from_queue_with_value_types() {
+ let queue = Arc::new(MockQueue::new());
+ let service =
+ NotificationIngressService::new(MockRepository::new(), queue.clone(), MockStateMachine);
+
+ let recipient = test_user_id("[email protected]");
+
+ // Build a typed request, then type-erase it through IngressQueueMessage
+ let typed_request = SendNotificationRequestBuilder {
+ notification_entity: model_entity::EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello from queue".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([recipient.clone()]),
+ }
+ .into_request()
+ .with_conn_gateway();
+
+ let ingress_msg =
+ crate::domain::models::queue_message::IngressQueueMessage::from_request(&typed_request)
+ .unwrap();
+
+ // Process the type-erased request
+ let result = service
+ .process_from_queue(ingress_msg.request)
+ .await
+ .unwrap()
+ .unwrap();
+
+ assert!(result.notified_recipients.contains(&recipient));
+
+ // Verify a queue message was published to the delivery queue
+ let published = queue.get_published();
+ assert_eq!(published.len(), 1);
+ assert!(published[0]["content"]["ConnGateway"].is_object());
+}
+
impl NotificationSender for std::sync::Arc<TrackingMobileSender> {
async fn send_ios_push_notification<T: Serialize + Send + Sync>(
&self,
diff --git a/rust/cloud-storage/notification/src/inbound.rs b/rust/cloud-storage/notification/src/inbound.rs
index 29c492e62e..872de00897 100644
--- a/rust/cloud-storage/notification/src/inbound.rs
+++ b/rust/cloud-storage/notification/src/inbound.rs
@@ -2,5 +2,9 @@
pub mod ai_tool;
#[cfg(feature = "axum")]
pub mod http;
+/// Worker for processing notification requests from the ingress queue.
+pub mod ingress_worker;
+/// Worker for processing push notification delivery events.
pub mod push_notification_event_worker;
+/// Worker for delivering notifications from the delivery queue.
pub mod worker;
diff --git a/rust/cloud-storage/notification/src/inbound/ingress_worker.rs b/rust/cloud-storage/notification/src/inbound/ingress_worker.rs
new file mode 100644
index 0000000000..e48affdb1e
--- /dev/null
+++ b/rust/cloud-storage/notification/src/inbound/ingress_worker.rs
@@ -0,0 +1,80 @@
+//! Worker for processing notification ingress messages from a queue.
+//!
+//! This worker picks up [`IngressQueueMessage`] messages from the ingress SQS
+//! queue, deserializes them, and processes them through
+//! [`NotificationIngressService::process_from_queue`].
+
+use crate::domain::models::email_notification_digest::BulkDigestStateMachine;
+use crate::domain::ports::{NotificationIngressQueue, NotificationQueue, NotificationRepository};
+use crate::domain::service::NotificationIngressService;
+use std::time::Duration;
+
+/// Worker that processes notification requests from the ingress queue.
+///
+/// Polls the ingress queue for [`IngressQueueMessage`] messages, deserializes
+/// them, and processes each through [`NotificationIngressService::process_from_queue`].
+/// Successfully processed messages are deleted from the queue; failures are left
+/// for SQS retry via visibility timeout.
+pub struct IngressWorker<N, Q, S, IQ> {
+ service: NotificationIngressService<N, Q, S>,
+ queue: IQ,
+}
+
+impl<N, Q, S, IQ> IngressWorker<N, Q, S, IQ>
+where
+ N: NotificationRepository,
+ Q: NotificationQueue,
+ S: BulkDigestStateMachine,
+ IQ: NotificationIngressQueue,
+{
+ /// Create a new ingress worker.
+ pub fn new(service: NotificationIngressService<N, Q, S>, queue: IQ) -> Self {
+ Self { service, queue }
+ }
+
+ /// Run the worker loop continuously.
+ ///
+ /// This method runs forever, polling the ingress queue and processing
+ /// messages. It includes a small delay between empty polls to avoid
+ /// hammering the queue.
+ pub async fn run(&self) -> ! {
+ loop {
+ match self.queue.receive_messages().await {
+ Ok(messages) if messages.is_empty() => {
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
+ }
+ Ok(messages) => {
+ let count = messages.len();
+ for message in messages {
+ match tokio::time::timeout(
+ Duration::from_secs(15),
+ self.service.process_from_queue(message.body.request),
+ )
+ .await
+ {
+ Ok(Ok(_)) => {
+ if let Err(e) =
+ self.queue.delete_message(&message.receipt_handle).await
+ {
+ tracing::error!(error=?e, "failed to delete ingress message");
+ }
+ }
+ Err(timeout) => {
+ tracing::warn!("Exceeded processing timeout {timeout}");
+ }
+
+ Ok(Err(e)) => {
+ tracing::error!(error=?e, "failed to process ingress notification");
+ }
+ }
+ }
+ tracing::debug!(count, "processed ingress messages");
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "failed to receive ingress messages");
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
+ }
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/notification/src/inbound/worker.rs b/rust/cloud-storage/notification/src/inbound/worker.rs
index 5e75d67aa7..9163a0dee9 100644
--- a/rust/cloud-storage/notification/src/inbound/worker.rs
+++ b/rust/cloud-storage/notification/src/inbound/worker.rs
@@ -4,7 +4,17 @@
//! and persisted. The main work (rate limiting, filtering) is done pre-queue,
//! so this worker focuses on delivery.
-use crate::domain::ports::NotificationEgress;
+use std::time::Duration;
+
+use rootcause::Report;
+
+use crate::domain::{
+ models::{
+ NotificationExtEmail,
+ email_notification_digest::ports::{ClaimResult, DigestBatch},
+ },
+ ports::NotificationEgress,
+};
/// Worker that processes notifications from the queue and delivers them.
///
@@ -27,7 +37,7 @@ where
///
/// Polls the queue and delivers notifications. Returns the number of
/// delivery results (may include failures).
- async fn poll_and_process(&self) -> usize {
+ async fn poll_and_process_notifications(&self) -> usize {
let results = self.service.poll_and_deliver().await;
let count = results.len();
@@ -45,9 +55,9 @@ where
///
/// This method runs forever, polling the queue and processing messages.
/// It includes a small delay between empty polls to avoid hammering the queue.
- pub async fn run(&self) -> ! {
+ pub async fn run_notifications(&self) -> ! {
loop {
- let count = self.poll_and_process().await;
+ let count = self.poll_and_process_notifications().await;
if count == 0 {
// No messages, wait a bit before next poll
@@ -57,4 +67,22 @@ where
}
}
}
+
+ /// runs the digest worker forever which will pick digest batch messages out of redis
+ /// template them into emails via the templater fn f
+ /// then place the formatted messages into the queue to be delievered
+ pub async fn run_digests<T: NotificationExtEmail>(
+ &self,
+ f: fn(DigestBatch) -> Result<T, Report>,
+ ) -> ! {
+ loop {
+ let sleep_duration = match self.service.poll_email_digests(f).await {
+ Ok(ClaimResult::Empty) => Duration::from_secs(5),
+ Ok(ClaimResult::Wait(duration)) => duration,
+ Ok(ClaimResult::Ready(())) => Duration::default(),
+ Err(_) => Duration::from_secs(1),
+ };
+ tokio::time::sleep(sleep_duration).await;
+ }
+ }
}
diff --git a/rust/cloud-storage/notification/src/outbound/queue.rs b/rust/cloud-storage/notification/src/outbound/queue.rs
index fddc1d0a33..e7413a51de 100644
--- a/rust/cloud-storage/notification/src/outbound/queue.rs
+++ b/rust/cloud-storage/notification/src/outbound/queue.rs
@@ -4,8 +4,10 @@ use aws_sdk_sqs::Client as SqsClient;
use rootcause::Report;
use serde::Serialize;
-use crate::domain::models::queue_message::{QueueMessage, RawQueueMessage};
-use crate::domain::ports::NotificationQueue;
+use crate::domain::models::queue_message::{
+ IngressQueueMessage, QueueMessage, RawIngressQueueMessage, RawQueueMessage,
+};
+use crate::domain::ports::{NotificationIngressQueue, NotificationQueue};
/// SQS-backed implementation of the notification queue port.
#[derive(Clone)]
@@ -24,7 +26,7 @@ impl SqsNotificationQueue {
impl NotificationQueue for SqsNotificationQueue {
async fn publish<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(
&self,
- messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,
+ messages: Vec<QueueMessage<'a, T, U>>,
) -> Result<(), Report> {
for message in messages {
let body = serde_json::to_string(&message)?;
@@ -102,7 +104,7 @@ impl FileQueue {
impl NotificationQueue for FileQueue {
async fn publish<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(
&self,
- messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,
+ messages: Vec<QueueMessage<'a, T, U>>,
) -> Result<(), Report> {
for message in messages {
let id = uuid::Uuid::new_v4();
@@ -161,3 +163,71 @@ impl NotificationQueue for FileQueue {
Ok(())
}
}
+
+/// SQS-backed implementation of the notification ingress queue port.
+///
+/// Used by [`crate::domain::service::SqsNotificationIngress`] to publish
+/// type-erased notification requests, and by the ingress worker to consume them.
+#[derive(Clone)]
+pub struct SqsIngressQueue {
+ client: SqsClient,
+ queue_url: String,
+}
+
+impl SqsIngressQueue {
+ /// Create a new SQS ingress queue adapter.
+ pub fn new(client: SqsClient, queue_url: String) -> Self {
+ Self { client, queue_url }
+ }
+}
+
+impl NotificationIngressQueue for SqsIngressQueue {
+ async fn publish(&self, message: IngressQueueMessage) -> Result<(), Report> {
+ let body = serde_json::to_string(&message)?;
+ self.client
+ .send_message()
+ .queue_url(&self.queue_url)
+ .message_body(body)
+ .send()
+ .await?;
+ Ok(())
+ }
+
+ async fn receive_messages(&self) -> Result<Vec<RawIngressQueueMessage>, Report> {
+ let result = self
+ .client
+ .receive_message()
+ .queue_url(&self.queue_url)
+ .max_number_of_messages(10)
+ .wait_time_seconds(20)
+ .send()
+ .await?;
+
+ let messages = result
+ .messages
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|msg| {
+ let body_str = msg.body?;
+ let body = serde_json::from_str(&body_str).ok()?;
+ let receipt_handle = msg.receipt_handle?;
+ Some(RawIngressQueueMessage {
+ body,
+ receipt_handle,
+ })
+ })
+ .collect();
+
+ Ok(messages)
+ }
+
+ async fn delete_message(&self, receipt_handle: &str) -> Result<(), Report> {
+ self.client
+ .delete_message()
+ .queue_url(&self.queue_url)
+ .receipt_handle(receipt_handle)
+ .send()
+ .await?;
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rs
index e977893393..ae6141c671 100644
--- a/rust/cloud-storage/notification/src/outbound/repository.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository.rs
@@ -5,7 +5,7 @@ mod test;
use crate::domain::models::device::DeviceType;
use crate::domain::models::{
- DeviceEndpoint, Notification, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,
+ DeviceEndpoint, NotificationIdAndCollapseKey, SendNotificationRequestBuilder, TaggedContent,
UserNotificationRow,
};
use crate::domain::ports::NotificationRepository;
@@ -16,6 +16,7 @@ use model_entity::EntityType;
use models_pagination::{CreatedAt, Query};
use rootcause::Report;
use rootcause::prelude::ResultExt;
+use serde::Serialize;
use serde::de::DeserializeOwned;
use sqlx::PgPool;
use std::collections::{HashMap, HashSet};
@@ -78,9 +79,9 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {
/// Create a notification record in the database.
///
/// Returns `Some(notification_id)` if created, `None` if it already exists (idempotent).
- fn create_notification<'a, T: Notification + Send + Sync>(
+ fn create_notification<'a, T: Serialize + Send + Sync>(
&self,
- request: SendNotificationRequestBuilder<'a, T>,
+ request: SendNotificationRequestBuilder<'a, TaggedContent<T>>,
notification_id: Uuid,
service_name: &str,
apns_collapse_key: Option<&str>,
@@ -260,9 +261,9 @@ impl NotificationDbOps for PgPool {
Ok(result)
}
- async fn create_notification<'a, T: Notification + Send + Sync>(
+ async fn create_notification<'a, T: Serialize + Send + Sync>(
&self,
- request: SendNotificationRequestBuilder<'a, T>,
+ request: SendNotificationRequestBuilder<'a, TaggedContent<T>>,
notification_id: Uuid,
service_name: &str,
apns_collapse_key: Option<&str>,
@@ -273,6 +274,7 @@ impl NotificationDbOps for PgPool {
let mut tx = self.begin().await?;
let sender_id = request.sender_id.as_ref().map(|id| id.to_string());
+ let typename = request.notification.tag.as_ref();
// Insert notification
let result = sqlx::query!(
@@ -282,7 +284,7 @@ impl NotificationDbOps for PgPool {
ON CONFLICT (id) DO NOTHING
"#,
notification_id,
- T::TYPE_NAME,
+ typename,
request.notification_entity.entity_id.as_ref(),
entity_type,
service_name,
@@ -322,7 +324,7 @@ impl NotificationDbOps for PgPool {
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 n = Arc::new(request.notification.content);
let rows = request
.recipient_ids
@@ -330,7 +332,7 @@ impl NotificationDbOps for PgPool {
.map(|recipient| UserNotificationRow {
owner_id: recipient.clone().into_owned(),
notification_id,
- notification_event_type: T::TYPE_NAME.to_string(),
+ notification_event_type: typename.to_string(),
entity: entity.clone(),
sent: false,
done: false,
@@ -780,9 +782,9 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
self.db.get_device_endpoints(user_ids).await
}
- async fn create_notification<'a, T: Notification + Send + Sync>(
+ async fn create_notification<'a, T: Serialize + Send + Sync>(
&self,
- request: SendNotificationRequestBuilder<'a, T>,
+ request: SendNotificationRequestBuilder<'a, TaggedContent<T>>,
notification_id: Uuid,
service_name: &str,
apns_collapse_key: Option<&str>,
diff --git a/rust/cloud-storage/notification/src/outbound/repository/test.rs b/rust/cloud-storage/notification/src/outbound/repository/test.rs
index 510287b36a..3d66ede6d1 100644
--- a/rust/cloud-storage/notification/src/outbound/repository/test.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository/test.rs
@@ -1,3 +1,5 @@
+use crate::domain::models::Notification;
+
use super::*;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
@@ -119,9 +121,9 @@ async fn test_create_notification(pool: Pool<Postgres>) {
let request = SendNotificationRequestBuilder {
notification_entity: EntityType::Document.with_entity_str("doc-1"),
- notification: TestNotification {
+ notification: TaggedContent::new(TestNotification {
message: "hello".to_string(),
- },
+ }),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient.clone()]),
};
@@ -380,9 +382,9 @@ async fn test_create_notification_returns_none_on_conflict(pool: Pool<Postgres>)
let request = SendNotificationRequestBuilder {
notification_entity: EntityType::Document.with_entity_str("doc-1"),
- notification: TestNotification {
+ notification: TaggedContent::new(TestNotification {
message: "hello".to_string(),
- },
+ }),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient.clone()]),
};
@@ -390,9 +392,9 @@ 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 {
+ notification: TaggedContent::new(TestNotification {
message: "hello".to_string(),
- },
+ }),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient.clone()]),
};
diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs b/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs
index 293bec77e4..81b94f69f8 100644
--- a/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs
+++ b/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs
@@ -40,7 +40,7 @@ impl Clone for MpscQueue {
impl NotificationQueue for MpscQueue {
async fn publish<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(
&self,
- messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,
+ messages: Vec<QueueMessage<'a, T, U>>,
) -> Result<(), Report> {
for message in messages {
let json = serde_json::to_value(&message)?;
diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
index cd1febbb65..3150d1c151 100644
--- a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
+++ b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
@@ -1,12 +1,14 @@
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Query};
+use notification::domain::models::TaggedContent;
use notification::domain::models::{
- DeviceEndpoint, Notification, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,
+ DeviceEndpoint, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,
UserNotificationRow, device::DeviceType,
};
use notification::domain::ports::NotificationRepository;
use notification::outbound::repository::DbNotificationRepository;
use rootcause::Report;
+use serde::Serialize;
use serde::de::DeserializeOwned;
use sqlx::PgPool;
use std::collections::HashMap;
@@ -52,9 +54,9 @@ impl NotificationRepository for SandboxNotificationRepository {
self.inner.get_unsubscribed_users(item_id, user_ids).await
}
- async fn create_notification<'a, T: Notification + Send + Sync>(
+ async fn create_notification<'a, T: Serialize + Send + Sync>(
&self,
- request: SendNotificationRequestBuilder<'a, T>,
+ request: SendNotificationRequestBuilder<'a, TaggedContent<T>>,
notification_id: Uuid,
service_sender: &str,
apns_collapse_key: Option<&str>,
diff --git a/rust/cloud-storage/notification_sandbox/src/sandbox_notification.rs b/rust/cloud-storage/notification_sandbox/src/sandbox_notification.rs
index 7dc598bd05..4288548b7b 100644
--- a/rust/cloud-storage/notification_sandbox/src/sandbox_notification.rs
+++ b/rust/cloud-storage/notification_sandbox/src/sandbox_notification.rs
@@ -25,15 +25,15 @@ impl NotificationExtIos for SandboxNotification {
NotifCollapseKey::new("sandbox")
}
- fn into_apns<'a>(
- self,
+ fn as_apns<'a>(
+ &self,
_sender_id: Option<MacroUserIdStr<'a>>,
_entity: &model_entity::Entity<'_>,
_notification_id: uuid::Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
Some(APNSPushNotification {
aps: Default::default(),
- push_notification_data: self,
+ push_notification_data: self.clone(),
})
}
}
diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.toml
index 71a79bf439..64ccdf716d 100644
--- a/rust/cloud-storage/notification_service/Cargo.toml
+++ b/rust/cloud-storage/notification_service/Cargo.toml
@@ -26,6 +26,7 @@ aws-sdk-sns = { workspace = true }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true }
chrono = { workspace = true }
+email_formatting = { path = "../email_formatting" }
email_validator = { path = "../email_validator" }
http-body-util = { workspace = true }
itertools = { workspace = true }
@@ -46,6 +47,7 @@ model = { path = "../model" }
model-entity = { path = "../model-entity" }
model-error-response = { path = "../model-error-response" }
model_file_type = { path = "../model_file_type" }
+last_online_tracker = { path = "../last_online_tracker" }
model_notifications = { path = "../model_notifications" }
model_user = { path = "../model_user", features = ["axum"] }
models_comms = { path = "../models_comms" }
diff --git a/rust/cloud-storage/notification_service/src/config.rs b/rust/cloud-storage/notification_service/src/config.rs
index 2d787e8521..81be840f71 100644
--- a/rust/cloud-storage/notification_service/src/config.rs
+++ b/rust/cloud-storage/notification_service/src/config.rs
@@ -9,6 +9,7 @@ pub static BASE_URL: LazyLock<String> = LazyLock::new(|| std::env::var("BASE_URL
env_var!(
pub(super) struct Vars {
pub(crate) NotificationQueue,
+ pub(crate) NotificationIngressQueue,
pub(crate) ConnectionGatewayUrl,
pub(crate) RedisUri,
pub(crate) AppleBundleId
diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rs
index b291504fae..590496e9b7 100644
--- a/rust/cloud-storage/notification_service/src/main.rs
+++ b/rust/cloud-storage/notification_service/src/main.rs
@@ -8,6 +8,7 @@ use ::notification::outbound::rate_limit::RedisRateLimitAdapter;
use ::notification::outbound::websocket::{ConnectionGatewayClient, WebSocketGatewayAdapter};
use anyhow::Context;
use config::Config;
+use email_formatting::EmailDigestNotification;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_env::Environment;
@@ -193,11 +194,70 @@ pub async fn main() -> anyhow::Result<()> {
digest_batcher: egress_digest_batcher,
};
- let worker = NotificationWorker::new(egress_service);
+ let worker = Arc::new(NotificationWorker::new(egress_service));
+ let worker_clone = worker.clone();
tokio::spawn(async move {
tracing::info!("starting notification egress worker");
- worker.run().await
+ worker_clone.run_notifications().await
+ });
+ tokio::spawn(async move {
+ tracing::info!("starting digest worker");
+ worker
+ .run_digests(EmailDigestNotification::new_from_digest_batch)
+ .await
+ });
+
+ // Set up ingress worker for processing notification requests from the ingress queue
+ let ingress_redis_conn = redis::Client::open(vars.redis_uri.as_ref())
+ .expect("failed to create redis client for ingress")
+ .get_multiplexed_async_connection()
+ .await
+ .context("failed to get redis connection for ingress state machine")?;
+
+ let ingress_state_machine =
+ ::notification::domain::models::email_notification_digest::StateMachineDriverA::new_with_defaults(
+ ::notification::outbound::user_existence_checker::DbUserExistenceChecker::new(
+ db.clone(),
+ ),
+ ::notification::outbound::push_notification_checker::PushNotificationCheckerImpl::new(
+ ::notification::outbound::repository::DbNotificationRepository::new(db.clone()),
+ ),
+ ::notification::outbound::last_online_checker::LastOnlineCheckerImpl::new(
+ last_online_tracker::domain::services::LastOnlineService::new(
+ last_online_tracker::outbound::time::DefaultTime,
+ last_online_tracker::outbound::redis::RedisLastOnlineRepo::new(
+ ingress_redis_conn.clone(),
+ ),
+ ),
+ ),
+ ::notification::outbound::digest_batcher::RedisDigestBatcher::new(ingress_redis_conn),
+ model_notifications::digest_state::common_email_block_list(),
+ model_notifications::digest_state::common_explicit_invite_allow_list(),
+ );
+
+ let ingress_repository =
+ ::notification::outbound::repository::DbNotificationRepository::new(db.clone());
+ let ingress_delivery_queue = ::notification::outbound::queue::SqsNotificationQueue::new(
+ aws_sdk_sqs::Client::new(&aws_config),
+ vars.notification_queue.as_ref().to_string(),
+ );
+ let ingress_service = ::notification::domain::service::NotificationIngressService::new(
+ ingress_repository,
+ ingress_delivery_queue,
+ ingress_state_machine,
+ );
+
+ let ingress_queue = ::notification::outbound::queue::SqsIngressQueue::new(
+ aws_sdk_sqs::Client::new(&aws_config),
+ vars.notification_ingress_queue.as_ref().to_string(),
+ );
+ let ingress_worker =
+ ::notification::inbound::ingress_worker::IngressWorker::new(ingress_service, ingress_queue);
+
+ tokio::spawn(async move {
+ tracing::info!("starting notification ingress worker");
+ ingress_worker.run().await
});
api::setup_and_serve(
diff --git a/rust/cloud-storage/properties_service/src/api/context.rs b/rust/cloud-storage/properties_service/src/api/context.rs
index 2cd9db8fb7..ad5a205616 100644
--- a/rust/cloud-storage/properties_service/src/api/context.rs
+++ b/rust/cloud-storage/properties_service/src/api/context.rs
@@ -1,32 +1,13 @@
use axum::extract::FromRef;
-use notification::domain::models::email_notification_digest::StateMachineDriverA;
-use notification::domain::service::NotificationIngressService;
-use notification::outbound::{
- digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
- push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
- repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
-};
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsIngressQueue;
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,
- StateMachine,
->;
+type NotificationIngressType = SqsNotificationIngress<SqsIngressQueue>;
/// Type alias for the properties service implementation used throughout the service.
pub type PropertiesService = PropertiesServiceImpl<