Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(notification_service): only send notification emails to non existing users (#408)
Will Hutchinsond4aa3d359003
diff --git a/infra/stacks/notification-service/Pulumi.dev.yaml b/infra/stacks/notification-service/Pulumi.dev.yamlindex 91ff825030..abb5ff897d 100644--- a/infra/stacks/notification-service/Pulumi.dev.yaml+++ b/infra/stacks/notification-service/Pulumi.dev.yaml@@ -13,3 +13,4 @@ config:secure: AAABABwFDqaa168byV3n4r7DZAxWY3DiN/JlTE2rWIHcWs966wvLVUe47u4ee/A35kf6d+JC+Qq/ouGs8GGUqgZN+LqHjIottuH7xYGqKliMWEWLUE/4bUAdDNrHUR/oJN12hgr8oh9ExqWSA7EY0Itd9/nbMxcjcICkfPOba6yQIXmZYYEpUQOAQQ58a0SP/EBgVG4VVbLq02yOEzTrHVhi6qzLb4jIrg6FjpfrEPuZL6/k8nq132Pw08GUVEzS69e90zEttexlc592rDcIC38A1/utFbmIsw0XFgBpzpWZyehHjJTEzks73wUBN4SOIQXQS3lO2lIopBHlvxREVhD1+oYMKK93/gIUr4QkqzkHmZYpixe+GJ48wvhHPM8x4Q==notification-service:fcm_secret_key: fcm-credential-devnotification-service:macro_cache_secret_key: macro-cache-dev+ notification-service:authentication_service_internal_api_key: authentication-service-internal-api-key-devdiff --git a/infra/stacks/notification-service/Pulumi.prod.yaml b/infra/stacks/notification-service/Pulumi.prod.yamlindex 10ec45351f..f605fbc866 100644--- a/infra/stacks/notification-service/Pulumi.prod.yaml+++ b/infra/stacks/notification-service/Pulumi.prod.yaml@@ -13,3 +13,4 @@ config:secure: AAABAKWe7JBlRN/BDxH4YFtm06Jry3kcv3jMudROKehPGxqEOEFsukTwQphhJm/+2dk3oFEHvqTDQEF4hOZmdNsa8Lz3f5jP+XgOEgcT2MBkH+QnvOwdYc97B72FRKPi6cmHLPz/9d4S05Jku0XCDhlGgMwYTc7K2vAzdPhCeC+KqAaKzcQmbm9hp5U4CEgo9FY9/GFZbgdHkdeLNC/U2rR8GSNmQoDQoCZEsvj9Btph5XURI6griy4Ou2iypKRRhcw+/jOLxVSOeRoVmKG3FGWsqsmlGC0AmvIKeD3bgrlFnMFUd1/EuP4tDsvhmi7/C7aeRcs+ryXWKFdIzWmnqyfPEu/otczlaMaTU0kiere3b1YsIO4sv8C/1i81FTvy/w==notification-service:fcm_secret_key: fcm-credential-prodnotification-service:macro_cache_secret_key: macro-cache-prod+ notification-service:authentication_service_internal_api_key: authentication-service-internal-api-key-proddiff --git a/infra/stacks/notification-service/index.ts b/infra/stacks/notification-service/index.tsindex fab4fed0f7..1b130600a4 100644--- a/infra/stacks/notification-service/index.ts+++ b/infra/stacks/notification-service/index.ts@@ -64,6 +64,17 @@ const MACRO_CACHE = aws.secretsmanager}).apply((secret) => secret.secretString);+const AUTHENTICATION_SERVICE_INTERNAL_API_KEY = config.require(+ `authentication_service_internal_api_key`+);++const authenticationServiceInternalApiKeyArn: pulumi.Output<string> =+ aws.secretsmanager+ .getSecretVersionOutput({+ secretId: AUTHENTICATION_SERVICE_INTERNAL_API_KEY,+ })+ .apply((secret) => secret.arn);+export const coparse_api_vpc = get_coparse_api_vpc();const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {@@ -162,6 +173,7 @@ const notificationService = new NotificationService('notification-service', {jwtSecretKeyArn,internalApiKeyArn,MACRO_API_TOKENS.macroApiTokenPublicKeyArn,+ authenticationServiceInternalApiKeyArn,],queueArns: [pushNotificationEventHandlerQueueArn, notificationQueueArn],snsPlatformArns: notificationSnsPlatformArns,@@ -264,6 +276,14 @@ const notificationService = new NotificationService('notification-service', {name: 'MACRO_API_TOKEN_PUBLIC_KEY',value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenPublicKey}`,},+ {+ name: 'AUTHENTICATION_SERVICE_URL',+ value: pulumi.interpolate`https://auth-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`,+ },+ {+ name: 'AUTHENTICATION_SERVICE_SECRET_KEY',+ value: pulumi.interpolate`${AUTHENTICATION_SERVICE_INTERNAL_API_KEY}`,+ },],});diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex c91a0c83e6..3558d755c8 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5668,6 +5668,7 @@ name = "notification_service"version = "0.1.0"dependencies = ["anyhow",+ "authentication_service_client","aws-config","aws-sdk-secretsmanager","aws-sdk-sesv2",diff --git a/rust/cloud-storage/authentication_service/src/api/internal/mod.rs b/rust/cloud-storage/authentication_service/src/api/internal/mod.rsindex 57151f4357..3f8403e340 100644--- a/rust/cloud-storage/authentication_service/src/api/internal/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/internal/mod.rs@@ -9,11 +9,13 @@ use super::user::post_get_names;// needs to be public in api crate for swaggermod google_access_token;+mod post_get_existing_users;mod remove_link;pub fn router() -> Router<ApiContext> {Router::new().route("/google_access_token", get(google_access_token::handler)).route("/get_names", post(post_get_names::handler_internal))+ .route("/get_existing_users", get(post_get_existing_users::handler)).route("/remove_link", delete(remove_link::handler))}diff --git a/rust/cloud-storage/authentication_service/src/api/internal/post_get_existing_users.rs b/rust/cloud-storage/authentication_service/src/api/internal/post_get_existing_users.rsnew file mode 100644index 0000000000..13271a8f37--- /dev/null+++ b/rust/cloud-storage/authentication_service/src/api/internal/post_get_existing_users.rs@@ -0,0 +1,85 @@+use crate::api::context::ApiContext;++use axum::{+ Json,+ extract::{self, State},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use macro_middleware::auth::internal_access::ValidInternalKey;+use macro_user_id::{cowlike::CowLike, lowercased::Lowercase, user_id::MacroUserId};+use model::response::ErrorResponse;+use utoipa::ToSchema;++#[derive(serde::Deserialize, Debug, ToSchema)]+pub struct GetExistingUsersRequest {+ /// List of user ids to check if they exist+ pub user_ids: Vec<String>,+}++#[derive(serde::Serialize, Debug, ToSchema)]+pub struct GetExistingUsersResponse {+ /// List of user ids that exist in our system+ pub existing_user_ids: Vec<String>,+}++#[derive(thiserror::Error, Debug)]+pub enum GetExistingUsersError {+ /// Some of the user ids provided are invalid macro user ids+ #[error("invalid macro user id provided")]+ InvalidMacroId,+ /// Internal error occurred+ #[error("internal error")]+ InternalError(#[from] anyhow::Error),+}++impl IntoResponse for GetExistingUsersError {+ fn into_response(self) -> Response {+ let status_code = match self {+ GetExistingUsersError::InvalidMacroId => StatusCode::BAD_REQUEST,+ GetExistingUsersError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ (+ status_code,+ Json(ErrorResponse {+ message: self.to_string().as_str(),+ }),+ )+ .into_response()+ }+}++/// Given a list of macro user ids, returns a list of user ids that exist in our system+#[utoipa::path(+ post,+ path = "/internal/get_existing_users",+ operation_id = "internal_get_existing_users",+ tag = "internal",+ responses(+ (status = 200, body = GetExistingUsersResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+ )]+#[tracing::instrument(skip(ctx, _valid_access))]+pub async fn handler(+ State(ctx): State<ApiContext>,+ _valid_access: ValidInternalKey,+ extract::Json(GetExistingUsersRequest { user_ids }): extract::Json<GetExistingUsersRequest>,+) -> Result<Json<GetExistingUsersResponse>, GetExistingUsersError> {+ tracing::info!("internal_get_existing_users");++ let user_ids: Vec<MacroUserId<Lowercase<'_>>> = user_ids+ .into_iter()+ .map(|id| {+ MacroUserId::parse_from_str(&id.to_lowercase()).map(|id| id.into_owned().lowercase())+ })+ .collect::<Result<Vec<_>, _>>()+ .map_err(|_| GetExistingUsersError::InvalidMacroId)?;++ let existing_user_ids =+ macro_db_client::user::get_all::get_existing_users(&ctx.db, &user_ids).await?;++ Ok(Json(GetExistingUsersResponse { existing_user_ids }))+}diff --git a/rust/cloud-storage/authentication_service_client/src/lib.rs b/rust/cloud-storage/authentication_service_client/src/lib.rsindex c67bcdfc36..c68fcca450 100644--- a/rust/cloud-storage/authentication_service_client/src/lib.rs+++ b/rust/cloud-storage/authentication_service_client/src/lib.rs@@ -2,6 +2,7 @@ pub mod error;pub mod get_names;pub mod google_access_token;pub mod unlink;+pub mod users;#[derive(Clone)]pub struct AuthServiceClient {diff --git a/rust/cloud-storage/authentication_service_client/src/users.rs b/rust/cloud-storage/authentication_service_client/src/users.rsnew file mode 100644index 0000000000..74fc5adc4d--- /dev/null+++ b/rust/cloud-storage/authentication_service_client/src/users.rs@@ -0,0 +1,63 @@+use std::collections::HashSet;+use std::fmt::{Debug, Display};++use crate::AuthServiceClient;+use crate::error::{AuthServiceClientError, GenericErrorResponse};+use anyhow::Result;++// HACK: duplicate code, should probably move this to a model crate at some point+#[derive(Default, Debug, serde::Serialize)]+pub struct PostGetExistingUsersRequestBody {+ pub user_ids: Vec<String>,+}++#[derive(Default, Debug, serde::Deserialize)]+pub struct PostGetExistingUsersResponse {+ pub existing_user_ids: Vec<String>,+}++impl AuthServiceClient {+ #[tracing::instrument(err, skip(self))]+ pub async fn get_existing_users(+ &self,+ user_ids: &[impl ToString + Display + Debug],+ ) -> Result<HashSet<String>> {+ let body = PostGetExistingUsersRequestBody {+ user_ids: user_ids.iter().map(|u| u.to_string()).collect(),+ };++ let res = self+ .client+ .post(format!("{}/internal/get_existing_users", self.url))+ .json(&body)+ .send()+ .await+ .map_err(|e| AuthServiceClientError::RequestBuildError {+ details: e.to_string(),+ })?;++ match res.status() {+ reqwest::StatusCode::OK => {+ let result = res+ .json::<PostGetExistingUsersResponse>()+ .await+ .map_err(|e| {+ AuthServiceClientError::Generic(GenericErrorResponse {+ message: e.to_string(),+ })+ })?;++ Ok(result.existing_user_ids.into_iter().collect())+ }+ status_code => {+ let body: String = res.text().await?;+ tracing::error!(+ body=%body,+ status=%status_code,+ "unexpected response from authentication service"+ );+ Err(anyhow::anyhow!(body))+ }+ }+ }+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-2c2e1fbbc52b300640cab8add807f581aba22df15410900b9f598daf699b60de.json b/rust/cloud-storage/macro_db_client/.sqlx/query-2c2e1fbbc52b300640cab8add807f581aba22df15410900b9f598daf699b60de.jsonnew file mode 100644index 0000000000..81c377d3c2--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-2c2e1fbbc52b300640cab8add807f581aba22df15410900b9f598daf699b60de.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n u.id\n FROM \"User\" u\n WHERE u.\"id\" = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "2c2e1fbbc52b300640cab8add807f581aba22df15410900b9f598daf699b60de"+}diff --git a/rust/cloud-storage/macro_db_client/src/user/get_all.rs b/rust/cloud-storage/macro_db_client/src/user/get_all.rsindex 56e3d001e0..d031a34493 100644--- a/rust/cloud-storage/macro_db_client/src/user/get_all.rs+++ b/rust/cloud-storage/macro_db_client/src/user/get_all.rs@@ -1,5 +1,33 @@+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};use model::organization::User;+/// Given a list of macro user ids, returns a list of user ids that exist in our system+#[tracing::instrument(skip(db), err)]+pub async fn get_existing_users(+ db: &sqlx::Pool<sqlx::Postgres>,+ user_ids: &[MacroUserId<Lowercase<'_>>],+) -> anyhow::Result<Vec<String>> {+ let user_ids: Vec<String> = user_ids+ .iter()+ .map(|id| id.as_ref().to_string())+ .collect::<Vec<_>>();++ let user_ids: Vec<String> = sqlx::query!(+ r#"+ SELECT+ u.id+ FROM "User" u+ WHERE u."id" = ANY($1)+ "#,+ &user_ids+ )+ .map(|r| r.id)+ .fetch_all(db)+ .await?;++ Ok(user_ids)+}+/// Gets all user ids in the database with null macro user idpub async fn get_all_user_ids_stripe_customer_id_with_null_macro_user_id(db: &sqlx::Pool<sqlx::Postgres>,diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.tomlindex d4a0c9f024..b8cc6876f7 100644--- a/rust/cloud-storage/notification_service/Cargo.toml+++ b/rust/cloud-storage/notification_service/Cargo.toml@@ -77,7 +77,7 @@ tracing = { workspace = true }url = { workspace = true }utoipa = { workspace = true }utoipa-swagger-ui = { workspace = true }-+authentication_service_client = { path = "../authentication_service_client" }[dev-dependencies]macro_auth = { path = "../macro_auth", features = ["testing"] }diff --git a/rust/cloud-storage/notification_service/src/config.rs b/rust/cloud-storage/notification_service/src/config.rsindex 60b3c0fda2..ee2d446c12 100644--- a/rust/cloud-storage/notification_service/src/config.rs+++ b/rust/cloud-storage/notification_service/src/config.rs@@ -60,6 +60,12 @@ pub struct Config {/// The redis uri for macro cachepub redis_uri: String,++ /// Auth service secret key, used for internal access+ pub auth_service_secret_key: String,++ /// URL for auth service+ pub auth_service_url: String,}impl Config {@@ -122,6 +128,12 @@ impl Config {let redis_uri = std::env::var("REDIS_URI").context("REDIS_URI must be provided")?;+ let auth_service_secret_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY")+ .context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?;++ let auth_service_url = std::env::var("AUTHENTICATION_SERVICE_URL")+ .context("AUTHENTICATION_SERVICE_URL must be provided")?;+Ok(Config {base_url,database_url,@@ -139,6 +151,8 @@ impl Config {apple_bundle_id,push_notification_event_handler_queue,redis_uri,+ auth_service_secret_key,+ auth_service_url,})}}diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rsindex 678f35bd5b..f8b3a5b26b 100644--- a/rust/cloud-storage/notification_service/src/main.rs+++ b/rust/cloud-storage/notification_service/src/main.rs@@ -128,6 +128,21 @@ pub async fn main() -> anyhow::Result<()> {#[cfg(feature = "notification_worker")]{use std::sync::Arc;++ let auth_service_internal_key = match config.environment {+ Environment::Local => config.auth_service_secret_key.clone(),+ _ => secretsmanager_client+ .get_secret_value(config.auth_service_secret_key.clone())+ .await+ .context("unable to get secret")?+ .to_string(),+ };++ let auth_service_client = authentication_service_client::AuthServiceClient::new(+ auth_service_internal_key,+ config.auth_service_url.clone(),+ );+let queue_worker_context = notification::context::QueueWorkerContext {db: db.clone(),worker: Arc::new(notification_worker),@@ -135,7 +150,9 @@ pub async fn main() -> anyhow::Result<()> {ses_client: Arc::new(ses_client),sns_client: Arc::new(sns_client.clone()),macro_cache_client: Arc::new(macro_cache_client),+ auth_service_client: Arc::new(auth_service_client),};+// Spawn the runner in a task of it's own so we don't block the main threadtokio::spawn(async move { notification::run_notification_worker(queue_worker_context).await },diff --git a/rust/cloud-storage/notification_service/src/notification/comms_utils.rs b/rust/cloud-storage/notification_service/src/notification/comms_utils.rsindex 383066d7a0..8fdd10e38e 100644--- a/rust/cloud-storage/notification_service/src/notification/comms_utils.rs+++ b/rust/cloud-storage/notification_service/src/notification/comms_utils.rs@@ -1,28 +1,44 @@use anyhow::Context;-use std::collections::HashMap;+use std::collections::HashSet;-/// Returns a map of user ids to a boolean indicating if we should email the user or not.+/// Returns a list of user ids that should be emailed.pub(in crate::notification) async fn should_email_channel_notification(+ auth_service_client: &authentication_service_client::AuthServiceClient,db: &sqlx::Pool<sqlx::Postgres>,channel_id: &str,user_ids: &[String],-) -> anyhow::Result<HashMap<String, bool>> {+) -> anyhow::Result<HashSet<String>> {+ // We only want to send channel notification emails to **non-macro** users.+ let existing_users: HashSet<String> = auth_service_client.get_existing_users(user_ids).await?;++ // Filter out the list of user ids to only include users that are not macro users+ let filtered_user_ids: Vec<String> = user_ids+ .iter()+ .filter_map(|user_id| {+ if existing_users.contains(user_id) {+ None+ } else {+ Some(user_id.to_string())+ }+ })+ .collect();+let channel_notification_email_sent = notification_db_client::channel_notification_email_sent::get::get_channel_notification_email_sent_bulk(db,channel_id,- user_ids,+ filtered_user_ids.as_slice(),).await.context("unable to get channel notification email sent")?;tracing::debug!(channel_notification_email_sent=?channel_notification_email_sent, "got channel notification email sent");- let mut should_email = HashMap::new();+ let mut should_email = HashSet::new();// If the user does not have a channel_notificaiton_email_sent record, we should email them.for user_id in user_ids {// If the user has not received an email notification for this channel, we should email them.if !channel_notification_email_sent.contains_key(user_id) {- should_email.insert(user_id.clone(), true);+ should_email.insert(user_id.clone());continue;}}diff --git a/rust/cloud-storage/notification_service/src/notification/context.rs b/rust/cloud-storage/notification_service/src/notification/context.rsindex ce5242ed36..af24a0a9ee 100644--- a/rust/cloud-storage/notification_service/src/notification/context.rs+++ b/rust/cloud-storage/notification_service/src/notification/context.rs@@ -10,4 +10,5 @@ pub struct QueueWorkerContext {pub ses_client: Arc<ses_client::Ses>,pub sns_client: Arc<sns_client::SNS>,pub macro_cache_client: Arc<macro_cache_client::MacroCache>,+ pub auth_service_client: Arc<authentication_service_client::AuthServiceClient>,}diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs b/rust/cloud-storage/notification_service/src/notification/send/email/filter.rsindex 6555a8fc3e..c3e4b40ee3 100644--- a/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs@@ -1,6 +1,7 @@-use std::collections::HashMap;+use std::collections::HashSet;use anyhow::Context;+use authentication_service_client::AuthServiceClient;use model_notifications::{NotificationEventType, NotificationWithRecipient};use notification_db_client::user_notification::get::should_email::should_email_based_on_user_notification_bulk;@@ -13,24 +14,17 @@ pub async fn filter_emails() -> anyhow::Result<Vec<String>> {// Filter out users that have already received an email for this event// This is done to prevent spam- let should_email: HashMap<String, bool> =- should_email(&queue_worker_context.db, notification, user_ids)- .await- .context("unable to get should email")?;- tracing::debug!(should_email=?should_email, "got should email");-- // Filter only users that should receive an email- let filtered_user_ids: Vec<String> = should_email- .iter()- .filter_map(|(user_id, should_email)| {- if *should_email {- Some(user_id.to_string())- } else {- None- }- })- .collect();- tracing::debug!(filtered_user_ids=?filtered_user_ids, "got filtered user ids");+ // Contains a list of user ids that should receive an email+ let filtered_user_ids: HashSet<String> = should_email(+ &queue_worker_context.auth_service_client,+ &queue_worker_context.db,+ notification,+ user_ids,+ )+ .await+ .context("unable to get should email")?;++ tracing::debug!(filtered_user_ids=?filtered_user_ids, filter_method="should_email", "filtered user ids");let emails: Vec<String> = filtered_user_ids.iter()@@ -77,10 +71,11 @@ pub async fn filter_emails(/// Given the notification and list of user ids to potentially send an email to, this will return/// a map of each user id and whether or not they should receive an email.async fn should_email(+ auth_service_client: &AuthServiceClient,db: &sqlx::Pool<sqlx::Postgres>,notification: &NotificationWithRecipient,user_ids: &[String],-) -> anyhow::Result<HashMap<String, bool>> {+) -> anyhow::Result<HashSet<String>> {match notification.inner.notification_event.event_type() {NotificationEventType::ItemSharedUser => {let result = should_email_based_on_user_notification_bulk(@@ -96,9 +91,21 @@ async fn should_email().await?;- Ok(result.into_iter().collect())+ let result: HashSet<String> = result+ .into_iter()+ .filter_map(|(user_id, should_email)| {+ if should_email {+ Some(user_id.to_string())+ } else {+ None+ }+ })+ .collect();++ Ok(result)}NotificationEventType::ChannelInvite => comms_utils::should_email_channel_notification(+ auth_service_client,db,¬ification.inner.notification_entity.event_item_id,user_ids,