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(soup): comms filter 3 (#957)

Sean Aye2c3dd9452de3
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 8b589aeb57..e8d89fb21d 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1833,16 +1833,20 @@ dependencies = [
name = "comms"
version = "0.1.0"
dependencies = [
+ "anyhow",
"axum",
"chrono",
"doppleganger",
+ "filter_ast",
"frecency",
"item_filters",
+ "macro_db_migrator",
"macro_user_id",
"model-entity",
"model_user",
"models_comms",
"models_pagination",
+ "recursion",
"reqwest",
"rootcause",
"serde",
diff --git a/rust/cloud-storage/comms/Cargo.toml b/rust/cloud-storage/comms/Cargo.toml
index c8431e1e6c..a003b67a44 100644
--- a/rust/cloud-storage/comms/Cargo.toml
+++ b/rust/cloud-storage/comms/Cargo.toml
@@ -13,6 +13,7 @@ outbound = ["dep:reqwest"]
axum = { workspace = true, optional = true }
chrono = { workspace = true }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
+filter_ast = { path = "../filter_ast" }
frecency = { path = "../frecency", features = ["ports"] }
item_filters = { path = "../item_filters" }
macro_user_id = { path = "../macro_user_id" }
@@ -20,6 +21,7 @@ model-entity = { path = "../model-entity" }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
models_comms = { path = "../models_comms" }
models_pagination = { path = "../models_pagination" }
+recursion = { workspace = true }
reqwest = { workspace = true, optional = true }
rootcause = "0.11"
serde = { workspace = true }
@@ -30,3 +32,7 @@ tokio = { workspace = true }
tracing = { workspace = true }
utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
+
+[dev-dependencies]
+anyhow = { workspace = true }
+macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/comms/src/domain/models.rs b/rust/cloud-storage/comms/src/domain/models.rs
index 4cd5fe5362..cf97afe802 100644
--- a/rust/cloud-storage/comms/src/domain/models.rs
+++ b/rust/cloud-storage/comms/src/domain/models.rs
@@ -64,7 +64,7 @@ impl GetChannelsRequest {
}
}
-#[expect(dead_code, reason = "This is used in a later PR")]
+#[derive(Debug)]
pub struct GetChannelsParams {
macro_id: MacroUserIdStr<'static>,
limit: u32,
@@ -75,4 +75,12 @@ impl GetChannelsParams {
pub fn user(&self) -> &MacroUserIdStr<'static> {
&self.macro_id
}
+
+ pub fn limit(&self) -> u32 {
+ self.limit
+ }
+
+ pub fn query(&self) -> &Query<Uuid, SimpleSortMethod, LiteralTree<ChannelLiteral>> {
+ &self.query
+ }
}
diff --git a/rust/cloud-storage/comms/src/outbound/fixtures/channels.sql b/rust/cloud-storage/comms/src/outbound/fixtures/channels.sql
new file mode 100644
index 0000000000..92b8215ef4
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/fixtures/channels.sql
@@ -0,0 +1,43 @@
+-- Channels for dynamic query tests
+-- Note: org_id can only be set when channel_type = 'organization'
+INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id, created_at, updated_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Org Channel A', 'organization', 1, 'macro|[email protected]', '2024-01-01 10:00:00', '2024-01-10 10:00:00'),
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Org Channel B', 'organization', 1, 'macro|[email protected]', '2024-01-02 10:00:00', '2024-01-09 10:00:00'),
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'Public Channel C', 'public', NULL, 'macro|[email protected]', '2024-01-03 10:00:00', '2024-01-08 10:00:00'),
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', NULL, 'direct_message', NULL, 'macro|[email protected]', '2024-01-04 10:00:00', '2024-01-07 10:00:00');
+
+-- Participants
+INSERT INTO comms_channel_participants (channel_id, role, user_id, joined_at)
+VALUES
+ -- user-1 is in channels A, B, and D
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'owner', 'macro|[email protected]', '2024-01-01 10:00:00'),
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'owner', 'macro|[email protected]', '2024-01-02 10:00:00'),
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'owner', 'macro|[email protected]', '2024-01-04 10:00:00'),
+ -- user-1 is also a member of channel C
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'member', 'macro|[email protected]', '2024-01-03 10:00:00'),
+ -- user-2 owns channel C
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'owner', 'macro|[email protected]', '2024-01-03 10:00:00'),
+ -- user-2 is a member of channel D (DM)
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'member', 'macro|[email protected]', '2024-01-04 10:00:00');
+
+-- Messages for latest message tests
+INSERT INTO comms_messages (id, channel_id, thread_id, sender_id, content, created_at, updated_at, deleted_at)
+VALUES
+ -- Channel A messages: 2 non-thread, 2 thread messages
+ ('aaaaaa2a-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'macro|[email protected]', 'First message in A', '2024-01-01 11:00:00', '2024-01-01 11:00:00', NULL),
+ ('aaaaaa2a-0000-0000-0000-000000000002', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'macro|[email protected]', 'Second message in A (latest non-thread)', '2024-01-01 12:00:00', '2024-01-01 12:00:00', NULL),
+ ('aaaaaa2a-0000-0000-0000-000000000003', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'aaaaaa2a-0000-0000-0000-000000000001', 'macro|[email protected]', 'Thread reply in A', '2024-01-01 13:00:00', '2024-01-01 13:00:00', NULL),
+ ('aaaaaa2a-0000-0000-0000-000000000004', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'aaaaaa2a-0000-0000-0000-000000000001', 'macro|[email protected]', 'Latest thread reply in A (latest overall)', '2024-01-01 14:00:00', '2024-01-01 14:00:00', NULL),
+
+ -- Channel B messages: all in a thread (no non-thread messages except the parent, which will be deleted)
+ ('bbbbbb2b-0000-0000-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NULL, 'macro|[email protected]', 'Deleted parent message', '2024-01-02 11:00:00', '2024-01-02 11:00:00', '2024-01-02 15:00:00'),
+ ('bbbbbb2b-0000-0000-0000-000000000002', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'bbbbbb2b-0000-0000-0000-000000000001', 'macro|[email protected]', 'Thread reply 1 in B', '2024-01-02 12:00:00', '2024-01-02 12:00:00', NULL),
+ ('bbbbbb2b-0000-0000-0000-000000000003', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'bbbbbb2b-0000-0000-0000-000000000001', 'macro|[email protected]', 'Latest thread reply in B (latest overall)', '2024-01-02 13:00:00', '2024-01-02 13:00:00', NULL),
+
+ -- Channel C messages: single non-thread message
+ ('cccccc2c-0000-0000-0000-000000000001', 'cccccccc-cccc-cccc-cccc-cccccccccccc', NULL, 'macro|[email protected]', 'First message in C', '2024-01-03 11:00:00', '2024-01-03 11:00:00', NULL),
+ ('cccccc2c-0000-0000-0000-000000000002', 'cccccccc-cccc-cccc-cccc-cccccccccccc', NULL, 'macro|[email protected]', 'Latest message in C (both latest and latest non-thread)', '2024-01-03 12:00:00', '2024-01-03 12:00:00', NULL),
+
+ -- Channel D messages: single message
+ ('dddddd1d-0000-0000-0000-000000000001', 'dddddddd-dddd-dddd-dddd-dddddddddddd', NULL, 'macro|[email protected]', 'Single message in D (DM)', '2024-01-04 11:00:00', '2024-01-04 11:00:00', NULL);
diff --git a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
index 96fdc202bc..05b3af29a3 100644
--- a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
+++ b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
@@ -13,6 +13,9 @@ use sqlx::PgPool;
use std::collections::HashMap;
use uuid::Uuid;
+mod dynamic;
+pub use dynamic::get_user_channels_dynamic;
+
#[derive(Debug, Clone, Copy, Doppleganger, sqlx::Type)]
#[sqlx(type_name = "comms_channel_type", rename_all = "snake_case")]
#[dg(forward = models_comms::channel::ChannelType)]
@@ -321,7 +324,7 @@ impl CommsRepo for PgCommsRepo {
&self,
req: GetChannelsParams,
) -> Result<Vec<ChannelWithParticipants>, rootcause::Report> {
- Ok(get_user_channels_with_participants(&self.pool, req.user().as_ref()).await?)
+ Ok(get_user_channels_dynamic(&self.pool, &req).await?)
}
async fn get_latest_channel_messages_batch(
diff --git a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/dynamic.rs b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/dynamic.rs
new file mode 100644
index 0000000000..e8ff07f33c
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/dynamic.rs
@@ -0,0 +1,200 @@
+//! This module exposes a dynamic query builder for channel queries
+//! which can filter channels based on an input AST
+
+use crate::domain::models::GetChannelsParams;
+use chrono::{DateTime, Utc};
+use filter_ast::Expr;
+use item_filters::ast::{LiteralTree, channel::ChannelLiteral};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use models_comms::channel::{
+ Channel, ChannelId, ChannelParticipant, ChannelWithParticipants, OrganizationId,
+};
+use recursion::CollapsibleExt;
+use sqlx::{FromRow, PgPool, Postgres, QueryBuilder, Row, postgres::PgRow};
+use uuid::Uuid;
+
+#[cfg(test)]
+mod tests;
+
+static PREFIX: &str = r#"
+ WITH user_channels AS (
+ SELECT DISTINCT c.*
+ FROM comms_channels c
+ INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id
+ WHERE cp.user_id = $1 AND cp.left_at IS NULL
+"#;
+
+static CHANNEL_SELECT: &str = r#"
+ ),
+ channel_participants_json AS (
+ SELECT
+ uc.id as channel_id,
+ ARRAY_AGG(
+ json_build_object(
+ 'channel_id', cp.channel_id,
+ 'user_id', cp.user_id,
+ 'role', cp.role,
+ 'joined_at', cp.joined_at,
+ 'left_at', cp.left_at
+ )
+ ) as participants
+ FROM user_channels uc
+ JOIN comms_channel_participants cp ON cp.channel_id = uc.id
+ WHERE cp.left_at IS NULL
+ GROUP BY uc.id
+ )
+ SELECT
+ uc.id as "id",
+ uc.name as "name",
+ uc.channel_type as "channel_type",
+ uc.org_id as "org_id",
+ uc.created_at as "created_at",
+ uc.updated_at as "updated_at",
+ uc.owner_id as "owner_id",
+ cpj.participants as "participants_json"
+ FROM user_channels uc
+ LEFT JOIN channel_participants_json cpj ON cpj.channel_id = uc.id
+ WHERE
+ ($4::timestamptz IS NULL)
+ OR
+ ((CASE $2 WHEN 'created_at' THEN uc.created_at ELSE uc.updated_at END), uc.id::text) < ($4, $5)
+ ORDER BY (CASE $2 WHEN 'created_at' THEN uc.created_at ELSE uc.updated_at END) DESC, uc.updated_at DESC
+ LIMIT $3
+"#;
+
+fn build_channel_filter(ast: Option<&Expr<ChannelLiteral>>) -> String {
+ let Some(expr) = ast else {
+ return String::new();
+ };
+ let formatting = expr.collapse_frames(|frame: filter_ast::ExprFrame<String, _>| match frame {
+ filter_ast::ExprFrame::And(a, b) => match (a.is_empty(), b.is_empty()) {
+ (true, true) => String::new(),
+ (true, false) => b,
+ (false, true) => a,
+ (false, false) => format!("({a} AND {b})"),
+ },
+ filter_ast::ExprFrame::Or(a, b) => match (a.is_empty(), b.is_empty()) {
+ (true, true) => String::new(),
+ (true, false) => b,
+ (false, true) => a,
+ (false, false) => format!("({a} OR {b})"),
+ },
+ filter_ast::ExprFrame::Not(a) => {
+ if a.is_empty() {
+ String::new()
+ } else {
+ format!("(NOT {a})")
+ }
+ }
+ filter_ast::ExprFrame::Literal(ChannelLiteral::ChannelId(id)) => {
+ format!("c.id = '{id}'")
+ }
+ filter_ast::ExprFrame::Literal(ChannelLiteral::OrganizationId(org_id)) => {
+ format!("c.org_id = {org_id}")
+ }
+ // These filters don't apply at the channel level, they're for messages
+ // So we return an empty string which will be filtered out
+ filter_ast::ExprFrame::Literal(ChannelLiteral::ThreadId(_)) => String::new(),
+ filter_ast::ExprFrame::Literal(ChannelLiteral::Mention(_)) => String::new(),
+ filter_ast::ExprFrame::Literal(ChannelLiteral::Sender(_)) => String::new(),
+ });
+ if formatting.is_empty() {
+ String::new()
+ } else {
+ format!(" AND {}", formatting)
+ }
+}
+
+fn build_query(filter_ast: &LiteralTree<ChannelLiteral>) -> QueryBuilder<'_, Postgres> {
+ let mut builder = sqlx::QueryBuilder::new(PREFIX);
+
+ // Add channel filter if present
+ builder.push(build_channel_filter(filter_ast.as_deref()));
+
+ builder.push(CHANNEL_SELECT);
+
+ builder
+}
+
+#[derive(Debug, FromRow)]
+struct ChannelRow {
+ id: Uuid,
+ name: Option<String>,
+ channel_type: super::ChannelType,
+ org_id: Option<i64>,
+ created_at: DateTime<Utc>,
+ updated_at: DateTime<Utc>,
+ owner_id: String,
+ participants_json: Option<Vec<serde_json::Value>>,
+}
+
+impl ChannelRow {
+ fn into_channel_with_participants(self) -> Result<ChannelWithParticipants, sqlx::Error> {
+ use doppleganger::Mirror;
+
+ let channel = Channel {
+ id: ChannelId(self.id),
+ name: self.name,
+ channel_type: super::ChannelType::mirror(self.channel_type),
+ org_id: self.org_id.map(|id| OrganizationId(id as u32)),
+ created_at: self.created_at,
+ updated_at: self.updated_at,
+ owner_id: MacroUserIdStr::parse_from_str(&self.owner_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ };
+
+ let participants = self
+ .participants_json
+ .map(|json_array| {
+ json_array
+ .iter()
+ .filter_map(|json_value| {
+ serde_json::from_value::<ChannelParticipant>(json_value.clone()).ok()
+ })
+ .collect::<Vec<ChannelParticipant>>()
+ })
+ .unwrap_or_default();
+
+ Ok(ChannelWithParticipants {
+ channel,
+ participants,
+ })
+ }
+}
+
+#[tracing::instrument(skip(db), err)]
+pub async fn get_user_channels_dynamic(
+ db: &PgPool,
+ params: &GetChannelsParams,
+) -> Result<Vec<ChannelWithParticipants>, sqlx::Error> {
+ let user_id = params.user();
+ let query_limit = params.limit() as i64;
+ let cursor = params.query();
+ let sort_method_str = cursor.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = cursor.vals();
+ let cursor_id_str = cursor_id.as_ref().map(|u| u.to_string());
+
+ build_query(cursor.filter())
+ .build()
+ .bind(user_id.as_ref())
+ .bind(sort_method_str)
+ .bind(query_limit)
+ .bind(cursor_timestamp)
+ .bind(cursor_id_str)
+ .try_map(|row: PgRow| {
+ let channel_row = ChannelRow {
+ id: row.try_get("id")?,
+ name: row.try_get("name")?,
+ channel_type: row.try_get("channel_type")?,
+ org_id: row.try_get("org_id")?,
+ created_at: row.try_get("created_at")?,
+ updated_at: row.try_get("updated_at")?,
+ owner_id: row.try_get("owner_id")?,
+ participants_json: row.try_get("participants_json")?,
+ };
+ channel_row.into_channel_with_participants()
+ })
+ .fetch_all(db)
+ .await
+}
diff --git a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/dynamic/tests.rs b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/dynamic/tests.rs
new file mode 100644
index 0000000000..662bf5375e
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/dynamic/tests.rs
@@ -0,0 +1,322 @@
+use crate::domain::models::GetChannelsRequest;
+use crate::outbound::postgres::comms_repo::{
+ get_latest_channel_message, get_latest_channel_messages_batch,
+};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use models_comms::channel::ChannelId;
+use models_pagination::{Query, SimpleSortMethod};
+use rootcause::Report;
+use sqlx::Pool;
+use uuid::Uuid;
+
+use super::get_user_channels_dynamic;
+
+fn uuid(s: &str) -> Uuid {
+ Uuid::parse_str(s).unwrap()
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("channels"))
+)]
+async fn test_get_user_channels_dynamic_no_filter(pool: Pool<sqlx::Postgres>) {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let params = GetChannelsRequest {
+ macro_id: user_id.into_owned(),
+ limit: Some(20),
+ query: Query::Sort(SimpleSortMethod::UpdatedAt, None),
+ }
+ .into_params();
+
+ let channels = get_user_channels_dynamic(&pool, &params).await.unwrap();
+
+ // user-1 is a participant in 4 channels (A, B, C, D)
+ assert_eq!(channels.len(), 4, "Should return 4 channels for user-1");
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("channels"))
+)]
+async fn test_get_user_channels_dynamic_filter_by_channel_id(pool: Pool<sqlx::Postgres>) {
+ use filter_ast::ExpandFrame;
+ use item_filters::ChannelFilters;
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let channel_id = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+
+ // Create filter for specific channel ID
+ let channel_filters = ChannelFilters {
+ channel_ids: vec![channel_id.to_string()],
+ ..Default::default()
+ };
+
+ let filter_ast = ChannelFilters::expand_ast(channel_filters)
+ .unwrap()
+ .map(std::sync::Arc::new);
+
+ let params = GetChannelsRequest {
+ macro_id: user_id.into_owned(),
+ limit: Some(20),
+ query: Query::Sort(SimpleSortMethod::UpdatedAt, filter_ast),
+ }
+ .into_params();
+
+ let channels = get_user_channels_dynamic(&pool, &params).await.unwrap();
+
+ // Should get exactly the filtered channel
+ assert_eq!(channels.len(), 1, "Should return exactly one channel");
+ assert_eq!(
+ channels[0].channel.id.0.to_string(),
+ channel_id,
+ "Should return the correct channel"
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("channels"))
+)]
+async fn test_get_user_channels_dynamic_filter_by_org_id(pool: Pool<sqlx::Postgres>) {
+ use filter_ast::ExpandFrame;
+ use item_filters::ChannelFilters;
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let org_id = 1i64;
+
+ // Create filter for specific organization
+ let channel_filters = ChannelFilters {
+ org_id: Some(org_id),
+ ..Default::default()
+ };
+
+ let filter_ast = ChannelFilters::expand_ast(channel_filters)
+ .unwrap()
+ .map(std::sync::Arc::new);
+
+ let params = GetChannelsRequest {
+ macro_id: user_id.into_owned(),
+ limit: Some(20),
+ query: Query::Sort(SimpleSortMethod::UpdatedAt, filter_ast),
+ }
+ .into_params();
+
+ let channels = get_user_channels_dynamic(&pool, &params).await.unwrap();
+
+ // Should get channels A and B (both have org_id = 1)
+ assert_eq!(channels.len(), 2, "Should return 2 channels with org_id=1");
+
+ // All returned channels should have the specified org_id
+ for channel in &channels {
+ assert_eq!(
+ channel.channel.org_id.as_ref().map(|o| o.0 as i64),
+ Some(org_id),
+ "All channels should belong to the specified org"
+ );
+ }
+}
+
+/// Tests that mixing supported (channel_id) and unsupported (thread_id) filters
+/// does not produce malformed SQL. Thread filters are message-level and should
+/// be ignored at the channel query level.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("channels"))
+)]
+async fn test_get_user_channels_dynamic_mixed_supported_and_unsupported_filters(
+ pool: Pool<sqlx::Postgres>,
+) {
+ use filter_ast::ExpandFrame;
+ use item_filters::ChannelFilters;
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let channel_id = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+ let thread_id = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
+
+ // Create filter with both channel_id (supported) and thread_id (unsupported at channel level)
+ // This combination previously produced malformed SQL like "( AND c.id = '...')"
+ let channel_filters = ChannelFilters {
+ channel_ids: vec![channel_id.to_string()],
+ thread_ids: vec![thread_id.to_string()],
+ ..Default::default()
+ };
+
+ let filter_ast = ChannelFilters::expand_ast(channel_filters)
+ .unwrap()
+ .map(std::sync::Arc::new);
+
+ let params = GetChannelsRequest {
+ macro_id: user_id.into_owned(),
+ limit: Some(20),
+ query: Query::Sort(SimpleSortMethod::UpdatedAt, filter_ast),
+ }
+ .into_params();
+
+ // This should not fail with a SQL syntax error
+ let channels = get_user_channels_dynamic(&pool, &params).await.unwrap();
+
+ // Should still filter by the supported channel_id filter
+ assert_eq!(channels.len(), 1, "Should return exactly one channel");
+ assert_eq!(
+ channels[0].channel.id.0.to_string(),
+ channel_id,
+ "Should return the correct channel"
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("channels"))
+)]
+async fn test_get_latest_channel_messages_batch(pool: Pool<sqlx::Postgres>) -> Result<(), Report> {
+ let ids = vec![
+ ChannelId(uuid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")),
+ ChannelId(uuid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")),
+ ChannelId(uuid("cccccccc-cccc-cccc-cccc-cccccccccccc")),
+ ChannelId(uuid("dddddddd-dddd-dddd-dddd-dddddddddddd")),
+ ];
+
+ let res = get_latest_channel_messages_batch(&pool, &ids).await?;
+
+ // aaaaaaaa
+ let a = res.get(&ids[0]).expect("channel a should exist");
+ assert_eq!(
+ a.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("aaaaaa2a-0000-0000-0000-000000000002")
+ );
+
+ // bbbbbbbb
+ let b = res.get(&ids[1]).expect("channel b should exist");
+ assert_eq!(
+ b.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("bbbbbb2b-0000-0000-0000-000000000003")
+ );
+ assert!(b.latest_non_thread_message.is_none());
+
+ // cccccccc
+ let c = res.get(&ids[2]).expect("channel c should exist");
+ assert_eq!(
+ c.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("cccccc2c-0000-0000-0000-000000000002")
+ );
+ assert_eq!(
+ c.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("cccccc2c-0000-0000-0000-000000000002")
+ );
+
+ // dddddddd
+ let d = res.get(&ids[3]).expect("channel d should exist");
+ assert_eq!(
+ d.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("dddddd1d-0000-0000-0000-000000000001")
+ );
+ assert_eq!(
+ d.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("dddddd1d-0000-0000-0000-000000000001")
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("channels"))
+)]
+async fn test_get_latest_channel_message(pool: Pool<sqlx::Postgres>) -> Result<(), Report> {
+ let a = get_latest_channel_message(
+ &pool,
+ ChannelId(uuid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")),
+ )
+ .await?;
+
+ assert_eq!(
+ a.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("aaaaaa2a-0000-0000-0000-000000000004")
+ );
+ assert_eq!(
+ a.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("aaaaaa2a-0000-0000-0000-000000000002")
+ );
+
+ let b = get_latest_channel_message(
+ &pool,
+ ChannelId(uuid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")),
+ )
+ .await?;
+ assert_eq!(
+ b.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("bbbbbb2b-0000-0000-0000-000000000003")
+ );
+ assert!(b.latest_non_thread_message.is_none());
+
+ let c = get_latest_channel_message(
+ &pool,
+ ChannelId(uuid("cccccccc-cccc-cccc-cccc-cccccccccccc")),
+ )
+ .await?;
+ assert_eq!(
+ c.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("cccccc2c-0000-0000-0000-000000000002")
+ );
+ assert_eq!(
+ c.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("cccccc2c-0000-0000-0000-000000000002")
+ );
+
+ let d = get_latest_channel_message(
+ &pool,
+ ChannelId(uuid("dddddddd-dddd-dddd-dddd-dddddddddddd")),
+ )
+ .await?;
+ assert_eq!(
+ d.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("dddddd1d-0000-0000-0000-000000000001")
+ );
+ assert_eq!(
+ d.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("dddddd1d-0000-0000-0000-000000000001")
+ );
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/tests.rs b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/tests.rs
deleted file mode 100644
index bf838a4be9..0000000000
--- a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/tests.rs
+++ /dev/null
@@ -1,155 +0,0 @@
-#[cfg(test)]
-mod tests {
- use super::*;
- use macro_db_migrator::MACRO_DB_MIGRATIONS;
-
- fn uuid(s: &str) -> Uuid {
- Uuid::parse_str(s).unwrap()
- }
-
- #[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("latest_messages"))
- )]
- async fn test_get_latest_channel_messages_batch(
- pool: sqlx::Pool<sqlx::Postgres>,
- ) -> Result<()> {
- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE
- let ids = vec![
- uuid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
- uuid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
- uuid("cccccccc-cccc-cccc-cccc-cccccccccccc"),
- uuid("dddddddd-dddd-dddd-dddd-dddddddddddd"),
- ];
-
- let res = get_latest_channel_messages_batch(&pool, &ids).await?;
-
- // aaaaaaaa
- let a = res.get(&ids[0]).expect("channel a should exist");
- assert_eq!(
- a.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("aaaaaa2a-0000-0000-0000-000000000002")
- );
-
- // bbbbbbbb
- let b = res.get(&ids[1]).expect("channel b should exist");
- assert_eq!(
- b.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("bbbbbb2b-0000-0000-0000-000000000003")
- );
- assert!(b.latest_non_thread_message.is_none());
-
- // cccccccc
- let c = res.get(&ids[2]).expect("channel c should exist");
- assert_eq!(
- c.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("cccccc2c-0000-0000-0000-000000000002")
- );
- assert_eq!(
- c.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("cccccc2c-0000-0000-0000-000000000002")
- );
-
- // dddddddd
- let d = res.get(&ids[3]).expect("channel d should exist");
- assert_eq!(
- d.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("dddddd1d-0000-0000-0000-000000000001")
- );
- assert_eq!(
- d.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("dddddd1d-0000-0000-0000-000000000001")
- );
-
- Ok(())
- }
-
- #[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("latest_messages"))
- )]
- async fn test_get_latest_channel_message(pool: sqlx::Pool<sqlx::Postgres>) -> Result<()> {
- let a =
- get_latest_channel_message(&pool, uuid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")).await?;
-
- assert_eq!(
- a.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("aaaaaa2a-0000-0000-0000-000000000004")
- );
- assert_eq!(
- a.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("aaaaaa2a-0000-0000-0000-000000000002")
- );
-
- let b =
- get_latest_channel_message(&pool, uuid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")).await?;
- assert_eq!(
- b.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("bbbbbb2b-0000-0000-0000-000000000003")
- );
- assert!(b.latest_non_thread_message.is_none());
-
- let c =
- get_latest_channel_message(&pool, uuid("cccccccc-cccc-cccc-cccc-cccccccccccc")).await?;
- assert_eq!(
- c.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("cccccc2c-0000-0000-0000-000000000002")
- );
- assert_eq!(
- c.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("cccccc2c-0000-0000-0000-000000000002")
- );
-
- let d =
- get_latest_channel_message(&pool, uuid("dddddddd-dddd-dddd-dddd-dddddddddddd")).await?;
- assert_eq!(
- d.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("dddddd1d-0000-0000-0000-000000000001")
- );
- assert_eq!(
- d.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("dddddd1d-0000-0000-0000-000000000001")
- );
-
- Ok(())
- }
-}
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
index 321767513e..523c7fb1b9 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
@@ -89,22 +89,39 @@ fn build_chat_filter(ast: Option<&Expr<ChatLiteral>>) -> String {
let Some(expr) = ast else {
return String::new();
};
- let formatting = expr.collapse_frames(|frame| match frame {
- filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
- filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
- filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
- filter_ast::ExprFrame::Literal(ChatLiteral::ProjectId(p)) => {
- format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "projectId" = '{p}' AND "deletedAt" IS NULL)"#)
- }
- filter_ast::ExprFrame::Literal(ChatLiteral::Role(_r)) => {
- // Chat role filtering doesn't apply to frecency aggregates
- String::new()
- }
- filter_ast::ExprFrame::Literal(ChatLiteral::ChatId(i)) => format!("entity_id = '{i}'"),
- filter_ast::ExprFrame::Literal(ChatLiteral::Owner(o)) => {
- format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "userId" = '{o}' AND "deletedAt" IS NULL)"#)
- }
- });
+ let formatting =
+ expr.collapse_frames(|frame: filter_ast::ExprFrame<String, _>| match frame {
+ filter_ast::ExprFrame::And(a, b) => match (a.is_empty(), b.is_empty()) {
+ (true, true) => String::new(),
+ (true, false) => b,
+ (false, true) => a,
+ (false, false) => format!("({a} AND {b})"),
+ },
+ filter_ast::ExprFrame::Or(a, b) => match (a.is_empty(), b.is_empty()) {
+ (true, true) => String::new(),
+ (true, false) => b,
+ (false, true) => a,
+ (false, false) => format!("({a} OR {b})"),
+ },
+ filter_ast::ExprFrame::Not(a) => {
+ if a.is_empty() {
+ String::new()
+ } else {
+ format!("(NOT {a})")
+ }
+ }
+ filter_ast::ExprFrame::Literal(ChatLiteral::ProjectId(p)) => {
+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "projectId" = '{p}' AND "deletedAt" IS NULL)"#)
+ }
+ filter_ast::ExprFrame::Literal(ChatLiteral::Role(_r)) => {
+ // Chat role filtering doesn't apply to frecency aggregates
+ String::new()
+ }
+ filter_ast::ExprFrame::Literal(ChatLiteral::ChatId(i)) => format!("entity_id = '{i}'"),
+ filter_ast::ExprFrame::Literal(ChatLiteral::Owner(o)) => {
+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "userId" = '{o}' AND "deletedAt" IS NULL)"#)
+ }
+ });
if formatting.is_empty() {
String::new()
} else {
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs
index 974ae834cc..9663770882 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs
@@ -2,6 +2,7 @@ use crate::domain::models::{AggregateId, FrecencyData};
use super::*;
use chrono::Utc;
+use item_filters::ChatFilters;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model_entity::{EntityType, TrackAction};
@@ -918,3 +919,63 @@ async fn it_cannot_be_read_concurrently(pool: PgPool) {
assert_eq!(res.len(), 1);
assert_eq!(res.first().unwrap().id, event_id);
}
+
+/// Tests that mixing supported (chat_id) and unsupported (role) filters
+/// does not produce malformed SQL. Role filters don't apply to frecency
+/// aggregates and should be ignored without breaking the query.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_get_top_entities_mixed_supported_and_unsupported_chat_filters(pool: PgPool) {
+ use item_filters::{EntityFilters, ast::EntityFilterAst};
+
+ let storage = FrecencyPgStorage::new(pool.clone());
+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Create a chat aggregate
+ let chat_id = "11111111-1111-1111-1111-111111111111";
+ let aggregate = AggregateFrecency {
+ id: AggregateId {
+ entity: EntityType::Chat.with_entity_string(chat_id.to_string()),
+ user_id: test_user_id.clone(),
+ },
+ data: FrecencyData {
+ event_count: 5,
+ frecency_score: 75.0,
+ first_event: Utc::now(),
+ recent_events: VecDeque::new(),
+ },
+ };
+ storage.set_aggregate(aggregate).await.unwrap();
+
+ // Create filter with both chat_id (supported) and role (unsupported at frecency level)
+ // This combination previously produced malformed SQL like "( AND entity_id = '...')"
+ let entity_filters = EntityFilters {
+ chat_filters: ChatFilters {
+ chat_ids: vec![chat_id.to_string()],
+ role: vec!["user".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filter = EntityFilterAst::new_from_filters(entity_filters)
+ .unwrap()
+ .unwrap();
+
+ // This should not fail with a SQL syntax error
+ let results = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 10,
+ filters: Some(filter),
+ })
+ .await
+ .unwrap();
+
+ // Should still filter by the supported chat_id filter
+ assert_eq!(results.len(), 1, "Should return exactly one chat");
+ assert_eq!(
+ results[0].id.entity.entity_id, chat_id,
+ "Should return the correct chat"
+ );
+}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index db87da5aad..0efea13767 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -50,6 +50,7 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./macro_db_client/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./email_db_client/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./comms_db_client/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./comms/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./document_cognition_service/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./document_text_extractor/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./organization_retention_handler/.env
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index 0f0785bd1b..9b928b8cc4 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -330,16 +330,13 @@ where
let comms_soup_fut = self.handle_comms_request(comms_request);
- let (main_soup, email_soup, _comms_soup) =
+ let (main_soup, email_soup, comms_soup) =
tokio::join!(main_soup_fut, email_soup_fut, comms_soup_fut);
Ok(Either::Left(
main_soup?
.chain(email_soup?)
- // .chain(match comms_soup {
- // Ok(iter) => Either::Left(iter),
- // Err(_) => Either::Right(None.into_iter()),
- // })
+ .chain(comms_soup?)
.paginate_on(limit.into(), sort_method)
.filter_on(paginate_filter)
.sort_desc()
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index ef51db659e..50a135b152 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -8,11 +8,12 @@ use email::domain::{
ports::EmailService,
};
use http_body_util::BodyExt;
+use item_filters::ast::EntityFilterAst;
use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use model_user::UserContext;
use models_pagination::{
- Cursor, CursorVal, Frecency, FrecencyValue, Identify, Paginate, PaginateOn, Query,
- SimpleSortMethod, SortOn, Sortable, TypeEraseCursor,
+ Cursor, CursorVal, Frecency, FrecencyValue, Identify, PaginateOn, Query, SimpleSortMethod,
+ SortOn, TypeEraseCursor,
};
use serde::Serialize;
use serde_json::json;
@@ -25,7 +26,7 @@ use crate::{
models::{SoupErr, SoupQuery, SoupRequest, SoupType},
ports::{SoupOutput, SoupService},
},
- inbound::axum_router::{SoupCursor, SoupRouterState, soup_router},
+ inbound::axum_router::{SoupRouterState, soup_router},
};
static CURSOR: &str = "eyJpZCI6ImUzNmM5MTJlLTU2M2MtNDIxZS1iMTAzLWE0YjAwY2ZmMzBlZSIsImxpbWl0IjoxMDAsInZhbCI6eyJzb3J0X3R5cGUiOiJ1cGRhdGVkX2F0IiwibGFzdF92YWwiOiIyMDI1LTExLTA3VDE5OjEyOjU5Ljc4MFoifX0=";
@@ -404,7 +405,7 @@ async fn cursor_with_assoc_works() {
}
impl SortOn<Frecency> for Data {
- fn sort_on(sort: Frecency) -> impl FnMut(&Self) -> models_pagination::CursorVal<Frecency> {
+ fn sort_on(_sort: Frecency) -> impl FnMut(&Self) -> models_pagination::CursorVal<Frecency> {
|v| CursorVal {
sort_type: Frecency,
last_val: FrecencyValue::FrecencyScore(v.0 as f64),
@@ -508,7 +509,7 @@ async fn cursor_with_all_works() {
}
impl SortOn<Frecency> for Data {
- fn sort_on(sort: Frecency) -> impl FnMut(&Self) -> models_pagination::CursorVal<Frecency> {
+ fn sort_on(_sort: Frecency) -> impl FnMut(&Self) -> models_pagination::CursorVal<Frecency> {
|v| CursorVal {
sort_type: Frecency,
last_val: FrecencyValue::FrecencyScore(v.0 as f64),
@@ -561,3 +562,62 @@ async fn cursor_with_all_works() {
}
)
}
+
+#[tokio::test]
+async fn it_parses_channel_filters() {
+ let soup = MockSoup::new();
+ let inner_counter = soup.called.clone();
+ let router: Router = soup_router(SoupRouterState::new(
+ soup.clone(),
+ MockEmailLinkResult {
+ get_link_result: Arc::new(|| Ok(None)),
+ },
+ ))
+ .layer(Extension(UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "1234".to_string(),
+ permissions: None,
+ organization_id: None,
+ }));
+
+ let uuid1 = Uuid::new_v4();
+ let uuid2 = Uuid::new_v4();
+ let request = Request::builder()
+ .uri("/soup")
+ .method(Method::POST)
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "channel_filters": {
+ "channel_ids": [uuid1, uuid2]
+ }
+ }))
+ .unwrap(),
+ ))
+ .unwrap();
+
+ let _res = router.oneshot(request).await.unwrap();
+
+ let arg = {
+ let mut guard = inner_counter.lock().unwrap();
+ guard.pop().unwrap()
+ };
+
+ assert_matches!(
+ arg,
+ SoupRequest {
+ cursor: SoupQuery::Simple(Query::Sort(
+ _,
+ Some(EntityFilterAst {
+ document_filter: None,
+ project_filter: None,
+ chat_filter: None,
+ email_filter: None,
+ channel_filter: Some(_),
+ ..
+ }),
+ )),
+ ..
+ }
+ )
+}