Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(channels): add support for notification filtering on channel message (#2858)

teo90b269689e61
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts
index ea5d5dd619..6de86c5d5e 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { ChannelMessageFiltersLastActivity } from './channelMessageFiltersLastActivity';
+import type { NotificationFilters } from './notificationFilters';
/**
* Filters for channel message queries.
@@ -16,4 +17,8 @@ this time, or a thread reply was created after this time. */
last_activity?: ChannelMessageFiltersLastActivity;
/** When non-empty, only return messages with these IDs. */
message_ids?: string[];
+ /** When set, only return top-level messages where the message itself or
+any active thread reply has a notification for the requesting user that
+matches these notification state constraints. */
+ notification_filters?: NotificationFilters;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/notificationFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/notificationFilters.ts
index af39ff82f7..1833310757 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/notificationFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/notificationFilters.ts
@@ -8,13 +8,13 @@ import type { NotificationFiltersDone } from './notificationFiltersDone';
import type { NotificationFiltersSeen } from './notificationFiltersSeen';
/**
- * Notification-level filters that apply to an entity type.
+ * Notification state filters for channel message queries.
*/
export interface NotificationFilters {
- /** Filter by notification done state.
-None to ignore, true to include only done notifications, false to include only not-done notifications. */
+ /** Filter by notification done state. `Some(true)` selects done
+notifications; `Some(false)` selects not-done notifications. */
done?: NotificationFiltersDone;
- /** Filter by notification seen state.
-None to ignore, true to include only seen notifications, false to include only unseen notifications. */
+ /** Filter by notification seen state. `Some(true)` selects seen
+notifications; `Some(false)` selects not-seen notifications. */
seen?: NotificationFiltersSeen;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/notificationFiltersDone.ts b/js/app/packages/service-clients/service-storage/generated/schemas/notificationFiltersDone.ts
index 09f5565eac..58446a861c 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/notificationFiltersDone.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/notificationFiltersDone.ts
@@ -6,7 +6,7 @@
*/
/**
- * Filter by notification done state.
-None to ignore, true to include only done notifications, false to include only not-done notifications.
+ * Filter by notification done state. `Some(true)` selects done
+notifications; `Some(false)` selects not-done notifications.
*/
export type NotificationFiltersDone = boolean | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/notificationFiltersSeen.ts b/js/app/packages/service-clients/service-storage/generated/schemas/notificationFiltersSeen.ts
index f9ac5330ef..6be23b916c 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/notificationFiltersSeen.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/notificationFiltersSeen.ts
@@ -6,7 +6,7 @@
*/
/**
- * Filter by notification seen state.
-None to ignore, true to include only seen notifications, false to include only unseen notifications.
+ * Filter by notification seen state. `Some(true)` selects seen
+notifications; `Some(false)` selects not-seen notifications.
*/
export type NotificationFiltersSeen = boolean | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 674ad96fbd..165867d5d9 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1464,6 +1464,23 @@ export const postChannelMessagesBody = zod
.array(zod.string().uuid())
.optional()
.describe('When non-empty, only return messages with these IDs.'),
+ notification_filters: zod
+ .object({
+ done: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Filter by notification done state. `Some(true)` selects done\nnotifications; `Some(false)` selects not-done notifications.'
+ ),
+ seen: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Filter by notification seen state. `Some(true)` selects seen\nnotifications; `Some(false)` selects not-seen notifications.'
+ ),
+ })
+ .optional()
+ .describe('Notification state filters for channel message queries.'),
})
.describe('Filters for channel message queries.');
@@ -5215,17 +5232,17 @@ export const postItemsSoupBody = zod
.boolean()
.nullish()
.describe(
- 'Filter by notification done state.\nNone to ignore, true to include only done notifications, false to include only not-done notifications.'
+ 'Filter by notification done state. `Some(true)` selects done\nnotifications; `Some(false)` selects not-done notifications.'
),
seen: zod
.boolean()
.nullish()
.describe(
- 'Filter by notification seen state.\nNone to ignore, true to include only seen notifications, false to include only unseen notifications.'
+ 'Filter by notification seen state. `Some(true)` selects seen\nnotifications; `Some(false)` selects not-seen notifications.'
),
})
.optional()
- .describe('Notification-level filters that apply to an entity type.'),
+ .describe('Notification state filters for channel message queries.'),
org_id: zod
.number()
.nullish()
@@ -5275,17 +5292,17 @@ export const postItemsSoupBody = zod
.boolean()
.nullish()
.describe(
- 'Filter by notification done state.\nNone to ignore, true to include only done notifications, false to include only not-done notifications.'
+ 'Filter by notification done state. `Some(true)` selects done\nnotifications; `Some(false)` selects not-done notifications.'
),
seen: zod
.boolean()
.nullish()
.describe(
- 'Filter by notification seen state.\nNone to ignore, true to include only seen notifications, false to include only unseen notifications.'
+ 'Filter by notification seen state. `Some(true)` selects seen\nnotifications; `Some(false)` selects not-seen notifications.'
),
})
.optional()
- .describe('Notification-level filters that apply to an entity type.'),
+ .describe('Notification state filters for channel message queries.'),
owners: zod
.array(zod.string())
.optional()
@@ -5341,17 +5358,17 @@ export const postItemsSoupBody = zod
.boolean()
.nullish()
.describe(
- 'Filter by notification done state.\nNone to ignore, true to include only done notifications, false to include only not-done notifications.'
+ 'Filter by notification done state. `Some(true)` selects done\nnotifications; `Some(false)` selects not-done notifications.'
),
seen: zod
.boolean()
.nullish()
.describe(
- 'Filter by notification seen state.\nNone to ignore, true to include only seen notifications, false to include only unseen notifications.'
+ 'Filter by notification seen state. `Some(true)` selects seen\nnotifications; `Some(false)` selects not-seen notifications.'
),
})
.optional()
- .describe('Notification-level filters that apply to an entity type.'),
+ .describe('Notification state filters for channel message queries.'),
owners: zod
.array(zod.string())
.optional()
@@ -5436,17 +5453,17 @@ export const postItemsSoupBody = zod
.boolean()
.nullish()
.describe(
- 'Filter by notification done state.\nNone to ignore, true to include only done notifications, false to include only not-done notifications.'
+ 'Filter by notification done state. `Some(true)` selects done\nnotifications; `Some(false)` selects not-done notifications.'
),
seen: zod
.boolean()
.nullish()
.describe(
- 'Filter by notification seen state.\nNone to ignore, true to include only seen notifications, false to include only unseen notifications.'
+ 'Filter by notification seen state. `Some(true)` selects seen\nnotifications; `Some(false)` selects not-seen notifications.'
),
})
.optional()
- .describe('Notification-level filters that apply to an entity type.'),
+ .describe('Notification state filters for channel message queries.'),
project_ids: zod
.array(zod.string())
.optional()
@@ -5490,17 +5507,17 @@ export const postItemsSoupBody = zod
.boolean()
.nullish()
.describe(
- 'Filter by notification done state.\nNone to ignore, true to include only done notifications, false to include only not-done notifications.'
+ 'Filter by notification done state. `Some(true)` selects done\nnotifications; `Some(false)` selects not-done notifications.'
),
seen: zod
.boolean()
.nullish()
.describe(
- 'Filter by notification seen state.\nNone to ignore, true to include only seen notifications, false to include only unseen notifications.'
+ 'Filter by notification seen state. `Some(true)` selects seen\nnotifications; `Some(false)` selects not-seen notifications.'
),
})
.optional()
- .describe('Notification-level filters that apply to an entity type.'),
+ .describe('Notification state filters for channel message queries.'),
owners: zod
.array(zod.string())
.optional()
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 23bbe3066a..3b680478a6 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -6620,6 +6620,10 @@
"format": "uuid"
},
"description": "When non-empty, only return messages with these IDs."
+ },
+ "notification_filters": {
+ "$ref": "#/components/schemas/NotificationFilters",
+ "description": "When set, only return top-level messages where the message itself or\nany active thread reply has a notification for the requesting user that\nmatches these notification state constraints."
}
}
},
@@ -9424,15 +9428,15 @@
},
"NotificationFilters": {
"type": "object",
- "description": "Notification-level filters that apply to an entity type.",
+ "description": "Notification state filters for channel message queries.",
"properties": {
"done": {
"type": ["boolean", "null"],
- "description": "Filter by notification done state.\nNone to ignore, true to include only done notifications, false to include only not-done notifications."
+ "description": "Filter by notification done state. `Some(true)` selects done\nnotifications; `Some(false)` selects not-done notifications."
},
"seen": {
"type": ["boolean", "null"],
- "description": "Filter by notification seen state.\nNone to ignore, true to include only seen notifications, false to include only unseen notifications."
+ "description": "Filter by notification seen state. `Some(true)` selects seen\nnotifications; `Some(false)` selects not-seen notifications."
}
}
},
diff --git a/rust/cloud-storage/channels/.sqlx/query-ec5e416378f73f769e797d9affa95f4dcc98ea607f84993efd70313e3b8b7d4f.json b/rust/cloud-storage/channels/.sqlx/query-ec5e416378f73f769e797d9affa95f4dcc98ea607f84993efd70313e3b8b7d4f.json
new file mode 100644
index 0000000000..b17ca020dc
--- /dev/null
+++ b/rust/cloud-storage/channels/.sqlx/query-ec5e416378f73f769e797d9affa95f4dcc98ea607f84993efd70313e3b8b7d4f.json
@@ -0,0 +1,72 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH done_top_level AS (\n SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid\n WHERE $8::bool IS NOT NULL\n AND un.user_id = $7::text\n AND un.deleted_at IS NULL\n AND un.done = $8\n AND n.event_item_type = 'channel'\n AND n.event_item_id = $1::uuid::text\n AND n.metadata->>'messageId' IS NOT NULL\n AND msg.channel_id = $1\n AND msg.deleted_at IS NULL\n ),\n seen_top_level AS (\n SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid\n WHERE $9::bool IS NOT NULL\n AND un.user_id = $7::text\n AND un.deleted_at IS NULL\n AND (un.seen_at IS NOT NULL) = $9\n AND n.event_item_type = 'channel'\n AND n.event_item_id = $1::uuid::text\n AND n.metadata->>'messageId' IS NOT NULL\n AND msg.channel_id = $1\n AND msg.deleted_at IS NULL\n )\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))\n AND ($5::uuid[] IS NULL OR m.id = ANY($5))\n AND ($6::timestamptz IS NULL OR (\n m.created_at > $6\n OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id\n AND r.deleted_at IS NULL\n AND r.created_at > $6\n )\n ))\n AND ($8::bool IS NULL OR EXISTS (\n SELECT 1 FROM done_top_level dt\n WHERE dt.top_level_id = m.id\n ))\n AND ($9::bool IS NULL OR EXISTS (\n SELECT 1 FROM seen_top_level st\n WHERE st.top_level_id = m.id\n ))\n ORDER BY m.created_at ASC, m.id ASC\n LIMIT $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Uuid",
+ "Int8",
+ "UuidArray",
+ "Timestamptz",
+ "Text",
+ "Bool",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "ec5e416378f73f769e797d9affa95f4dcc98ea607f84993efd70313e3b8b7d4f"
+}
diff --git a/rust/cloud-storage/channels/.sqlx/query-fb06661528090b1781ae1f2bad6be9dd410315f4f4f376429d9f9e2e3c822383.json b/rust/cloud-storage/channels/.sqlx/query-fb06661528090b1781ae1f2bad6be9dd410315f4f4f376429d9f9e2e3c822383.json
new file mode 100644
index 0000000000..8bd9568af3
--- /dev/null
+++ b/rust/cloud-storage/channels/.sqlx/query-fb06661528090b1781ae1f2bad6be9dd410315f4f4f376429d9f9e2e3c822383.json
@@ -0,0 +1,72 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH done_top_level AS (\n SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid\n WHERE $8::bool IS NOT NULL\n AND un.user_id = $7::text\n AND un.deleted_at IS NULL\n AND un.done = $8\n AND n.event_item_type = 'channel'\n AND n.event_item_id = $1::uuid::text\n AND n.metadata->>'messageId' IS NOT NULL\n AND msg.channel_id = $1\n AND msg.deleted_at IS NULL\n ),\n seen_top_level AS (\n SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid\n WHERE $9::bool IS NOT NULL\n AND un.user_id = $7::text\n AND un.deleted_at IS NULL\n AND (un.seen_at IS NOT NULL) = $9\n AND n.event_item_type = 'channel'\n AND n.event_item_id = $1::uuid::text\n AND n.metadata->>'messageId' IS NOT NULL\n AND msg.channel_id = $1\n AND msg.deleted_at IS NULL\n )\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))\n AND ($5::uuid[] IS NULL OR m.id = ANY($5))\n AND ($6::timestamptz IS NULL OR (\n m.created_at > $6\n OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id\n AND r.deleted_at IS NULL\n AND r.created_at > $6\n )\n ))\n AND ($8::bool IS NULL OR EXISTS (\n SELECT 1 FROM done_top_level dt\n WHERE dt.top_level_id = m.id\n ))\n AND ($9::bool IS NULL OR EXISTS (\n SELECT 1 FROM seen_top_level st\n WHERE st.top_level_id = m.id\n ))\n ORDER BY m.created_at DESC, m.id DESC\n LIMIT $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Uuid",
+ "Int8",
+ "UuidArray",
+ "Timestamptz",
+ "Text",
+ "Bool",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "fb06661528090b1781ae1f2bad6be9dd410315f4f4f376429d9f9e2e3c822383"
+}
diff --git a/rust/cloud-storage/channels/Cargo.toml b/rust/cloud-storage/channels/Cargo.toml
index 5c377cbf28..6bc2369c6e 100644
--- a/rust/cloud-storage/channels/Cargo.toml
+++ b/rust/cloud-storage/channels/Cargo.toml
@@ -23,6 +23,7 @@ axum = { workspace = true, optional = true }
chrono = { workspace = true }
entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["inbound"] }
model-error-response = { path = "../model-error-response", optional = true }
+macro_user_id = { path = "../macro_user_id" }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
models_pagination = { path = "../models_pagination" }
serde = { workspace = true }
@@ -36,7 +37,6 @@ uuid = { workspace = true }
[dev-dependencies]
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
-macro_user_id = { path = "../macro_user_id" }
mockall = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rs
index ce708bbdbe..456348cca2 100644
--- a/rust/cloud-storage/channels/src/domain/models.rs
+++ b/rust/cloud-storage/channels/src/domain/models.rs
@@ -35,6 +35,32 @@ pub struct ChannelMessageFilters {
/// this time, or a thread reply was created after this time.
#[serde(default)]
pub last_activity: Option<DateTime<Utc>>,
+ /// When set, only return top-level messages where the message itself or
+ /// any active thread reply has a notification for the requesting user that
+ /// matches these notification state constraints.
+ #[serde(default)]
+ pub notification_filters: NotificationFilters,
+}
+
+/// Notification state filters for channel message queries.
+#[derive(Debug, Clone, Copy, Default, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct NotificationFilters {
+ /// Filter by notification done state. `Some(true)` selects done
+ /// notifications; `Some(false)` selects not-done notifications.
+ #[serde(default)]
+ pub done: Option<bool>,
+ /// Filter by notification seen state. `Some(true)` selects seen
+ /// notifications; `Some(false)` selects not-seen notifications.
+ #[serde(default)]
+ pub seen: Option<bool>,
+}
+
+impl NotificationFilters {
+ /// Returns true when no notification constraints are requested.
+ pub fn is_empty(&self) -> bool {
+ self.done.is_none() && self.seen.is_none()
+ }
}
/// Direction for cursor-based message pagination.
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index bd8f4b7c51..aa70049be3 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -4,6 +4,7 @@ use crate::domain::models::{
ThreadReplyRow, TopLevelMessageRow,
};
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Query};
use std::collections::HashMap;
use uuid::Uuid;
@@ -15,6 +16,8 @@ pub trait ChannelMessagesRepo: Send + Sync + 'static {
type Err: Send;
/// Fetch top-level messages (thread_id IS NULL). Cursor-paginated on created_at DESC.
+ ///
+ /// `notification_user_id` is used only when `filters.notification_filters` is non-empty.
fn get_top_level_messages(
&self,
channel_id: Uuid,
@@ -22,6 +25,7 @@ pub trait ChannelMessagesRepo: Send + Sync + 'static {
direction: MessagePageDirection,
limit: u16,
filters: &ChannelMessageFilters,
+ notification_user_id: Option<MacroUserIdStr<'static>>,
) -> impl Future<Output = Result<TopLevelMessagesQueryResult, Self::Err>> + Send;
/// Batch-fetch thread data (stats + preview replies) for parent messages in a single query.
@@ -86,6 +90,8 @@ pub trait ChannelMessagesRepo: Send + Sync + 'static {
/// Service for fetching paginated channel messages.
pub trait ChannelMessagesService: Send + Sync + 'static {
/// Fetch a page of channel messages with thread previews, reactions, and attachments.
+ ///
+ /// `notification_user_id` is used only when `filters.notification_filters` is non-empty.
fn get_channel_messages(
&self,
channel_id: Uuid,
@@ -93,6 +99,7 @@ pub trait ChannelMessagesService: Send + Sync + 'static {
direction: MessagePageDirection,
limit: u16,
filters: &ChannelMessageFilters,
+ notification_user_id: Option<MacroUserIdStr<'static>>,
) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send;
/// Fetch a paginated page of channel-level attachments.
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index 48359bedd6..6cd32dbf0b 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -8,6 +8,7 @@ use crate::domain::{
ChannelMessagesRepo, ChannelMessagesService,
},
};
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, PaginateOn, Query};
use uuid::Uuid;
@@ -185,12 +186,20 @@ where
direction: MessagePageDirection,
limit: u16,
filters: &ChannelMessageFilters,
+ notification_user_id: Option<MacroUserIdStr<'static>>,
) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
let limit = limit.clamp(1, 100);
let rows_result = self
.repo
- .get_top_level_messages(channel_id, &query, direction, limit, filters)
+ .get_top_level_messages(
+ channel_id,
+ &query,
+ direction,
+ limit,
+ filters,
+ notification_user_id,
+ )
.await
.map_err(anyhow::Error::from)?;
diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rs
index d97f8fcb26..456fb000d2 100644
--- a/rust/cloud-storage/channels/src/domain/service/test.rs
+++ b/rust/cloud-storage/channels/src/domain/service/test.rs
@@ -26,7 +26,7 @@ fn make_row(id: Uuid, minutes_ago: i64) -> TopLevelMessageRow {
fn empty_repo() -> MockChannelMessagesRepo {
let mut repo = MockChannelMessagesRepo::new();
repo.expect_get_top_level_messages()
- .returning(|_, _, _, _, _| {
+ .returning(|_, _, _, _, _, _| {
Box::pin(async {
Ok(TopLevelMessagesQueryResult {
rows: vec![],
@@ -63,6 +63,7 @@ async fn returns_empty_page_for_no_messages() {
MessagePageDirection::Older,
50,
&ChannelMessageFilters::default(),
+ None,
)
.await
.unwrap();
@@ -93,7 +94,7 @@ async fn returns_messages_with_thread_info() {
let row_clone = row.clone();
repo.expect_get_top_level_messages()
- .returning(move |_, _, _, _, _| {
+ .returning(move |_, _, _, _, _, _| {
let r = row_clone.clone();
Box::pin(async move {
Ok(TopLevelMessagesQueryResult {
@@ -151,6 +152,7 @@ async fn returns_messages_with_thread_info() {
MessagePageDirection::Older,
50,
&ChannelMessageFilters::default(),
+ None,
)
.await
.unwrap();
@@ -169,8 +171,8 @@ async fn returns_messages_with_thread_info() {
async fn clamps_limit() {
let mut repo = MockChannelMessagesRepo::new();
repo.expect_get_top_level_messages()
- .withf(|_, _, _, limit, _| *limit == 100)
- .returning(|_, _, _, _, _| {
+ .withf(|_, _, _, limit, _, _| *limit == 100)
+ .returning(|_, _, _, _, _, _| {
Box::pin(async {
Ok(TopLevelMessagesQueryResult {
rows: vec![],
@@ -193,6 +195,7 @@ async fn clamps_limit() {
MessagePageDirection::Older,
200,
&ChannelMessageFilters::default(),
+ None,
)
.await
.unwrap();
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index 302a17a363..e08a08ce19 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -1,11 +1,11 @@
#[cfg(test)]
mod test;
-pub use crate::domain::models::ChannelMessageFilters;
use crate::domain::models::{
ChannelAttachment, ChannelAttachmentType, ChannelMessage, ChannelParticipant, CountedReaction,
MessageAttachment, MessagePageDirection, ParticipantRole, ThreadInfo, ThreadReply,
};
+pub use crate::domain::models::{ChannelMessageFilters, NotificationFilters};
use crate::domain::ports::{
ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesQueryResult, ChannelMessagesService,
};
@@ -24,6 +24,7 @@ use entity_access::{
},
inbound::axum_extractors::ChannelAccessLevelExtractor,
};
+use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
use models_pagination::{
Base64Str, BidirectionalCursor, CreatedAt, Cursor, CursorOptionExt, CursorVal,
@@ -71,6 +72,20 @@ fn channel_id_from_receipt<T: RequiredPermission>(
.map_err(|_| ChannelsHandlerErr::BadRequest("Invalid channel_id"))
}
+fn notification_user_id_from_receipt<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+ filters: &ChannelMessageFilters,
+) -> Result<Option<MacroUserIdStr<'static>>, ChannelsHandlerErr> {
+ if filters.notification_filters.is_empty() {
+ return Ok(None);
+ }
+
+ let user = receipt.get_authenticated_user().map_err(|_| {
+ ChannelsHandlerErr::BadRequest("notification filters require authenticated user")
+ })?;
+ Ok(Some(user.clone()))
+}
+
const MAX_MESSAGE_ID_FILTERS: usize = 100;
/// Query parameters for the messages endpoint.
@@ -205,7 +220,7 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService, Svc: Entity
) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
let filters = ChannelMessageFilters::default();
- channel_messages_response(&state, params, cursor, channel_id, &filters).await
+ channel_messages_response(&state, params, cursor, channel_id, &filters, None).await
}
/// Handler for `POST /channels/{channel_id}/messages`.
@@ -251,7 +266,17 @@ pub async fn post_channel_messages_handler<S: ChannelMessagesService, Svc: Entit
if filters.message_ids.len() > MAX_MESSAGE_ID_FILTERS {
return Err(ChannelsHandlerErr::BadRequest("too many message_ids"));
}
- channel_messages_response(&state, params, cursor, channel_id, &filters).await
+ let notification_user_id =
+ notification_user_id_from_receipt(&access.entity_access_receipt, &filters)?;
+ channel_messages_response(
+ &state,
+ params,
+ cursor,
+ channel_id,
+ &filters,
+ notification_user_id,
+ )
+ .await
}
async fn channel_messages_response<S: ChannelMessagesService, Svc>(
@@ -260,6 +285,7 @@ async fn channel_messages_response<S: ChannelMessagesService, Svc>(
cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
channel_id: Uuid,
filters: &ChannelMessageFilters,
+ notification_user_id: Option<MacroUserIdStr<'static>>,
) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {
let limit = params.limit.unwrap_or(50).clamp(1, 100);
let (query, direction, has_cursor) = parse_messages_query(cursor);
@@ -291,7 +317,14 @@ async fn channel_messages_response<S: ChannelMessagesService, Svc>(
has_more_newer,
} = state
.service
- .get_channel_messages(channel_id, query, direction, limit, filters)
+ .get_channel_messages(
+ channel_id,
+ query,
+ direction,
+ limit,
+ filters,
+ notification_user_id,
+ )
.await?;
(page, has_more_newer)
}
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
index b9cea6d061..a12ec93be9 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -18,6 +18,7 @@ use entity_access::domain::{
ports::EntityAccessService,
};
use http_body_util::BodyExt;
+use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use model_user::UserContext;
@@ -172,6 +173,7 @@ impl ChannelMessagesService for MockService {
_direction: MessagePageDirection,
_limit: u16,
_filters: &ChannelMessageFilters,
+ _notification_user_id: Option<MacroUserIdStr<'_>>,
) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
Ok(ChannelMessagesQueryResult {
page: Vec::<ChannelMessage>::new()
@@ -239,6 +241,7 @@ impl ChannelMessagesService for ErrorService {
_direction: MessagePageDirection,
_limit: u16,
_filters: &ChannelMessageFilters,
+ _notification_user_id: Option<MacroUserIdStr<'_>>,
) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))
}
@@ -288,6 +291,7 @@ impl ChannelMessagesService for ParticipantsService {
_direction: MessagePageDirection,
_limit: u16,
_filters: &ChannelMessageFilters,
+ _notification_user_id: Option<MacroUserIdStr<'_>>,
) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
Ok(ChannelMessagesQueryResult {
page: Vec::<ChannelMessage>::new()
@@ -591,6 +595,7 @@ impl ChannelMessagesService for NotFoundService {
_direction: MessagePageDirection,
_limit: u16,
_filters: &ChannelMessageFilters,
+ _notification_user_id: Option<MacroUserIdStr<'_>>,
) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
Ok(ChannelMessagesQueryResult {
page: Vec::<ChannelMessage>::new()
@@ -653,6 +658,7 @@ impl ChannelMessagesService for AroundHasItemsService {
_direction: MessagePageDirection,
_limit: u16,
_filters: &ChannelMessageFilters,
+ _notification_user_id: Option<MacroUserIdStr<'_>>,
) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
Ok(ChannelMessagesQueryResult {
page: Vec::<ChannelMessage>::new()
@@ -832,12 +838,14 @@ async fn messages_around_returns_404_when_not_found() {
struct CapturingService {
captured: std::sync::Mutex<Option<ChannelMessageFilters>>,
+ captured_notification_user_id: std::sync::Mutex<Option<MacroUserIdStr<'static>>>,
}
impl CapturingService {
fn new() -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
captured: std::sync::Mutex::new(None),
+ captured_notification_user_id: std::sync::Mutex::new(None),
})
}
}
@@ -850,8 +858,11 @@ impl ChannelMessagesService for std::sync::Arc<CapturingService> {
_direction: MessagePageDirection,
_limit: u16,
filters: &ChannelMessageFilters,
+ notification_user_id: Option<MacroUserIdStr<'_>>,
) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
*self.captured.lock().unwrap() = Some(filters.clone());
+ *self.captured_notification_user_id.lock().unwrap() =
+ notification_user_id.map(CowLike::into_owned);
Ok(ChannelMessagesQueryResult {
page: Vec::<ChannelMessage>::new()
.into_iter()
@@ -931,6 +942,8 @@ async fn post_messages_empty_body_uses_default_filters() {
let captured = svc.captured.lock().unwrap().clone().unwrap();
assert!(captured.message_ids.is_empty());
assert!(captured.last_activity.is_none());
+ assert!(captured.notification_filters.is_empty());
+ assert!(svc.captured_notification_user_id.lock().unwrap().is_none());
}
#[tokio::test]
@@ -994,6 +1007,46 @@ async fn post_messages_forwards_last_activity_filter() {
);
}
+#[tokio::test]
+async fn post_messages_forwards_notification_filter_for_authenticated_user() {
+ let svc = CapturingService::new();
+ let router = channels_router(ChannelsRouterState::new(
+ svc.clone(),
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension());
+
+ let channel_id = Uuid::new_v4();
+ let body = serde_json::json!({
+ "notification_filters": {
+ "done": false,
+ "seen": true
+ }
+ })
+ .to_string();
+
+ let request = Request::builder()
+ .method("POST")
+ .uri(format!("/{channel_id}/messages"))
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(body))
+ .unwrap();
+
+ let res = router.oneshot(request).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let captured = svc.captured.lock().unwrap().clone().unwrap();
+ assert_eq!(captured.notification_filters.done, Some(false));
+ assert_eq!(captured.notification_filters.seen, Some(true));
+ let captured_user_id = svc
+ .captured_notification_user_id
+ .lock()
+ .unwrap()
+ .as_ref()
+ .map(ToString::to_string);
+ assert_eq!(captured_user_id.as_deref(), Some("macro|[email protected]"));
+}
+
#[tokio::test]
async fn post_messages_rejects_oversized_filter_list() {
let router = channels_router(ChannelsRouterState::new(
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
index e79927078a..b954545fd3 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
@@ -10,6 +10,7 @@ use crate::domain::{
ports::{ChannelMessagesRepo, TopLevelMessagesQueryResult},
};
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Query};
use sqlx::PgPool;
use std::collections::HashMap;
@@ -121,6 +122,7 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
direction: MessagePageDirection,
limit: u16,
filters: &ChannelMessageFilters,
+ notification_user_id: Option<MacroUserIdStr<'static>>,
) -> Result<TopLevelMessagesQueryResult, Self::Err> {
let (cursor_created_at, cursor_id) = match query.vals() {
(Some(id), Some(val)) => (Some(*val), Some(*id)),
@@ -135,12 +137,108 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
Some(&filters.message_ids)
};
let last_activity = filters.last_activity;
+ let notification_filter_active = !filters.notification_filters.is_empty();
+ let notification_user_id = match (notification_filter_active, notification_user_id.as_ref())
+ {
+ (true, Some(user_id)) => user_id.as_ref(),
+ (true, None) => {
+ anyhow::bail!("notification_user_id is required when notification_filters are set")
+ }
+ (false, _) => "",
+ };
+ let notification_done = filters.notification_filters.done;
+ let notification_seen = filters.notification_filters.seen;
let (rows, has_more_newer) = match direction {
MessagePageDirection::Older => {
- let rows = sqlx::query_as!(
- TopLevelRow,
- r#"
+ let rows = if notification_filter_active {
+ sqlx::query_as!(
+ TopLevelRow,
+ r#"
+ WITH done_top_level AS (
+ SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id
+ FROM notification n
+ JOIN user_notification un ON un.notification_id = n.id
+ JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
+ WHERE $8::bool IS NOT NULL
+ AND un.user_id = $7::text
+ AND un.deleted_at IS NULL
+ AND un.done = $8
+ AND n.event_item_type = 'channel'
+ AND n.event_item_id = $1::uuid::text
+ AND n.metadata->>'messageId' IS NOT NULL
+ AND msg.channel_id = $1
+ AND msg.deleted_at IS NULL
+ ),
+ seen_top_level AS (
+ SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id
+ FROM notification n
+ JOIN user_notification un ON un.notification_id = n.id
+ JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
+ WHERE $9::bool IS NOT NULL
+ AND un.user_id = $7::text
+ AND un.deleted_at IS NULL
+ AND (un.seen_at IS NOT NULL) = $9
+ AND n.event_item_type = 'channel'
+ AND n.event_item_id = $1::uuid::text
+ AND n.metadata->>'messageId' IS NOT NULL
+ AND msg.channel_id = $1
+ AND msg.deleted_at IS NULL
+ )
+ SELECT
+ m.id,
+ m.channel_id,
+ m.sender_id,
+ m.content,
+ m.created_at,
+ m.updated_at,
+ m.edited_at::timestamptz AS "edited_at?",
+ m.deleted_at::timestamptz AS "deleted_at?"
+ FROM comms_messages m
+ WHERE m.channel_id = $1
+ AND m.thread_id IS NULL
+ AND (m.deleted_at IS NULL OR EXISTS (
+ SELECT 1 FROM comms_messages r
+ WHERE r.thread_id = m.id AND r.deleted_at IS NULL
+ ))
+ AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))
+ AND ($5::uuid[] IS NULL OR m.id = ANY($5))
+ AND ($6::timestamptz IS NULL OR (
+ m.created_at > $6
+ OR EXISTS (
+ SELECT 1 FROM comms_messages r
+ WHERE r.thread_id = m.id
+ AND r.deleted_at IS NULL
+ AND r.created_at > $6
+ )
+ ))
+ AND ($8::bool IS NULL OR EXISTS (
+ SELECT 1 FROM done_top_level dt
+ WHERE dt.top_level_id = m.id
+ ))
+ AND ($9::bool IS NULL OR EXISTS (
+ SELECT 1 FROM seen_top_level st
+ WHERE st.top_level_id = m.id
+ ))
+ ORDER BY m.created_at DESC, m.id DESC
+ LIMIT $4
+ "#,
+ channel_id,
+ cursor_created_at,
+ cursor_id,
+ limit_i64,
+ message_ids_filter as Option<&[Uuid]>,
+ last_activity,
+ notification_user_id,
+ notification_done,
+ notification_seen,
+ )
+ .fetch_all(&self.pool)
+ .await?
+ } else {
+ sqlx::query_as!(
+ TopLevelRow,
+ r#"
SELECT
m.id,
m.channel_id,
@@ -171,22 +269,108 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
ORDER BY m.created_at DESC, m.id DESC
LIMIT $4
"#,
- channel_id,
- cursor_created_at,
- cursor_id,
- limit_i64,
- message_ids_filter as Option<&[Uuid]>,
- last_activity,
- )
- .fetch_all(&self.pool)
- .await?;
+ channel_id,
+ cursor_created_at,
+ cursor_id,
+ limit_i64,
+ message_ids_filter as Option<&[Uuid]>,
+ last_activity,
+ )
+ .fetch_all(&self.pool)
+ .await?
+ };
(rows, cursor_created_at.is_some())
}
MessagePageDirection::Newer => {
- let mut rows = sqlx::query_as!(
- TopLevelRow,
- r#"
+ let mut rows = if notification_filter_active {
+ sqlx::query_as!(
+ TopLevelRow,
+ r#"
+ WITH done_top_level AS (
+ SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id
+ FROM notification n
+ JOIN user_notification un ON un.notification_id = n.id
+ JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
+ WHERE $8::bool IS NOT NULL
+ AND un.user_id = $7::text
+ AND un.deleted_at IS NULL
+ AND un.done = $8
+ AND n.event_item_type = 'channel'
+ AND n.event_item_id = $1::uuid::text
+ AND n.metadata->>'messageId' IS NOT NULL
+ AND msg.channel_id = $1
+ AND msg.deleted_at IS NULL
+ ),
+ seen_top_level AS (
+ SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id
+ FROM notification n
+ JOIN user_notification un ON un.notification_id = n.id
+ JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
+ WHERE $9::bool IS NOT NULL
+ AND un.user_id = $7::text
+ AND un.deleted_at IS NULL
+ AND (un.seen_at IS NOT NULL) = $9
+ AND n.event_item_type = 'channel'
+ AND n.event_item_id = $1::uuid::text
+ AND n.metadata->>'messageId' IS NOT NULL
+ AND msg.channel_id = $1
+ AND msg.deleted_at IS NULL
+ )
+ SELECT
+ m.id,
+ m.channel_id,
+ m.sender_id,
+ m.content,
+ m.created_at,
+ m.updated_at,
+ m.edited_at::timestamptz AS "edited_at?",
+ m.deleted_at::timestamptz AS "deleted_at?"
+ FROM comms_messages m
+ WHERE m.channel_id = $1
+ AND m.thread_id IS NULL
+ AND (m.deleted_at IS NULL OR EXISTS (
+ SELECT 1 FROM comms_messages r
+ WHERE r.thread_id = m.id AND r.deleted_at IS NULL
+ ))
+ AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))
+ AND ($5::uuid[] IS NULL OR m.id = ANY($5))
+ AND ($6::timestamptz IS NULL OR (
+ m.created_at > $6
+ OR EXISTS (
+ SELECT 1 FROM comms_messages r
+ WHERE r.thread_id = m.id
+ AND r.deleted_at IS NULL
+ AND r.created_at > $6
+ )
+ ))
+ AND ($8::bool IS NULL OR EXISTS (
+ SELECT 1 FROM done_top_level dt
+ WHERE dt.top_level_id = m.id
+ ))
+ AND ($9::bool IS NULL OR EXISTS (
+ SELECT 1 FROM seen_top_level st
+ WHERE st.top_level_id = m.id
+ ))
+ ORDER BY m.created_at ASC, m.id ASC
+ LIMIT $4
+ "#,
+ channel_id,
+ cursor_created_at,
+ cursor_id,
+ limit_i64 + 1,
+ message_ids_filter as Option<&[Uuid]>,
+ last_activity,
+ notification_user_id,
+ notification_done,
+ notification_seen,
+ )
+ .fetch_all(&self.pool)
+ .await?
+ } else {
+ sqlx::query_as!(
+ TopLevelRow,
+ r#"
SELECT
m.id,
m.channel_id,
@@ -217,15 +401,16 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
ORDER BY m.created_at ASC, m.id ASC
LIMIT $4
"#,
- channel_id,
- cursor_created_at,
- cursor_id,
- limit_i64 + 1,
- message_ids_filter as Option<&[Uuid]>,
- last_activity,
- )
- .fetch_all(&self.pool)
- .await?;
+ channel_id,
+ cursor_created_at,
+ cursor_id,
+ limit_i64 + 1,
+ message_ids_filter as Option<&[Uuid]>,
+ last_activity,
+ )
+ .fetch_all(&self.pool)
+ .await?
+ };
let has_more_newer = rows.len() > limit_usize;
if has_more_newer {
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
index df90601c6b..4180595b6e 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
@@ -1,7 +1,10 @@
-use crate::domain::models::{ChannelMessageFilters, MessagePageDirection, ParticipantRole};
+use crate::domain::models::{
+ ChannelMessageFilters, MessagePageDirection, NotificationFilters, ParticipantRole,
+};
use crate::domain::ports::ChannelMessagesRepo;
use crate::outbound::pg_channels_repo::PgChannelMessagesRepo;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Cursor, CursorVal, Query};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -9,6 +12,10 @@ use uuid::Uuid;
const NO_FILTERS: ChannelMessageFilters = ChannelMessageFilters {
message_ids: Vec::new(),
last_activity: None,
+ notification_filters: NotificationFilters {
+ done: None,
+ seen: None,
+ },
};
const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);
@@ -19,11 +26,74 @@ const MSG3: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000003);
const REPLY1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b001);
const REPLY5: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b005);
const DELETED_MSG_ATTACHMENT: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000a004);
+const USER_A: &str = "macro|[email protected]";
+const USER_B: &str = "macro|[email protected]";
fn repo(pool: Pool<Postgres>) -> PgChannelMessagesRepo {
PgChannelMessagesRepo::new(pool)
}
+fn macro_user_id(user_id: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(user_id.to_owned()).expect("valid macro user id")
+}
+
+async fn insert_channel_message_notification(
+ pool: &Pool<Postgres>,
+ user_id: &str,
+ channel_id: Uuid,
+ message_id: Uuid,
+ done: bool,
+ seen: bool,
+) -> anyhow::Result<()> {
+ let notification_id = Uuid::new_v4();
+ sqlx::query(
+ r#"
+ INSERT INTO notification (
+ id,
+ notification_event_type,
+ event_item_id,
+ event_item_type,
+ service_sender,
+ metadata
+ )
+ VALUES (
+ $1,
+ 'channel_message_send',
+ $2,
+ 'channel',
+ 'channels-test',
+ jsonb_build_object('messageId', $3::text)
+ )
+ "#,
+ )
+ .bind(notification_id)
+ .bind(channel_id.to_string())
+ .bind(message_id.to_string())
+ .execute(pool)
+ .await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO user_notification (user_id, notification_id, created_at, seen_at, done)
+ VALUES (
+ $1,
+ $2,
+ '2024-01-02 00:00:00'::timestamp,
+ CASE WHEN $3::bool THEN '2024-01-02 00:00:00'::timestamp ELSE NULL END,
+ $4
+ )
+ "#,
+ )
+ .bind(user_id)
+ .bind(notification_id)
+ .bind(seen)
+ .bind(done)
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
#[sqlx::test(
fixtures(path = "../../../fixtures", scripts("channels_repo")),
migrator = "MACRO_DB_MIGRATIONS"
@@ -39,6 +109,7 @@ async fn top_level_excludes_thread_replies_and_fully_deleted(
MessagePageDirection::Older,
50,
&NO_FILTERS,
+ None,
)
.await?;
let rows = result.rows;
@@ -68,6 +139,7 @@ async fn top_level_ordered_newest_first(pool: Pool<Postgres>) -> anyhow::Result<
MessagePageDirection::Older,
50,
&NO_FILTERS,
+ None,
)
.await?;
let rows = result.rows;
@@ -91,6 +163,7 @@ async fn top_level_cursor_skips_earlier_messages(pool: Pool<Postgres>) -> anyhow
MessagePageDirection::Older,
50,
&NO_FILTERS,
+ None,
)
.await?
.rows;
@@ -107,7 +180,14 @@ async fn top_level_cursor_skips_earlier_messages(pool: Pool<Postgres>) -> anyhow
filter: (),
});
let page2 = repo
- .get_top_level_messages(CH1, &cursor, MessagePageDirection::Older, 50, &NO_FILTERS)
+ .get_top_level_messages(
+ CH1,
+ &cursor,
+ MessagePageDirection::Older,
+ 50,
+ &NO_FILTERS,
+ None,
+ )
.await?
.rows;
let ids: Vec<Uuid> = page2.iter().map(|r| r.id).collect();
@@ -130,6 +210,7 @@ async fn top_level_newer_direction_returns_nearest_newer_page(
MessagePageDirection::Older,
50,
&NO_FILTERS,
+ None,
)
.await?
.rows;
@@ -145,7 +226,14 @@ async fn top_level_newer_direction_returns_nearest_newer_page(
filter: (),
});
let page = repo
- .get_top_level_messages(CH1, &cursor, MessagePageDirection::Newer, 2, &NO_FILTERS)
+ .get_top_level_messages(
+ CH1,
+ &cursor,
+ MessagePageDirection::Newer,
+ 2,
+ &NO_FILTERS,
+ None,
+ )
.await?;
let ids: Vec<Uuid> = page.rows.iter().map(|r| r.id).collect();
@@ -169,6 +257,7 @@ async fn top_level_newer_direction_sets_has_more_newer_with_overfetch(
MessagePageDirection::Older,
50,
&NO_FILTERS,
+ None,
)
.await?
.rows;
@@ -184,7 +273,14 @@ async fn top_level_newer_direction_sets_has_more_newer_with_overfetch(
filter: (),
});
let page = repo
- .get_top_level_messages(CH1, &cursor, MessagePageDirection::Newer, 1, &NO_FILTERS)
+ .get_top_level_messages(
+ CH1,
+ &cursor,
+ MessagePageDirection::Newer,
+ 1,
+ &NO_FILTERS,
+ None,
+ )
.await?;
let ids: Vec<Uuid> = page.rows.iter().map(|r| r.id).collect();
@@ -206,6 +302,7 @@ async fn top_level_limit_is_respected(pool: Pool<Postgres>) -> anyhow::Result<()
MessagePageDirection::Older,
2,
&NO_FILTERS,
+ None,
)
.await?;
let rows = result.rows;
@@ -230,6 +327,7 @@ async fn top_level_scoped_to_channel(pool: Pool<Postgres>) -> anyhow::Result<()>
MessagePageDirection::Older,
50,
&NO_FILTERS,
+ None,
)
.await?;
let rows = result.rows;
@@ -256,6 +354,7 @@ async fn top_level_message_ids_filter_limits_to_subset(pool: Pool<Postgres>) ->
MessagePageDirection::Older,
50,
&filters,
+ None,
)
.await?;
@@ -415,7 +514,7 @@ async fn reactions_grouped_by_emoji(pool: Pool<Postgres>) -> anyhow::Result<()>
assert_eq!(msg3_reactions[0].users.len(), 1);
// msg2 has no reactions
- assert!(map.get(&MSG2).is_none());
+ assert!(!map.contains_key(&MSG2));
Ok(())
}
@@ -727,6 +826,7 @@ async fn last_activity_filters_by_message_created_at(pool: Pool<Postgres>) -> an
MessagePageDirection::Older,
50,
&filters,
+ None,
)
.await?;
@@ -763,6 +863,7 @@ async fn last_activity_includes_messages_with_recent_thread_replies(
MessagePageDirection::Older,
50,
&filters,
+ None,
)
.await?;
@@ -785,6 +886,7 @@ async fn last_activity_combined_with_message_ids(pool: Pool<Postgres>) -> anyhow
.unwrap()
.with_timezone(&chrono::Utc),
),
+ ..Default::default()
};
let result = repo
.get_top_level_messages(
@@ -793,6 +895,178 @@ async fn last_activity_combined_with_message_ids(pool: Pool<Postgres>) -> anyhow
MessagePageDirection::Older,
50,
&filters,
+ None,
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = result.rows.iter().map(|r| r.id).collect();
+ assert_eq!(ids, vec![MSG3]);
+ Ok(())
+}
+
+// -- notification filters -----------------------------------------------------
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn notification_done_filter_matches_top_level_messages_and_thread_replies(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ insert_channel_message_notification(&pool, USER_A, CH1, MSG3, true, false).await?;
+ insert_channel_message_notification(&pool, USER_A, CH1, REPLY1, true, false).await?;
+ insert_channel_message_notification(&pool, USER_A, CH1, MSG2, false, false).await?;
+
+ let filters = ChannelMessageFilters {
+ notification_filters: NotificationFilters {
+ done: Some(true),
+ seen: None,
+ },
+ ..Default::default()
+ };
+ let result = repo(pool)
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ &filters,
+ Some(macro_user_id(USER_A)),
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = result.rows.iter().map(|r| r.id).collect();
+ assert_eq!(ids, vec![MSG3, MSG1]);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn notification_not_done_filter_matches_top_level_messages_and_thread_replies(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ insert_channel_message_notification(&pool, USER_A, CH1, MSG3, false, false).await?;
+ insert_channel_message_notification(&pool, USER_A, CH1, REPLY1, false, false).await?;
+ insert_channel_message_notification(&pool, USER_A, CH1, MSG2, true, false).await?;
+
+ let filters = ChannelMessageFilters {
+ notification_filters: NotificationFilters {
+ done: Some(false),
+ seen: None,
+ },
+ ..Default::default()
+ };
+ let result = repo(pool)
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ &filters,
+ Some(macro_user_id(USER_A)),
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = result.rows.iter().map(|r| r.id).collect();
+ assert_eq!(ids, vec![MSG3, MSG1]);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn notification_seen_filter_matches_top_level_messages_and_thread_replies(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ insert_channel_message_notification(&pool, USER_A, CH1, MSG3, false, true).await?;
+ insert_channel_message_notification(&pool, USER_A, CH1, REPLY1, false, true).await?;
+ insert_channel_message_notification(&pool, USER_A, CH1, REPLY5, false, true).await?;
+
+ let filters = ChannelMessageFilters {
+ notification_filters: NotificationFilters {
+ done: None,
+ seen: Some(true),
+ },
+ ..Default::default()
+ };
+ let result = repo(pool)
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ &filters,
+ Some(macro_user_id(USER_A)),
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = result.rows.iter().map(|r| r.id).collect();
+ assert_eq!(ids, vec![MSG3, MSG2, MSG1]);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn notification_not_seen_filter_matches_top_level_messages_and_thread_replies(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ insert_channel_message_notification(&pool, USER_A, CH1, MSG3, false, false).await?;
+ insert_channel_message_notification(&pool, USER_A, CH1, REPLY1, false, false).await?;
+ insert_channel_message_notification(&pool, USER_A, CH1, MSG2, false, true).await?;
+
+ let filters = ChannelMessageFilters {
+ notification_filters: NotificationFilters {
+ done: None,
+ seen: Some(false),
+ },
+ ..Default::default()
+ };
+ let result = repo(pool)
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ &filters,
+ Some(macro_user_id(USER_A)),
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = result.rows.iter().map(|r| r.id).collect();
+ assert_eq!(ids, vec![MSG3, MSG1]);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn notification_done_and_seen_filters_match_soup_independent_exists_semantics(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ insert_channel_message_notification(&pool, USER_A, CH1, MSG3, false, true).await?;
+ insert_channel_message_notification(&pool, USER_A, CH1, MSG3, true, false).await?;
+
+ let filters = ChannelMessageFilters {
+ notification_filters: NotificationFilters {
+ done: Some(false),
+ seen: Some(false),
+ },
+ ..Default::default()
+ };
+ let result = repo(pool)
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ &filters,
+ Some(macro_user_id(USER_A)),
)
.await?;
@@ -800,3 +1074,65 @@ async fn last_activity_combined_with_message_ids(pool: Pool<Postgres>) -> anyhow
assert_eq!(ids, vec![MSG3]);
Ok(())
}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn notification_filter_is_scoped_to_requesting_user(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ insert_channel_message_notification(&pool, USER_B, CH1, MSG3, false, false).await?;
+
+ let filters = ChannelMessageFilters {
+ notification_filters: NotificationFilters {
+ done: Some(false),
+ seen: None,
+ },
+ ..Default::default()
+ };
+ let result = repo(pool)
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ &filters,
+ Some(macro_user_id(USER_A)),
+ )
+ .await?;
+
+ assert!(result.rows.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn notification_filter_requires_requesting_user(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let filters = ChannelMessageFilters {
+ notification_filters: NotificationFilters {
+ done: Some(false),
+ seen: None,
+ },
+ ..Default::default()
+ };
+
+ let result = repo(pool)
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ &filters,
+ None,
+ )
+ .await;
+
+ let Err(err) = result else {
+ anyhow::bail!("notification filters require a user id");
+ };
+ assert_eq!(
+ err.to_string(),
+ "notification_user_id is required when notification_filters are set"
+ );
+ Ok(())
+}