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.

Seanaye/feat/mutate notification by entity (#5695)

Sean Aye52aae73f4cf4
diff --git a/.sqlx/query-d164a8fc7b761c64c8da24a9cdbae3c5a8a716f2f391656ac0b0aef4b12e78b8.json b/.sqlx/query-d164a8fc7b761c64c8da24a9cdbae3c5a8a716f2f391656ac0b0aef4b12e78b8.json
new file mode 100644
index 0000000000..847561ee8a
--- /dev/null
+++ b/.sqlx/query-d164a8fc7b761c64c8da24a9cdbae3c5a8a716f2f391656ac0b0aef4b12e78b8.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH requested_entities AS (\n SELECT entity_type, entity_id\n FROM UNNEST($2::text[], $3::text[]) AS entity(entity_type, entity_id)\n )\n SELECT un.notification_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.deleted_at IS NULL\n AND EXISTS (\n SELECT 1\n FROM requested_entities entity\n WHERE (\n n.event_item_type = entity.entity_type\n AND n.event_item_id = entity.entity_id\n )\n OR (\n n.secondary_event_item_type = entity.entity_type\n AND n.secondary_event_item_id = entity.entity_id\n )\n OR (\n entity.entity_type = 'channel_message'\n AND COALESCE(n.metadata->>'messageId', n.metadata->>'message_id', '') = entity.entity_id\n )\n )\n ORDER BY un.created_at, un.notification_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "notification_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "d164a8fc7b761c64c8da24a9cdbae3c5a8a716f2f391656ac0b0aef4b12e78b8"
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 84cdff09a5..30ea0c0107 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -1693,17 +1693,22 @@ export const ListNotifications = z.object({
z.array(
z.object({
entityType: z.enum([
- 'email',
- 'message',
+ 'user',
+ 'chat',
'channel',
+ 'channel_message',
'document',
'project',
- 'chat',
+ 'email_thread',
+ 'calendar_event',
+ 'team',
'call',
- 'task',
- 'github',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
'reminder',
- 'calendar',
+ 'skill',
]),
id: z.string(),
})
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index be480b2523..76af119da6 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -392,10 +392,33 @@ export type SortBy =
| 'recently_viewed'
| 'recently_updated'
| 'recently_created';
+/**
+ * Canonical entity types accepted by the notification-listing tool.
+ *
+ * This mirrors [`EntityType`] because the shared model intentionally does not
+ * depend on `schemars`, while AI tool inputs require [`JsonSchema`].
+ */
+export type NotificationEntityType =
+ | 'user'
+ | 'chat'
+ | 'channel'
+ | 'channel_message'
+ | 'document'
+ | 'project'
+ | 'email_thread'
+ | 'calendar_event'
+ | 'team'
+ | 'call'
+ | 'foreign_entity'
+ | 'static_file'
+ | 'crm_company'
+ | 'crm_contact'
+ | 'reminder'
+ | 'skill';
/**
* User-facing notification categories used for list filtering.
*/
-export type NotificationItemType =
+export type NotificationCategory =
| 'email'
| 'message'
| 'channel'
@@ -2326,13 +2349,13 @@ export interface ListNotifications {
*/
done?: boolean | null;
/**
- * Filter to notifications for specific entities. Pair each id with entityType to avoid ambiguity. Example: [{"entityType":"email","id":"..."}] returns notifications for one email thread.
+ * Filter to notifications for specific entities. Pair each id with its canonical entityType to avoid ambiguity. Example: [{"entityType":"email_thread","id":"..."}] returns notifications for one email thread.
*/
- entities?: NotificationEntityRef[] | null;
+ entities?: NotificationEntityFilter[] | null;
/**
* Filter to specific notification item types. If omitted, returns all types. Example: ["email", "message"] returns only email and message notifications.
*/
- includeTypes?: NotificationItemType[] | null;
+ includeTypes?: NotificationCategory[] | null;
/**
* Maximum number of notifications to return. Defaults to 20, max 50.
*/
@@ -2345,10 +2368,10 @@ export interface ListNotifications {
/**
* User-facing reference to one specific entity to filter notifications by.
*/
-export interface NotificationEntityRef {
- entityType: NotificationItemType;
+export interface NotificationEntityFilter {
+ entityType: NotificationEntityType;
/**
- * Entity id. For `email`, this is the email thread id. For `message`, this is the channel message id.
+ * Canonical entity identifier.
*/
id: string;
}
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index 3ae9cd2684..2ba0344533 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -46,7 +46,7 @@ pub use graphql_favorite::{
pub use graphql_notification::{
EntityNotificationsLoader, GraphqlNotificationUpdateOperation, NoOpNotificationMutationService,
NotificationMutationRoot, NotificationMutationService, SoupNotificationEdgeReader,
- UpdateNotificationsInput, entity_notifications_loader,
+ UpdateNotificationsForEntityInput, UpdateNotificationsInput, entity_notifications_loader,
};
pub use graphql_permission::{
EntityPermissionEdgeReader, EntityPermissionLoader, GraphqlAccessLevelPermission,
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 8b66e09a5d..f60c802284 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -75,6 +75,12 @@ fn soup_response_schema_exposes_frontend_fields() {
"effects: [SoupPatch!]!",
"recordChannelActivity(input: RecordChannelActivityInput!): GraphqlChannelActivity!",
"updateNotifications(input: UpdateNotificationsInput!): [GraphqlNotification!]!",
+ "updateNotificationsForEntity(input: UpdateNotificationsForEntityInput!): [GraphqlNotification!]!",
+ "input UpdateNotificationsForEntityInput {",
+ "entities: [NotificationEntityInput!]!",
+ "input NotificationEntityInput {",
+ "entityType: GraphqlEntityType!",
+ "entityId: ID!",
"markEmailThreadSeen(input: MarkEmailThreadSeenInput!): GraphqlSoupEmailThread!",
"updateEmailThreadLabel(input: UpdateEmailThreadLabelInput!): GraphqlSoupEmailThread!",
"input MarkEmailThreadSeenInput {",
diff --git a/crates/graphql_notification/src/lib.rs b/crates/graphql_notification/src/lib.rs
index 093c302fdb..5af2858f25 100644
--- a/crates/graphql_notification/src/lib.rs
+++ b/crates/graphql_notification/src/lib.rs
@@ -19,8 +19,9 @@ pub use loaders::{
entity_notifications_loader,
};
pub use mutations::{
- GraphqlNotificationUpdateOperation, NoOpNotificationMutationService, NotificationMutationRoot,
- NotificationMutationService, UpdateNotificationsInput,
+ GraphqlNotificationUpdateOperation, NoOpNotificationMutationService, NotificationEntityInput,
+ NotificationMutationRoot, NotificationMutationService, UpdateNotificationsForEntityInput,
+ UpdateNotificationsInput,
};
pub use notification_event::GraphqlNotifEvent;
pub use objects::{GraphqlNotification, load_entity_notifications};
diff --git a/crates/graphql_notification/src/loaders.rs b/crates/graphql_notification/src/loaders.rs
index c7359ae39e..a384ed6855 100644
--- a/crates/graphql_notification/src/loaders.rs
+++ b/crates/graphql_notification/src/loaders.rs
@@ -3,62 +3,13 @@ use std::{collections::HashMap, sync::Arc};
use async_graphql::dataloader::{DataLoader, Loader};
use macro_user_id::user_id::MacroUserIdStr;
use model_notifications::NotifEvent;
-use notification::domain::models::{
- UserNotificationRow,
- request::{NotificationEntityRef, NotificationItemType},
-};
+use notification::domain::models::UserNotificationRow;
use rootcause::markers::{Cloneable, Dynamic};
-/// Tests for notification entity mapping and batching.
+/// Tests for notification entity batching.
#[cfg(test)]
mod test;
-/// Map a shared entity type to the notification domain's item type.
-///
-/// Some Soup entities, such as CRM companies, do not have a corresponding
-/// notification type. Those entities have an empty notification edge rather
-/// than failing the whole DataLoader batch.
-fn notification_item_type(entity_type: model_entity::EntityType) -> Option<NotificationItemType> {
- use model_entity::EntityType;
- match entity_type {
- EntityType::EmailThread => Some(NotificationItemType::Email),
- EntityType::ChannelMessage => Some(NotificationItemType::Message),
- EntityType::Channel => Some(NotificationItemType::Channel),
- EntityType::Document => Some(NotificationItemType::Document),
- EntityType::Project => Some(NotificationItemType::Project),
- EntityType::Chat => Some(NotificationItemType::Chat),
- EntityType::Call => Some(NotificationItemType::Call),
- EntityType::ForeignEntity => Some(NotificationItemType::Github),
- EntityType::Reminder => Some(NotificationItemType::Reminder),
- EntityType::CalendarEvent => Some(NotificationItemType::Calendar),
- EntityType::User
- | EntityType::Team
- | EntityType::StaticFile
- | EntityType::CrmCompany
- | EntityType::CrmContact
- | EntityType::Skill => None,
- }
-}
-
-/// Build notification-service references for the subset of entities that can
-/// own notifications.
-fn notification_refs(
- keys: &[model_entity::Entity<'static>],
-) -> Vec<(model_entity::Entity<'static>, NotificationEntityRef)> {
- keys.iter()
- .filter_map(|key| {
- let entity_type = notification_item_type(key.entity_type)?;
- Some((
- key.clone(),
- NotificationEntityRef {
- entity_type,
- id: key.entity_id.to_string(),
- },
- ))
- })
- .collect()
-}
-
/// Reader used by GraphQL notification edges.
pub trait SoupNotificationEdgeReader: Send + Sync + 'static {
/// Load notifications for the requested entity keys.
@@ -79,42 +30,17 @@ impl<T> SoupNotificationEdgeReader for Arc<T>
where
T: notification::domain::service::NotificationReader,
{
- async fn get_notifications(
+ fn get_notifications(
&self,
user_id: MacroUserIdStr<'static>,
keys: Vec<model_entity::Entity<'static>>,
- ) -> Result<
- HashMap<model_entity::Entity<'static>, Vec<UserNotificationRow<NotifEvent>>>,
- rootcause::Report,
+ ) -> impl Future<
+ Output = Result<
+ HashMap<model_entity::Entity<'static>, Vec<UserNotificationRow<NotifEvent>>>,
+ rootcause::Report,
+ >,
> {
- let mut result = keys
- .iter()
- .cloned()
- .map(|key| (key, Vec::new()))
- .collect::<HashMap<_, _>>();
-
- let requested_refs = notification_refs(&keys);
- if requested_refs.is_empty() {
- return Ok(result);
- }
-
- let entity_refs = requested_refs
- .iter()
- .map(|(_, entity_ref)| entity_ref.clone())
- .collect();
-
- let mut notifications_by_entity = self
- .get_entity_notifications_batch::<NotifEvent>(user_id, entity_refs)
- .await
- .map_err(|err| rootcause::report!(err))?;
-
- for (original_key, entity_ref) in requested_refs {
- if let Some(notifications) = notifications_by_entity.remove(&entity_ref) {
- result.insert(original_key, notifications);
- }
- }
-
- Ok(result)
+ self.get_entity_notifications_batch::<NotifEvent>(user_id, keys)
}
}
diff --git a/crates/graphql_notification/src/loaders/test.rs b/crates/graphql_notification/src/loaders/test.rs
index d805ad1299..6d91bccf3a 100644
--- a/crates/graphql_notification/src/loaders/test.rs
+++ b/crates/graphql_notification/src/loaders/test.rs
@@ -1,43 +1,22 @@
use super::*;
-/// CRM companies are omitted because the notification domain has no CRM
-/// notification item type.
-#[test]
-fn crm_companies_have_an_empty_notification_edge() {
- let keys =
- vec![model_entity::EntityType::CrmCompany.with_entity_string("company-1".to_owned())];
-
- assert!(notification_refs(&keys).is_empty());
-}
-
-/// Calendar events own reminder notifications, so their edge must resolve —
-/// an empty edge would override the client's notification fallback and hide
-/// the row from notification-gated views.
-#[test]
-fn calendar_events_map_to_the_calendar_notification_type() {
- let keys =
- vec![model_entity::EntityType::CalendarEvent.with_entity_string("event-1".to_owned())];
-
- let refs = notification_refs(&keys);
-
- assert_eq!(refs.len(), 1);
- assert_eq!(refs[0].1.entity_type, NotificationItemType::Calendar);
- assert_eq!(refs[0].1.id, "event-1");
+fn test_user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
}
-/// Unsupported entities do not prevent supported entities in the same Soup
-/// page from being requested.
-#[test]
-fn mixed_batches_keep_supported_notification_entities() {
+#[tokio::test]
+async fn schema_reader_preserves_canonical_entity_keys() {
let keys = vec![
model_entity::EntityType::CrmCompany.with_entity_string("company-1".to_owned()),
model_entity::EntityType::Document.with_entity_string("document-1".to_owned()),
+ model_entity::EntityType::ForeignEntity.with_entity_string("foreign-1".to_owned()),
];
- let refs = notification_refs(&keys);
+ let result = NoOpSoupNotificationEdgeReader
+ .get_notifications(test_user(), keys.clone())
+ .await
+ .unwrap();
- assert_eq!(refs.len(), 1);
- assert_eq!(refs[0].0, keys[1]);
- assert_eq!(refs[0].1.entity_type, NotificationItemType::Document);
- assert_eq!(refs[0].1.id, "document-1");
+ assert_eq!(result.len(), keys.len());
+ assert!(keys.iter().all(|key| result[key].is_empty()));
}
diff --git a/crates/graphql_notification/src/mutations.rs b/crates/graphql_notification/src/mutations.rs
index 54fafb6273..8727daa014 100644
--- a/crates/graphql_notification/src/mutations.rs
+++ b/crates/graphql_notification/src/mutations.rs
@@ -1,10 +1,17 @@
use std::{marker::PhantomData, sync::Arc};
use async_graphql::{Context, Enum, ID, InputObject, Object};
-use graphql_common::{parse_id, require_authenticated_user};
+use graphql_common::{GraphqlEntityType, parse_id, require_authenticated_user};
use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use model_notifications::NotifEvent;
use notification::domain::{
- models::{UserNotificationRow, request::NotificationStatus},
+ models::{
+ UserNotificationRow,
+ request::{
+ NotificationStatus, UpdateNotificationsForEntitiesRequest, UpdateNotificationsRequest,
+ },
+ },
service::NotificationReader,
};
use rootcause::Report;
@@ -23,7 +30,15 @@ pub trait NotificationMutationService: Send + Sync + 'static {
user_id: MacroUserIdStr<'static>,
notification_ids: Vec<Uuid>,
status: NotificationStatus,
- ) -> impl Future<Output = Result<Vec<UserNotificationRow<serde_json::Value>>, Report>> + Send;
+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<NotifEvent>>, Report>> + Send;
+
+ /// Update every user-owned notification associated with any requested entity.
+ fn update_notifications_for_entities(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ entities: Vec<Entity<'static>>,
+ status: NotificationStatus,
+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<NotifEvent>>, Report>> + Send;
}
impl<S> NotificationMutationService for S
@@ -35,11 +50,27 @@ where
user_id: MacroUserIdStr<'static>,
notification_ids: Vec<Uuid>,
status: NotificationStatus,
- ) -> Result<Vec<UserNotificationRow<serde_json::Value>>, Report> {
- self.update_notifications_and_return(
- notification::domain::models::request::UpdateNotificationsRequest {
+ ) -> Result<Vec<UserNotificationRow<NotifEvent>>, Report> {
+ self.update_notifications_and_return::<NotifEvent>(UpdateNotificationsRequest {
+ user_id,
+ notification_ids: &notification_ids,
+ status,
+ })
+ .await
+ }
+
+ async fn update_notifications_for_entities(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ entities: Vec<Entity<'static>>,
+ status: NotificationStatus,
+ ) -> Result<Vec<UserNotificationRow<NotifEvent>>, Report> {
+ // Qualify the trait call to disambiguate it from this method and avoid recursive self-calls.
+ NotificationReader::update_notifications_for_entities::<NotifEvent>(
+ self,
+ UpdateNotificationsForEntitiesRequest {
user_id,
- notification_ids: &notification_ids,
+ entities,
status,
},
)
@@ -57,7 +88,18 @@ impl NotificationMutationService for NoOpNotificationMutationService {
_user_id: MacroUserIdStr<'static>,
_notification_ids: Vec<Uuid>,
_status: NotificationStatus,
- ) -> Result<Vec<UserNotificationRow<serde_json::Value>>, Report> {
+ ) -> Result<Vec<UserNotificationRow<NotifEvent>>, Report> {
+ Err(rootcause::report!(
+ "notification mutations are not configured"
+ ))
+ }
+
+ async fn update_notifications_for_entities(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ _entities: Vec<Entity<'static>>,
+ _status: NotificationStatus,
+ ) -> Result<Vec<UserNotificationRow<NotifEvent>>, Report> {
Err(rootcause::report!(
"notification mutations are not configured"
))
@@ -114,6 +156,24 @@ pub struct UpdateNotificationsInput {
pub operation: GraphqlNotificationUpdateOperation,
}
+/// Canonical entity reference used to select notifications for updating.
+#[derive(InputObject)]
+pub struct NotificationEntityInput {
+ /// Canonical entity type.
+ pub entity_type: GraphqlEntityType,
+ /// Canonical entity identifier.
+ pub entity_id: ID,
+}
+
+/// Input for updating all notifications associated with any requested entity.
+#[derive(InputObject)]
+pub struct UpdateNotificationsForEntityInput {
+ /// Canonical entities whose notifications should be updated.
+ pub entities: Vec<NotificationEntityInput>,
+ /// Status operation applied to every matching notification.
+ pub operation: GraphqlNotificationUpdateOperation,
+}
+
/// GraphQL notification mutations.
#[Object]
impl<S> NotificationMutationRoot<S>
@@ -138,16 +198,42 @@ where
.await
.map_err(|error| async_graphql::Error::new(error.to_string()))?;
- notifications
+ Ok(to_graphql_notifications(notifications))
+ }
+
+ /// Update all notifications associated with the requested entities for the authenticated user.
+ async fn update_notifications_for_entity(
+ &self,
+ ctx: &Context<'_>,
+ input: UpdateNotificationsForEntityInput,
+ ) -> async_graphql::Result<Vec<GraphqlNotification>> {
+ let user_id = require_authenticated_user(ctx)?;
+ let entities = input
+ .entities
.into_iter()
- .map(GraphqlNotification::try_from)
- .collect::<Result<Vec<_>, _>>()
- .map_err(|error| {
- tracing::error!(
- error = ?error,
- "failed to deserialize notification metadata"
- );
- async_graphql::Error::new("notification metadata is unavailable")
+ .map(|entity| {
+ entity
+ .entity_type
+ .into_model()
+ .with_entity_string(entity.entity_id.0)
})
+ .collect();
+ let service = ctx.data::<Arc<S>>()?;
+ let notifications = service
+ .update_notifications_for_entities(user_id, entities, input.operation.into())
+ .await
+ .map_err(|error| async_graphql::Error::new(error.to_string()))?;
+
+ Ok(to_graphql_notifications(notifications))
}
}
+
+/// Convert authoritative domain rows into typed GraphQL notifications.
+fn to_graphql_notifications(
+ notifications: Vec<UserNotificationRow<NotifEvent>>,
+) -> Vec<GraphqlNotification> {
+ notifications
+ .into_iter()
+ .map(GraphqlNotification::from)
+ .collect()
+}
diff --git a/crates/graphql_notification/src/mutations/test.rs b/crates/graphql_notification/src/mutations/test.rs
index 8baa396d7a..af12562706 100644
--- a/crates/graphql_notification/src/mutations/test.rs
+++ b/crates/graphql_notification/src/mutations/test.rs
@@ -2,8 +2,10 @@ use std::sync::{Arc, Mutex};
use async_graphql::{EmptySubscription, Object, Schema};
use chrono::Utc;
-use model_entity::EntityType;
-use model_notifications::{ChannelMessageSendMetadata, ChannelType, CommonChannelMetadata};
+use model_entity::{Entity, EntityType};
+use model_notifications::{
+ ChannelMessageSendMetadata, ChannelType, CommonChannelMetadata, NotifEvent,
+};
use notification::domain::models::request::NotificationStatus;
use super::*;
@@ -20,6 +22,49 @@ impl QueryRoot {
#[derive(Default)]
struct CapturingNotificationService {
calls: Mutex<Vec<(String, Vec<Uuid>, &'static str)>>,
+ entity_calls: Mutex<Vec<(String, Vec<(EntityType, String)>, &'static str)>>,
+}
+
+fn operation_name(status: &NotificationStatus) -> &'static str {
+ match status {
+ NotificationStatus::Seen => "seen",
+ NotificationStatus::Done(true) => "done",
+ NotificationStatus::Done(false) => "undone",
+ }
+}
+
+fn notification_row(
+ user_id: MacroUserIdStr<'static>,
+ notification_id: Uuid,
+ entity: Entity<'static>,
+ status: &NotificationStatus,
+) -> UserNotificationRow<NotifEvent> {
+ let now = Utc::now();
+ UserNotificationRow {
+ owner_id: user_id,
+ notification_id,
+ notification_event_type: "channel_message_send".to_string(),
+ entity,
+ sent: true,
+ done: matches!(status, NotificationStatus::Done(true)),
+ created_at: now,
+ viewed_at: matches!(status, NotificationStatus::Seen).then_some(now),
+ updated_at: now,
+ deleted_at: None,
+ notification_metadata: NotifEvent::ChannelMessageSend(ChannelMessageSendMetadata {
+ sender: None,
+ sender_display_name: None,
+ message_content: "Test message".to_string(),
+ message_id: "message-1".to_string(),
+ has_attachments: false,
+ common: CommonChannelMetadata {
+ channel_type: ChannelType::Public,
+ channel_name: "Test channel".to_string(),
+ },
+ sender_profile_picture_url: None,
+ }),
+ sender_id: None,
+ }
}
impl NotificationMutationService for CapturingNotificationService {
@@ -28,44 +73,50 @@ impl NotificationMutationService for CapturingNotificationService {
user_id: MacroUserIdStr<'static>,
notification_ids: Vec<Uuid>,
status: NotificationStatus,
- ) -> Result<Vec<UserNotificationRow<serde_json::Value>>, Report> {
- let operation = match status {
- NotificationStatus::Seen => "seen",
- NotificationStatus::Done(true) => "done",
- NotificationStatus::Done(false) => "undone",
- };
+ ) -> Result<Vec<UserNotificationRow<NotifEvent>>, Report> {
+ let operation = operation_name(&status);
self.calls
.lock()
.unwrap()
.push((user_id.to_string(), notification_ids.clone(), operation));
- let now = Utc::now();
Ok(notification_ids
.into_iter()
- .map(|notification_id| UserNotificationRow {
- owner_id: user_id.clone(),
- notification_id,
- notification_event_type: "channel_message_send".to_string(),
- entity: EntityType::Channel.with_entity_string("channel-1".to_string()),
- sent: true,
- done: false,
- created_at: now,
- viewed_at: Some(now),
- updated_at: now,
- deleted_at: None,
- notification_metadata: serde_json::to_value(ChannelMessageSendMetadata {
- sender: None,
- sender_display_name: None,
- message_content: "Test message".to_string(),
- message_id: "message-1".to_string(),
- has_attachments: false,
- common: CommonChannelMetadata {
- channel_type: ChannelType::Public,
- channel_name: "Test channel".to_string(),
- },
- sender_profile_picture_url: None,
- })
- .unwrap(),
- sender_id: None,
+ .map(|notification_id| {
+ notification_row(
+ user_id.clone(),
+ notification_id,
+ EntityType::Channel.with_entity_string("channel-1".to_string()),
+ &status,
+ )
+ })
+ .collect())
+ }
+
+ async fn update_notifications_for_entities(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ entities: Vec<Entity<'static>>,
+ status: NotificationStatus,
+ ) -> Result<Vec<UserNotificationRow<NotifEvent>>, Report> {
+ let operation = operation_name(&status);
+ self.entity_calls.lock().unwrap().push((
+ user_id.to_string(),
+ entities
+ .iter()
+ .map(|entity| (entity.entity_type, entity.entity_id.to_string()))
+ .collect(),
+ operation,
+ ));
+ Ok(entities
+ .into_iter()
+ .enumerate()
+ .map(|(index, entity)| {
+ notification_row(
+ user_id.clone(),
+ Uuid::from_u128(index as u128 + 1),
+ entity,
+ &status,
+ )
})
.collect())
}
@@ -129,3 +180,71 @@ async fn update_notifications_maps_operation_and_returns_normalized_rows_in_orde
),]
);
}
+
+#[tokio::test]
+async fn update_notifications_for_entity_maps_entities_and_operation() {
+ let service = Arc::new(CapturingNotificationService::default());
+ let user = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let schema = Schema::build(
+ QueryRoot,
+ NotificationMutationRoot::<CapturingNotificationService>::new(),
+ EmptySubscription,
+ )
+ .data(service.clone())
+ .data(user)
+ .finish();
+
+ let response = schema
+ .execute(
+ r#"mutation {
+ updateNotificationsForEntity(input: {
+ entities: [
+ { entityType: DOCUMENT, entityId: "document-1" },
+ { entityType: CHANNEL_MESSAGE, entityId: "message-1" }
+ ],
+ operation: MARK_DONE
+ }) {
+ id
+ done
+ entityType
+ entityId
+ }
+ }"#,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ assert_eq!(
+ data["updateNotificationsForEntity"][0]["id"],
+ Uuid::from_u128(1).to_string()
+ );
+ assert_eq!(data["updateNotificationsForEntity"][0]["done"], true);
+ assert_eq!(
+ data["updateNotificationsForEntity"][0]["entityType"],
+ "DOCUMENT"
+ );
+ assert_eq!(
+ data["updateNotificationsForEntity"][0]["entityId"],
+ "document-1"
+ );
+ assert_eq!(
+ data["updateNotificationsForEntity"][1]["entityType"],
+ "CHANNEL_MESSAGE"
+ );
+ assert_eq!(
+ data["updateNotificationsForEntity"][1]["entityId"],
+ "message-1"
+ );
+ assert_eq!(
+ service.entity_calls.lock().unwrap().as_slice(),
+ [(
+ "macro|[email protected]".to_string(),
+ vec![
+ (EntityType::Document, "document-1".to_string()),
+ (EntityType::ChannelMessage, "message-1".to_string()),
+ ],
+ "done",
+ )]
+ );
+}
diff --git a/crates/notification/src/domain/models/request.rs b/crates/notification/src/domain/models/request.rs
index 789b9ea051..06c9dc70fe 100644
--- a/crates/notification/src/domain/models/request.rs
+++ b/crates/notification/src/domain/models/request.rs
@@ -20,7 +20,7 @@ use uuid::Uuid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "ai_tool", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
-pub enum NotificationItemType {
+pub enum NotificationCategory {
Email,
Message,
Channel,
@@ -34,41 +34,6 @@ pub enum NotificationItemType {
Calendar,
}
-impl NotificationItemType {
- pub(crate) fn filter_token(self) -> &'static str {
- match self {
- Self::Email => "email",
- Self::Message => "message",
- Self::Channel => "channel",
- Self::Document => "document",
- Self::Project => "project",
- Self::Chat => "chat",
- Self::Call => "call",
- Self::Task => "task",
- Self::Github => "github",
- Self::Reminder => "reminder",
- Self::Calendar => "calendar",
- }
- }
-}
-
-/// User-facing reference to one specific entity to filter notifications by.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
-#[cfg_attr(feature = "ai_tool", derive(schemars::JsonSchema))]
-#[serde(rename_all = "camelCase")]
-pub struct NotificationEntityRef {
- /// Entity type for the provided id.
- pub entity_type: NotificationItemType,
- /// Entity id. For `email`, this is the email thread id. For `message`, this is the channel message id.
- pub id: String,
-}
-
-impl NotificationEntityRef {
- pub(crate) fn filter_token(&self) -> String {
- format!("{}:{}", self.entity_type.filter_token(), self.id)
- }
-}
-
/// Request to send a notification.
///
/// Generic over the notification payload type `T`, which must implement
@@ -320,6 +285,17 @@ pub struct UpdateNotificationsRequest<'a> {
pub status: NotificationStatus,
}
+/// Request to update every notification associated with any of several entities for a user.
+#[derive(Debug)]
+pub struct UpdateNotificationsForEntitiesRequest<'a> {
+ /// The user whose notifications are being updated.
+ pub user_id: MacroUserIdStr<'a>,
+ /// The primary or secondary entities whose notifications should be updated.
+ pub entities: Vec<Entity<'a>>,
+ /// The status to set on matching notifications.
+ pub status: NotificationStatus,
+}
+
/// Optional filters for listing user notifications.
#[derive(Debug, Clone)]
pub struct NotificationListFilters {
@@ -328,9 +304,9 @@ pub struct NotificationListFilters {
/// Filter by seen status. `None` means include both seen and unseen notifications.
pub seen: Option<bool>,
/// Optional user-facing notification categories to include. Empty means include all types.
- pub include_types: Vec<NotificationItemType>,
+ pub include_types: Vec<NotificationCategory>,
/// Optional specific entities to include. Empty means include all entities.
- pub entities: Vec<NotificationEntityRef>,
+ pub entities: Vec<Entity<'static>>,
}
impl NotificationListFilters {
@@ -343,20 +319,6 @@ impl NotificationListFilters {
entities: Vec::new(),
}
}
-
- pub(crate) fn include_type_tokens(&self) -> Vec<String> {
- self.include_types
- .iter()
- .map(|item_type| item_type.filter_token().to_string())
- .collect()
- }
-
- pub(crate) fn entity_tokens(&self) -> Vec<String> {
- self.entities
- .iter()
- .map(NotificationEntityRef::filter_token)
- .collect()
- }
}
/// Request to get a user's notifications filtered by event item IDs.
diff --git a/crates/notification/src/domain/ports.rs b/crates/notification/src/domain/ports.rs
index bcf8061f85..b6608ae5c5 100644
--- a/crates/notification/src/domain/ports.rs
+++ b/crates/notification/src/domain/ports.rs
@@ -13,13 +13,14 @@ use serde::Serialize;
use serde::de::DeserializeOwned;
use uuid::Uuid;
+use model_entity::Entity;
use models_pagination::{CreatedAt, Query};
use crate::domain::models::device::DeviceType;
use crate::domain::models::{NotificationStatusPayload, TaggedContent};
use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};
-use crate::domain::models::request::{NotificationEntityRef, NotificationListFilters};
+use crate::domain::models::request::NotificationListFilters;
use crate::domain::models::{
DeviceEndpoint, DisabledNotificationType, NotificationExtEmail, NotificationIdAndCollapseKey,
SendNotificationRequestBuilder, UserNotificationRow, VoipPushTarget,
@@ -108,6 +109,13 @@ pub trait NotificationRepository: Send + Sync + 'static {
done: bool,
) -> impl Future<Output = Result<Vec<UserNotificationRow<serde_json::Value>>, Report>> + Send;
+ /// Get active user-owned notification IDs associated with any primary or secondary entity.
+ fn get_notification_ids_for_entities(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ entities: &[Entity<'_>],
+ ) -> impl Future<Output = Result<Vec<Uuid>, Report>> + Send;
+
/// Get basic notification data (collapse keys) needed for push clearing.
fn get_basic_notifications(
&self,
@@ -150,10 +158,10 @@ pub trait NotificationRepository: Send + Sync + 'static {
fn get_entity_notifications_batch(
&self,
user_id: MacroUserIdStr<'_>,
- entity_refs: Vec<NotificationEntityRef>,
+ entities: Vec<Entity<'static>>,
) -> impl Future<
Output = Result<
- HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>,
+ HashMap<Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>,
Report,
>,
> + Send;
diff --git a/crates/notification/src/domain/service/device/test.rs b/crates/notification/src/domain/service/device/test.rs
index 461f35ac98..53cf90b953 100644
--- a/crates/notification/src/domain/service/device/test.rs
+++ b/crates/notification/src/domain/service/device/test.rs
@@ -179,6 +179,13 @@ impl NotificationRepository for MockNotifRepo {
) -> Result<Vec<crate::domain::models::UserNotificationRow<serde_json::Value>>, Report> {
unimplemented!()
}
+ async fn get_notification_ids_for_entities(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ _: &[model_entity::Entity<'_>],
+ ) -> Result<Vec<uuid::Uuid>, Report> {
+ unimplemented!()
+ }
async fn get_basic_notifications(
&self,
_: &[uuid::Uuid],
@@ -214,10 +221,10 @@ impl NotificationRepository for MockNotifRepo {
async fn get_entity_notifications_batch(
&self,
_: macro_user_id::user_id::MacroUserIdStr<'_>,
- entity_refs: Vec<crate::domain::models::request::NotificationEntityRef>,
+ entity_refs: Vec<model_entity::Entity<'static>>,
) -> Result<
std::collections::HashMap<
- crate::domain::models::request::NotificationEntityRef,
+ model_entity::Entity<'static>,
Vec<crate::domain::models::UserNotificationRow<serde_json::Value>>,
>,
Report,
diff --git a/crates/notification/src/domain/service/ingress.rs b/crates/notification/src/domain/service/ingress.rs
index 8587c9e6d6..56be388aa8 100644
--- a/crates/notification/src/domain/service/ingress.rs
+++ b/crates/notification/src/domain/service/ingress.rs
@@ -13,8 +13,8 @@ use crate::domain::models::queue_message::{
QueueMessageNeedsStateMachine, UserApnsEndpoints,
};
use crate::domain::models::request::{
- BuildApnsOutput, GetNotificationsByEventItemIdsRequest, NotificationEntityRef,
- NotificationListFilters, NotificationStatus, SendNotificationRequest,
+ BuildApnsOutput, GetNotificationsByEventItemIdsRequest, NotificationListFilters,
+ NotificationStatus, SendNotificationRequest, UpdateNotificationsForEntitiesRequest,
UpdateNotificationsRequest,
};
use crate::domain::models::{
@@ -29,6 +29,7 @@ use crate::domain::service::SendNotificationError;
use ::futures::future::join_all;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
use models_pagination::{CreatedAt, PaginateOn, Paginated, Query, TypeEraseCursor};
use rootcause::Report;
use rootcause::prelude::ResultExt;
@@ -63,10 +64,16 @@ pub trait NotificationReader: Send + Sync + 'static {
) -> impl Future<Output = Result<(), Report>> + Send;
/// Update notifications and return the authoritative active rows owned by the user.
- fn update_notifications_and_return(
+ fn update_notifications_and_return<T: DeserializeOwned + Send>(
&self,
req: UpdateNotificationsRequest,
- ) -> impl Future<Output = Result<Vec<UserNotificationRow<serde_json::Value>>, Report>> + Send;
+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;
+
+ /// Update every active notification associated with any requested entity for a user.
+ fn update_notifications_for_entities<T: DeserializeOwned + Send>(
+ &self,
+ req: UpdateNotificationsForEntitiesRequest,
+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;
/// Get a user's non-deleted notifications, paginated.
///
@@ -92,10 +99,8 @@ pub trait NotificationReader: Send + Sync + 'static {
fn get_entity_notifications_batch<T: DeserializeOwned + Send>(
&self,
user_id: MacroUserIdStr<'_>,
- entity_refs: Vec<NotificationEntityRef>,
- ) -> impl Future<
- Output = Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<T>>>, Report>,
- > + Send;
+ entities: Vec<Entity<'static>>,
+ ) -> impl Future<Output = Result<HashMap<Entity<'static>, Vec<UserNotificationRow<T>>>, Report>> + Send;
/// Get a single user notification by ID.
fn get_user_notification_by_id<T: DeserializeOwned + Send>(
@@ -495,10 +500,10 @@ where
/// b. Look up the user's iOS device endpoints
/// c. Publish silent background push messages to clear badges on devices
#[tracing::instrument(err, skip(self))]
- async fn update_notifications_impl(
+ async fn update_notifications_impl<T: DeserializeOwned + Send>(
&self,
req: UpdateNotificationsRequest<'_>,
- ) -> Result<Vec<UserNotificationRow<serde_json::Value>>, Report> {
+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {
let changed = match &req.status {
NotificationStatus::Seen => {
self.repository
@@ -529,7 +534,7 @@ where
}
if !req.status.should_clear_push_notifs() {
- return Ok(changed);
+ return deserialize_updated_notifications(changed);
}
let notifications_with_keys = self
@@ -538,7 +543,7 @@ where
.await?;
if notifications_with_keys.is_empty() {
- return Ok(changed);
+ return deserialize_updated_notifications(changed);
}
let device_endpoints = self
@@ -571,7 +576,7 @@ where
.collect();
if ios_endpoints.is_empty() {
- return Ok(changed);
+ return deserialize_updated_notifications(changed);
}
let messages: Vec<QueueMessage<'_, ClearPushIdentifier, ClearPushIdentifier>> =
@@ -609,10 +614,35 @@ where
self.queue.publish(messages).await?;
- Ok(changed)
+ deserialize_updated_notifications(changed)
}
}
+/// Deserialize updated rows from their persisted event-tagged metadata representation.
+fn deserialize_updated_notifications<T: DeserializeOwned>(
+ notifications: Vec<UserNotificationRow<serde_json::Value>>,
+) -> Result<Vec<UserNotificationRow<T>>, Report> {
+ Ok(notifications
+ .into_iter()
+ .filter_map(|notification| {
+ let notification_id = notification.notification_id;
+ let notification_event_type = notification.notification_event_type.clone();
+ match notification.into_tagged().deserialize_metadata::<T>() {
+ Ok(notification) => Some(notification),
+ Err(error) => {
+ tracing::warn!(
+ error = ?error,
+ %notification_id,
+ notification_event_type,
+ "skipping updated notification with invalid metadata"
+ );
+ None
+ }
+ }
+ })
+ .collect())
+}
+
impl<N, Q, S, R> NotificationReader for NotificationReaderService<N, Q, S, R>
where
N: NotificationRepository,
@@ -624,17 +654,41 @@ where
&self,
req: UpdateNotificationsRequest<'_>,
) -> Result<(), Report> {
- self.update_notifications_impl(req).await.map(|_| ())
+ self.update_notifications_impl::<serde_json::Value>(req)
+ .await
+ .map(|_| ())
}
#[tracing::instrument(err, skip(self))]
- async fn update_notifications_and_return(
+ async fn update_notifications_and_return<T: DeserializeOwned + Send>(
&self,
req: UpdateNotificationsRequest<'_>,
- ) -> Result<Vec<UserNotificationRow<serde_json::Value>>, Report> {
+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {
self.update_notifications_impl(req).await
}
+ #[tracing::instrument(err, skip(self))]
+ async fn update_notifications_for_entities<T: DeserializeOwned + Send>(
+ &self,
+ req: UpdateNotificationsForEntitiesRequest<'_>,
+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {
+ let notification_ids = self
+ .repository
+ .get_notification_ids_for_entities(req.user_id.copied(), &req.entities)
+ .await?;
+
+ if notification_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ self.update_notifications_impl(UpdateNotificationsRequest {
+ user_id: req.user_id,
+ notification_ids: &notification_ids,
+ status: req.status,
+ })
+ .await
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
@@ -690,14 +744,14 @@ where
async fn get_entity_notifications_batch<T: DeserializeOwned + Send>(
&self,
user_id: MacroUserIdStr<'_>,
- entity_refs: Vec<NotificationEntityRef>,
- ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<T>>>, Report> {
+ entities: Vec<Entity<'static>>,
+ ) -> Result<HashMap<Entity<'static>, Vec<UserNotificationRow<T>>>, Report> {
Ok(self
.repository
- .get_entity_notifications_batch(user_id, entity_refs)
+ .get_entity_notifications_batch(user_id, entities)
.await?
.into_iter()
- .map(|(entity_ref, notifications)| {
+ .map(|(entity, notifications)| {
let notifications = notifications
.into_iter()
.filter_map(|notification| {
@@ -710,8 +764,8 @@ where
error = ?error,
%notification_id,
notification_event_type,
- entity_type = ?entity_ref.entity_type,
- entity_id = %entity_ref.id,
+ entity_type = ?entity.entity_type,
+ entity_id = %entity.entity_id,
"skipping notification with invalid metadata"
);
None
@@ -720,7 +774,7 @@ where
})
.collect();
- (entity_ref, notifications)
+ (entity, notifications)
})
.collect())
}
diff --git a/crates/notification/src/domain/service/push_notification_event/test.rs b/crates/notification/src/domain/service/push_notification_event/test.rs
index 24ad79c638..824657506a 100644
--- a/crates/notification/src/domain/service/push_notification_event/test.rs
+++ b/crates/notification/src/domain/service/push_notification_event/test.rs
@@ -110,6 +110,13 @@ impl NotificationRepository for MockNotifRepo {
) -> Result<Vec<crate::domain::models::UserNotificationRow<serde_json::Value>>, Report> {
unimplemented!()
}
+ async fn get_notification_ids_for_entities(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ _: &[model_entity::Entity<'_>],
+ ) -> Result<Vec<uuid::Uuid>, Report> {
+ unimplemented!()
+ }
async fn get_basic_notifications(
&self,
_: &[uuid::Uuid],
@@ -145,10 +152,10 @@ impl NotificationRepository for MockNotifRepo {
async fn get_entity_notifications_batch(
&self,
_: macro_user_id::user_id::MacroUserIdStr<'_>,
- entity_refs: Vec<crate::domain::models::request::NotificationEntityRef>,
+ entity_refs: Vec<model_entity::Entity<'static>>,
) -> Result<
std::collections::HashMap<
- crate::domain::models::request::NotificationEntityRef,
+ model_entity::Entity<'static>,
Vec<crate::domain::models::UserNotificationRow<serde_json::Value>>,
>,
Report,
diff --git a/crates/notification/src/domain/service/test.rs b/crates/notification/src/domain/service/test.rs
index 603284ab9c..c3a4d87fa1 100644
--- a/crates/notification/src/domain/service/test.rs
+++ b/crates/notification/src/domain/service/test.rs
@@ -11,7 +11,7 @@ use crate::domain::models::queue_message::{
RawQueueMessage, RealtimeNotif,
};
use crate::domain::models::request::{
- NotificationEntityRef, NotificationItemType, NotificationStatus, UpdateNotificationsRequest,
+ NotificationStatus, UpdateNotificationsForEntitiesRequest, UpdateNotificationsRequest,
};
use crate::domain::models::{
DeviceEndpoint, Notification, NotificationExtEmail, NotificationExtIos,
@@ -29,7 +29,7 @@ use crate::domain::service::{
use chrono::Utc;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
-use model_entity::EntityType;
+use model_entity::{Entity, EntityType};
use rate_limit::domain::models::RateLimitOk;
use rootcause::{Report, report};
use serde::de::DeserializeOwned;
@@ -111,8 +111,10 @@ struct MockRepository {
stored_collapse_keys: Mutex<Vec<(Uuid, Option<String>)>>,
basic_notifications: Vec<NotificationIdAndCollapseKey>,
digest_eligible_notification_ids: Option<HashSet<Uuid>>,
- entity_notifications:
- HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>,
+ entity_notifications: HashMap<Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>,
+ entity_notification_ids: Vec<Uuid>,
+ updated_notifications: Option<Vec<UserNotificationRow<serde_json::Value>>>,
+ entity_lookup_calls: Mutex<Vec<(String, Vec<(EntityType, String)>)>>,
mark_seen_calls: Mutex<Vec<(String, Vec<Uuid>)>>,
mark_done_calls: Mutex<Vec<(String, Vec<Uuid>, bool)>>,
}
@@ -129,6 +131,9 @@ impl MockRepository {
basic_notifications: Vec::new(),
digest_eligible_notification_ids: None,
entity_notifications: HashMap::new(),
+ entity_notification_ids: Vec::new(),
+ updated_notifications: None,
+ entity_lookup_calls: Mutex::new(Vec::new()),
mark_seen_calls: Mutex::new(Vec::new()),
mark_done_calls: Mutex::new(Vec::new()),
}
@@ -152,10 +157,23 @@ impl MockRepository {
fn with_entity_notifications(
mut self,
- entity_ref: NotificationEntityRef,
+ entity: Entity<'static>,
notifications: Vec<UserNotificationRow<serde_json::Value>>,
) -> Self {
- self.entity_notifications.insert(entity_ref, notifications);
+ self.entity_notifications.insert(entity, notifications);
+ self
+ }
+
+ fn with_entity_notification_ids(mut self, notification_ids: Vec<Uuid>) -> Self {
+ self.entity_notification_ids = notification_ids;
+ self
+ }
+
+ fn with_updated_notifications(
+ mut self,
+ notifications: Vec<UserNotificationRow<serde_json::Value>>,
+ ) -> Self {
+ self.updated_notifications = Some(notifications);
self
}
@@ -217,7 +235,7 @@ fn updated_notification(
viewed_at,
updated_at,
deleted_at: None,
- notification_metadata: json!({}),
+ notification_metadata: json!({ "message": "updated notification" }),
sender_id: None,
}
}
@@ -301,6 +319,9 @@ impl NotificationRepository for MockRepository {
.lock()
.unwrap()
.push((user_id.to_string(), notification_ids.to_vec()));
+ if let Some(notifications) = &self.updated_notifications {
+ return Ok(notifications.clone());
+ }
let now = Utc::now();
Ok(notification_ids
.iter()
@@ -319,6 +340,9 @@ impl NotificationRepository for MockRepository {
notification_ids.to_vec(),
done,
));
+ if let Some(notifications) = &self.updated_notifications {
+ return Ok(notifications.clone());
+ }
let now = Utc::now();
Ok(notification_ids
.iter()
@@ -326,6 +350,21 @@ impl NotificationRepository for MockRepository {
.collect())
}
+ async fn get_notification_ids_for_entities(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ entities: &[model_entity::Entity<'_>],
+ ) -> Result<Vec<Uuid>, Report> {
+ self.entity_lookup_calls.lock().unwrap().push((
+ user_id.to_string(),
+ entities
+ .iter()
+ .map(|entity| (entity.entity_type, entity.entity_id.to_string()))
+ .collect(),
+ ));
+ Ok(self.entity_notification_ids.clone())
+ }
+
async fn get_basic_notifications(
&self,
_notification_ids: &[Uuid],
@@ -368,18 +407,17 @@ impl NotificationRepository for MockRepository {
async fn get_entity_notifications_batch(
&self,
_user_id: MacroUserIdStr<'_>,
- entity_refs: Vec<NotificationEntityRef>,
- ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>, Report>
- {
- Ok(entity_refs
+ entities: Vec<Entity<'static>>,
+ ) -> Result<HashMap<Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>, Report> {
+ Ok(entities
.into_iter()
- .map(|entity_ref| {
+ .map(|entity| {
let notifications = self
.entity_notifications
- .get(&entity_ref)
+ .get(&entity)
.cloned()
.unwrap_or_default();
- (entity_ref, notifications)
+ (entity, notifications)
})
.collect())
}
@@ -551,6 +589,16 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
.await
}
+ async fn get_notification_ids_for_entities(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ entities: &[model_entity::Entity<'_>],
+ ) -> Result<Vec<Uuid>, Report> {
+ (**self)
+ .get_notification_ids_for_entities(user_id, entities)
+ .await
+ }
+
async fn get_basic_notifications(
&self,
notification_ids: &[Uuid],
@@ -602,11 +650,10 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
async fn get_entity_notifications_batch(
&self,
user_id: MacroUserIdStr<'_>,
- entity_refs: Vec<NotificationEntityRef>,
- ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>, Report>
- {
+ entities: Vec<Entity<'static>>,
+ ) -> Result<HashMap<Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>, Report> {
(**self)
- .get_entity_notifications_batch(user_id, entity_refs)
+ .get_entity_notifications_batch(user_id, entities)
.await
}
@@ -1528,10 +1575,7 @@ async fn test_egress_conn_gateway_not_rate_limited() {
#[tokio::test]
async fn test_get_entity_notifications_batch_skips_invalid_tagged_metadata() {
let user = test_user_id("[email protected]");
- let entity_ref = NotificationEntityRef {
- entity_type: NotificationItemType::Document,
- id: "doc-1".to_string(),
- };
+ let entity_ref = EntityType::Document.with_entity_string("doc-1".to_string());
let now = Utc::now();
let valid_id = Uuid::now_v7();
let invalid_id = Uuid::now_v7();
@@ -1570,10 +1614,7 @@ async fn test_get_entity_notifications_batch_skips_invalid_tagged_metadata() {
#[tokio::test]
async fn test_get_entity_notifications_batch_deserializes_tagged_metadata() {
let user = test_user_id("[email protected]");
- let entity_ref = NotificationEntityRef {
- entity_type: NotificationItemType::Document,
- id: "doc-1".to_string(),
- };
+ let entity_ref = EntityType::Document.with_entity_string("doc-1".to_string());
let notification_id = Uuid::now_v7();
let now = Utc::now();
let mut notification = updated_notification(user.clone(), notification_id, false, None, now);
@@ -1751,7 +1792,7 @@ async fn test_update_notifications_and_return_preserves_requested_order() {
let notification_ids = [second, first];
let updated = service
- .update_notifications_and_return(UpdateNotificationsRequest {
+ .update_notifications_and_return::<TestNotifEvent>(UpdateNotificationsRequest {
user_id: user.clone(),
notification_ids: &notification_ids,
status: NotificationStatus::Done(false),
@@ -1771,6 +1812,151 @@ async fn test_update_notifications_and_return_preserves_requested_order() {
.iter()
.all(|notification| notification.owner_id == user)
);
+ assert!(updated.iter().all(|notification| matches!(
+ &notification.notification_metadata,
+ TestNotifEvent::TestNotification(TestNotification { message })
+ if message == "updated notification"
+ )));
+}
+
+#[tokio::test]
+async fn test_update_notifications_and_return_skips_invalid_tagged_metadata() {
+ let user = test_user_id("[email protected]");
+ let valid_id = Uuid::now_v7();
+ let invalid_id = Uuid::now_v7();
+ let now = Utc::now();
+ let valid = updated_notification(user.clone(), valid_id, false, None, now);
+ let mut invalid = updated_notification(user.clone(), invalid_id, false, None, now);
+ invalid.notification_event_type = "unknown_notification".to_string();
+
+ let repo = Arc::new(MockRepository::new().with_updated_notifications(vec![invalid, valid]));
+ let service = NotificationReaderService {
+ repository: repo,
+ queue: Arc::new(MockQueue::new()),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
+
+ let updated = service
+ .update_notifications_and_return::<TestNotifEvent>(UpdateNotificationsRequest {
+ user_id: user,
+ notification_ids: &[invalid_id, valid_id],
+ status: NotificationStatus::Done(false),
+ })
+ .await
+ .expect("invalid metadata does not fail an already-committed update");
+
+ assert_eq!(updated.len(), 1);
+ assert_eq!(updated[0].notification_id, valid_id);
+}
+
+#[tokio::test]
+async fn test_update_notifications_for_entities_uses_single_batch_lookup() {
+ let user = test_user_id("[email protected]");
+ let first = Uuid::now_v7();
+ let second = Uuid::now_v7();
+ let repo = Arc::new(MockRepository::new().with_entity_notification_ids(vec![first, second]));
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: Arc::new(MockQueue::new()),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
+
+ let updated = service
+ .update_notifications_for_entities::<TestNotifEvent>(
+ UpdateNotificationsForEntitiesRequest {
+ user_id: user.clone(),
+ entities: vec![
+ EntityType::ChannelMessage.with_entity_str("message-1"),
+ EntityType::Document.with_entity_str("document-1"),
+ ],
+ status: NotificationStatus::Seen,
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ updated
+ .iter()
+ .map(|notification| notification.notification_id)
+ .collect::<Vec<_>>(),
+ vec![first, second]
+ );
+ assert_eq!(
+ repo.entity_lookup_calls.lock().unwrap().as_slice(),
+ [(
+ user.to_string(),
+ vec![
+ (EntityType::ChannelMessage, "message-1".to_string()),
+ (EntityType::Document, "document-1".to_string()),
+ ],
+ )]
+ );
+ assert_eq!(
+ repo.mark_seen_calls.lock().unwrap().as_slice(),
+ [(user.to_string(), vec![first, second])]
+ );
+}
+
+#[tokio::test]
+async fn test_update_notifications_for_entities_supports_done_status() {
+ let user = test_user_id("[email protected]");
+ let notification_id = Uuid::now_v7();
+ let repo = Arc::new(MockRepository::new().with_entity_notification_ids(vec![notification_id]));
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: Arc::new(MockQueue::new()),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
+
+ service
+ .update_notifications_for_entities::<TestNotifEvent>(
+ UpdateNotificationsForEntitiesRequest {
+ user_id: user.clone(),
+ entities: vec![EntityType::Document.with_entity_str("document-1")],
+ status: NotificationStatus::Done(true),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ repo.mark_done_calls.lock().unwrap().as_slice(),
+ [(user.to_string(), vec![notification_id], true)]
+ );
+}
+
+#[tokio::test]
+async fn test_update_notifications_for_entities_noops_when_no_notifications_match() {
+ let user = test_user_id("[email protected]");
+ let repo = Arc::new(MockRepository::new());
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: Arc::new(MockQueue::new()),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
+
+ let updated = service
+ .update_notifications_for_entities::<TestNotifEvent>(
+ UpdateNotificationsForEntitiesRequest {
+ user_id: user,
+ entities: vec![EntityType::Document.with_entity_str("doc-without-notifications")],
+ status: NotificationStatus::Done(true),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert!(updated.is_empty());
+ assert!(repo.mark_done_calls.lock().unwrap().is_empty());
}
#[tokio::test]
diff --git a/crates/notification/src/domain/service/voip/test.rs b/crates/notification/src/domain/service/voip/test.rs
index 45d7afdbc7..b34c2e2536 100644
--- a/crates/notification/src/domain/service/voip/test.rs
+++ b/crates/notification/src/domain/service/voip/test.rs
@@ -145,6 +145,13 @@ impl NotificationRepository for MockRepo {
) -> Result<Vec<crate::domain::models::UserNotificationRow<serde_json::Value>>, Report> {
unimplemented!()
}
+ async fn get_notification_ids_for_entities(
+ &self,
+ _: MacroUserIdStr<'_>,
+ _: &[model_entity::Entity<'_>],
+ ) -> Result<Vec<uuid::Uuid>, Report> {
+ unimplemented!()
+ }
async fn get_basic_notifications(
&self,
_: &[uuid::Uuid],
@@ -180,10 +187,10 @@ impl NotificationRepository for MockRepo {
async fn get_entity_notifications_batch(
&self,
_: MacroUserIdStr<'_>,
- entity_refs: Vec<crate::domain::models::request::NotificationEntityRef>,
+ entity_refs: Vec<model_entity::Entity<'static>>,
) -> Result<
std::collections::HashMap<
- crate::domain::models::request::NotificationEntityRef,
+ model_entity::Entity<'static>,
Vec<crate::domain::models::UserNotificationRow<serde_json::Value>>,
>,
Report,
diff --git a/crates/notification/src/inbound/ai_tool/mod.rs b/crates/notification/src/inbound/ai_tool/mod.rs
index e78bc77439..a33bfe4228 100644
--- a/crates/notification/src/inbound/ai_tool/mod.rs
+++ b/crates/notification/src/inbound/ai_tool/mod.rs
@@ -7,8 +7,8 @@ use crate::domain::{
models::{
UserNotificationRow,
request::{
- NotificationEntityRef, NotificationItemType, NotificationListFilters,
- NotificationStatus, UpdateNotificationsRequest,
+ NotificationCategory, NotificationListFilters, NotificationStatus,
+ UpdateNotificationsRequest,
},
},
service::NotificationReader,
@@ -19,6 +19,7 @@ use ai_toolset::{
use async_trait::async_trait;
use cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
use models_pagination::CreatedAt;
use rootcause::compat::boxed_error::IntoBoxedError;
use schemars::JsonSchema;
@@ -60,6 +61,75 @@ where
.add_tool::<MarkNotificationsDone, NotificationToolContext<T>>()
}
+/// Canonical entity types accepted by the notification-listing tool.
+///
+/// This mirrors [`EntityType`] because the shared model intentionally does not
+/// depend on `schemars`, while AI tool inputs require [`JsonSchema`].
+#[allow(missing_docs)]
+#[derive(Debug, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum NotificationEntityType {
+ User,
+ Chat,
+ Channel,
+ #[serde(alias = "message")]
+ ChannelMessage,
+ Document,
+ Project,
+ #[serde(alias = "email")]
+ EmailThread,
+ #[serde(alias = "calendar")]
+ CalendarEvent,
+ Team,
+ Call,
+ #[serde(alias = "github")]
+ ForeignEntity,
+ StaticFile,
+ CrmCompany,
+ CrmContact,
+ Reminder,
+ Skill,
+}
+
+impl From<NotificationEntityType> for EntityType {
+ fn from(value: NotificationEntityType) -> Self {
+ match value {
+ NotificationEntityType::User => Self::User,
+ NotificationEntityType::Chat => Self::Chat,
+ NotificationEntityType::Channel => Self::Channel,
+ NotificationEntityType::ChannelMessage => Self::ChannelMessage,
+ NotificationEntityType::Document => Self::Document,
+ NotificationEntityType::Project => Self::Project,
+ NotificationEntityType::EmailThread => Self::EmailThread,
+ NotificationEntityType::CalendarEvent => Self::CalendarEvent,
+ NotificationEntityType::Team => Self::Team,
+ NotificationEntityType::Call => Self::Call,
+ NotificationEntityType::ForeignEntity => Self::ForeignEntity,
+ NotificationEntityType::StaticFile => Self::StaticFile,
+ NotificationEntityType::CrmCompany => Self::CrmCompany,
+ NotificationEntityType::CrmContact => Self::CrmContact,
+ NotificationEntityType::Reminder => Self::Reminder,
+ NotificationEntityType::Skill => Self::Skill,
+ }
+ }
+}
+
+/// User-facing reference to one specific entity to filter notifications by.
+#[derive(Debug, Deserialize, JsonSchema, Clone, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct NotificationEntityFilter {
+ /// Canonical entity type.
+ pub entity_type: NotificationEntityType,
+ /// Canonical entity identifier.
+ pub id: String,
+}
+
+impl NotificationEntityFilter {
+ fn into_entity(self) -> Entity<'static> {
+ EntityType::from(self.entity_type).with_entity_string(self.id)
+ }
+}
+
/// List the current user's active notifications.
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "camelCase")]
@@ -92,14 +162,14 @@ pub struct ListNotifications {
description = "Filter to specific notification item types. If omitted, returns all types. Example: [\"email\", \"message\"] returns only email and message notifications."
)]
#[serde(default)]
- pub include_types: Option<Vec<NotificationItemType>>,
+ pub include_types: Option<Vec<NotificationCategory>>,
/// Filter to notifications for specific entities. If omitted, returns notifications for all entities.
#[schemars(
- description = "Filter to notifications for specific entities. Pair each id with entityType to avoid ambiguity. Example: [{\"entityType\":\"email\",\"id\":\"...\"}] returns notifications for one email thread."
+ description = "Filter to notifications for specific entities. Pair each id with its canonical entityType to avoid ambiguity. Example: [{\"entityType\":\"email_thread\",\"id\":\"...\"}] returns notifications for one email thread."
)]
#[serde(default)]
- pub entities: Option<Vec<NotificationEntityRef>>,
+ pub entities: Option<Vec<NotificationEntityFilter>>,
}
/// A single notification item in the list response.
@@ -179,7 +249,13 @@ where
done: self.done.or(Some(false)),
seen: self.seen,
include_types: self.include_types.clone().unwrap_or_default(),
- entities: self.entities.clone().unwrap_or_default(),
+ entities: self
+ .entities
+ .clone()
+ .unwrap_or_default()
+ .into_iter()
+ .map(NotificationEntityFilter::into_entity)
+ .collect(),
},
)
.await
diff --git a/crates/notification/src/inbound/ai_tool/test.rs b/crates/notification/src/inbound/ai_tool/test.rs
index 88dd9aba6d..89ecdf1c76 100644
--- a/crates/notification/src/inbound/ai_tool/test.rs
+++ b/crates/notification/src/inbound/ai_tool/test.rs
@@ -37,20 +37,20 @@ fn test_list_notifications_deserialization() {
assert_eq!(
tool.include_types,
Some(vec![
- NotificationItemType::Email,
- NotificationItemType::Message,
- NotificationItemType::Github
+ NotificationCategory::Email,
+ NotificationCategory::Message,
+ NotificationCategory::Github
])
);
assert_eq!(
tool.entities,
Some(vec![
- NotificationEntityRef {
- entity_type: NotificationItemType::Email,
+ NotificationEntityFilter {
+ entity_type: NotificationEntityType::EmailThread,
id: "thread-1".to_string()
},
- NotificationEntityRef {
- entity_type: NotificationItemType::Github,
+ NotificationEntityFilter {
+ entity_type: NotificationEntityType::ForeignEntity,
id: "foreign-entity-1".to_string()
}
])
diff --git a/crates/notification/src/inbound/http/test.rs b/crates/notification/src/inbound/http/test.rs
index 0e03273f87..6ca074fc2b 100644
--- a/crates/notification/src/inbound/http/test.rs
+++ b/crates/notification/src/inbound/http/test.rs
@@ -11,6 +11,7 @@ use macro_authorization::{
MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
use model_user::UserContext;
use models_pagination::{CreatedAt, Paginated, Query};
use reqwest::StatusCode;
@@ -25,7 +26,7 @@ use crate::domain::{
DisabledNotificationType, UserNotificationRow,
device::DeviceType,
request::{
- GetNotificationsByEventItemIdsRequest, NotificationEntityRef,
+ GetNotificationsByEventItemIdsRequest, UpdateNotificationsForEntitiesRequest,
UpdateNotificationsRequest,
},
signing::SignedUrl,
@@ -91,11 +92,17 @@ impl NotificationReader for AuthenticationTestService {
async { unreachable!("should not be called") }
}
- fn update_notifications_and_return(
+ fn update_notifications_and_return<T: DeserializeOwned + Send>(
&self,
_req: UpdateNotificationsRequest,
- ) -> impl Future<Output = Result<Vec<UserNotificationRow<serde_json::Value>>, Report>> + Send
- {
+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send {
+ async { unreachable!("should not be called") }
+ }
+
+ fn update_notifications_for_entities<T: DeserializeOwned + Send>(
+ &self,
+ _req: UpdateNotificationsForEntitiesRequest,
+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send {
async { unreachable!("should not be called") }
}
@@ -121,10 +128,9 @@ impl NotificationReader for AuthenticationTestService {
fn get_entity_notifications_batch<T: DeserializeOwned + Send>(
&self,
_user_id: MacroUserIdStr<'_>,
- _entity_refs: Vec<NotificationEntityRef>,
- ) -> impl Future<
- Output = Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<T>>>, Report>,
- > + Send {
+ _entity_refs: Vec<Entity<'static>>,
+ ) -> impl Future<Output = Result<HashMap<Entity<'static>, Vec<UserNotificationRow<T>>>, Report>> + Send
+ {
async { unreachable!("should not be called") }
}
@@ -570,11 +576,17 @@ impl NotificationReader for PresignedTestService {
async { unreachable!() }
}
- fn update_notifications_and_return(
+ fn update_notifications_and_return<T: DeserializeOwned + Send>(
&self,
_req: UpdateNotificationsRequest,
- ) -> impl Future<Output = Result<Vec<UserNotificationRow<serde_json::Value>>, Report>> + Send
- {
+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send {
+ async { unreachable!() }
+ }
+
+ fn update_notifications_for_entities<T: DeserializeOwned + Send>(
+ &self,
+ _req: UpdateNotificationsForEntitiesRequest,
+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send {
async { unreachable!() }
}
@@ -600,10 +612,9 @@ impl NotificationReader for PresignedTestService {
fn get_entity_notifications_batch<T: DeserializeOwned + Send>(
&self,
_user_id: MacroUserIdStr<'_>,
- _entity_refs: Vec<NotificationEntityRef>,
- ) -> impl Future<
- Output = Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<T>>>, Report>,
- > + Send {
+ _entity_refs: Vec<Entity<'static>>,
+ ) -> impl Future<Output = Result<HashMap<Entity<'static>, Vec<UserNotificationRow<T>>>, Report>> + Send
+ {
async { unreachable!() }
}
diff --git a/crates/notification/src/outbound/repository.rs b/crates/notification/src/outbound/repository.rs
index 7f9f78dde6..345203c28b 100644
--- a/crates/notification/src/outbound/repository.rs
+++ b/crates/notification/src/outbound/repository.rs
@@ -4,9 +4,7 @@
mod test;
use crate::domain::models::device::DeviceType;
-use crate::domain::models::request::{
- NotificationEntityRef, NotificationItemType, NotificationListFilters,
-};
+use crate::domain::models::request::{NotificationCategory, NotificationListFilters};
use crate::domain::models::{
DeviceEndpoint, DisabledNotificationType, NotificationIdAndCollapseKey,
SendNotificationRequestBuilder, TaggedContent, UserNotificationRow,
@@ -16,7 +14,7 @@ use crate::outbound::device_registration::DeviceRegistrationDbOps;
use chrono::{DateTime, Utc};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
-use model_entity::EntityType;
+use model_entity::{Entity, EntityType};
use models_pagination::{CreatedAt, Query};
use rootcause::Report;
use serde::Serialize;
@@ -117,8 +115,6 @@ struct UserNotificationsQueryArgs<'a> {
cursor_id: Option<Uuid>,
cursor_timestamp: Option<DateTime<Utc>>,
filters: &'a NotificationListFilters,
- include_types: &'a [String],
- entity_tokens: &'a [String],
}
fn build_user_notifications_query<'a>(
@@ -131,8 +127,6 @@ fn build_user_notifications_query<'a>(
cursor_id,
cursor_timestamp,
filters,
- include_types,
- entity_tokens,
} = args;
let mut builder = QueryBuilder::new(
@@ -159,8 +153,8 @@ fn build_user_notifications_query<'a>(
push_event_item_ids_filter(&mut builder, event_item_ids);
push_notification_status_filters(&mut builder, filters);
- push_include_types_filter(&mut builder, include_types);
- push_entities_filter(&mut builder, entity_tokens);
+ push_include_types_filter(&mut builder, &filters.include_types);
+ push_entities_filter(&mut builder, &filters.entities);
push_cursor_filter(&mut builder, cursor_timestamp, cursor_id);
builder.push(" ORDER BY un.created_at DESC, un.notification_id DESC LIMIT ");
@@ -211,55 +205,42 @@ const GITHUB_EVENT_TYPES_SQL: &str = concat!(
")",
);
-fn push_include_types_filter(builder: &mut QueryBuilder<'_, Postgres>, include_types: &[String]) {
+fn push_include_types_filter(
+ builder: &mut QueryBuilder<'_, Postgres>,
+ include_types: &[NotificationCategory],
+) {
if !include_types.is_empty() {
builder.push(" AND (");
let mut needs_or = false;
for clause in [
- include_types
- .iter()
- .any(|t| t == "email")
+ include_types.contains(&NotificationCategory::Email)
.then_some("n.event_item_type = 'email_thread'"),
- include_types.iter().any(|t| t == "message").then_some(
+ include_types.contains(&NotificationCategory::Message).then_some(
r#"(
n.notification_event_type IN ('channel_mention', 'channel_message_reply', 'channel_message_send')
OR n.metadata ? 'messageId'
OR n.metadata ? 'message_id'
)"#,
),
- include_types
- .iter()
- .any(|t| t == "channel")
+ include_types.contains(&NotificationCategory::Channel)
.then_some("n.event_item_type = 'channel'"),
- include_types.iter().any(|t| t == "document").then_some(
+ include_types.contains(&NotificationCategory::Document).then_some(
"n.event_item_type = 'document' AND COALESCE(n.metadata->>'subType', n.metadata->>'sub_type', '') <> 'task'",
),
- include_types.iter().any(|t| t == "task").then_some(
+ include_types.contains(&NotificationCategory::Task).then_some(
"n.event_item_type = 'document' AND COALESCE(n.metadata->>'subType', n.metadata->>'sub_type', '') = 'task'",
),
- include_types
- .iter()
- .any(|t| t == "project")
+ include_types.contains(&NotificationCategory::Project)
.then_some("n.event_item_type = 'project'"),
- include_types
- .iter()
- .any(|t| t == "chat")
+ include_types.contains(&NotificationCategory::Chat)
.then_some("n.event_item_type = 'chat'"),
- include_types
- .iter()
- .any(|t| t == "call")
+ include_types.contains(&NotificationCategory::Call)
.then_some("n.event_item_type = 'call'"),
- include_types
- .iter()
- .any(|t| t == "github")
+ include_types.contains(&NotificationCategory::Github)
.then_some(GITHUB_EVENT_TYPES_SQL),
- include_types
- .iter()
- .any(|t| t == "reminder")
+ include_types.contains(&NotificationCategory::Reminder)
.then_some("n.event_item_type = 'reminder'"),
- include_types
- .iter()
- .any(|t| t == "calendar")
+ include_types.contains(&NotificationCategory::Calendar)
.then_some("n.event_item_type = 'calendar_event'"),
]
.into_iter()
@@ -277,131 +258,79 @@ fn push_include_types_filter(builder: &mut QueryBuilder<'_, Postgres>, include_t
}
}
-fn push_entities_filter<'a>(builder: &mut QueryBuilder<'a, Postgres>, entity_tokens: &'a [String]) {
- if !entity_tokens.is_empty() {
- builder.push(" AND (");
-
- builder.push("(n.event_item_type = 'email_thread' AND 'email:' || n.event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
-
- builder.push("(n.event_item_type = 'channel' AND 'channel:' || n.event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
-
- builder.push("(n.event_item_type = 'document' AND 'document:' || n.event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
-
- builder.push("(n.event_item_type = 'document' AND COALESCE(n.metadata->>'subType', n.metadata->>'sub_type', '') = 'task' AND 'task:' || n.event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
-
- builder.push("(n.event_item_type = 'project' AND 'project:' || n.event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
-
- builder.push("(n.event_item_type = 'chat' AND 'chat:' || n.event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
-
- builder.push("(n.event_item_type = 'call' AND 'call:' || n.event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
-
- builder.push("(n.event_item_type = 'reminder' AND 'reminder:' || n.event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
-
- builder.push(
- "(n.event_item_type = 'calendar_event' AND 'calendar:' || n.event_item_id = ANY(",
- );
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
+fn push_entities_filter<'a>(
+ builder: &mut QueryBuilder<'a, Postgres>,
+ entities: &'a [Entity<'static>],
+) {
+ if entities.is_empty() {
+ return;
+ }
- builder.push("(n.event_item_type = 'foreign_entity' AND ");
- builder.push(GITHUB_EVENT_TYPES_SQL);
- builder.push(" AND 'github:' || n.event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
+ builder.push(" AND (");
+ for (index, entity) in entities.iter().enumerate() {
+ if index > 0 {
+ builder.push(" OR ");
+ }
- builder.push("('message:' || COALESCE(n.metadata->>'messageId', n.metadata->>'message_id', '') = ANY(");
- builder.push_bind(entity_tokens);
- builder.push(")) OR ");
+ builder.push("((n.event_item_type = ");
+ builder.push_bind(entity.entity_type.as_ref());
+ builder.push(" AND n.event_item_id = ");
+ builder.push_bind(entity.entity_id.as_ref());
+ builder.push(") OR (n.secondary_event_item_type = ");
+ builder.push_bind(entity.entity_type.as_ref());
+ builder.push(" AND n.secondary_event_item_id = ");
+ builder.push_bind(entity.entity_id.as_ref());
+ builder.push(")");
- builder.push("(n.secondary_event_item_type = 'channel_message' AND 'message:' || n.secondary_event_item_id = ANY(");
- builder.push_bind(entity_tokens);
- builder.push("))");
+ if entity.entity_type == EntityType::ChannelMessage {
+ builder
+ .push(" OR COALESCE(n.metadata->>'messageId', n.metadata->>'message_id', '') = ");
+ builder.push_bind(entity.entity_id.as_ref());
+ }
builder.push(")");
}
+ builder.push(")");
}
-fn notification_ref_matches_row(
- entity_ref: &NotificationEntityRef,
- event_item_id: &str,
- event_item_type: &str,
+fn message_ref_matches_row(
+ message_id: &str,
secondary_event_item_id: Option<&str>,
secondary_event_item_type: Option<&str>,
- notification_event_type: &str,
metadata: &serde_json::Value,
) -> bool {
- if entity_ref.entity_type == NotificationItemType::Message {
- let directly_targets_message = metadata
- .get("messageId")
- .or_else(|| metadata.get("message_id"))
- .and_then(|value| value.as_str())
- .is_some_and(|message_id| message_id == entity_ref.id);
- let targets_message_as_thread = secondary_event_item_type == Some("channel_message")
- && secondary_event_item_id == Some(entity_ref.id.as_str());
-
- return directly_targets_message || targets_message_as_thread;
- }
-
- if entity_ref.id != event_item_id {
- return false;
- }
+ let directly_targets_message = metadata
+ .get("messageId")
+ .or_else(|| metadata.get("message_id"))
+ .and_then(|value| value.as_str())
+ .is_some_and(|stored_message_id| stored_message_id == message_id);
+ let targets_message_as_thread = secondary_event_item_type == Some("channel_message")
+ && secondary_event_item_id == Some(message_id);
- match entity_ref.entity_type {
- NotificationItemType::Email => event_item_type == "email_thread",
- NotificationItemType::Channel => event_item_type == "channel",
- NotificationItemType::Document => {
- event_item_type == "document" && !notification_metadata_is_task(metadata)
- }
- NotificationItemType::Task => {
- event_item_type == "document" && notification_metadata_is_task(metadata)
- }
- NotificationItemType::Project => event_item_type == "project",
- NotificationItemType::Chat => event_item_type == "chat",
- NotificationItemType::Call => event_item_type == "call",
- NotificationItemType::Github => {
- event_item_type == "foreign_entity"
- && notification_event_type_is_github(notification_event_type)
- }
- NotificationItemType::Reminder => event_item_type == "reminder",
- NotificationItemType::Calendar => event_item_type == "calendar_event",
- NotificationItemType::Message => false,
- }
+ directly_targets_message || targets_message_as_thread
}
-fn notification_metadata_is_task(metadata: &serde_json::Value) -> bool {
- metadata
- .get("subType")
- .or_else(|| metadata.get("sub_type"))
- .and_then(|value| value.as_str())
- == Some("task")
-}
+fn notification_entity_matches_row(
+ entity: &Entity<'_>,
+ event_item_id: &str,
+ event_item_type: &str,
+ secondary_event_item_id: Option<&str>,
+ secondary_event_item_type: Option<&str>,
+ metadata: &serde_json::Value,
+) -> bool {
+ let directly_targets_entity = event_item_type == entity.entity_type.as_ref()
+ && event_item_id == entity.entity_id.as_ref();
+ let targets_secondary_entity = secondary_event_item_type == Some(entity.entity_type.as_ref())
+ && secondary_event_item_id == Some(entity.entity_id.as_ref());
+ let targets_message = entity.entity_type == EntityType::ChannelMessage
+ && message_ref_matches_row(
+ entity.entity_id.as_ref(),
+ secondary_event_item_id,
+ secondary_event_item_type,
+ metadata,
+ );
-fn notification_event_type_is_github(notification_event_type: &str) -> bool {
- matches!(
- notification_event_type,
- "github_pr_status_changed"
- | "github_review_requested"
- | "github_pr_comment"
- | "github_pr_mention"
- | "github_pr_review"
- | "github_pr_check_run"
- )
+ directly_targets_entity || targets_secondary_entity || targets_message
}
fn push_cursor_filter(
@@ -509,6 +438,13 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {
Output = Result<Vec<UserNotificationRow<serde_json::Value>>, Report>,
> + Send;
+ /// Get active user-owned notification IDs associated with any primary or secondary entity.
+ fn get_notification_ids_for_entities(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entities: &[Entity<'_>],
+ ) -> impl std::future::Future<Output = Result<Vec<Uuid>, Report>> + Send;
+
/// Get basic notification data (collapse keys) for push clearing.
fn get_basic_notifications(
&self,
@@ -549,10 +485,10 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {
fn get_entity_notifications_batch(
&self,
user_id: MacroUserIdStr<'_>,
- entity_refs: Vec<NotificationEntityRef>,
+ entities: Vec<Entity<'static>>,
) -> impl std::future::Future<
Output = Result<
- HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>,
+ HashMap<Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>,
Report,
>,
> + Send;
@@ -945,6 +881,58 @@ impl NotificationDbOps for PgPool {
.collect()
}
+ async fn get_notification_ids_for_entities(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entities: &[Entity<'_>],
+ ) -> Result<Vec<Uuid>, Report> {
+ let entity_types = entities
+ .iter()
+ .map(|entity| entity.entity_type.as_ref().to_owned())
+ .collect::<Vec<_>>();
+ let entity_ids = entities
+ .iter()
+ .map(|entity| entity.entity_id.to_string())
+ .collect::<Vec<_>>();
+ let notification_ids = sqlx::query_scalar!(
+ r#"
+ WITH requested_entities AS (
+ SELECT entity_type, entity_id
+ FROM UNNEST($2::text[], $3::text[]) AS entity(entity_type, entity_id)
+ )
+ SELECT un.notification_id
+ FROM user_notification un
+ JOIN notification n ON n.id = un.notification_id
+ WHERE un.user_id = $1
+ AND un.deleted_at IS NULL
+ AND EXISTS (
+ SELECT 1
+ FROM requested_entities entity
+ WHERE (
+ n.event_item_type = entity.entity_type
+ AND n.event_item_id = entity.entity_id
+ )
+ OR (
+ n.secondary_event_item_type = entity.entity_type
+ AND n.secondary_event_item_id = entity.entity_id
+ )
+ OR (
+ entity.entity_type = 'channel_message'
+ AND COALESCE(n.metadata->>'messageId', n.metadata->>'message_id', '') = entity.entity_id
+ )
+ )
+ ORDER BY un.created_at, un.notification_id
+ "#,
+ user_id.as_ref(),
+ &entity_types,
+ &entity_ids,
+ )
+ .fetch_all(self)
+ .await?;
+
+ Ok(notification_ids)
+ }
+
async fn get_basic_notifications(
&self,
notification_ids: &[Uuid],
@@ -1004,8 +992,6 @@ impl NotificationDbOps for PgPool {
) -> Result<Vec<UserNotificationRow<T>>, Report> {
let query_limit = limit as i64;
let (cursor_id, cursor_timestamp) = cursor.vals();
- let include_types = filters.include_type_tokens();
- let entity_tokens = filters.entity_tokens();
let rows = build_user_notifications_query(UserNotificationsQueryArgs {
user_id: user_id.as_ref(),
@@ -1014,8 +1000,6 @@ impl NotificationDbOps for PgPool {
cursor_id: cursor_id.copied(),
cursor_timestamp: cursor_timestamp.copied(),
filters: &filters,
- include_types: &include_types,
- entity_tokens: &entity_tokens,
})
.build_query_as::<UserNotificationListRow>()
.fetch_all(self)
@@ -1102,8 +1086,6 @@ impl NotificationDbOps for PgPool {
let query_limit = limit as i64;
let (cursor_id, cursor_timestamp) = cursor.vals();
let event_item_ids: Vec<String> = event_item_ids.iter().map(|id| id.to_string()).collect();
- let include_types = filters.include_type_tokens();
- let entity_tokens = filters.entity_tokens();
let rows = build_user_notifications_query(UserNotificationsQueryArgs {
user_id: user_id.as_ref(),
@@ -1112,8 +1094,6 @@ impl NotificationDbOps for PgPool {
cursor_id: cursor_id.copied(),
cursor_timestamp: cursor_timestamp.copied(),
filters: &filters,
- include_types: &include_types,
- entity_tokens: &entity_tokens,
})
.build_query_as::<UserNotificationListRow>()
.fetch_all(self)
@@ -1192,22 +1172,21 @@ impl NotificationDbOps for PgPool {
async fn get_entity_notifications_batch(
&self,
user_id: MacroUserIdStr<'_>,
- entity_refs: Vec<NotificationEntityRef>,
- ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>, Report>
- {
- let mut seen_entity_refs = HashSet::new();
- let entity_refs = entity_refs
+ entities: Vec<Entity<'static>>,
+ ) -> Result<HashMap<Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>, Report> {
+ let mut seen_entities = HashSet::new();
+ let entities = entities
.into_iter()
- .filter(|entity_ref| seen_entity_refs.insert(entity_ref.clone()))
+ .filter(|entity| seen_entities.insert(entity.clone()))
.collect::<Vec<_>>();
- let mut result = entity_refs
+ let mut result = entities
.iter()
.cloned()
- .map(|entity_ref| (entity_ref, Vec::new()))
+ .map(|entity| (entity, Vec::new()))
.collect::<HashMap<_, _>>();
- if entity_refs.is_empty() {
+ if entities.is_empty() {
return Ok(result);
}
@@ -1215,9 +1194,8 @@ impl NotificationDbOps for PgPool {
done: Some(false),
seen: None,
include_types: Vec::new(),
- entities: entity_refs.clone(),
+ entities: entities.clone(),
};
- let entity_tokens = filters.entity_tokens();
let mut builder = QueryBuilder::new(
r#"
@@ -1243,7 +1221,7 @@ impl NotificationDbOps for PgPool {
);
builder.push_bind(user_id.as_ref());
push_notification_status_filters(&mut builder, &filters);
- push_entities_filter(&mut builder, &entity_tokens);
+ push_entities_filter(&mut builder, &entities);
builder.push(" ORDER BY un.created_at DESC, un.notification_id DESC");
let rows = builder
@@ -1311,18 +1289,17 @@ impl NotificationDbOps for PgPool {
sender_id,
};
- for entity_ref in &entity_refs {
- if notification_ref_matches_row(
- entity_ref,
+ for requested_entity in &entities {
+ if notification_entity_matches_row(
+ requested_entity,
&event_item_id,
&event_item_type,
secondary_event_item_id.as_deref(),
secondary_event_item_type.as_deref(),
- &notification_event_type,
&notification_metadata,
) {
result
- .entry(entity_ref.clone())
+ .entry(requested_entity.clone())
.or_default()
.push(notification.clone());
}
@@ -1626,6 +1603,16 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
.await
}
+ async fn get_notification_ids_for_entities(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ entities: &[Entity<'_>],
+ ) -> Result<Vec<Uuid>, Report> {
+ self.db
+ .get_notification_ids_for_entities(&user_id, entities)
+ .await
+ }
+
async fn get_basic_notifications(
&self,
notification_ids: &[Uuid],
@@ -1677,11 +1664,10 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
async fn get_entity_notifications_batch(
&self,
user_id: MacroUserIdStr<'_>,
- entity_refs: Vec<NotificationEntityRef>,
- ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>, Report>
- {
+ entities: Vec<Entity<'static>>,
+ ) -> Result<HashMap<Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>, Report> {
self.db
- .get_entity_notifications_batch(user_id, entity_refs)
+ .get_entity_notifications_batch(user_id, entities)
.await
}
diff --git a/crates/notification/src/outbound/repository/test.rs b/crates/notification/src/outbound/repository/test.rs
index 69f48ba48b..6228e80999 100644
--- a/crates/notification/src/outbound/repository/test.rs
+++ b/crates/notification/src/outbound/repository/test.rs
@@ -1,7 +1,4 @@
-use crate::domain::models::{
- Notification,
- request::{NotificationEntityRef, NotificationItemType},
-};
+use crate::domain::models::{Notification, request::NotificationCategory};
use super::*;
@@ -30,6 +27,16 @@ impl Notification for TestMessageNotification {
const TYPE_NAME: &'static str = "test_message_notification";
}
+#[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,
@@ -376,6 +383,212 @@ async fn test_mark_notifications_seen_does_not_affect_other_users(pool: Pool<Pos
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)
+ .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)],
+ )
+ .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)],
+ )
+ .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)],
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(notification_ids, vec![github_id, generic_id]);
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(
@@ -640,7 +853,7 @@ async fn test_get_user_notifications_filters_type_and_entity(pool: Pool<Postgres
NotificationListFilters {
done: Some(false),
seen: None,
- include_types: vec![crate::domain::models::request::NotificationItemType::Document],
+ include_types: vec![crate::domain::models::request::NotificationCategory::Document],
entities: Vec::new(),
},
)
@@ -656,7 +869,7 @@ async fn test_get_user_notifications_filters_type_and_entity(pool: Pool<Postgres
NotificationListFilters {
done: Some(false),
seen: None,
- include_types: vec![crate::domain::models::request::NotificationItemType::Email],
+ include_types: vec![crate::domain::models::request::NotificationCategory::Email],
entities: Vec::new(),
},
)
@@ -673,10 +886,7 @@ async fn test_get_user_notifications_filters_type_and_entity(pool: Pool<Postgres
done: Some(false),
seen: None,
include_types: Vec::new(),
- entities: vec![crate::domain::models::request::NotificationEntityRef {
- entity_type: crate::domain::models::request::NotificationItemType::Document,
- id: "item-1".to_string(),
- }],
+ entities: vec![EntityType::Document.with_entity_string("item-1".to_string())],
},
)
.await
@@ -692,10 +902,7 @@ async fn test_get_user_notifications_filters_type_and_entity(pool: Pool<Postgres
done: Some(false),
seen: None,
include_types: Vec::new(),
- entities: vec![crate::domain::models::request::NotificationEntityRef {
- entity_type: crate::domain::models::request::NotificationItemType::Email,
- id: "item-1".to_string(),
- }],
+ entities: vec![EntityType::EmailThread.with_entity_string("item-1".to_string())],
},
)
.await
@@ -732,14 +939,8 @@ async fn test_get_entity_notifications_batch_matches_channel_thread_secondary_en
)
.await;
- let thread_ref = NotificationEntityRef {
- entity_type: NotificationItemType::Message,
- id: thread_id,
- };
- let other_thread_ref = NotificationEntityRef {
- entity_type: NotificationItemType::Message,
- id: other_thread_id,
- };
+ 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()])
.await
@@ -764,6 +965,89 @@ async fn test_get_entity_notifications_batch_matches_channel_thread_secondary_en
);
}
+#[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()])
+ .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]");
@@ -771,6 +1055,7 @@ async fn test_get_user_notifications_filters_github_type_and_entity(pool: Pool<P
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
@@ -817,7 +1102,7 @@ async fn test_get_user_notifications_filters_github_type_and_entity(pool: Pool<P
};
pool.create_notification(
non_github_request,
- uuid::Uuid::new_v4(),
+ non_github_notification_id,
"test_service",
None,
)
@@ -832,7 +1117,7 @@ async fn test_get_user_notifications_filters_github_type_and_entity(pool: Pool<P
NotificationListFilters {
done: Some(false),
seen: None,
- include_types: vec![NotificationItemType::Github],
+ include_types: vec![NotificationCategory::Github],
entities: Vec::new(),
},
)
@@ -884,18 +1169,20 @@ async fn test_get_user_notifications_filters_github_type_and_entity(pool: Pool<P
done: Some(false),
seen: None,
include_types: Vec::new(),
- entities: vec![NotificationEntityRef {
- entity_type: NotificationItemType::Github,
- id: foreign_entity_id.clone(),
- }],
+ entities: vec![
+ EntityType::ForeignEntity.with_entity_string(foreign_entity_id.clone()),
+ ],
},
)
.await
.unwrap();
- assert_eq!(github_entity_results.len(), 1);
+ assert_eq!(github_entity_results.len(), 2);
assert_eq!(
- github_entity_results[0].notification_id,
- github_notification_id
+ 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
@@ -907,10 +1194,10 @@ async fn test_get_user_notifications_filters_github_type_and_entity(pool: Pool<P
done: Some(false),
seen: None,
include_types: Vec::new(),
- entities: vec![NotificationEntityRef {
- entity_type: NotificationItemType::Github,
- id: check_run_foreign_entity_id.clone(),
- }],
+ entities: vec![
+ EntityType::ForeignEntity
+ .with_entity_string(check_run_foreign_entity_id.clone()),
+ ],
},
)
.await
@@ -938,10 +1225,7 @@ async fn test_get_user_notifications_filters_github_type_and_entity(pool: Pool<P
done: Some(false),
seen: None,
include_types: Vec::new(),
- entities: vec![NotificationEntityRef {
- entity_type: NotificationItemType::Document,
- id: foreign_entity_id,
- }],
+ entities: vec![EntityType::Document.with_entity_string(foreign_entity_id)],
},
)
.await
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index d06ed81f3a..24af2c2005 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -94,6 +94,10 @@ type CompleteMutationRoot {
"""
updateNotifications(input: UpdateNotificationsInput!): [GraphqlNotification!]!
"""
+ Update all notifications associated with the requested entities for the authenticated user.
+ """
+ updateNotificationsForEntity(input: UpdateNotificationsForEntityInput!): [GraphqlNotification!]!
+ """
Mark an accessible email thread as seen and return its authoritative cache record.
"""
markEmailThreadSeen(input: MarkEmailThreadSeenInput!): GraphqlSoupEmailThread!
@@ -5270,6 +5274,20 @@ input MoveEntityInput {
projectId: ID
}
+"""
+Canonical entity reference used to select notifications for updating.
+"""
+input NotificationEntityInput {
+ """
+ Canonical entity type.
+ """
+ entityType: GraphqlEntityType!
+ """
+ Canonical entity identifier.
+ """
+ entityId: ID!
+}
+
"""
Explicit notification status operation exposed by GraphQL.
"""
@@ -5479,6 +5497,20 @@ input UpdateEntitySharePolicyInput {
policy: EntitySharePolicyInput!
}
+"""
+Input for updating all notifications associated with any requested entity.
+"""
+input UpdateNotificationsForEntityInput {
+ """
+ Canonical entities whose notifications should be updated.
+ """
+ entities: [NotificationEntityInput!]!
+ """
+ Status operation applied to every matching notification.
+ """
+ operation: NotificationUpdateOperation!
+}
+
"""
Input for updating notification statuses.
"""
diff --git a/tooling/notification_sandbox/src/adapters/sandbox_repository.rs b/tooling/notification_sandbox/src/adapters/sandbox_repository.rs
index bc4b0b06fe..671b898290 100644
--- a/tooling/notification_sandbox/src/adapters/sandbox_repository.rs
+++ b/tooling/notification_sandbox/src/adapters/sandbox_repository.rs
@@ -1,7 +1,8 @@
use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
use models_pagination::{CreatedAt, Query};
use notification::domain::models::TaggedContent;
-use notification::domain::models::request::{NotificationEntityRef, NotificationListFilters};
+use notification::domain::models::request::NotificationListFilters;
use notification::domain::models::{
DeviceEndpoint, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,
UserNotificationRow, device::DeviceType,
@@ -106,6 +107,16 @@ impl NotificationRepository for SandboxNotificationRepository {
.await
}
+ async fn get_notification_ids_for_entities(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ entities: &[Entity<'_>],
+ ) -> Result<Vec<Uuid>, Report> {
+ self.inner
+ .get_notification_ids_for_entities(user_id, entities)
+ .await
+ }
+
async fn get_basic_notifications(
&self,
notification_ids: &[Uuid],
@@ -157,11 +168,10 @@ impl NotificationRepository for SandboxNotificationRepository {
async fn get_entity_notifications_batch(
&self,
user_id: MacroUserIdStr<'_>,
- entity_refs: Vec<NotificationEntityRef>,
- ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>, Report>
- {
+ entities: Vec<Entity<'static>>,
+ ) -> Result<HashMap<Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>, Report> {
self.inner
- .get_entity_notifications_batch(user_id, entity_refs)
+ .get_entity_notifications_batch(user_id, entities)
.await
}