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
Improve notif repo queries (#1228)
Sean Aye62d5da186651
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex e0ed86fcc9..05cd0f33ef 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5848,6 +5848,7 @@ dependencies = ["aws-sdk-sqs","hex","itertools 0.14.0",+ "macro_db_migrator","macro_user_id","model-entity","redis",diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 2a6abecf3a..e4c3d4da2b 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -56,6 +56,7 @@ build_lambdas:setup_test_envs:echo "DATABASE_URL={{ MACRODB }}" >> ./contacts_db_client/.envecho "DATABASE_URL={{ MACRODB }}" >> ./notification_db_client/.env+ echo "DATABASE_URL={{ MACRODB }}" >> ./notification/.envecho "DATABASE_URL={{ MACRODB }}" >> ./properties_db_client/.envecho "DATABASE_URL={{ MACRODB }}" >> ./macro_db_client/.envecho "DATABASE_URL={{ MACRODB }}" >> ./email_db_client/.envdiff --git a/rust/cloud-storage/notification/.sqlx/query-55d88928c73de7aa07a858d79c4e1b0ab25746c723e48a2aa5baba0fc13b21a1.json b/rust/cloud-storage/notification/.sqlx/query-55d88928c73de7aa07a858d79c4e1b0ab25746c723e48a2aa5baba0fc13b21a1.jsonnew file mode 100644index 0000000000..7ad415f82a--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-55d88928c73de7aa07a858d79c4e1b0ab25746c723e48a2aa5baba0fc13b21a1.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Varchar",+ "Text",+ "Text",+ "Text",+ "Jsonb",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "55d88928c73de7aa07a858d79c4e1b0ab25746c723e48a2aa5baba0fc13b21a1"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6.json b/rust/cloud-storage/notification/.sqlx/query-621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6.jsonnew file mode 100644index 0000000000..d0a749ebd2--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user_id FROM user_mute_notification\n WHERE user_id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.json b/rust/cloud-storage/notification/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.jsonnew file mode 100644index 0000000000..a8e7326c35--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user_id FROM user_notification_item_unsubscribe\n WHERE item_id = $1 AND user_id = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116.json b/rust/cloud-storage/notification/.sqlx/query-81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116.jsonnew file mode 100644index 0000000000..4cb16ae2df--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO user_notification (notification_id, user_id)\n SELECT $1, user_id\n FROM UNNEST($2::text[]) as user_id\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436.json b/rust/cloud-storage/notification/.sqlx/query-86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436.jsonnew file mode 100644index 0000000000..eab49b91f7--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE user_notification\n SET sent = true\n WHERE notification_id = $1 AND user_id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json b/rust/cloud-storage/notification/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.jsonnew file mode 100644index 0000000000..ad14cfedba--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json@@ -0,0 +1,44 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user_id, device_endpoint, device_type as \"device_type: DbDeviceType\"\n FROM notification_user_device_registration\n WHERE user_id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "device_endpoint",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "device_type: DbDeviceType",+ "type_info": {+ "Custom": {+ "name": "notification_device_type_option",+ "kind": {+ "Enum": [+ "ios",+ "android"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1"+}diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.tomlindex eed6885f13..a58d96fc78 100644--- a/rust/cloud-storage/notification/Cargo.toml+++ b/rust/cloud-storage/notification/Cargo.toml@@ -24,4 +24,5 @@ tracing = { workspace = true }uuid = { workspace = true }[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }tokio = { workspace = true, features = ["macros", "rt"] }diff --git a/rust/cloud-storage/notification/fixtures/muted_users.sql b/rust/cloud-storage/notification/fixtures/muted_users.sqlnew file mode 100644index 0000000000..a129dc3d4f--- /dev/null+++ b/rust/cloud-storage/notification/fixtures/muted_users.sql@@ -0,0 +1 @@+INSERT INTO user_mute_notification (user_id) VALUES ('macro|[email protected]');diff --git a/rust/cloud-storage/notification/fixtures/unsubscribed_users.sql b/rust/cloud-storage/notification/fixtures/unsubscribed_users.sqlnew file mode 100644index 0000000000..8d34d58690--- /dev/null+++ b/rust/cloud-storage/notification/fixtures/unsubscribed_users.sql@@ -0,0 +1,2 @@+INSERT INTO user_notification_item_unsubscribe (user_id, item_id, item_type)+VALUES ('macro|[email protected]', 'item-123', 'document');diff --git a/rust/cloud-storage/notification/fixtures/user_devices.sql b/rust/cloud-storage/notification/fixtures/user_devices.sqlnew file mode 100644index 0000000000..96f45189cc--- /dev/null+++ b/rust/cloud-storage/notification/fixtures/user_devices.sql@@ -0,0 +1,17 @@+INSERT INTO notification_user_device_registration (+ id, user_id, device_token, device_endpoint, device_type, created_at, updated_at+) VALUES+ ('017d85a8-c7c6-7c40-b4f3-a6c1b3c0d1e2'::uuid,+ 'macro|[email protected]',+ 'ios_token_123',+ 'arn:aws:sns:us-east-1:000:endpoint/APNS/app/device123',+ 'ios',+ '2025-02-28 10:00:00',+ '2025-02-28 10:00:00'),+ ('017d85a8-c7c6-7c40-b4f3-a6c1b3c0d1e3'::uuid,+ 'macro|[email protected]',+ 'android_token_456',+ 'arn:aws:sns:us-east-1:000:endpoint/GCM/app/device456',+ 'android',+ '2025-02-28 11:00:00',+ '2025-02-28 11:00:00');diff --git a/rust/cloud-storage/notification/fixtures/user_notifications.sql b/rust/cloud-storage/notification/fixtures/user_notifications.sqlnew file mode 100644index 0000000000..51a2435073--- /dev/null+++ b/rust/cloud-storage/notification/fixtures/user_notifications.sql@@ -0,0 +1,5 @@+INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)+VALUES ('0193b1ea-a542-7589-893b-2b4a509c1e76', 'test', 'item-1', 'document', 'test_service', NULL, NULL);++INSERT INTO user_notification (user_id, notification_id, created_at)+VALUES ('macro|[email protected]', '0193b1ea-a542-7589-893b-2b4a509c1e76', '2025-01-01 00:00:00');diff --git a/rust/cloud-storage/notification/justfile b/rust/cloud-storage/notification/justfilenew file mode 100644index 0000000000..d5a52bc432--- /dev/null+++ b/rust/cloud-storage/notification/justfile@@ -0,0 +1,6 @@+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"++mod sqlx '../sqlx.just'++prepare_db:+ just sqlx::prepare_db {{ DATABASE_URL }}diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rsindex d1a2c04b6e..a3f8781c89 100644--- a/rust/cloud-storage/notification/src/outbound/repository.rs+++ b/rust/cloud-storage/notification/src/outbound/repository.rs@@ -1,15 +1,28 @@//! Database repository adapter for notifications.-use std::collections::{HashMap, HashSet};+#[cfg(test)]+mod test;+use crate::domain::models::{DeviceEndpoint, Notification, SendNotificationRequestBuilder};+use crate::domain::ports::NotificationRepository;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;use sqlx::PgPool;+use std::collections::{HashMap, HashSet};use uuid::Uuid;-use crate::domain::models::{DeviceEndpoint, Notification, SendNotificationRequestBuilder};-use crate::domain::ports::NotificationRepository;+/// Local representation of the `notification_device_type_option` Postgres enum+/// for compile-time checked sqlx queries.+#[derive(Debug, sqlx::Type)]+#[sqlx(+ type_name = "notification_device_type_option",+ rename_all = "lowercase"+)]+enum DbDeviceType {+ Ios,+ Android,+}/// Database-backed implementation of the notification repository port.///@@ -77,13 +90,13 @@ impl NotificationDbOps for PgPool {) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {let ids: Vec<String> = user_ids.iter().map(|id| id.to_string()).collect();- let muted_users: Vec<String> = sqlx::query_scalar(+ let muted_users: Vec<String> = sqlx::query_scalar!(r#"SELECT user_id FROM user_mute_notificationWHERE user_id = ANY($1)"#,+ &ids)- .bind(&ids).fetch_all(self).await?;@@ -107,14 +120,14 @@ impl NotificationDbOps for PgPool {) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {let ids: Vec<String> = user_ids.iter().map(|id| id.to_string()).collect();- let unsubscribed: Vec<String> = sqlx::query_scalar(+ let unsubscribed: Vec<String> = sqlx::query_scalar!(r#"SELECT user_id FROM user_notification_item_unsubscribeWHERE item_id = $1 AND user_id = ANY($2)"#,+ item_id,+ &ids)- .bind(item_id)- .bind(&ids).fetch_all(self).await?;@@ -137,28 +150,27 @@ impl NotificationDbOps for PgPool {) -> Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report> {let ids: Vec<String> = user_ids.iter().map(|id| id.to_string()).collect();- let rows: Vec<(String, String, String)> = sqlx::query_as(+ let rows = sqlx::query!(r#"- SELECT user_id, device_endpoint, device_type- FROM user_device_registration+ SELECT user_id, device_endpoint, device_type as "device_type: DbDeviceType"+ FROM notification_user_device_registrationWHERE user_id = ANY($1)"#,+ &ids)- .bind(&ids).fetch_all(self).await?;let mut result: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>> = HashMap::new();- for (user_id, endpoint, device_type) in rows {- let Ok(parsed_id) = MacroUserIdStr::parse_from_str(&user_id) else {+ for row in rows {+ let Ok(parsed_id) = MacroUserIdStr::parse_from_str(&row.user_id) else {continue;};- let device = match device_type.as_str() {- "ios" => DeviceEndpoint::Ios(endpoint),- "android" => DeviceEndpoint::Android(endpoint),- _ => continue,+ let device = match row.device_type {+ DbDeviceType::Ios => DeviceEndpoint::Ios(row.device_endpoint),+ DbDeviceType::Android => DeviceEndpoint::Android(row.device_endpoint),};result@@ -182,36 +194,38 @@ impl NotificationDbOps for PgPool {let mut tx = self.begin().await?;+ let sender_id = request.sender_id.as_ref().map(|id| id.to_string());+// Insert notification- sqlx::query(+ sqlx::query!(r#"INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)VALUES ($1, $2, $3, $4, $5, $6, $7)ON CONFLICT (id) DO NOTHING"#,+ notification_id,+ T::TYPE_NAME,+ request.notification_entity.entity_id.as_ref(),+ entity_type,+ service_name,+ metadata as Option<serde_json::Value>,+ sender_id)- .bind(notification_id)- .bind(T::TYPE_NAME)- .bind(request.notification_entity.entity_id.as_ref())- .bind(entity_type)- .bind(service_name)- .bind(&metadata)- .bind(request.sender_id.as_ref().map(|id| id.to_string())).execute(&mut *tx).await?;// Insert user notificationslet user_ids: Vec<String> = recipient_ids.iter().map(|id| id.to_string()).collect();- sqlx::query(+ sqlx::query!(r#"INSERT INTO user_notification (notification_id, user_id)SELECT $1, user_idFROM UNNEST($2::text[]) as user_id"#,+ notification_id,+ &user_ids)- .bind(notification_id)- .bind(&user_ids).execute(&mut *tx).await?;@@ -227,15 +241,15 @@ impl NotificationDbOps for PgPool {) -> Result<(), Report> {let ids: Vec<String> = user_ids.iter().map(|id| id.to_string()).collect();- sqlx::query(+ sqlx::query!(r#"UPDATE user_notificationSET sent = trueWHERE notification_id = $1 AND user_id = ANY($2)"#,+ notification_id,+ &ids)- .bind(notification_id)- .bind(&ids).execute(self).await?;diff --git a/rust/cloud-storage/notification/src/outbound/repository/test.rs b/rust/cloud-storage/notification/src/outbound/repository/test.rsnew file mode 100644index 0000000000..303091d68a--- /dev/null+++ b/rust/cloud-storage/notification/src/outbound/repository/test.rs@@ -0,0 +1,192 @@+use super::*;++use macro_db_migrator::MACRO_DB_MIGRATIONS;+use model_entity::EntityType;+use serde::{Deserialize, Serialize};+use sqlx::{Pool, Postgres};++#[derive(Debug, Clone, Serialize, Deserialize)]+struct TestNotification {+ message: String,+}++impl Notification for TestNotification {+ const TYPE_NAME: &'static str = "test_notification";++ fn title(&self) -> String {+ "Test".to_string()+ }++ fn body(&self) -> String {+ self.message.clone()+ }++ fn rate_limit_config() -> Option<crate::domain::models::RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<crate::domain::models::RateLimitKey> {+ None+ }+}++fn test_user(email: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email(email).unwrap()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("muted_users"))+)]+async fn test_get_muted_users(pool: Pool<Postgres>) {+ let muted = test_user("[email protected]");+ let not_muted = test_user("[email protected]");++ let result = pool+ .get_muted_users(&[muted.clone(), not_muted])+ .await+ .unwrap();++ assert_eq!(result.len(), 1);+ assert!(result.contains(&muted));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_get_muted_users_empty(pool: Pool<Postgres>) {+ let user = test_user("[email protected]");++ let result = pool.get_muted_users(&[user]).await.unwrap();++ assert!(result.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("unsubscribed_users"))+)]+async fn test_get_unsubscribed_users(pool: Pool<Postgres>) {+ let unsub = test_user("[email protected]");+ let other = test_user("[email protected]");++ let result = pool+ .get_unsubscribed_users("item-123", &[unsub.clone(), other])+ .await+ .unwrap();++ assert_eq!(result.len(), 1);+ assert!(result.contains(&unsub));+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("unsubscribed_users"))+)]+async fn test_get_unsubscribed_users_different_item(pool: Pool<Postgres>) {+ let unsub = test_user("[email protected]");++ let result = pool+ .get_unsubscribed_users("other-item", &[unsub])+ .await+ .unwrap();++ assert!(result.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_devices"))+)]+async fn test_get_device_endpoints(pool: Pool<Postgres>) {+ let user = test_user("[email protected]");++ let result = pool.get_device_endpoints(&[user.clone()]).await.unwrap();++ let endpoints = result.get(&user).expect("user should have endpoints");+ assert_eq!(endpoints.len(), 2);++ let has_ios = endpoints+ .iter()+ .any(|e| matches!(e, DeviceEndpoint::Ios(_)));+ let has_android = endpoints+ .iter()+ .any(|e| matches!(e, DeviceEndpoint::Android(_)));++ assert!(has_ios, "should have iOS endpoint");+ assert!(has_android, "should have Android endpoint");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_get_device_endpoints_no_devices(pool: Pool<Postgres>) {+ let user = test_user("[email protected]");++ let result = pool.get_device_endpoints(&[user]).await.unwrap();++ assert!(result.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_create_notification(pool: Pool<Postgres>) {+ let recipient = test_user("[email protected]");+ let notification_id = uuid::Uuid::new_v4();++ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::Document.with_entity_str("doc-1"),+ notification: TestNotification {+ message: "hello".to_string(),+ },+ sender_id: None,+ recipient_ids: std::collections::HashSet::from([recipient.clone()]),+ };++ let result = pool+ .create_notification(+ &request,+ notification_id,+ "test_service",+ &[recipient.clone()],+ )+ .await+ .unwrap();++ assert_eq!(result, Some(notification_id));++ // Verify notification was inserted+ let row = sqlx::query!("SELECT id FROM notification WHERE id = $1", notification_id)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(row.id, notification_id);++ // Verify user_notification was inserted+ let user_row = sqlx::query!(+ "SELECT user_id FROM user_notification WHERE notification_id = $1",+ notification_id+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(user_row.user_id, recipient.to_string());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_notifications"))+)]+async fn test_update_sent_status(pool: Pool<Postgres>) {+ let notification_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();+ let user = test_user("[email protected]");++ pool.update_sent_status(notification_id, &[user])+ .await+ .unwrap();++ let row = sqlx::query!(+ "SELECT sent FROM user_notification WHERE notification_id = $1",+ notification_id+ )+ .fetch_one(&pool)+ .await+ .unwrap();++ assert!(row.sent);+}