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
mod publication;
mod state;
use crate::domain::models::{Notification, request::NotificationCategory};
use super::*;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use model_entity::EntityType;
use models_pagination::CreatedAt;
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";
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TestMessageNotification {
message_id: String,
}
impl Notification for TestMessageNotification {
const TYPE_NAME: &'static str = "test_message_notification";
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TestCalendarJoinRequest;
impl Notification for TestCalendarJoinRequest {
const TYPE_NAME: &'static str = "calendar_event_join_request";
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TestTaskNotification {
sub_type: String,
}
impl Notification for TestTaskNotification {
const TYPE_NAME: &'static str = "test_task_notification";
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TestGithubNotification {
message: String,
}
impl Notification for TestGithubNotification {
const TYPE_NAME: &'static str = "github_pr_status_changed";
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TestGithubCheckRunNotification {
message: String,
}
impl Notification for TestGithubCheckRunNotification {
const TYPE_NAME: &'static str = "github_pr_check_run";
}
fn test_user(email: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email(email).unwrap()
}
async fn create_message_notification(
pool: &Pool<Postgres>,
recipient: &MacroUserIdStr<'static>,
notification_id: Uuid,
message_id: &str,
thread_id: Option<&str>,
) {
let request = SendNotificationRequestBuilder {
notification_entity: EntityType::Channel.with_entity_str("channel-1"),
secondary_notification_entity: thread_id
.map(|thread_id| EntityType::ChannelMessage.with_entity_str(thread_id)),
notification: TaggedContent::new(TestMessageNotification {
message_id: message_id.to_owned(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient.clone()]),
};
pool.create_notification(request, notification_id, "test_service", None)
.await
.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(std::slice::from_ref(&user))
.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"),
secondary_notification_entity: None,
notification: TaggedContent::new(TestNotification {
message: "hello".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient.clone()]),
};
let result = pool
.create_notification(request, notification_id, "test_service", None)
.await
.unwrap();
assert!(result.is_some());
// 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")]
async fn a_join_request_for_an_event_that_has_gone_is_nothing_to_deliver(pool: Pool<Postgres>) {
let request = SendNotificationRequestBuilder {
notification_entity: EntityType::CalendarEvent
.with_entity_string(Uuid::now_v7().to_string()),
secondary_notification_entity: None,
notification: TaggedContent::new(TestCalendarJoinRequest),
sender_id: None,
recipient_ids: std::collections::HashSet::from([test_user("[email protected]")]),
};
assert!(
pool.create_notification(request, Uuid::now_v7(), "test_service", None)
.await
.unwrap()
.is_none()
);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_create_notification_stores_secondary_entity(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"),
secondary_notification_entity: Some(EntityType::Channel.with_entity_str("channel-1")),
notification: TaggedContent::new(TestNotification {
message: "hello".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient]),
};
pool.create_notification(request, notification_id, "test_service", None)
.await
.unwrap();
let row = sqlx::query!(
r#"
SELECT
event_item_id,
event_item_type,
secondary_event_item_id,
secondary_event_item_type
FROM notification
WHERE id = $1
"#,
notification_id
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(row.event_item_id, "doc-1");
assert_eq!(row.event_item_type, "document");
assert_eq!(row.secondary_event_item_id.as_deref(), Some("channel-1"));
assert_eq!(row.secondary_event_item_type.as_deref(), Some("channel"));
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_create_notification_returns_timestamps(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"),
secondary_notification_entity: None,
notification: TaggedContent::new(TestNotification {
message: "hello".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient.clone()]),
};
let rows = pool
.create_notification(request, notification_id, "test_service", None)
.await
.unwrap()
.expect("should return Some for new notification");
assert_eq!(rows.len(), 1);
let row = &rows[0];
assert_eq!(row.created_at, row.updated_at);
}
#[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);
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../fixtures",
scripts("notifications_with_collapse_keys")
)
)]
async fn test_mark_notifications_seen(pool: Pool<Postgres>) {
let user = test_user("[email protected]");
let notification_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
let updated = pool
.mark_notifications_seen(&user, &[notification_id])
.await
.unwrap();
assert_eq!(updated.len(), 1);
assert_eq!(updated[0].owner_id, user);
assert_eq!(updated[0].notification_id, notification_id);
assert_eq!(updated[0].entity.entity_id, "item-1");
assert!(updated[0].viewed_at.is_some());
let row = sqlx::query!(
"SELECT seen_at FROM user_notification WHERE notification_id = $1 AND user_id = $2",
notification_id,
user.to_string()
)
.fetch_one(&pool)
.await
.unwrap();
assert!(row.seen_at.is_some());
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../fixtures",
scripts("notifications_with_collapse_keys")
)
)]
async fn test_mark_notifications_seen_does_not_affect_other_users(pool: Pool<Postgres>) {
let user = test_user("[email protected]");
let other_user = test_user("[email protected]");
let notification_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
// Insert a user_notification for the other user
sqlx::query!(
"INSERT INTO user_notification (user_id, notification_id, created_at) VALUES ($1, $2, '2025-01-01 00:00:00')",
other_user.to_string(),
notification_id,
)
.execute(&pool)
.await
.unwrap();
// Mark seen only for the first user
let updated = pool
.mark_notifications_seen(&user, &[notification_id])
.await
.unwrap();
assert_eq!(updated.len(), 1);
assert_eq!(updated[0].owner_id, user);
// Other user's notification should still be unseen
let row = sqlx::query!(
"SELECT seen_at FROM user_notification WHERE notification_id = $1 AND user_id = $2",
notification_id,
other_user.to_string()
)
.fetch_one(&pool)
.await
.unwrap();
assert!(row.seen_at.is_none());
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_notification_ids_for_entities_matches_multiple_primary_and_secondary_for_user(
pool: Pool<Postgres>,
) {
let user = test_user("[email protected]");
let other_user = test_user("[email protected]");
let primary_id = Uuid::new_v4();
let secondary_id = Uuid::new_v4();
let deleted_id = Uuid::new_v4();
let other_user_id = Uuid::new_v4();
let wrong_type_id = Uuid::new_v4();
for (notification_id, recipient, primary_entity, secondary_entity) in [
(
primary_id,
user.clone(),
EntityType::Document.with_entity_str("entity-1"),
None,
),
(
secondary_id,
user.clone(),
EntityType::Channel.with_entity_str("channel-1"),
Some(EntityType::Document.with_entity_str("entity-1")),
),
(
deleted_id,
user.clone(),
EntityType::Document.with_entity_str("entity-1"),
None,
),
(
other_user_id,
other_user,
EntityType::Document.with_entity_str("entity-1"),
None,
),
(
wrong_type_id,
user.clone(),
EntityType::Project.with_entity_str("entity-1"),
None,
),
] {
pool.create_notification(
SendNotificationRequestBuilder {
notification_entity: primary_entity,
secondary_notification_entity: secondary_entity,
notification: TaggedContent::new(TestNotification {
message: "entity notification".to_string(),
}),
sender_id: None,
recipient_ids: HashSet::from([recipient]),
},
notification_id,
"test_service",
None,
)
.await
.unwrap();
}
sqlx::query!(
"UPDATE user_notification SET deleted_at = NOW() WHERE user_id = $1 AND notification_id = $2",
user.as_ref(),
deleted_id,
)
.execute(&pool)
.await
.unwrap();
let entities = [
EntityType::Document.with_entity_str("entity-1"),
EntityType::Project.with_entity_str("entity-1"),
];
let notification_ids = pool
.get_notification_ids_for_entities(&user, &entities, &NotificationStatus::Seen)
.await
.unwrap()
.into_iter()
.collect::<HashSet<_>>();
assert_eq!(
notification_ids,
HashSet::from([primary_id, secondary_id, wrong_type_id])
);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_notification_ids_for_entities_matches_task_entity(pool: Pool<Postgres>) {
let user = test_user("[email protected]");
let task_id = Uuid::new_v4();
let task_entity_id = "task-1";
pool.create_notification(
SendNotificationRequestBuilder {
notification_entity: EntityType::Document.with_entity_str(task_entity_id),
secondary_notification_entity: None,
notification: TaggedContent::new(TestTaskNotification {
sub_type: "task".to_string(),
}),
sender_id: None,
recipient_ids: HashSet::from([user.clone()]),
},
task_id,
"test_service",
None,
)
.await
.unwrap();
let notification_ids = pool
.get_notification_ids_for_entities(
&user,
&[EntityType::Document.with_entity_str(task_entity_id)],
&NotificationStatus::Seen,
)
.await
.unwrap();
assert_eq!(notification_ids, vec![task_id]);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_notification_ids_for_entities_matches_message_entity(pool: Pool<Postgres>) {
let user = test_user("[email protected]");
let message_id = Uuid::new_v4().to_string();
let direct_id = Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
let thread_reply_id = Uuid::parse_str("0193b1ea-b642-7589-893b-2b4a509c1e76").unwrap();
create_message_notification(&pool, &user, direct_id, &message_id, None).await;
create_message_notification(
&pool,
&user,
thread_reply_id,
&Uuid::new_v4().to_string(),
Some(&message_id),
)
.await;
let notification_ids = pool
.get_notification_ids_for_entities(
&user,
&[EntityType::ChannelMessage.with_entity_str(&message_id)],
&NotificationStatus::Seen,
)
.await
.unwrap();
assert_eq!(notification_ids, vec![direct_id, thread_reply_id]);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_notification_ids_for_entities_matches_foreign_entities_including_github(
pool: Pool<Postgres>,
) {
let user = test_user("[email protected]");
let github_id = Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
let generic_id = Uuid::parse_str("0193b1ea-b642-7589-893b-2b4a509c1e76").unwrap();
let foreign_entity_id = Uuid::new_v4().to_string();
pool.create_notification(
SendNotificationRequestBuilder {
notification_entity: EntityType::ForeignEntity
.with_entity_string(foreign_entity_id.clone()),
secondary_notification_entity: None,
notification: TaggedContent::new(TestGithubNotification {
message: "github".to_string(),
}),
sender_id: None,
recipient_ids: HashSet::from([user.clone()]),
},
github_id,
"test_service",
None,
)
.await
.unwrap();
pool.create_notification(
SendNotificationRequestBuilder {
notification_entity: EntityType::ForeignEntity
.with_entity_string(foreign_entity_id.clone()),
secondary_notification_entity: None,
notification: TaggedContent::new(TestNotification {
message: "generic foreign entity".to_string(),
}),
sender_id: None,
recipient_ids: HashSet::from([user.clone()]),
},
generic_id,
"test_service",
None,
)
.await
.unwrap();
let notification_ids = pool
.get_notification_ids_for_entities(
&user,
&[EntityType::ForeignEntity.with_entity_str(&foreign_entity_id)],
&NotificationStatus::Seen,
)
.await
.unwrap();
assert_eq!(notification_ids, vec![github_id, generic_id]);
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../fixtures",
scripts("notifications_with_collapse_keys")
)
)]
async fn test_mark_notifications_done_returns_owned_rows_in_requested_order(pool: Pool<Postgres>) {
let user = test_user("[email protected]");
let other_user = test_user("[email protected]");
let first = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
let second = uuid::Uuid::parse_str("0193b1ea-b642-7589-893b-2b4a509c1e76").unwrap();
let other_only = uuid::Uuid::new_v4();
let request = SendNotificationRequestBuilder {
notification_entity: EntityType::Document.with_entity_str("doc-other"),
secondary_notification_entity: None,
notification: TaggedContent::new(TestNotification {
message: "other".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([other_user]),
};
pool.create_notification(request, other_only, "test_service", None)
.await
.unwrap();
let rows = pool
.mark_notifications_done(&user, &[second, other_only, first], true)
.await
.unwrap();
assert_eq!(
rows.iter()
.map(|notification| notification.notification_id)
.collect::<Vec<_>>(),
vec![second, first]
);
assert!(
rows.iter()
.all(|notification| notification.owner_id == user)
);
assert!(
rows.iter()
.all(|notification| notification.state == NotificationState::Done)
);
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../fixtures",
scripts("notifications_with_collapse_keys")
)
)]
async fn test_get_basic_notifications(pool: Pool<Postgres>) {
let with_key = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
let without_key = uuid::Uuid::parse_str("0193b1ea-b642-7589-893b-2b4a509c1e76").unwrap();
let result = pool
.get_basic_notifications(&[with_key, without_key])
.await
.unwrap();
// Only the notification with a collapse key should be returned
assert_eq!(result.len(), 1);
assert_eq!(result[0].id, with_key);
assert_eq!(result[0].apns_collapse_key, "collapse-key-1");
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_basic_notifications_empty(pool: Pool<Postgres>) {
let id = uuid::Uuid::new_v4();
let result = pool.get_basic_notifications(&[id]).await.unwrap();
assert!(result.is_empty());
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
path = "../../../fixtures",
scripts("notifications_with_collapse_keys")
)
)]
async fn test_get_digest_eligible_notification_ids_filters_seen_deleted_missing_and_other_users(
pool: Pool<Postgres>,
) {
let user = test_user("[email protected]");
let other_user = test_user("[email protected]");
let eligible_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
let seen_id = uuid::Uuid::parse_str("0193b1ea-b642-7589-893b-2b4a509c1e76").unwrap();
let deleted_id = uuid::Uuid::parse_str("0193b1ea-c742-7589-893b-2b4a509c1e76").unwrap();
let other_user_id = uuid::Uuid::parse_str("0193b1ea-d842-7589-893b-2b4a509c1e76").unwrap();
let missing_id = uuid::Uuid::parse_str("0193b1ea-e942-7589-893b-2b4a509c1e76").unwrap();
sqlx::query!(
r#"
INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata)
VALUES
($1, 'test', 'item-3', 'document', 'test_service', '{}'),
($2, 'test', 'item-4', 'document', 'test_service', '{}')
"#,
deleted_id,
other_user_id
)
.execute(&pool)
.await
.unwrap();
sqlx::query!(
r#"
INSERT INTO user_notification (user_id, notification_id, created_at, deleted_at)
VALUES ($1, $2, '2025-01-01 00:00:02', '2025-01-01 00:01:00')
"#,
user.to_string(),
deleted_id
)
.execute(&pool)
.await
.unwrap();
sqlx::query!(
r#"
INSERT INTO user_notification (user_id, notification_id, created_at)
VALUES ($1, $2, '2025-01-01 00:00:03')
"#,
other_user.to_string(),
other_user_id
)
.execute(&pool)
.await
.unwrap();
pool.mark_notifications_seen(&user, &[seen_id])
.await
.unwrap();
let result = pool
.get_digest_eligible_notification_ids(
&user,
&[eligible_id, seen_id, deleted_id, other_user_id, missing_id],
)
.await
.unwrap();
assert_eq!(result.len(), 1);
assert!(result.contains(&eligible_id));
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_digest_eligible_notification_ids_empty_input(pool: Pool<Postgres>) {
let user = test_user("[email protected]");
let result = pool
.get_digest_eligible_notification_ids(&user, &[])
.await
.unwrap();
assert!(result.is_empty());
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_notifications"))
)]
async fn test_get_user_notifications(pool: Pool<Postgres>) {
let result: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters::active(),
)
.await
.unwrap();
assert_eq!(result.len(), 1);
let row = &result[0];
assert_eq!(
row.owner_id,
MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
);
assert_eq!(
row.notification_id,
uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap()
);
assert_eq!(row.entity.entity_type, EntityType::Document);
assert!(!row.sent);
assert_eq!(row.state, NotificationState::Unseen);
assert_eq!(row.notification_metadata.message, "hello");
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_notifications"))
)]
async fn test_get_user_notifications_filters_exact_states(pool: Pool<Postgres>) {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let notification_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
pool.mark_notifications_seen(&user, &[notification_id])
.await
.unwrap();
pool.mark_notifications_done(&user, &[notification_id], true)
.await
.unwrap();
let active: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
user.clone(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters::active(),
)
.await
.unwrap();
assert!(active.is_empty());
let done: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
user.clone(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Done],
include_types: Vec::new(),
entities: Vec::new(),
},
)
.await
.unwrap();
assert_eq!(done.len(), 1);
let unseen: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
user,
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Unseen],
include_types: Vec::new(),
entities: Vec::new(),
},
)
.await
.unwrap();
assert!(unseen.is_empty());
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_notifications"))
)]
async fn test_get_user_notifications_filters_type_and_entity(pool: Pool<Postgres>) {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let document_results: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
user.clone(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Unseen, NotificationState::Seen],
include_types: vec![crate::domain::models::request::NotificationCategory::Document],
entities: Vec::new(),
},
)
.await
.unwrap();
assert_eq!(document_results.len(), 1);
let email_results: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
user.clone(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Unseen, NotificationState::Seen],
include_types: vec![crate::domain::models::request::NotificationCategory::Email],
entities: Vec::new(),
},
)
.await
.unwrap();
assert!(email_results.is_empty());
let entity_results: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
user.clone(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Unseen, NotificationState::Seen],
include_types: Vec::new(),
entities: vec![EntityType::Document.with_entity_string("item-1".to_string())],
},
)
.await
.unwrap();
assert_eq!(entity_results.len(), 1);
let wrong_entity_results: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
user,
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Unseen, NotificationState::Seen],
include_types: Vec::new(),
entities: vec![EntityType::EmailThread.with_entity_string("item-1".to_string())],
},
)
.await
.unwrap();
assert!(wrong_entity_results.is_empty());
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_entity_notifications_batch_matches_channel_thread_secondary_entity(
pool: Pool<Postgres>,
) {
let user = test_user("[email protected]");
let thread_id = Uuid::new_v4().to_string();
let other_thread_id = Uuid::new_v4().to_string();
let direct_notification_id = Uuid::new_v4();
let reply_notification_id = Uuid::new_v4();
let other_thread_notification_id = Uuid::new_v4();
create_message_notification(&pool, &user, direct_notification_id, &thread_id, None).await;
create_message_notification(
&pool,
&user,
reply_notification_id,
&Uuid::new_v4().to_string(),
Some(&thread_id),
)
.await;
create_message_notification(
&pool,
&user,
other_thread_notification_id,
&Uuid::new_v4().to_string(),
Some(&other_thread_id),
)
.await;
let thread_ref = EntityType::ChannelMessage.with_entity_string(thread_id);
let other_thread_ref = EntityType::ChannelMessage.with_entity_string(other_thread_id);
let result = pool
.get_entity_notifications_batch(
user,
vec![thread_ref.clone(), other_thread_ref.clone()],
Default::default(),
)
.await
.unwrap();
let thread_notification_ids = result[&thread_ref]
.iter()
.map(|notification| notification.notification_id)
.collect::<HashSet<_>>();
assert_eq!(
thread_notification_ids,
HashSet::from([direct_notification_id, reply_notification_id])
);
let other_thread_notification_ids = result[&other_thread_ref]
.iter()
.map(|notification| notification.notification_id)
.collect::<HashSet<_>>();
assert_eq!(
other_thread_notification_ids,
HashSet::from([other_thread_notification_id])
);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_entity_notifications_batch_preserves_canonical_entity_identity(
pool: Pool<Postgres>,
) {
let user = test_user("[email protected]");
let task_entity = EntityType::Document.with_entity_string("task-1".to_string());
let foreign_entity = EntityType::ForeignEntity.with_entity_string("foreign-1".to_string());
let task_notification_id = Uuid::new_v4();
let github_notification_id = Uuid::new_v4();
let generic_foreign_notification_id = Uuid::new_v4();
pool.create_notification(
SendNotificationRequestBuilder {
notification_entity: task_entity.clone(),
secondary_notification_entity: None,
notification: TaggedContent::new(TestTaskNotification {
sub_type: "task".to_string(),
}),
sender_id: None,
recipient_ids: HashSet::from([user.clone()]),
},
task_notification_id,
"test_service",
None,
)
.await
.unwrap();
pool.create_notification(
SendNotificationRequestBuilder {
notification_entity: foreign_entity.clone(),
secondary_notification_entity: None,
notification: TaggedContent::new(TestGithubNotification {
message: "github".to_string(),
}),
sender_id: None,
recipient_ids: HashSet::from([user.clone()]),
},
github_notification_id,
"test_service",
None,
)
.await
.unwrap();
pool.create_notification(
SendNotificationRequestBuilder {
notification_entity: foreign_entity.clone(),
secondary_notification_entity: None,
notification: TaggedContent::new(TestNotification {
message: "generic foreign entity".to_string(),
}),
sender_id: None,
recipient_ids: HashSet::from([user.clone()]),
},
generic_foreign_notification_id,
"test_service",
None,
)
.await
.unwrap();
let result = pool
.get_entity_notifications_batch(
user,
vec![task_entity.clone(), foreign_entity.clone()],
Default::default(),
)
.await
.unwrap();
assert_eq!(
result[&task_entity]
.iter()
.map(|notification| notification.notification_id)
.collect::<HashSet<_>>(),
HashSet::from([task_notification_id])
);
assert_eq!(
result[&foreign_entity]
.iter()
.map(|notification| notification.notification_id)
.collect::<HashSet<_>>(),
HashSet::from([github_notification_id, generic_foreign_notification_id])
);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_user_notifications_filters_github_type_and_entity(pool: Pool<Postgres>) {
let user = test_user("[email protected]");
let foreign_entity_id = uuid::Uuid::new_v4().to_string();
let check_run_foreign_entity_id = uuid::Uuid::new_v4().to_string();
let github_notification_id = uuid::Uuid::new_v4();
let check_run_notification_id = uuid::Uuid::new_v4();
let non_github_notification_id = uuid::Uuid::new_v4();
let github_request = SendNotificationRequestBuilder {
notification_entity: EntityType::ForeignEntity
.with_entity_string(foreign_entity_id.clone()),
secondary_notification_entity: None,
notification: TaggedContent::new(TestGithubNotification {
message: "github".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([user.clone()]),
};
pool.create_notification(github_request, github_notification_id, "test_service", None)
.await
.unwrap();
let check_run_request = SendNotificationRequestBuilder {
notification_entity: EntityType::ForeignEntity
.with_entity_string(check_run_foreign_entity_id.clone()),
secondary_notification_entity: None,
notification: TaggedContent::new(TestGithubCheckRunNotification {
message: "check run".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([user.clone()]),
};
pool.create_notification(
check_run_request,
check_run_notification_id,
"test_service",
None,
)
.await
.unwrap();
let non_github_request = SendNotificationRequestBuilder {
notification_entity: EntityType::ForeignEntity
.with_entity_string(foreign_entity_id.clone()),
secondary_notification_entity: None,
notification: TaggedContent::new(TestNotification {
message: "foreign entity".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([user.clone()]),
};
pool.create_notification(
non_github_request,
non_github_notification_id,
"test_service",
None,
)
.await
.unwrap();
let github_type_results: Vec<UserNotificationRow<serde_json::Value>> = pool
.get_user_notifications(
user.clone(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Unseen, NotificationState::Seen],
include_types: vec![NotificationCategory::Github],
entities: Vec::new(),
},
)
.await
.unwrap();
assert_eq!(github_type_results.len(), 2);
let github_type_result_ids: std::collections::HashSet<_> = github_type_results
.iter()
.map(|row| row.notification_id)
.collect();
assert_eq!(
github_type_result_ids,
std::collections::HashSet::from([github_notification_id, check_run_notification_id])
);
let github_type_event_types: std::collections::HashSet<_> = github_type_results
.iter()
.map(|row| row.notification_event_type.as_str())
.collect();
assert_eq!(
github_type_event_types,
std::collections::HashSet::from(["github_pr_status_changed", "github_pr_check_run"])
);
let github_type_entity_ids: std::collections::HashSet<_> = github_type_results
.iter()
.map(|row| row.entity.entity_id.as_ref())
.collect();
assert_eq!(
github_type_entity_ids,
std::collections::HashSet::from([
foreign_entity_id.as_str(),
check_run_foreign_entity_id.as_str(),
])
);
assert!(
github_type_results
.iter()
.all(|row| row.entity.entity_type == EntityType::ForeignEntity)
);
let github_entity_results: Vec<UserNotificationRow<serde_json::Value>> = pool
.get_user_notifications(
user.clone(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Unseen, NotificationState::Seen],
include_types: Vec::new(),
entities: vec![
EntityType::ForeignEntity.with_entity_string(foreign_entity_id.clone()),
],
},
)
.await
.unwrap();
assert_eq!(github_entity_results.len(), 2);
assert_eq!(
github_entity_results
.iter()
.map(|row| row.notification_id)
.collect::<HashSet<_>>(),
HashSet::from([github_notification_id, non_github_notification_id])
);
let check_run_entity_results: Vec<UserNotificationRow<serde_json::Value>> = pool
.get_user_notifications(
user.clone(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Unseen, NotificationState::Seen],
include_types: Vec::new(),
entities: vec![
EntityType::ForeignEntity
.with_entity_string(check_run_foreign_entity_id.clone()),
],
},
)
.await
.unwrap();
assert_eq!(check_run_entity_results.len(), 1);
assert_eq!(
check_run_entity_results[0].notification_id,
check_run_notification_id
);
assert_eq!(
check_run_entity_results[0].notification_event_type,
"github_pr_check_run"
);
assert_eq!(
check_run_entity_results[0].entity.entity_id.as_ref(),
check_run_foreign_entity_id.as_str()
);
let wrong_entity_results: Vec<UserNotificationRow<serde_json::Value>> = pool
.get_user_notifications(
user,
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: vec![NotificationState::Unseen, NotificationState::Seen],
include_types: Vec::new(),
entities: vec![EntityType::Document.with_entity_string(foreign_entity_id)],
},
)
.await
.unwrap();
assert!(wrong_entity_results.is_empty());
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_notifications_with_invalid"))
)]
async fn test_get_user_notifications_skips_invalid_entity_type(pool: Pool<Postgres>) {
let result: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters::active(),
)
.await
.unwrap();
// 3 notifications inserted, but only the valid one (with entity_type "document"
// and correct metadata) should survive. The one with "bogus_entity" and the one
// with non-matching metadata are silently filtered out.
assert_eq!(result.len(), 1);
assert_eq!(
result[0].notification_id,
uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap()
);
assert_eq!(result[0].entity.entity_type, EntityType::Document);
assert_eq!(result[0].notification_metadata.message, "hello");
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_notifications_with_invalid"))
)]
async fn test_get_user_notifications_by_event_item_ids_skips_invalid(pool: Pool<Postgres>) {
let valid_item = uuid::Uuid::parse_str("a0000000-0000-0000-0000-000000000001").unwrap();
let invalid_entity_item =
uuid::Uuid::parse_str("a0000000-0000-0000-0000-000000000002").unwrap();
let invalid_metadata_item =
uuid::Uuid::parse_str("a0000000-0000-0000-0000-000000000003").unwrap();
let result: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications_by_event_item_ids(
MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
&[valid_item, invalid_entity_item, invalid_metadata_item],
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters::active(),
)
.await
.unwrap();
// All three are requested, but only the valid one survives filtering.
assert_eq!(result.len(), 1);
assert_eq!(
result[0].notification_id,
uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap()
);
assert_eq!(result[0].entity.entity_type, EntityType::Document);
assert_eq!(result[0].notification_metadata.message, "hello");
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_user_notifications_empty(pool: Pool<Postgres>) {
let result: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters::active(),
)
.await
.unwrap();
assert!(result.is_empty());
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_create_notification_returns_none_on_conflict(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"),
secondary_notification_entity: None,
notification: TaggedContent::new(TestNotification {
message: "hello".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient.clone()]),
};
// First creation should succeed
let request2 = SendNotificationRequestBuilder {
notification_entity: EntityType::Document.with_entity_str("doc-1"),
secondary_notification_entity: None,
notification: TaggedContent::new(TestNotification {
message: "hello".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient.clone()]),
};
let result = pool
.create_notification(request, notification_id, "test_service", None)
.await
.unwrap();
assert!(result.is_some());
pool.complete_notification_publication(notification_id)
.await
.unwrap();
// Second creation with same ID should return None
let result = pool
.create_notification(request2, notification_id, "test_service", None)
.await
.unwrap();
assert!(result.is_none());
// Verify only one notification exists
let count: i64 = sqlx::query_scalar!(
"SELECT COUNT(*) FROM notification WHERE id = $1",
notification_id
)
.fetch_one(&pool)
.await
.unwrap()
.unwrap();
assert_eq!(count, 1);
// Verify only one user_notification exists (not duplicated)
let user_count: i64 = sqlx::query_scalar!(
"SELECT COUNT(*) FROM user_notification WHERE notification_id = $1",
notification_id
)
.fetch_one(&pool)
.await
.unwrap()
.unwrap();
assert_eq!(user_count, 1);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_create_notification_stores_bare_metadata(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"),
secondary_notification_entity: None,
notification: TaggedContent::new(TestNotification {
message: "hello".to_string(),
}),
sender_id: None,
recipient_ids: std::collections::HashSet::from([recipient.clone()]),
};
pool.create_notification(request, notification_id, "test_service", None)
.await
.unwrap();
// Read the raw metadata JSON from the DB
let row = sqlx::query!(
r#"SELECT metadata as "metadata: serde_json::Value" FROM notification WHERE id = $1"#,
notification_id
)
.fetch_one(&pool)
.await
.unwrap();
let metadata = row.metadata;
// The metadata column must store bare content, not the TaggedContent wrapper.
// Bare content: {"message": "hello"}
// Wrong (wrapped): {"tag": "test_notification", "content": {"message": "hello"}}
assert!(
!metadata.as_object().unwrap().contains_key("tag"),
"metadata should not contain a 'tag' key — it should be bare content, not TaggedContent. Got: {metadata}"
);
assert_eq!(metadata["message"], "hello");
// Verify round-trip: get_user_notifications deserializes the bare metadata back into T
let rows: Vec<UserNotificationRow<TestNotification>> = pool
.get_user_notifications(
recipient,
10,
Query::Sort(CreatedAt, ()),
NotificationListFilters::active(),
)
.await
.unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].notification_metadata.message, "hello");
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_notifications"))
)]
async fn test_delete_all_user_notifications(pool: Pool<Postgres>) {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let notification_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
// Verify the notification exists before deletion
let count_before: i64 = sqlx::query_scalar!(
"SELECT COUNT(*) FROM user_notification WHERE user_id = $1",
user.to_string()
)
.fetch_one(&pool)
.await
.unwrap()
.unwrap();
assert_eq!(count_before, 1);
pool.delete_all_user_notifications(user.clone())
.await
.unwrap();
// Verify the user_notification row is hard-deleted
let count_after: i64 = sqlx::query_scalar!(
"SELECT COUNT(*) FROM user_notification WHERE user_id = $1",
user.to_string()
)
.fetch_one(&pool)
.await
.unwrap()
.unwrap();
assert_eq!(count_after, 0);
// Verify the parent notification record still exists
let notif_count: i64 = sqlx::query_scalar!(
"SELECT COUNT(*) FROM notification WHERE id = $1",
notification_id
)
.fetch_one(&pool)
.await
.unwrap()
.unwrap();
assert_eq!(notif_count, 1);
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_notifications"))
)]
async fn test_delete_all_user_notifications_does_not_affect_other_users(pool: Pool<Postgres>) {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let other_user = test_user("[email protected]");
let notification_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
// Add a user_notification for the other user
sqlx::query!(
"INSERT INTO user_notification (user_id, notification_id, created_at) VALUES ($1, $2, '2025-01-01 00:00:00')",
other_user.to_string(),
notification_id,
)
.execute(&pool)
.await
.unwrap();
// Delete all notifications for the first user only
pool.delete_all_user_notifications(user).await.unwrap();
// The other user's notification should still exist
let other_count: i64 = sqlx::query_scalar!(
"SELECT COUNT(*) FROM user_notification WHERE user_id = $1",
other_user.to_string()
)
.fetch_one(&pool)
.await
.unwrap()
.unwrap();
assert_eq!(other_count, 1);
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_devices"))
)]
async fn android_native_call_capability_round_trips_and_can_be_cleared(pool: Pool<Postgres>) {
use crate::domain::models::device::DeviceType;
use crate::outbound::device_registration::DeviceRegistrationDbOps;
let user = test_user("[email protected]");
for capable in [true, false] {
pool.upsert_device(
user.clone(),
"native-token",
"native-endpoint",
&DeviceType::Android,
capable,
)
.await
.unwrap();
let devices = pool
.get_device_endpoints(std::slice::from_ref(&user))
.await
.unwrap();
let endpoints = &devices[&user];
assert!(endpoints.iter().any(|endpoint| match endpoint {
DeviceEndpoint::AndroidNativeCall(arn) => capable && arn == "native-endpoint",
DeviceEndpoint::Android(arn) => !capable && arn == "native-endpoint",
_ => false,
}));
}
}