Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore(comms): merge comms into channels (#4128)
Sean Ayed480398ad327
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 692f3f0b37..91e3a6102e 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -28,7 +28,6 @@"call","channels","chat",- "comms","connection","connection_gateway_client","connection_gateway_models",@@ -72,7 +71,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -155,12 +153,14 @@"attachment","authentication_service","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","comms_db_client","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -210,7 +210,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -228,7 +227,6 @@"opensearch_client","opensearch_query_builder","rate_limit",- "readonly_pool","referral","remote_env_var","roles_and_permissions",@@ -236,7 +234,9 @@"secretsmanager_client","serde_utils","ses_client",+ "share_permission_db_utils","sqs_client",+ "sqs_worker","sync_service","sync_service_client","system_properties",@@ -254,9 +254,6 @@"authentication_service_client","cowlike","document_sub_type",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_user_id","macro_uuid",@@ -266,7 +263,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -326,7 +322,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -359,42 +354,64 @@"ai_toolset","ai_usage","attachment",+ "authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike",+ "crm","decode_jwt","document_sub_type",+ "email",+ "email_utils","entity_access","entity_access_db_utils","filter_ast","frecency",+ "invite_email",+ "ip_extractor","item_filters","last_online_tracker","macro_auth","macro_aws_config",+ "macro_db_client","macro_env","macro_env_var",+ "macro_middleware","macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms",+ "models_dcs",+ "models_email","models_entity_access_management",+ "models_opensearch","models_pagination","models_permissions",+ "models_properties",+ "models_team","non_empty","notification","rate_limit",- "readonly_pool","remote_env_var",+ "s3_key",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker",+ "system_properties",+ "unfurl",+ "user_quota","workspace-hack"],"call_recording_preview_handler": [@@ -418,7 +435,6 @@"channel_bots","channels","chat",- "comms","connection","connection_gateway_client","connection_gateway_models",@@ -462,7 +478,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -543,7 +558,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -576,9 +590,6 @@"entity_access","entity_access_db_utils","entity_access_management",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_user_id","macro_uuid",@@ -588,7 +599,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_entity_access_management","models_pagination","models_permissions",@@ -596,34 +606,6 @@"roles_and_permissions","workspace-hack"],- "comms": [- "agent",- "ai_toolset",- "ai_usage",- "attachment",- "comms",- "cowlike",- "document_sub_type",- "entity_access",- "filter_ast",- "frecency",- "item_filters",- "macro_env_var",- "macro_user_id",- "macro_uuid",- "model",- "model-entity",- "model-error-response",- "model_file_type",- "model_user",- "models_bulk_upload",- "models_comms",- "models_pagination",- "models_permissions",- "non_empty",- "readonly_pool",- "workspace-hack"- ],"comms_db_client": ["agent","ai_toolset",@@ -632,9 +614,6 @@"comms_db_client","cowlike","document_sub_type",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_user_id","macro_uuid",@@ -644,7 +623,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -661,9 +639,6 @@"cowlike","document_sub_type","entity_access",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_user_id","macro_uuid",@@ -673,7 +648,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -712,7 +686,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",@@ -751,10 +724,7 @@"decode_jwt","document_sub_type","entity_access_db_utils",- "filter_ast",- "frecency","ip_extractor",- "item_filters","macro_auth","macro_db_client","macro_env",@@ -768,7 +738,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",@@ -795,10 +764,7 @@"decode_jwt","document_sub_type","entity_access_db_utils",- "filter_ast",- "frecency","ip_extractor",- "item_filters","macro_auth","macro_aws_config","macro_config",@@ -819,7 +785,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",@@ -875,7 +840,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -909,9 +873,6 @@"crm","document_sub_type","entity_access",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_user_id","macro_uuid",@@ -921,7 +882,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -993,7 +953,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -1022,7 +981,6 @@"call","channels","chat",- "comms","connection","connection_gateway","connection_gateway_client",@@ -1073,7 +1031,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -1132,7 +1089,6 @@"channel_bots","channels","chat",- "comms","comms_db_client","connection","connection_gateway_client",@@ -1187,7 +1143,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -1239,9 +1194,6 @@"cowlike","document_storage_service_client","document_sub_type",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_user_id","macro_uuid",@@ -1251,7 +1203,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -1269,9 +1220,6 @@"cowlike","document_sub_type","document_text_extractor",- "filter_ast",- "frecency",- "item_filters","macro_aws_config","macro_entrypoint","macro_env",@@ -1284,7 +1232,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -1297,11 +1244,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -1317,6 +1266,7 @@"filter_ast","foreign_entity","frecency",+ "invite_email","ip_extractor","item_filters","last_online_tracker",@@ -1331,14 +1281,16 @@"macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs",+ "models_email","models_entity_access_management","models_opensearch","models_pagination",@@ -1353,10 +1305,12 @@"opensearch_client","opensearch_query_builder","rate_limit",- "readonly_pool","remote_env_var","s3_key","secretsmanager_client",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker","sync_service","sync_service_client","system_properties",@@ -1371,11 +1325,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -1390,6 +1346,7 @@"filter_ast","foreign_entity","frecency",+ "invite_email","ip_extractor","item_filters","last_online_tracker",@@ -1404,14 +1361,16 @@"macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs",+ "models_email","models_entity_access_management","models_opensearch","models_pagination",@@ -1426,10 +1385,12 @@"opensearch_client","opensearch_query_builder","rate_limit",- "readonly_pool","remote_env_var","s3_key","secretsmanager_client",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker","sync_service","sync_service_client","system_properties",@@ -1470,7 +1431,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -1520,7 +1480,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -1542,12 +1501,8 @@"ai_toolset","cowlike","decode_jwt",- "document_sub_type","email_formatting",- "filter_ast",- "frecency","invite_email",- "item_filters","last_online_tracker","macro_auth","macro_env",@@ -1558,12 +1513,9 @@"mention_utils","model-entity","model-error-response",- "model_file_type","model_notifications","model_user",- "models_comms","models_pagination",- "non_empty","notification","rate_limit","remote_env_var",@@ -1597,7 +1549,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -1635,7 +1586,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -1691,7 +1641,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -1741,7 +1690,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -1777,7 +1725,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -1796,9 +1743,6 @@"document_sub_type","email_suppression_handler","entity_access_db_utils",- "filter_ast",- "frecency",- "item_filters","macro_db_client","macro_entrypoint","macro_env",@@ -1811,7 +1755,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",@@ -1848,9 +1791,6 @@"cowlike","document_sub_type","entity_access",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_user_id","macro_uuid",@@ -1860,7 +1800,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -1903,7 +1842,6 @@"entity_access","filter_ast","foreign_entity",- "frecency","item_filters","macro_env_var","macro_user_id",@@ -1914,7 +1852,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -1944,11 +1881,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -1988,8 +1927,8 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs",+ "models_email","models_entity_access_management","models_opensearch","models_pagination",@@ -2004,10 +1943,12 @@"opensearch_client","opensearch_query_builder","rate_limit",- "readonly_pool","remote_env_var","s3_key","secretsmanager_client",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker","sync_service","sync_service_client","system_properties",@@ -2043,11 +1984,8 @@"decode_jwt","document_sub_type","entity_access_db_utils",- "filter_ast",- "frecency","image_proxy_service","ip_extractor",- "item_filters","macro_auth","macro_aws_config","macro_cors",@@ -2064,7 +2002,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",@@ -2130,11 +2067,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -2145,23 +2084,30 @@"entity_access_db_utils","filter_ast","frecency",+ "invite_email",+ "ip_extractor","item_filters","last_online_tracker","lexical_client","macro_auth","macro_aws_config",+ "macro_db_client","macro_env","macro_env_var",+ "macro_middleware","macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms",+ "models_dcs",+ "models_email","models_entity_access_management","models_opensearch","models_pagination",@@ -2170,14 +2116,20 @@"models_search","models_search_cursor","models_soup",+ "models_team","non_empty","notification","opensearch_client","opensearch_query_builder","rate_limit",- "readonly_pool","remote_env_var",+ "s3_key",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker",+ "system_properties","unfurl",+ "user_quota","workspace-hack"],"load-test": [@@ -2247,9 +2199,6 @@"cowlike","document_sub_type","entity_access_db_utils",- "filter_ast",- "frecency",- "item_filters","macro_db_client","macro_env_var","macro_user_id",@@ -2260,7 +2209,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",@@ -2301,10 +2249,7 @@"decode_jwt","document_sub_type","entity_access_db_utils",- "filter_ast",- "frecency","ip_extractor",- "item_filters","macro_auth","macro_db_client","macro_env",@@ -2318,7 +2263,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",@@ -2353,9 +2297,6 @@"attachment","cowlike","document_sub_type",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_sha_count_client","macro_user_id",@@ -2366,7 +2307,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -2425,7 +2365,6 @@"call","channels","chat",- "comms","connection","connection_gateway_client","connection_gateway_models",@@ -2472,7 +2411,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -2524,7 +2462,6 @@"call","channels","chat",- "comms","connection","connection_gateway_client","connection_gateway_models",@@ -2569,7 +2506,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -2626,9 +2562,6 @@"attachment","cowlike","document_sub_type",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_user_id","macro_uuid",@@ -2638,7 +2571,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -2661,11 +2593,7 @@"ai_toolset","cowlike","decode_jwt",- "document_sub_type",- "filter_ast",- "frecency","invite_email",- "item_filters","last_online_tracker","macro_auth","macro_env",@@ -2676,12 +2604,9 @@"mention_utils","model-entity","model-error-response",- "model_file_type","model_notifications","model_user",- "models_comms","models_pagination",- "non_empty","notification","rate_limit","remote_env_var",@@ -2697,19 +2622,6 @@"models_bulk_upload","workspace-hack"],- "models_comms": [- "cowlike",- "document_sub_type",- "filter_ast",- "frecency",- "item_filters",- "macro_user_id",- "model-entity",- "model_file_type",- "models_comms",- "non_empty",- "workspace-hack"- ],"models_dcs": ["models_dcs","workspace-hack"@@ -2755,11 +2667,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -2770,22 +2684,29 @@"entity_access_db_utils","filter_ast","frecency",+ "invite_email",+ "ip_extractor","item_filters","last_online_tracker","macro_auth","macro_aws_config",+ "macro_db_client","macro_env","macro_env_var",+ "macro_middleware","macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms",+ "models_dcs",+ "models_email","models_entity_access_management","models_opensearch","models_pagination",@@ -2794,14 +2715,20 @@"models_search","models_search_cursor","models_soup",+ "models_team","non_empty","notification","opensearch_client","opensearch_query_builder","rate_limit",- "readonly_pool","remote_env_var",+ "s3_key",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker",+ "system_properties","unfurl",+ "user_quota","workspace-hack"],"models_search_cursor": [@@ -2818,11 +2745,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -2833,33 +2762,47 @@"entity_access_db_utils","filter_ast","frecency",+ "invite_email",+ "ip_extractor","item_filters","last_online_tracker","macro_auth","macro_aws_config",+ "macro_db_client","macro_env","macro_env_var",+ "macro_middleware","macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms",+ "models_dcs",+ "models_email","models_entity_access_management",+ "models_opensearch","models_pagination","models_permissions","models_properties","models_soup",+ "models_team","non_empty","notification","rate_limit",- "readonly_pool","remote_env_var",+ "s3_key",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker",+ "system_properties","unfurl",+ "user_quota","workspace-hack"],"models_team": [@@ -2913,11 +2856,7 @@"ai_toolset","cowlike","decode_jwt",- "document_sub_type",- "filter_ast",- "frecency","invite_email",- "item_filters","last_online_tracker","macro_auth","macro_env",@@ -2928,12 +2867,9 @@"mention_utils","model-entity","model-error-response",- "model_file_type","model_notifications","model_user",- "models_comms","models_pagination",- "non_empty","notification","notification_db_client","rate_limit",@@ -2944,12 +2880,8 @@"ai_toolset","cowlike","decode_jwt",- "document_sub_type","email_formatting",- "filter_ast",- "frecency","invite_email",- "item_filters","last_online_tracker","macro_auth","macro_aws_config",@@ -2961,12 +2893,9 @@"mention_utils","model-entity","model-error-response",- "model_file_type","model_notifications","model_user",- "models_comms","models_pagination",- "non_empty","notification","notification_sandbox","rate_limit",@@ -2983,11 +2912,8 @@"document_sub_type","email_formatting","entity_access_db_utils",- "filter_ast",- "frecency","invite_email","ip_extractor",- "item_filters","last_online_tracker","macro_auth","macro_aws_config",@@ -3012,7 +2938,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",@@ -3070,7 +2995,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -3108,7 +3032,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -3135,10 +3058,7 @@"email_utils","entity_access","entity_access_db_utils",- "filter_ast",- "frecency","invite_email",- "item_filters","last_online_tracker","macro_auth","macro_db_client",@@ -3155,7 +3075,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -3191,11 +3110,8 @@"email_utils","entity_access","entity_access_db_utils",- "filter_ast",- "frecency","invite_email","ip_extractor",- "item_filters","last_online_tracker","macro_auth","macro_db_client",@@ -3213,7 +3129,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -3302,7 +3217,6 @@"call","channels","chat",- "comms","connection","connection_gateway_client","connection_gateway_models",@@ -3348,7 +3262,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -3395,12 +3308,14 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","comms_db_client","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -3413,6 +3328,7 @@"entity_access_db_utils","filter_ast","frecency",+ "invite_email","ip_extractor","item_filters","last_online_tracker",@@ -3433,9 +3349,9 @@"model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -3452,12 +3368,12 @@"opensearch_client","opensearch_query_builder","rate_limit",- "readonly_pool","remote_env_var","s3_client","s3_key","search_processing_service","secretsmanager_client",+ "share_permission_db_utils","sqs_client","sqs_worker","system_properties",@@ -3471,12 +3387,14 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","comms_db_client","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -3488,6 +3406,7 @@"entity_access_db_utils","filter_ast","frecency",+ "invite_email","ip_extractor","item_filters","last_online_tracker",@@ -3500,13 +3419,14 @@"macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -3527,8 +3447,12 @@"rate_limit","readonly_pool","remote_env_var",+ "s3_key","search_service","secretsmanager_client",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker","system_properties","unfurl","user_quota",@@ -3540,11 +3464,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -3555,22 +3481,29 @@"entity_access_db_utils","filter_ast","frecency",+ "invite_email",+ "ip_extractor","item_filters","last_online_tracker","macro_auth","macro_aws_config",+ "macro_db_client","macro_env","macro_env_var",+ "macro_middleware","macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms",+ "models_dcs",+ "models_email","models_entity_access_management","models_opensearch","models_pagination",@@ -3579,15 +3512,21 @@"models_search","models_search_cursor","models_soup",+ "models_team","non_empty","notification","opensearch_client","opensearch_query_builder","rate_limit",- "readonly_pool","remote_env_var",+ "s3_key","search_service_client",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker",+ "system_properties","unfurl",+ "user_quota","workspace-hack"],"search_upload_handler": [@@ -3619,7 +3558,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -3648,10 +3586,7 @@"email_db_client","email_utils","entity_access_db_utils",- "filter_ast",- "frecency","fusionauth",- "item_filters","macro_aws_config","macro_db_client","macro_entrypoint",@@ -3665,7 +3600,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_email","models_entity_access_management",@@ -3718,11 +3652,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -3734,37 +3670,51 @@"filter_ast","foreign_entity","frecency",+ "invite_email",+ "ip_extractor","item_filters","last_online_tracker","macro_auth","macro_aws_config",+ "macro_db_client","macro_env","macro_env_var",+ "macro_middleware","macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms",+ "models_dcs",+ "models_email","models_entity_access_management","models_grouping",+ "models_opensearch","models_pagination","models_permissions","models_properties","models_soup",+ "models_team","non_empty","notification","properties_db_client","rate_limit","readonly_pool","remote_env_var",+ "s3_key",+ "share_permission_db_utils","soup",+ "sqs_client",+ "sqs_worker","system_properties","unfurl",+ "user_quota","workspace-hack"],"sqs_client": [@@ -3791,7 +3741,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -3824,10 +3773,7 @@"decode_jwt","document_sub_type","entity_access_db_utils",- "filter_ast",- "frecency","ip_extractor",- "item_filters","macro_auth","macro_aws_config","macro_cors",@@ -3845,7 +3791,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",@@ -3885,9 +3830,6 @@"attachment","cowlike","document_sub_type",- "filter_ast",- "frecency",- "item_filters","macro_env_var","macro_user_id","macro_uuid",@@ -3897,7 +3839,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","non_empty",@@ -3919,11 +3860,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id","call",- "comms",+ "channels","connection","connection_gateway_client","connection_gateway_models",+ "contacts","cowlike","crm","decode_jwt",@@ -3935,6 +3878,7 @@"entity_access_db_utils","filter_ast","frecency",+ "invite_email","ip_extractor","item_filters","last_online_tracker",@@ -3949,14 +3893,16 @@"macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",- "models_comms","models_dcs",+ "models_email","models_entity_access_management","models_opensearch","models_pagination",@@ -3971,9 +3917,12 @@"opensearch_client","opensearch_query_builder","rate_limit",- "readonly_pool","remote_env_var",+ "s3_key","secretsmanager_client",+ "share_permission_db_utils",+ "sqs_client",+ "sqs_worker","system_properties","task_dedup","unfurl",@@ -4012,7 +3961,6 @@"model_notifications","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -4072,7 +4020,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -4111,7 +4058,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_email","models_pagination","models_permissions",@@ -4130,9 +4076,6 @@"cowlike","document_sub_type","entity_access_db_utils",- "filter_ast",- "frecency",- "item_filters","macro_db_client","macro_entrypoint","macro_env",@@ -4145,7 +4088,6 @@"model_file_type","model_user","models_bulk_upload",- "models_comms","models_dcs","models_entity_access_management","models_opensearch",diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channel.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channel.tsindex 9b0415f6c7..131e294866 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/channel.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channel.ts@@ -11,13 +11,23 @@ import type { ChannelTeamId } from './channelTeamId';import type { ChannelType } from './channelType';export interface Channel {+ /** type of the channel */channel_type: ChannelType;+ /** timestamp of when the channel was created */created_at: string;+ /** uuid of the channel */id: string;+ /** string name of the channel */name?: ChannelName;- /** @minimum 0 */+ /**+ * id of the organization this channel belongs too+ * @minimum 0+ */org_id?: ChannelOrgId;+ /** id of the user who created the channel */owner_id: string;+ /** id of the team this channel belongs to */team_id?: ChannelTeamId;+ /** timestamp of when the channel was last updated */updated_at: string;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelName.tsindex 1ee4e57f6c..1041b280c1 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelName.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelName.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * string name of the channel+ */export type ChannelName = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelOrgId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelOrgId.tsindex 531a1611e9..a199b927db 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelOrgId.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelOrgId.ts@@ -6,6 +6,7 @@*//**+ * id of the organization this channel belongs too* @minimum 0*/export type ChannelOrgId = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelTeamId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelTeamId.tsindex fa7015f927..557898877d 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelTeamId.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelTeamId.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * id of the team this channel belongs to+ */export type ChannelTeamId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 1a5a7355b9..26ddbe352a 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -7356,16 +7356,29 @@ export const getItemsSoupResponse = zod.object({channel_type: zod.enum(['public', 'private', 'direct_message', 'team']).describe('Type of channel.'),- created_at: zod.iso.datetime({}),- id: zod.uuid(),- name: zod.string().nullish(),+ created_at: zod.iso+ .datetime({})+ .describe('timestamp of when the channel was created'),+ id: zod.uuid().describe('uuid of the channel'),+ name: zod+ .string()+ .nullish()+ .describe('string name of the channel'),org_id: zod.number().min(getItemsSoupResponseItemsItemDataChannelOrgIdMin)- .nullish(),- owner_id: zod.string(),- team_id: zod.uuid().nullish(),- updated_at: zod.iso.datetime({}),+ .nullish()+ .describe('id of the organization this channel belongs too'),+ owner_id: zod+ .string()+ .describe('id of the user who created the channel'),+ team_id: zod+ .uuid()+ .nullish()+ .describe('id of the team this channel belongs to'),+ updated_at: zod.iso+ .datetime({})+ .describe('timestamp of when the channel was last updated'),}),participants: zod.array(zod.object({@@ -9257,16 +9270,29 @@ export const postItemsSoupResponse = zod.object({channel_type: zod.enum(['public', 'private', 'direct_message', 'team']).describe('Type of channel.'),- created_at: zod.iso.datetime({}),- id: zod.uuid(),- name: zod.string().nullish(),+ created_at: zod.iso+ .datetime({})+ .describe('timestamp of when the channel was created'),+ id: zod.uuid().describe('uuid of the channel'),+ name: zod+ .string()+ .nullish()+ .describe('string name of the channel'),org_id: zod.number().min(postItemsSoupResponseItemsItemDataChannelOrgIdMin)- .nullish(),- owner_id: zod.string(),- team_id: zod.uuid().nullish(),- updated_at: zod.iso.datetime({}),+ .nullish()+ .describe('id of the organization this channel belongs too'),+ owner_id: zod+ .string()+ .describe('id of the user who created the channel'),+ team_id: zod+ .uuid()+ .nullish()+ .describe('id of the team this channel belongs to'),+ updated_at: zod.iso+ .datetime({})+ .describe('timestamp of when the channel was last updated'),}),participants: zod.array(zod.object({@@ -10718,16 +10744,29 @@ export const postItemsSoupAstResponse = zod.object({channel_type: zod.enum(['public', 'private', 'direct_message', 'team']).describe('Type of channel.'),- created_at: zod.iso.datetime({}),- id: zod.uuid(),- name: zod.string().nullish(),+ created_at: zod.iso+ .datetime({})+ .describe('timestamp of when the channel was created'),+ id: zod.uuid().describe('uuid of the channel'),+ name: zod+ .string()+ .nullish()+ .describe('string name of the channel'),org_id: zod.number().min(postItemsSoupAstResponseItemsItemDataChannelOrgIdMin)- .nullish(),- owner_id: zod.string(),- team_id: zod.uuid().nullish(),- updated_at: zod.iso.datetime({}),+ .nullish()+ .describe('id of the organization this channel belongs too'),+ owner_id: zod+ .string()+ .describe('id of the user who created the channel'),+ team_id: zod+ .uuid()+ .nullish()+ .describe('id of the team this channel belongs to'),+ updated_at: zod.iso+ .datetime({})+ .describe('timestamp of when the channel was last updated'),}),participants: zod.array(zod.object({@@ -12465,18 +12504,37 @@ export const postItemsSoupAstGroupedResponse = zodchannel_type: zod.enum(['public', 'private', 'direct_message', 'team']).describe('Type of channel.'),- created_at: zod.iso.datetime({}),- id: zod.uuid(),- name: zod.string().nullish(),+ created_at: zod.iso+ .datetime({})+ .describe(+ 'timestamp of when the channel was created'+ ),+ id: zod.uuid().describe('uuid of the channel'),+ name: zod+ .string()+ .nullish()+ .describe('string name of the channel'),org_id: zod.number().min(postItemsSoupAstGroupedResponseItemsDataChannelOrgIdMin)- .nullish(),- owner_id: zod.string(),- team_id: zod.uuid().nullish(),- updated_at: zod.iso.datetime({}),+ .nullish()+ .describe(+ 'id of the organization this channel belongs too'+ ),+ owner_id: zod+ .string()+ .describe('id of the user who created the channel'),+ team_id: zod+ .uuid()+ .nullish()+ .describe('id of the team this channel belongs to'),+ updated_at: zod.iso+ .datetime({})+ .describe(+ 'timestamp of when the channel was last updated'+ ),}),participants: zod.array(zod.object({@@ -13920,18 +13978,37 @@ export const postItemsSoupAstGroupedResponse = zodchannel_type: zod.enum(['public', 'private', 'direct_message', 'team']).describe('Type of channel.'),- created_at: zod.iso.datetime({}),- id: zod.uuid(),- name: zod.string().nullish(),+ created_at: zod.iso+ .datetime({})+ .describe(+ 'timestamp of when the channel was created'+ ),+ id: zod.uuid().describe('uuid of the channel'),+ name: zod+ .string()+ .nullish()+ .describe('string name of the channel'),org_id: zod.number().min(postItemsSoupAstGroupedResponseItemsDataChannelOrgIdMinOne)- .nullish(),- owner_id: zod.string(),- team_id: zod.uuid().nullish(),- updated_at: zod.iso.datetime({}),+ .nullish()+ .describe(+ 'id of the organization this channel belongs too'+ ),+ owner_id: zod+ .string()+ .describe('id of the user who created the channel'),+ team_id: zod+ .uuid()+ .nullish()+ .describe('id of the team this channel belongs to'),+ updated_at: zod.iso+ .datetime({})+ .describe(+ 'timestamp of when the channel was last updated'+ ),}),participants: zod.array(zod.object({diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 62a78cf400..2e8a809274 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -10803,34 +10803,42 @@],"properties": {"channel_type": {- "$ref": "#/components/schemas/ChannelType"+ "$ref": "#/components/schemas/ChannelType",+ "description": "type of the channel"},"created_at": {"type": "string",- "format": "date-time"+ "format": "date-time",+ "description": "timestamp of when the channel was created"},"id": {"type": "string",- "format": "uuid"+ "format": "uuid",+ "description": "uuid of the channel"},"name": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "string name of the channel"},"org_id": {"type": ["integer", "null"],"format": "int32",+ "description": "id of the organization this channel belongs too","minimum": 0},"owner_id": {- "type": "string"+ "type": "string",+ "description": "id of the user who created the channel"},"team_id": {"type": ["string", "null"],- "format": "uuid"+ "format": "uuid",+ "description": "id of the team this channel belongs to"},"updated_at": {"type": "string",- "format": "date-time"+ "format": "date-time",+ "description": "timestamp of when the channel was last updated"}}},diff --git a/js/bun.lock b/js/bun.lockindex ec0ae9c0ba..ab75f4ccc7 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -846,7 +846,7 @@"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],@@ -2556,7 +2556,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 2453ca922a..bb9be3196c 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -112,7 +112,6 @@ dependencies = ["channels","chat","chrono",- "comms","connection","cool_asserts","crm",@@ -1961,8 +1960,8 @@ dependencies = ["async-trait","aws-sdk-s3","axum",+ "channels","chrono",- "comms","connection","entity_access","entity_access_db_utils",@@ -2149,6 +2148,7 @@ dependencies = ["ai_toolset","anyhow","async-trait",+ "attachment","axum","bot_id","chrono",@@ -2156,7 +2156,11 @@ dependencies = ["contacts","entity_access","entity_access_db_utils",+ "filter_ast",+ "frecency",+ "futures","http-body-util",+ "item_filters","macro_db_migrator","macro_user_id","macro_uuid",@@ -2167,7 +2171,10 @@ dependencies = ["model_user","models_pagination","models_permissions",+ "non_empty","notification",+ "recursion",+ "rootcause","schemars 1.2.1","serde","serde_json",@@ -2372,41 +2379,6 @@ dependencies = ["tokio-util",]-[[package]]-name = "comms"-version = "0.1.0"-dependencies = [- "anyhow",- "attachment",- "axum",- "chrono",- "doppleganger",- "entity_access",- "filter_ast",- "frecency",- "futures",- "item_filters",- "macro_db_migrator",- "macro_user_id",- "model-entity",- "model_user",- "models_comms",- "models_pagination",- "non_empty",- "readonly_pool",- "recursion",- "rootcause",- "serde",- "serde_json",- "sqlx",- "thiserror 2.0.18",- "tokio",- "tracing",- "utoipa",- "uuid",- "workspace-hack",-]-[[package]]name = "comms_db_client"version = "0.1.0"@@ -2420,7 +2392,6 @@ dependencies = ["macro_user_id","macro_uuid","model",- "models_comms","serde","serde_json","sqlx",@@ -3507,9 +3478,9 @@ dependencies = ["aws-sdk-sqs","axum","call",+ "channels","chat","chrono",- "comms","connection_gateway","cookie","crm",@@ -3612,7 +3583,6 @@ dependencies = ["chrono","clap","cloudfront_sign",- "comms","comms_db_client","connection","connection_gateway_client",@@ -7242,8 +7212,8 @@ dependencies = ["aws-sdk-sqs","axum","call",+ "channels","chat",- "comms","crm","documents","email",@@ -7320,8 +7290,8 @@ dependencies = ["anyhow","axum","call",+ "channels","chrono",- "comms","crm","documents","email",@@ -7501,7 +7471,6 @@ dependencies = ["model_file_type","model_user","models_bulk_upload",- "models_comms","models_pagination","models_permissions","schemars 1.2.1",@@ -7557,12 +7526,10 @@ version = "0.1.0"dependencies = ["anyhow","chrono",- "doppleganger","invite_email","macro_user_id","mention_utils","model-entity",- "models_comms","models_pagination","notification","paste",@@ -7600,22 +7567,6 @@ dependencies = ["workspace-hack",]-[[package]]-name = "models_comms"-version = "0.1.0"-dependencies = [- "anyhow",- "chrono",- "doppleganger",- "frecency",- "macro_user_id",- "serde",- "strum",- "thiserror 2.0.18",- "uuid",- "workspace-hack",-]-[[package]]name = "models_dcs"version = "0.1.0"@@ -7772,13 +7723,13 @@ dependencies = ["anyhow","call","chrono",- "comms","crm","document_sub_type","doppleganger","email","item_filters","macro_user_id",+ "model","model-entity","models_pagination","models_properties",@@ -8166,7 +8117,6 @@ dependencies = ["model_file_type","model_notifications","model_user",- "models_comms","models_pagination","notification","notification_db_client",@@ -10733,8 +10683,8 @@ dependencies = ["anyhow","aws-sdk-secretsmanager","axum",+ "channels","chrono",- "comms","comms_db_client","crm","document_sub_type",@@ -11456,8 +11406,8 @@ dependencies = ["axum","axum-extra","call",+ "channels","chrono",- "comms","cool_asserts","cowlike","crm",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex a494749531..2f8d56d945 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -23,7 +23,6 @@ chat = { path = "../chat", features = ["ai_tools", "outbound"] }channels = { path = "../channels", features = ["ai_tools", "outbound"] }chrono.workspace = truedateparser.workspace = true-comms = { path = "../comms", features = ["outbound"] }connection = { path = "../connection", default-features = false, features = ["ports",] }diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rsindex 6acc9e2718..666c372c35 100644--- a/rust/cloud-storage/ai_tools/src/build_context.rs+++ b/rust/cloud-storage/ai_tools/src/build_context.rs@@ -10,9 +10,8 @@ use crate::tool_context::{};use anthropic::toolset::AnthropicToolContext;use anyhow::Context;-use comms::domain::service::ChannelServiceImpl;-use comms::outbound::postgres::comms_repo::PgCommsRepo;-use comms::outbound::postgres::user_repo::PgUserRepo;+use channels::domain::list_service::ChannelListServiceImpl;+use channels::outbound::pg_channels_repo::PgChannelsRepo;use documents::domain::models::CloudFrontConfig;use documents::inbound::toolset::DocumentToolContext;use documents::outbound::pg_document_repo::PgDocumentRepo;@@ -157,9 +156,9 @@ pub async fn build_tool_service_context_from_env(crm_service.clone(),0,);- let channels_service = ChannelServiceImpl::new(- PgCommsRepo::new(ReadOnlyPool(pool.clone())),- PgUserRepo::new(pool.clone()),+ let channels_service = ChannelListServiceImpl::new(+ PgChannelsRepo::new(pool.clone()),+ PgChannelsRepo::new(pool.clone()),frecency_storage,);let channel_tool_context = crate::tool_context::build_channel_tool_context(pool.clone());diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex ed0a63bb0f..e30190fdbe 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -6,7 +6,7 @@ use call::domain::service::{CallRecordQueryServiceImpl, CallServiceImpl};use call::inbound::toolset::CallToolContext;use call::outbound::pg_call_repo::PgCallRepo;use call::outbound::s3_recording_storage::S3RecordingStorage;-use channels::domain::service::ChannelServiceImpl;+use channels::domain::{list_service::ChannelListServiceImpl, service::ChannelServiceImpl};use channels::inbound::toolset::ChannelToolContext;use channels::outbound::pg_channels_repo::PgChannelsRepo;use chat::domain::service::ChatServiceImpl;@@ -62,10 +62,10 @@ pub type ToolEmailService = EmailServiceImpl<pub type ToolUserEmailService =EmailServiceImpl<EmailPgRepo, ToolFrecencyService, sqs_client::SQS, ToolCrmService>;-/// Type alias for the comms/channels service implementation-pub type ToolCommsService = comms::domain::service::ChannelServiceImpl<- comms::outbound::postgres::comms_repo::PgCommsRepo,- comms::outbound::postgres::user_repo::PgUserRepo,+/// Type alias for the channel list service implementation.+pub type ToolCommsService = ChannelListServiceImpl<+ PgChannelsRepo,+ PgChannelsRepo,frecency::outbound::postgres::FrecencyPgStorage,>;diff --git a/rust/cloud-storage/call/Cargo.toml b/rust/cloud-storage/call/Cargo.tomlindex 3577e9e1a3..400576de4a 100644--- a/rust/cloud-storage/call/Cargo.toml+++ b/rust/cloud-storage/call/Cargo.toml@@ -20,7 +20,7 @@ outbound = ["dep:agent","dep:ai_usage","dep:aws-sdk-s3",- "comms/outbound",+ "channels/outbound","dep:entity_access_db_utils","dep:futures","dep:livekit-api",@@ -41,7 +41,7 @@ async-trait = { workspace = true, optional = true }aws-sdk-s3 = { workspace = true, optional = true }axum = { workspace = true, optional = true }chrono = { workspace = true }-comms = { path = "../comms", default-features = false }+channels = { path = "../channels", default-features = false, optional = true }connection = { path = "../connection", default-features = false, features = ["ports",] }diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex 1f9e228d7c..6bae73e994 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -7,8 +7,8 @@ mod test;use std::collections::{HashMap, HashSet};+use channels::outbound::channel_name::batch_resolve_channel_names;use chrono::Utc;-use comms::outbound::postgres::channel_name::batch_resolve_channel_names;use entity_access::domain::models::AccessLevel;use filter_ast::Expr;use item_filters::{diff --git a/rust/cloud-storage/channels/Cargo.toml b/rust/cloud-storage/channels/Cargo.tomlindex 6b4313074d..ce5614fe1c 100644--- a/rust/cloud-storage/channels/Cargo.toml+++ b/rust/cloud-storage/channels/Cargo.toml@@ -5,6 +5,15 @@ publish = falseversion = "0.1.0"[features]+attachment = [+ "dep:attachment",+ "dep:entity_access",+ "dep:futures",+ "dep:model-entity",+ "dep:non_empty",+ "entity_access/ports",+ "ports",+]ai_tools = ["dep:ai_toolset","dep:async-trait",@@ -23,7 +32,19 @@ inbound = ["models_pagination/axum","ports",]+list = [+ "dep:filter_ast",+ "dep:frecency",+ "dep:item_filters",+ "dep:model-entity",+ "dep:recursion",+ "dep:rootcause",+ "dep:serde_json",+ "frecency/ports",+ "ports",+]outbound = [+ "list","ports","dep:connection_gateway_client","dep:contacts",@@ -45,6 +66,7 @@ ports = ["dep:tokio"][dependencies]anyhow = { workspace = true }+attachment = { path = "../attachment", optional = true }axum = { workspace = true, optional = true }bot_id = { path = "../bot_id" }chrono = { workspace = true }@@ -52,6 +74,9 @@ connection_gateway_client = { path = "../connection_gateway_client", optional =contacts = { path = "../contacts", default-features = false, features = ["outbound"], optional = true }entity_access = { path = "../entity_access", optional = true, default-features = false }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }+filter_ast = { path = "../filter_ast", optional = true }+frecency = { path = "../frecency", optional = true }+futures = { workspace = true, optional = true }model-error-response = { path = "../model-error-response", optional = true }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid", optional = true }@@ -60,12 +85,16 @@ model_notifications = { path = "../model_notifications", optional = true }model_user = { path = "../model_user", optional = true, features = ["axum"] }models_pagination = { path = "../models_pagination" }models_permissions = { path = "../models_permissions", optional = true }+item_filters = { path = "../item_filters", optional = true }+non_empty = { path = "../non_empty", optional = true }notification_hex = { path = "../notification", package = "notification", optional = true }serde = { workspace = true }serde_json = { workspace = true, optional = true }share_permission_db_utils = { path = "../share_permission_db_utils", optional = true }sqlx = { workspace = true, optional = true }sqs_client = { path = "../sqs_client", default-features = false, features = ["search"], optional = true }+recursion = { workspace = true, optional = true }+rootcause = { workspace = true, optional = true }thiserror = { workspace = true }tokio = { workspace = true, features = ["macros", "sync"], optional = true }tracing = { workspace = true }diff --git a/rust/cloud-storage/channels/src/domain/list_service.rs b/rust/cloud-storage/channels/src/domain/list_service.rsnew file mode 100644index 0000000000..b6d546cdd4--- /dev/null+++ b/rust/cloud-storage/channels/src/domain/list_service.rs@@ -0,0 +1,198 @@+//! Service implementation for legacy channel list APIs.++use std::{collections::HashMap, str::FromStr};++use frecency::domain::{models::AggregateFrecency, ports::AggregateFrecencyStorage};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use model_entity::EntityType;+use uuid::Uuid;++use crate::domain::{+ models::{Activity, ChannelType, ChannelWithLatest, GetChannelsRequest, UserName},+ ports::{ChannelListRepo, ChannelListService, ChannelListUserRepo},+};++/// Channel list service backed by channel, user, and frecency repositories.+pub struct ChannelListServiceImpl<Channels, Users, Frec> {+ channels: Channels,+ users: Users,+ frecency: Frec,+}++impl<Channels, Users, Frec> ChannelListServiceImpl<Channels, Users, Frec>+where+ Channels: ChannelListRepo,+ Users: ChannelListUserRepo,+ Frec: AggregateFrecencyStorage,+{+ /// Create a new channel list service.+ pub fn new(channels: Channels, users: Users, frecency: Frec) -> Self {+ Self {+ channels,+ users,+ frecency,+ }+ }+}++impl<Channels, Users, Frec> ChannelListService for ChannelListServiceImpl<Channels, Users, Frec>+where+ Channels: ChannelListRepo,+ Users: ChannelListUserRepo,+ Frec: AggregateFrecencyStorage,+{+ #[tracing::instrument(err, skip(self))]+ async fn get_channels(+ &self,+ req: GetChannelsRequest,+ ) -> Result<Vec<ChannelWithLatest>, rootcause::Report> {+ let params = req.into_params();+ let user = params.user().clone();++ let channels = self+ .channels+ .get_user_channels_with_participants(params)+ .await?;++ let channel_entities: Vec<_> = channels+ .iter()+ .map(|chan| EntityType::Channel.with_entity_string(chan.channel.id.to_string()))+ .collect();++ let channel_ids: Vec<_> = channels.iter().map(|chan| chan.channel.id).collect();++ let participant_ids = channels+ .iter()+ .flat_map(|chan| chan.participants.iter().map(|p| p.user_id.as_str()))+ .filter_map(|id| {+ MacroUserIdStr::parse_from_str(id)+ .ok()+ .map(|id| id.into_owned())+ })+ .collect();++ let (names, latest_messages, activities, frecency) = tokio::join!(+ self.users.get_names_for_ids(participant_ids),+ self.channels+ .get_latest_channel_messages_batch(&channel_ids),+ self.channels.get_channel_list_activities(user.clone()),+ self.frecency+ .get_aggregate_for_user_entities(user.clone(), channel_entities.as_slice())+ );++ let mut activity_lookup: HashMap<Uuid, Activity> = activities+ .unwrap_or_default()+ .into_iter()+ .map(|a| (a.channel_id, a))+ .collect();++ let mut frecency_map: HashMap<Uuid, AggregateFrecency> = frecency+ .unwrap_or_default()+ .into_iter()+ .filter_map(|f| match Uuid::from_str(&f.id.entity.entity_id) {+ Ok(channel_id) => Some((channel_id, f)),+ Err(error) => {+ tracing::warn!(+ %error,+ entity_id = %f.id.entity.entity_id,+ "invalid channel entity id in frecency result"+ );+ None+ }+ })+ .collect();++ let name_lookup = names.map(|n| {+ n.into_iter()+ .filter_map(|n| {+ let display = n.display_name()?;+ Some((n.id.to_string(), display))+ })+ .collect::<HashMap<_, _>>()+ })?;++ let mut latest_messages = latest_messages?;++ Ok(channels+ .into_iter()+ .map(|mut channel| {+ let resolved_name = resolve_channel_name(+ channel.channel.channel_type,+ channel.channel.name.as_deref(),+ channel.channel.id,+ user.as_ref(),+ &channel.participants,+ &name_lookup,+ );+ channel.channel.name = Some(resolved_name);+ let activity = activity_lookup.remove(&channel.channel.id);+ let viewed_at = activity.as_ref().and_then(|a| a.viewed_at);+ let interacted_at = activity.as_ref().and_then(|a| a.interacted_at);+ let channel_id = channel.channel.id;+ ChannelWithLatest {+ channel,+ latest_message: latest_messages.remove(&channel_id).unwrap_or_default(),+ viewed_at,+ interacted_at,+ frecency_score: frecency_map.remove(&channel_id),+ }+ })+ .collect())+ }++ fn get_activities(+ &self,+ user: MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<Activity>, rootcause::Report>> + Send {+ self.channels.get_channel_list_activities(user)+ }++ fn get_names(+ &self,+ names: std::collections::HashSet<MacroUserIdStr<'_>>,+ ) -> impl Future<Output = Result<Vec<UserName>, rootcause::Report>> + Send {+ self.users.get_names_for_ids(names)+ }+}++fn resolve_channel_name(+ channel_type: ChannelType,+ stored_name: Option<&str>,+ channel_id: Uuid,+ viewer_user_id: &str,+ participants: &[crate::domain::models::ChannelParticipant],+ name_lookup: &HashMap<String, String>,+) -> String {+ if let Some(name) = stored_name.filter(|name| !name.is_empty()) {+ return name.to_string();+ }++ match channel_type {+ ChannelType::Public | ChannelType::Team => format!("#{}", &channel_id.to_string()[..8]),+ ChannelType::Private => {+ let mut names: Vec<_> = participants+ .iter()+ .filter(|p| p.user_id != viewer_user_id)+ .map(|p| display_name(&p.user_id, name_lookup))+ .collect();+ names.sort();+ if names.is_empty() {+ "Private channel".to_string()+ } else {+ names.join(", ")+ }+ }+ ChannelType::DirectMessage => participants+ .iter()+ .find(|p| p.user_id != viewer_user_id)+ .map(|p| display_name(&p.user_id, name_lookup))+ .unwrap_or_else(|| "Direct message".to_string()),+ }+}++fn display_name(user_id: &str, name_lookup: &HashMap<String, String>) -> String {+ name_lookup+ .get(user_id)+ .cloned()+ .unwrap_or_else(|| user_id.to_string())+}diff --git a/rust/cloud-storage/channels/src/domain/mod.rs b/rust/cloud-storage/channels/src/domain/mod.rsindex 0524cd6faa..1e8be8d4d6 100644--- a/rust/cloud-storage/channels/src/domain/mod.rs+++ b/rust/cloud-storage/channels/src/domain/mod.rs@@ -1,5 +1,8 @@/// Domain events emitted by channel workflows.pub mod events;+/// Legacy channel list service implementation.+#[cfg(feature = "list")]+pub mod list_service;/// Domain models for channel messages.pub mod models;#[cfg(feature = "ports")]diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rsindex 0e30f1ec61..45a8f6a9e0 100644--- a/rust/cloud-storage/channels/src/domain/models.rs+++ b/rust/cloud-storage/channels/src/domain/models.rs@@ -1,6 +1,10 @@use chrono::{DateTime, Utc};+#[cfg(feature = "list")]+use item_filters::ast::{LiteralTree, channel::ChannelLiteral};use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};+#[cfg(feature = "list")]+use models_pagination::{Query, SimpleSortMethod};use serde::{Deserialize, Serialize, Serializer};use uuid::Uuid;@@ -245,6 +249,27 @@ impl Identify for ChannelMessage {}}+/// Lightweight channel message used when rendering a channel as an AI attachment.+#[derive(Debug, Clone)]+pub struct RecentChannelMessage {+ /// Message id.+ pub message_id: Uuid,+ /// Thread parent id, if this message is a reply.+ pub thread_id: Option<Uuid>,+ /// Sender actor id.+ pub sender_id: String,+ /// Message body.+ pub content: String,+ /// Message creation timestamp.+ pub created_at: DateTime<Utc>,+ /// Message update timestamp.+ pub updated_at: DateTime<Utc>,+ /// Message deletion timestamp, if any.+ pub deleted_at: Option<DateTime<Utc>>,+ /// Message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`.+ pub mentions: Vec<String>,+}+impl SortOn<CreatedAt> for ChannelMessage {fn sort_on(sort_type: CreatedAt) -> impl FnMut(&Self) -> CursorVal<CreatedAt> {move |msg| CursorVal {@@ -355,7 +380,8 @@ impl SortOn<CreatedAt> for ChannelAttachment {}/// Role of a channel participant.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]#[cfg_attr(feature = "outbound", derive(sqlx::Type))]#[cfg_attr(feature = "outbound",@@ -367,6 +393,7 @@ pub enum ParticipantRole {/// Channel admin.Admin,/// Regular member.+ #[default]Member,}@@ -384,7 +411,7 @@ impl std::str::FromStr for ParticipantRole {}/// An active participant in a channel.-#[derive(Debug, Clone)]+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct ChannelParticipant {/// Channel id.pub channel_id: Uuid,@@ -968,6 +995,144 @@ pub struct WithChannelId {pub channel_id: String,}+/// User display-name components used for channel-name resolution.+#[cfg(feature = "list")]+#[derive(Debug, Deserialize)]+pub struct UserName {+ /// Macro user id.+ pub id: MacroUserIdStr<'static>,+ /// First name, if present.+ pub first_name: Option<String>,+ /// Last name, if present.+ pub last_name: Option<String>,+}++#[cfg(feature = "list")]+impl UserName {+ /// Attempt to create a display name for this user.+ pub fn display_name(&self) -> Option<String> {+ const NA: &str = "N/A";+ match (+ self.first_name.as_deref().filter(|v| *v != NA),+ self.last_name.as_deref().filter(|v| *v != NA),+ ) {+ (None, None) => None,+ (None, Some(last)) => Some(last.to_string()),+ (Some(first), None) => Some(first.to_string()),+ (Some(first), Some(last)) => Some(format!("{first} {last}")),+ }+ }+}++/// Channel list request.+#[cfg(feature = "list")]+#[derive(Debug)]+pub struct GetChannelsRequest {+ /// Requesting user id.+ pub macro_id: MacroUserIdStr<'static>,+ /// Optional result limit.+ pub limit: Option<u32>,+ /// Cursor, sort, and channel-level filter.+ pub query: Query<Uuid, SimpleSortMethod, LiteralTree<ChannelLiteral>>,+}++#[cfg(feature = "list")]+impl GetChannelsRequest {+ /// Convert into repository params.+ pub fn into_params(self) -> GetChannelsParams {+ GetChannelsParams {+ macro_id: self.macro_id,+ limit: self.limit,+ query: self.query,+ }+ }+}++/// Channel list repository parameters.+#[cfg(feature = "list")]+#[derive(Debug)]+pub struct GetChannelsParams {+ macro_id: MacroUserIdStr<'static>,+ limit: Option<u32>,+ query: Query<Uuid, SimpleSortMethod, LiteralTree<ChannelLiteral>>,+}++#[cfg(feature = "list")]+impl GetChannelsParams {+ /// Requesting user id.+ pub fn user(&self) -> &MacroUserIdStr<'static> {+ &self.macro_id+ }++ /// Optional result limit.+ pub fn limit(&self) -> Option<u32> {+ self.limit+ }++ /// Cursor, sort, and channel-level filter.+ pub fn query(&self) -> &Query<Uuid, SimpleSortMethod, LiteralTree<ChannelLiteral>> {+ &self.query+ }+}++/// Channel data plus active participants.+#[cfg(feature = "list")]+#[derive(Debug, Clone)]+pub struct ChannelWithParticipants {+ /// Channel info.+ pub channel: ChannelListItem,+ /// Active channel participants.+ pub participants: Vec<ChannelParticipant>,+}++/// Channel list item.+#[cfg(feature = "list")]+#[derive(Debug, Clone)]+pub struct ChannelListItem {+ /// Channel id.+ pub id: Uuid,+ /// Resolved or stored name.+ pub name: Option<String>,+ /// Channel type.+ pub channel_type: ChannelType,+ /// Organization id.+ pub org_id: Option<i64>,+ /// Team id.+ pub team_id: Option<Uuid>,+ /// Creation timestamp.+ pub created_at: DateTime<Utc>,+ /// Update timestamp.+ pub updated_at: DateTime<Utc>,+ /// Channel owner user id.+ pub owner_id: MacroUserIdStr<'static>,+}++/// Latest-message bundle for channel list results.+#[cfg(feature = "list")]+#[derive(Debug, Clone, Default)]+pub struct LatestMessage {+ /// Latest message including thread replies.+ pub latest_message: Option<RecentChannelMessage>,+ /// Latest non-thread top-level message.+ pub latest_non_thread_message: Option<RecentChannelMessage>,+}++/// Channel list result enriched with latest messages, activity, and frecency.+#[cfg(feature = "list")]+#[derive(Debug, Clone)]+pub struct ChannelWithLatest {+ /// Channel plus participants.+ pub channel: ChannelWithParticipants,+ /// Latest message data.+ pub latest_message: LatestMessage,+ /// Last viewed timestamp for requesting user.+ pub viewed_at: Option<DateTime<Utc>>,+ /// Last interaction timestamp for requesting user.+ pub interacted_at: Option<DateTime<Utc>>,+ /// Aggregate frecency score.+ pub frecency_score: Option<frecency::domain::models::AggregateFrecency>,+}+/// Raw preview row returned from the repository.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ChannelPreviewRow {diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rsindex 6ad4396ca5..a884aec158 100644--- a/rust/cloud-storage/channels/src/domain/ports.rs+++ b/rust/cloud-storage/channels/src/domain/ports.rs@@ -1,4 +1,6 @@use crate::domain::events::ChannelEvent;+#[cfg(feature = "attachment")]+use crate::domain::models::RecentChannelMessage;use crate::domain::models::{Activity, ActivityType, AddParticipantsRequest, AttachmentEntityReference, BotId,BotSenderProfile, ChannelAttachment, ChannelAttachmentType, ChannelContextMessage, ChannelInfo,@@ -11,6 +13,11 @@ use crate::domain::models::{ReferencedShareItem, RemoveParticipantsRequest, ResolvedChannelMessage, Sender, SimpleMention,ThreadData, ThreadReply, ThreadReplyRow, TopLevelMessageRow,};+#[cfg(feature = "list")]+use crate::domain::models::{+ ChannelWithLatest, ChannelWithParticipants, GetChannelsParams, GetChannelsRequest,+ LatestMessage, UserName,+};use crate::domain::side_effects::{ChannelDocumentMention, ChannelNotificationEffect, ChannelRealtimeEffect,ThreadNotificationContext,@@ -21,6 +28,80 @@ use models_pagination::{CreatedAt, Query};use std::collections::{HashMap, HashSet};use uuid::Uuid;+/// Repository for channel list persistence and query data.+#[cfg(feature = "list")]+pub trait ChannelListRepo: Send + Sync + 'static {+ /// Fetch channels visible to a user with their active participants.+ fn get_user_channels_with_participants(+ &self,+ req: GetChannelsParams,+ ) -> impl Future<Output = Result<Vec<ChannelWithParticipants>, rootcause::Report>> + Send;++ /// Batch-fetch latest messages for channels.+ fn get_latest_channel_messages_batch(+ &self,+ channels: &[Uuid],+ ) -> impl Future<Output = Result<HashMap<Uuid, LatestMessage>, rootcause::Report>> + Send;++ /// Fetch recent activity for a user.+ fn get_channel_list_activities(+ &self,+ user_id: MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<Activity>, rootcause::Report>> + Send;+}++/// Repository for user display names needed by channel list rendering.+#[cfg(feature = "list")]+pub trait ChannelListUserRepo: Send + Sync + 'static {+ /// Fetch names for user ids.+ fn get_names_for_ids(+ &self,+ names: HashSet<MacroUserIdStr<'_>>,+ ) -> impl Future<Output = Result<Vec<UserName>, rootcause::Report>> + Send;+}++/// Service for legacy channel list APIs.+#[cfg(feature = "list")]+pub trait ChannelListService: Send + Sync + 'static {+ /// Fetch channels visible to a user, enriched for list display.+ fn get_channels(+ &self,+ req: GetChannelsRequest,+ ) -> impl Future<Output = Result<Vec<ChannelWithLatest>, rootcause::Report>> + Send;++ /// Fetch recent activity for a user.+ fn get_activities(+ &self,+ user: MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<Activity>, rootcause::Report>> + Send;++ /// Fetch names for user ids.+ fn get_names(+ &self,+ names: HashSet<MacroUserIdStr<'_>>,+ ) -> impl Future<Output = Result<Vec<UserName>, rootcause::Report>> + Send;+}++/// Repository methods needed to render channels as AI attachments.+#[cfg(feature = "attachment")]+pub trait ChannelAttachmentRepo: Send + Sync + 'static {+ /// Error type for repo operations.+ type Err: Into<anyhow::Error> + Send;++ /// Fetch the stored channel name, if one exists.+ fn get_channel_name_for_attachment(+ &self,+ channel_id: Uuid,+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;++ /// Fetch recent non-deleted channel messages, newest-first.+ fn get_recent_messages_for_attachment(+ &self,+ channel_id: Uuid,+ limit: u32,+ ) -> impl Future<Output = Result<Vec<RecentChannelMessage>, Self::Err>> + Send;+}+/// Repository for channel persistence and query data.#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]pub trait ChannelRepo: Send + Sync + 'static {diff --git a/rust/cloud-storage/comms/src/inbound/attachment.rs b/rust/cloud-storage/channels/src/inbound/attachment.rssimilarity index 72%rename from rust/cloud-storage/comms/src/inbound/attachment.rsrename to rust/cloud-storage/channels/src/inbound/attachment.rsindex 362b096651..4d740ca493 100644--- a/rust/cloud-storage/comms/src/inbound/attachment.rs+++ b/rust/cloud-storage/channels/src/inbound/attachment.rs@@ -1,4 +1,4 @@-//! Attachment inbound adapter for the comms domain.+//! Attachment inbound adapter for the channels domain.use std::fmt::Write;use std::sync::Arc;@@ -12,30 +12,32 @@ use entity_access::domain::{models::MemberParticipantRole, ports::EntityAccessSeuse futures::future::join_all;use macro_user_id::user_id::MacroUserIdStr;use model_entity::{Entity, EntityType};-use models_comms::channel::{ChannelId, ChannelMessage};use non_empty::NonEmpty;+use uuid::Uuid;-use crate::domain::ports::CommsRepo;+use crate::domain::{models::RecentChannelMessage, ports::ChannelAttachmentRepo};const MESSAGE_LIMIT: u32 = 50;/// Resolves channel IDs into [`Attachments`].-pub struct CommsAttachmentService<C, E> {- comms_repo: Arc<C>,+pub struct ChannelAttachmentService<C, E> {+ channel_repo: Arc<C>,entity_access_service: Arc<E>,}-impl<C, E> CommsAttachmentService<C, E> {- /// Create a new comms attachment service.- pub fn new(comms_repo: Arc<C>, entity_access_service: Arc<E>) -> Self {+impl<C, E> ChannelAttachmentService<C, E> {+ /// Create a new channel attachment service.+ pub fn new(channel_repo: Arc<C>, entity_access_service: Arc<E>) -> Self {Self {- comms_repo,+ channel_repo,entity_access_service,}}}-impl<C: CommsRepo, E: EntityAccessService> AttachmentService for CommsAttachmentService<C, E> {+impl<C: ChannelAttachmentRepo, E: EntityAccessService> AttachmentService+ for ChannelAttachmentService<C, E>+{#[tracing::instrument(skip_all)]async fn resolve_attachments<'a>(&self,@@ -58,7 +60,7 @@ impl<C: CommsRepo, E: EntityAccessService> AttachmentService for CommsAttachment}}-impl<C: CommsRepo, E: EntityAccessService> CommsAttachmentService<C, E> {+impl<C: ChannelAttachmentRepo, E: EntityAccessService> ChannelAttachmentService<C, E> {#[tracing::instrument(skip(self), err)]async fn resolve_one(&self,@@ -66,8 +68,7 @@ impl<C: CommsRepo, E: EntityAccessService> CommsAttachmentService<C, E> {entity: &Entity<'_>,) -> Result<AttachmentContent<'static>, AttachmentError> {let id = &*entity.entity_id;- let channel_id =- ChannelId(uuid::Uuid::parse_str(id).map_err(|e| AttachmentError::Internal(e.into()))?);+ let channel_id = Uuid::parse_str(id).map_err(|e| AttachmentError::Internal(e.into()))?;self.entity_access_service.generate_entity_access_receipt::<MemberParticipantRole>(@@ -80,14 +81,14 @@ impl<C: CommsRepo, E: EntityAccessService> CommsAttachmentService<C, E> {.map_err(|e| AttachmentError::PermissionDenied(Box::new(e)))?;let (name, messages) = tokio::join!(- self.comms_repo.get_channel_name(channel_id),- self.comms_repo- .get_recent_messages(channel_id, MESSAGE_LIMIT),+ self.channel_repo+ .get_channel_name_for_attachment(channel_id),+ self.channel_repo+ .get_recent_messages_for_attachment(channel_id, MESSAGE_LIMIT),);- let name = name.map_err(|e| AttachmentError::Internal(anyhow::anyhow!("{e:#}")))?;- let mut messages =- messages.map_err(|e| AttachmentError::Internal(anyhow::anyhow!("{e:#}")))?;+ let name = name.map_err(|e| AttachmentError::Internal(e.into()))?;+ let mut messages = messages.map_err(|e| AttachmentError::Internal(e.into()))?;messages.reverse();let parts = format_messages(&messages);@@ -107,7 +108,7 @@ impl<C: CommsRepo, E: EntityAccessService> CommsAttachmentService<C, E> {}}-fn format_messages(messages: &[ChannelMessage]) -> String {+fn format_messages(messages: &[RecentChannelMessage]) -> String {if messages.is_empty() {return "(no messages)".to_string();}diff --git a/rust/cloud-storage/channels/src/inbound/list_router.rs b/rust/cloud-storage/channels/src/inbound/list_router.rsnew file mode 100644index 0000000000..32736f1b57--- /dev/null+++ b/rust/cloud-storage/channels/src/inbound/list_router.rs@@ -0,0 +1,386 @@+use std::sync::Arc;++use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::get};+use frecency::domain::models::AggregateFrecency;+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use model_user::axum_extractor::MacroUserExtractor;+use serde::Serialize;+use thiserror::Error;+use utoipa::ToSchema;+use uuid::Uuid;++use crate::domain::{+ models::{+ Activity, ChannelListItem, ChannelType as DomainChannelType, ChannelWithLatest,+ GetChannelsRequest, ParticipantRole as DomainParticipantRole, RecentChannelMessage,+ },+ ports::ChannelListService,+};++const DEFAULT_CHANNEL_LIST_LIMIT: u32 = 100;++/// Router state for legacy channel-list endpoints.+pub struct ChannelListRouterState<S> {+ /// Inner channel list service.+ pub inner: Arc<S>,+}++impl<S> Clone for ChannelListRouterState<S> {+ fn clone(&self) -> Self {+ Self {+ inner: Arc::clone(&self.inner),+ }+ }+}++impl<S: ChannelListService> ChannelListRouterState<S> {+ /// Build router state from a channel list service.+ pub fn new(s: S) -> Self {+ Self { inner: Arc::new(s) }+ }+}++/// Legacy `/channels` and `/activity` list routes.+pub fn channel_list_router<S: ChannelListService, T: Send + Sync + 'static>(+ s: ChannelListRouterState<S>,+) -> Router<T> {+ Router::new()+ .route("/channels", get(get_channels_handler))+ .route("/activity", get(get_activity_handler))+ .with_state(s)+}++/// Errors returned by channel list routes.+#[derive(Debug, Error)]+pub enum ChannelListRouterErr {+ /// Internal server error.+ #[error("Internal server error")]+ Internal,+}++impl IntoResponse for ChannelListRouterErr {+ fn into_response(self) -> axum::response::Response {+ let status = match self {+ Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,+ };++ (status, self.to_string()).into_response()+ }+}++#[utoipa::path(+ get,+ path = "/channels",+ tag = "channels",+ operation_id = "get_channels",+ responses(+ (status = 200, body=Vec<ApiChannelWithLatest>),+ (status = 401, body=String),+ (status = 404, body=String),+ (status = 500, body=String),+ )+)]+async fn get_channels_handler<S: ChannelListService>(+ State(service): State<ChannelListRouterState<S>>,+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,+) -> Result<Json<Vec<ApiChannelWithLatest>>, ChannelListRouterErr> {+ let res = service+ .inner+ .get_channels(GetChannelsRequest {+ macro_id: macro_user_id,+ limit: Some(DEFAULT_CHANNEL_LIST_LIMIT),+ query: models_pagination::Query::Sort(+ models_pagination::SimpleSortMethod::UpdatedAt,+ None,+ ),+ })+ .await+ .map_err(|_| ChannelListRouterErr::Internal)?;++ res.into_iter()+ .map(ApiChannelWithLatest::try_from)+ .collect::<Result<Vec<_>, _>>()+ .map(Json)+}++#[tracing::instrument(skip(service))]+#[utoipa::path(get,+ tag = "activity",+ operation_id = "get_activity",+ path = "/activity", responses(+ (status = 200, body=Vec<ApiActivity>),+ (status = 401, body=String),+ (status = 404, body=String),+ (status = 500, body=String),+))]+/// Handle legacy channel activity list requests.+pub async fn get_activity_handler<S: ChannelListService>(+ State(service): State<ChannelListRouterState<S>>,+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,+) -> Result<Json<Vec<ApiActivity>>, ChannelListRouterErr> {+ let res = service+ .inner+ .get_activities(macro_user_id)+ .await+ .map_err(|_| ChannelListRouterErr::Internal)?;++ Ok(Json(res.into_iter().map(ApiActivity::from).collect()))+}++/// Participant role in API responses.+#[derive(Debug, Clone, Copy, Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum ParticipantRole {+ /// Channel owner.+ Owner,+ /// Channel admin.+ Admin,+ /// Regular member.+ Member,+}++impl From<DomainParticipantRole> for ParticipantRole {+ fn from(value: DomainParticipantRole) -> Self {+ match value {+ DomainParticipantRole::Owner => Self::Owner,+ DomainParticipantRole::Admin => Self::Admin,+ DomainParticipantRole::Member => Self::Member,+ }+ }+}++/// Channel participant in API responses.+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct ChannelParticipant {+ /// id of the channel+ pub channel_id: Uuid,+ /// id of the user+ #[schema(value_type = String)]+ pub user_id: MacroUserIdStr<'static>,+ /// type of the participant+ pub role: ParticipantRole,+ /// timestamp of when the user joined the channel+ pub joined_at: chrono::DateTime<chrono::Utc>,+ /// timestamp of when the user left the channel+ pub left_at: Option<chrono::DateTime<chrono::Utc>>,+}++impl TryFrom<crate::domain::models::ChannelParticipant> for ChannelParticipant {+ type Error = ChannelListRouterErr;++ fn try_from(value: crate::domain::models::ChannelParticipant) -> Result<Self, Self::Error> {+ Ok(Self {+ channel_id: value.channel_id,+ user_id: MacroUserIdStr::parse_from_str(&value.user_id)+ .map_err(|_| ChannelListRouterErr::Internal)?+ .into_owned(),+ role: value.role.into(),+ joined_at: value.joined_at,+ left_at: value.left_at,+ })+ }+}++/// Channel with participants in API responses.+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct ChannelWithParticipants {+ /// Channel fields.+ #[serde(flatten)]+ pub channel: Channel,+ /// Active participants.+ pub participants: Vec<ChannelParticipant>,+}++/// Channel list response item.+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct ApiChannelWithLatest {+ /// Channel and participants.+ #[serde(flatten)]+ pub channel: ChannelWithParticipants,+ /// Latest message fields.+ #[serde(flatten)]+ pub latest_message: LatestMessage,+ /// Last viewed timestamp for requesting user.+ pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,+ /// Last interaction timestamp for requesting user.+ pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,+ /// Aggregate frecency score.+ pub frecency_score: Option<f64>,+}++impl TryFrom<ChannelWithLatest> for ApiChannelWithLatest {+ type Error = ChannelListRouterErr;++ fn try_from(value: ChannelWithLatest) -> Result<Self, Self::Error> {+ Ok(Self {+ channel: ChannelWithParticipants {+ channel: value.channel.channel.into(),+ participants: value+ .channel+ .participants+ .into_iter()+ .map(ChannelParticipant::try_from)+ .collect::<Result<Vec<_>, _>>()?,+ },+ latest_message: value.latest_message.into(),+ viewed_at: value.viewed_at,+ interacted_at: value.interacted_at,+ frecency_score: map_frecency(value.frecency_score),+ })+ }+}++fn map_frecency(f: Option<AggregateFrecency>) -> Option<f64> {+ f.map(|f| f.data.frecency_score)+}++/// Channel fields in API responses.+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct Channel {+ /// uuid of the channel+ pub id: Uuid,+ /// string name of the channel+ pub name: Option<String>,+ /// type of the channel+ pub channel_type: ChannelType,+ /// id of the organization this channel belongs too+ #[schema(value_type = Option<u32>)]+ pub org_id: Option<u32>,+ /// id of the team this channel belongs to+ pub team_id: Option<Uuid>,+ /// timestamp of when the channel was created+ pub created_at: chrono::DateTime<chrono::Utc>,+ /// timestamp of when the channel was last updated+ pub updated_at: chrono::DateTime<chrono::Utc>,+ /// id of the user who created the channel+ #[schema(value_type = String)]+ pub owner_id: MacroUserIdStr<'static>,+}++impl From<ChannelListItem> for Channel {+ fn from(value: ChannelListItem) -> Self {+ Self {+ id: value.id,+ name: value.name,+ channel_type: value.channel_type.into(),+ org_id: value.org_id.and_then(|org_id| u32::try_from(org_id).ok()),+ team_id: value.team_id,+ created_at: value.created_at,+ updated_at: value.updated_at,+ owner_id: value.owner_id,+ }+ }+}++/// Latest-message bundle in API responses.+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct LatestMessage {+ /// Latest message including thread replies.+ pub latest_message: Option<ChannelMessage>,+ /// Latest non-thread top-level message.+ pub latest_non_thread_message: Option<ChannelMessage>,+}++impl From<crate::domain::models::LatestMessage> for LatestMessage {+ fn from(value: crate::domain::models::LatestMessage) -> Self {+ Self {+ latest_message: value.latest_message.map(ChannelMessage::from),+ latest_non_thread_message: value.latest_non_thread_message.map(ChannelMessage::from),+ }+ }+}++/// Channel type in API responses.+#[derive(Debug, Clone, Copy, Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum ChannelType {+ /// Public channel.+ Public,+ /// Private channel.+ Private,+ /// Direct message channel.+ DirectMessage,+ /// Team channel.+ Team,+}++impl From<DomainChannelType> for ChannelType {+ fn from(value: DomainChannelType) -> Self {+ match value {+ DomainChannelType::Public => Self::Public,+ DomainChannelType::Private => Self::Private,+ DomainChannelType::DirectMessage => Self::DirectMessage,+ DomainChannelType::Team => Self::Team,+ }+ }+}++/// Channel message in API responses.+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct ChannelMessage {+ /// Message id.+ pub message_id: Uuid,+ /// Thread id, if the message is a reply.+ pub thread_id: Option<Uuid>,+ /// Sender user id.+ pub sender_id: String,+ /// Message content.+ pub content: String,+ /// Creation timestamp.+ pub created_at: chrono::DateTime<chrono::Utc>,+ /// Update timestamp.+ pub updated_at: chrono::DateTime<chrono::Utc>,+ /// Deletion timestamp, if deleted.+ pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,+ /// message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`+ pub mentions: Vec<String>,+}++impl From<RecentChannelMessage> for ChannelMessage {+ fn from(value: RecentChannelMessage) -> Self {+ Self {+ message_id: value.message_id,+ thread_id: value.thread_id,+ sender_id: value.sender_id,+ content: value.content,+ created_at: value.created_at,+ updated_at: value.updated_at,+ deleted_at: value.deleted_at,+ mentions: value.mentions,+ }+ }+}++/// Activity item in API responses.+#[derive(Debug, ToSchema, Serialize)]+pub struct ApiActivity {+ /// Activity id.+ pub id: Uuid,+ /// User id.+ pub user_id: String,+ /// Channel id.+ pub channel_id: Uuid,+ /// Created timestamp.+ pub created_at: chrono::DateTime<chrono::Utc>,+ /// Updated timestamp.+ pub updated_at: chrono::DateTime<chrono::Utc>,+ /// the last time the user viewed the channel+ pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,+ /// the last time the user intereacted with the channel+ /// eg. reacting, replying, sending a message+ pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,+}++impl From<Activity> for ApiActivity {+ fn from(value: Activity) -> Self {+ Self {+ id: value.id,+ user_id: value.user_id,+ channel_id: value.channel_id,+ created_at: value.created_at,+ updated_at: value.updated_at,+ viewed_at: value.viewed_at,+ interacted_at: value.interacted_at,+ }+ }+}diff --git a/rust/cloud-storage/channels/src/inbound/mod.rs b/rust/cloud-storage/channels/src/inbound/mod.rsindex a58543c20a..705faeb16a 100644--- a/rust/cloud-storage/channels/src/inbound/mod.rs+++ b/rust/cloud-storage/channels/src/inbound/mod.rs@@ -1,6 +1,12 @@+/// Attachment adapter for resolving channel references into AI-consumable context.+#[cfg(feature = "attachment")]+pub mod attachment;/// Axum handler and router for channel messages.#[cfg(feature = "inbound")]pub mod axum_router;+/// Axum handler and router for legacy channel list routes.+#[cfg(all(feature = "inbound", feature = "list"))]+pub mod list_router;/// AI toolset for reading channel messages and threads.#[cfg(feature = "ai_tools")]pub mod toolset;diff --git a/rust/cloud-storage/channels/src/lib.rs b/rust/cloud-storage/channels/src/lib.rsindex 2996f1bc26..3d4d173209 100644--- a/rust/cloud-storage/channels/src/lib.rs+++ b/rust/cloud-storage/channels/src/lib.rs@@ -3,8 +3,8 @@/// Domain layer: models, ports, and service.pub mod domain;-/// Inbound layer: axum handler and router.-#[cfg(any(feature = "inbound", feature = "ai_tools"))]+/// Inbound layer: axum handler, AI tools, and attachment adapters.+#[cfg(any(feature = "inbound", feature = "ai_tools", feature = "attachment"))]pub mod inbound;/// Outbound layer: postgres repository.#[cfg(feature = "outbound")]diff --git a/rust/cloud-storage/comms/src/outbound/postgres/channel_name.rs b/rust/cloud-storage/channels/src/outbound/channel_name.rssimilarity index 60%rename from rust/cloud-storage/comms/src/outbound/postgres/channel_name.rsrename to rust/cloud-storage/channels/src/outbound/channel_name.rsindex 2aa3575fa8..44eab0b209 100644--- a/rust/cloud-storage/comms/src/outbound/postgres/channel_name.rs+++ b/rust/cloud-storage/channels/src/outbound/channel_name.rs@@ -1,19 +1,12 @@//! Batch channel-name resolution backed by Postgres.-//!-//! Queries channels, their participants, and user display names, then-//! delegates to the canonical [`resolve_channel_name`] domain function.use std::collections::{HashMap, HashSet};-use chrono::{DateTime, Utc};-use doppleganger::Mirror;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use models_comms::channel::{ChannelId, ChannelParticipant, ParticipantRole};+use macro_user_id::user_id::MacroUserIdStr;use sqlx::PgPool;use uuid::Uuid;-use crate::domain::models::channel_name::{NameLookup, resolve_channel_name};-use crate::outbound::postgres::comms_repo::ChannelType;+use crate::domain::models::ChannelType;/// Batch-resolve display names for a list of channel ids from the perspective/// of `viewer_user_id`. The viewer is only used to pick the right "other@@ -41,25 +34,23 @@ pub async fn batch_resolve_channel_names<'a>(.fetch_all(pool).await?;- let channels: HashMap<Uuid, (Option<String>, models_comms::channel::ChannelType)> =- channel_rows- .into_iter()- .map(|r| (r.id, (r.name, ChannelType::mirror(r.channel_type))))- .collect();+ let channels: HashMap<Uuid, (Option<String>, ChannelType)> = channel_rows+ .into_iter()+ .map(|r| (r.id, (r.name, r.channel_type)))+ .collect();- // Channels that need participant-derived names (DMs, unnamed privates).let needs_participants: Vec<Uuid> = channels.iter().filter(|(_, (name, ct))| {- matches!(ct, models_comms::channel::ChannelType::DirectMessage)- || (matches!(ct, models_comms::channel::ChannelType::Private)+ matches!(ct, ChannelType::DirectMessage)+ || (matches!(ct, ChannelType::Private)&& name.as_ref().is_none_or(|n| n.trim().is_empty()))}).map(|(id, _)| *id).collect();let (participants_by_channel, name_lookup) = if needs_participants.is_empty() {- (HashMap::new(), NameLookup::new())+ (HashMap::new(), HashMap::new())} else {load_participants_and_names(pool, &needs_participants).await?};@@ -69,11 +60,11 @@ pub async fn batch_resolve_channel_names<'a>(let empty = Vec::new();let participants = participants_by_channel.get(channel_id).unwrap_or(&empty);let resolved_name = resolve_channel_name(- channel_type,+ *channel_type,name.as_deref(),+ *channel_id,+ viewer_user_id.as_ref(),participants,- &ChannelId(*channel_id),- viewer_user_id.copied(),&name_lookup,);resolved.insert(*channel_id, resolved_name);@@ -85,7 +76,7 @@ pub async fn batch_resolve_channel_names<'a>(async fn load_participants_and_names(pool: &PgPool,channel_ids: &[Uuid],-) -> Result<(HashMap<Uuid, Vec<ChannelParticipant>>, NameLookup), sqlx::Error> {+) -> Result<(HashMap<Uuid, Vec<String>>, HashMap<String, String>), sqlx::Error> {let participant_rows = sqlx::query!(r#"SELECT channel_id, user_id@@ -97,24 +88,14 @@ async fn load_participants_and_names(.fetch_all(pool).await?;- let mut participants_by_channel: HashMap<Uuid, Vec<ChannelParticipant>> = HashMap::new();+ let mut participants_by_channel: HashMap<Uuid, Vec<String>> = HashMap::new();let mut all_user_ids: HashSet<String> = HashSet::new();- let placeholder_ts: DateTime<Utc> = DateTime::<Utc>::from_timestamp(0, 0).expect("epoch");for row in participant_rows {- let user_id = MacroUserIdStr::parse_from_str(&row.user_id)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned();- all_user_ids.insert(row.user_id);+ all_user_ids.insert(row.user_id.clone());participants_by_channel.entry(row.channel_id).or_default()- .push(ChannelParticipant {- channel_id: ChannelId(row.channel_id),- user_id,- role: ParticipantRole::Member,- joined_at: placeholder_ts,- left_at: None,- });+ .push(row.user_id);}let user_id_strings: Vec<String> = all_user_ids.into_iter().collect();@@ -130,20 +111,59 @@ async fn load_participants_and_names(.fetch_all(pool).await?;- let mut name_lookup = NameLookup::new();+ let mut name_lookup = HashMap::new();for row in name_rows {let Some(name) = display_name(row.first_name.as_deref(), row.last_name.as_deref()) else {continue;};- let user_id = MacroUserIdStr::parse_from_str(&row.user_profile_id)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned();- name_lookup.insert(user_id, name);+ name_lookup.insert(row.user_profile_id, name);}Ok((participants_by_channel, name_lookup))}+fn resolve_channel_name(+ channel_type: ChannelType,+ stored_name: Option<&str>,+ channel_id: Uuid,+ viewer_user_id: &str,+ participants: &[String],+ name_lookup: &HashMap<String, String>,+) -> String {+ if let Some(name) = stored_name.filter(|name| !name.trim().is_empty()) {+ return name.to_string();+ }++ match channel_type {+ ChannelType::Public | ChannelType::Team => format!("#{}", &channel_id.to_string()[..8]),+ ChannelType::Private => {+ let mut names: Vec<_> = participants+ .iter()+ .filter(|id| id.as_str() != viewer_user_id)+ .map(|id| display_name_for_user(id, name_lookup))+ .collect();+ names.sort();+ if names.is_empty() {+ "Private channel".to_string()+ } else {+ names.join(", ")+ }+ }+ ChannelType::DirectMessage => participants+ .iter()+ .find(|id| id.as_str() != viewer_user_id)+ .map(|id| display_name_for_user(id, name_lookup))+ .unwrap_or_else(|| "Direct message".to_string()),+ }+}++fn display_name_for_user(user_id: &str, name_lookup: &HashMap<String, String>) -> String {+ name_lookup+ .get(user_id)+ .cloned()+ .unwrap_or_else(|| user_id.to_string())+}+fn display_name(first: Option<&str>, last: Option<&str>) -> Option<String> {const NA: &str = "N/A";match (first.filter(|v| *v != NA), last.filter(|v| *v != NA)) {diff --git a/rust/cloud-storage/channels/src/outbound/mod.rs b/rust/cloud-storage/channels/src/outbound/mod.rsindex 1cdfb473f5..1864dddfb2 100644--- a/rust/cloud-storage/channels/src/outbound/mod.rs+++ b/rust/cloud-storage/channels/src/outbound/mod.rs@@ -1,3 +1,5 @@+/// Batch channel-name resolution backed by Postgres.+pub mod channel_name;/// Connection-gateway realtime adapter for channel side effects.pub mod connection_gateway_realtime;/// Contacts adapter for channel side effects.diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rsindex cbcdbaf973..52a2b2a49e 100644--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs@@ -1,25 +1,39 @@#[cfg(test)]mod tests;+#[cfg(feature = "attachment")]+use crate::domain::ports::ChannelAttachmentRepo;+#[cfg(feature = "list")]+use crate::domain::ports::{ChannelListRepo, ChannelListUserRepo};use crate::domain::{models::{Activity, ActivityType, AttachmentChannelReference, AttachmentEntityReference,AttachmentGenericReference, BotId, BotSenderProfile, ChannelAttachment,- ChannelAttachmentType, ChannelContextMessage, ChannelInfo, ChannelMessageFilters,- ChannelMessageKind, ChannelMetadata, ChannelParticipant, ChannelPreviewRow, ChannelType,- CountedReaction, CreateChannelRequest, CreateEntityMentionOptions, EntityMention,- MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,- NewChannelAttachment, ParticipantRole, PatchChannelRequest, ResolvedChannelMessage, Sender,- SimpleMention, ThreadData, ThreadReplyRow, TopLevelMessageRow,+ ChannelAttachmentType, ChannelContextMessage, ChannelInfo, ChannelListItem,+ ChannelMessageFilters, ChannelMessageKind, ChannelMetadata, ChannelParticipant,+ ChannelPreviewRow, ChannelType, ChannelWithParticipants, CountedReaction,+ CreateChannelRequest, CreateEntityMentionOptions, EntityMention, GetChannelsParams,+ LatestMessage, MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,+ NewChannelAttachment, ParticipantRole, PatchChannelRequest, RecentChannelMessage,+ ResolvedChannelMessage, Sender, SimpleMention, ThreadData, ThreadReplyRow,+ TopLevelMessageRow, UserName,},ports::{ChannelRepo, TopLevelMessagesQueryResult},};use anyhow::Context;use chrono::{DateTime, Utc};-use macro_user_id::user_id::MacroUserIdStr;+#[cfg(feature = "list")]+use filter_ast::Expr;+#[cfg(feature = "list")]+use item_filters::ast::{LiteralTree, channel::ChannelLiteral};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use models_pagination::{CreatedAt, Query};+#[cfg(feature = "list")]+use recursion::CollapsibleExt;use sqlx::{Executor, PgPool, Postgres};-use std::collections::HashMap;+#[cfg(feature = "list")]+use sqlx::{QueryBuilder, Row, postgres::PgRow};+use std::collections::{HashMap, HashSet};use uuid::Uuid;/// Postgres-backed repository for channels.@@ -614,6 +628,531 @@ fn fallback_user_name(user_id: &str) -> String {.to_string()}+#[cfg(feature = "list")]+static CHANNEL_LIST_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+"#;++#[cfg(feature = "list")]+static CHANNEL_LIST_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.team_id as "team_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.id::text DESC+ LIMIT $3+"#;++#[cfg(feature = "list")]+fn build_channel_notification_exists_clause(+ entity_id_sql: &str,+ entity_type: &str,+ predicate_sql: &str,+) -> String {+ format!(+ r#"EXISTS (+ SELECT 1+ FROM notification n+ JOIN user_notification un ON un.notification_id = n.id+ WHERE un.user_id = $1+ AND un.deleted_at IS NULL+ AND n.event_item_type = '{entity_type}'+ AND n.event_item_id = ({entity_id_sql})::text+ AND {predicate_sql}+ )"#+ )+}++#[cfg(feature = "list")]+fn build_channel_list_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}")+ }+ filter_ast::ExprFrame::Literal(ChannelLiteral::TeamId(team_id)) => {+ format!("c.team_id = '{team_id}'")+ }+ filter_ast::ExprFrame::Literal(ChannelLiteral::ChannelType(ct)) => {+ format!("c.channel_type = '{ct}'")+ }+ filter_ast::ExprFrame::Literal(ChannelLiteral::ThreadId(_))+ | filter_ast::ExprFrame::Literal(ChannelLiteral::Mention(_))+ | filter_ast::ExprFrame::Literal(ChannelLiteral::Sender(_))+ | filter_ast::ExprFrame::Literal(ChannelLiteral::Importance(true)) => String::new(),+ filter_ast::ExprFrame::Literal(ChannelLiteral::Importance(false)) => "1=0".to_string(),+ filter_ast::ExprFrame::Literal(ChannelLiteral::NotificationDone(done)) => {+ build_channel_notification_exists_clause(+ "c.id",+ "channel",+ if done {+ "un.done = true"+ } else {+ "un.done = false"+ },+ )+ }+ filter_ast::ExprFrame::Literal(ChannelLiteral::NotificationSeen(seen)) => {+ build_channel_notification_exists_clause(+ "c.id",+ "channel",+ if seen {+ "un.seen_at IS NOT NULL"+ } else {+ "un.seen_at IS NULL"+ },+ )+ }+ });+ if formatting.is_empty() {+ String::new()+ } else {+ format!(" AND {formatting}")+ }+}++#[cfg(feature = "list")]+fn build_channel_list_query(+ filter_ast: &LiteralTree<ChannelLiteral>,+) -> QueryBuilder<'_, Postgres> {+ let mut builder = QueryBuilder::new(CHANNEL_LIST_PREFIX);+ builder.push(build_channel_list_filter(filter_ast.as_deref()));+ builder.push(CHANNEL_LIST_SELECT);+ builder+}++#[cfg(feature = "list")]+struct ChannelListRow {+ id: Uuid,+ name: Option<String>,+ channel_type: ChannelType,+ org_id: Option<i64>,+ team_id: Option<Uuid>,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+ owner_id: String,+ participants_json: Option<Vec<serde_json::Value>>,+}++#[cfg(feature = "list")]+impl ChannelListRow {+ fn into_channel_with_participants(self) -> Result<ChannelWithParticipants, sqlx::Error> {+ let channel = ChannelListItem {+ id: self.id,+ name: self.name,+ channel_type: self.channel_type,+ org_id: self.org_id,+ team_id: self.team_id,+ 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<_>>()+ })+ .unwrap_or_default();++ Ok(ChannelWithParticipants {+ channel,+ participants,+ })+ }+}++#[cfg(feature = "list")]+impl ChannelListRepo for PgChannelsRepo {+ async fn get_user_channels_with_participants(+ &self,+ params: GetChannelsParams,+ ) -> Result<Vec<ChannelWithParticipants>, rootcause::Report> {+ let user_id = params.user();+ let query_limit = params.limit().map(i64::from);+ 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());++ Ok(build_channel_list_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| {+ ChannelListRow {+ id: row.try_get("id")?,+ name: row.try_get("name")?,+ channel_type: row.try_get("channel_type")?,+ org_id: row.try_get("org_id")?,+ team_id: row.try_get("team_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")?,+ }+ .into_channel_with_participants()+ })+ .fetch_all(&self.pool)+ .await?)+ }++ async fn get_latest_channel_messages_batch(+ &self,+ channel_ids: &[Uuid],+ ) -> Result<HashMap<Uuid, LatestMessage>, rootcause::Report> {+ if channel_ids.is_empty() {+ return Ok(HashMap::new());+ }++ let rows = sqlx::query!(+ r#"+ WITH input_ids AS (+ SELECT UNNEST($1::uuid[]) AS channel_id+ )+ SELECT+ i.channel_id AS "channel_id!",+ l.message_id AS "l_message_id?: uuid::Uuid",+ l.thread_id AS "l_thread_id?: uuid::Uuid",+ l.sender_id AS "l_sender_id?: String",+ l.content AS "l_content?: String",+ l.created_at AS "l_created_at?: chrono::DateTime<chrono::Utc>",+ l.updated_at AS "l_updated_at?: chrono::DateTime<chrono::Utc>",+ l.deleted_at AS "l_deleted_at?: chrono::DateTime<chrono::Utc>",+ l.mentions AS "l_mentions?: Vec<String>",+ n.message_id AS "n_message_id?: uuid::Uuid",+ n.thread_id AS "n_thread_id?: uuid::Uuid",+ n.sender_id AS "n_sender_id?: String",+ n.content AS "n_content?: String",+ n.created_at AS "n_created_at?: chrono::DateTime<chrono::Utc>",+ n.updated_at AS "n_updated_at?: chrono::DateTime<chrono::Utc>",+ n.deleted_at AS "n_deleted_at?: chrono::DateTime<chrono::Utc>",+ n.mentions AS "n_mentions?: Vec<String>"+ FROM input_ids i+ LEFT JOIN LATERAL (+ SELECT+ m.id AS message_id,+ m.thread_id,+ m.sender_id,+ m.content,+ m.created_at,+ m.updated_at,+ m.deleted_at::timestamptz AS deleted_at,+ COALESCE(+ ARRAY(+ SELECT entity_type || ':' || entity_id+ FROM comms_entity_mentions em+ WHERE em.source_entity_type = 'message'+ AND em.source_entity_id = m.id::text+ ),+ '{}'::text[]+ ) AS mentions+ FROM comms_messages m+ WHERE m.channel_id = i.channel_id+ AND m.deleted_at IS NULL+ ORDER BY m.created_at DESC+ LIMIT 1+ ) l ON TRUE+ LEFT JOIN LATERAL (+ SELECT+ m.id AS message_id,+ m.thread_id,+ m.sender_id,+ m.content,+ m.created_at,+ m.updated_at,+ m.deleted_at::timestamptz AS deleted_at,+ COALESCE(+ ARRAY(+ SELECT entity_type || ':' || entity_id+ FROM comms_entity_mentions em+ WHERE em.source_entity_type = 'message'+ AND em.source_entity_id = m.id::text+ ),+ '{}'::text[]+ ) AS mentions+ FROM comms_messages m+ WHERE m.channel_id = i.channel_id+ AND m.deleted_at IS NULL+ AND m.thread_id IS NULL+ ORDER BY m.created_at DESC+ LIMIT 1+ ) n ON TRUE+ "#,+ channel_ids+ )+ .fetch_all(&self.pool)+ .await?;++ let build_message = |message_id: Option<Uuid>,+ thread_id: Option<Uuid>,+ sender_id: Option<String>,+ content: Option<String>,+ created_at: Option<DateTime<Utc>>,+ updated_at: Option<DateTime<Utc>>,+ deleted_at: Option<DateTime<Utc>>,+ mentions: Option<Vec<String>>| {+ match (message_id, sender_id, content, created_at, updated_at) {+ (+ Some(message_id),+ Some(sender_id),+ Some(content),+ Some(created_at),+ Some(updated_at),+ ) => Some(RecentChannelMessage {+ message_id,+ thread_id,+ sender_id,+ content,+ created_at,+ updated_at,+ deleted_at,+ mentions: mentions.unwrap_or_default(),+ }),+ (None, _, _, _, _) => None,+ _ => {+ tracing::warn!("incomplete latest message row; skipping");+ None+ }+ }+ };++ Ok(rows+ .into_iter()+ .map(|row| {+ (+ row.channel_id,+ LatestMessage {+ latest_message: build_message(+ row.l_message_id,+ row.l_thread_id,+ row.l_sender_id,+ row.l_content,+ row.l_created_at,+ row.l_updated_at,+ row.l_deleted_at,+ row.l_mentions,+ ),+ latest_non_thread_message: build_message(+ row.n_message_id,+ row.n_thread_id,+ row.n_sender_id,+ row.n_content,+ row.n_created_at,+ row.n_updated_at,+ row.n_deleted_at,+ row.n_mentions,+ ),+ },+ )+ })+ .collect())+ }++ async fn get_channel_list_activities(+ &self,+ user_id: MacroUserIdStr<'_>,+ ) -> Result<Vec<Activity>, rootcause::Report> {+ Ok(sqlx::query!(+ r#"+ SELECT+ a.id as "id!: Uuid",+ a.user_id as "user_id!: String",+ a.channel_id as "channel_id!: Uuid",+ a.viewed_at as "viewed_at?: DateTime<Utc>",+ a.interacted_at as "interacted_at?: DateTime<Utc>",+ a.created_at as "created_at!: DateTime<Utc>",+ a.updated_at as "updated_at!: DateTime<Utc>"+ FROM comms_activity a+ WHERE a.user_id = $1+ ORDER BY+ GREATEST(+ COALESCE(a.viewed_at, '1970-01-01'::timestamp),+ COALESCE(a.interacted_at, '1970-01-01'::timestamp)+ ) DESC,+ a.created_at DESC+ LIMIT 100+ "#,+ user_id.as_ref()+ )+ .map(|row| Activity {+ id: row.id,+ user_id: row.user_id,+ channel_id: row.channel_id,+ created_at: row.created_at,+ updated_at: row.updated_at,+ viewed_at: row.viewed_at,+ interacted_at: row.interacted_at,+ })+ .fetch_all(&self.pool)+ .await?)+ }+}++#[cfg(feature = "list")]+impl ChannelListUserRepo for PgChannelsRepo {+ async fn get_names_for_ids(+ &self,+ ids: HashSet<MacroUserIdStr<'_>>,+ ) -> Result<Vec<UserName>, rootcause::Report> {+ let ids = ids.into_iter().map(|s| s.to_string()).collect::<Vec<_>>();+ Ok(sqlx::query!(+ r#"+ SELECT+ u.id as user_profile_id,+ mui.first_name,+ mui.last_name+ FROM macro_user_info mui+ JOIN "User" u ON mui.macro_user_id = u.macro_user_id+ WHERE u.id = ANY($1)+ "#,+ &ids+ )+ .try_map(|row| {+ Ok(UserName {+ id: MacroUserIdStr::parse_from_str(&row.user_profile_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?+ .into_owned(),+ first_name: row.first_name,+ last_name: row.last_name,+ })+ })+ .fetch_all(&self.pool)+ .await?)+ }+}++#[cfg(feature = "attachment")]+impl ChannelAttachmentRepo for PgChannelsRepo {+ type Err = anyhow::Error;++ #[tracing::instrument(skip(self), err)]+ async fn get_channel_name_for_attachment(+ &self,+ channel_id: Uuid,+ ) -> Result<Option<String>, Self::Err> {+ sqlx::query_scalar!("SELECT name FROM comms_channels WHERE id = $1", channel_id)+ .fetch_optional(&self.pool)+ .await+ .map(|row| row.flatten())+ .map_err(Into::into)+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_recent_messages_for_attachment(+ &self,+ channel_id: Uuid,+ limit: u32,+ ) -> Result<Vec<RecentChannelMessage>, Self::Err> {+ Ok(sqlx::query!(+ r#"+ SELECT+ m.id AS "message_id!",+ m.thread_id,+ m.sender_id AS "sender_id!",+ m.content AS "content!",+ m.created_at AS "created_at!",+ m.updated_at AS "updated_at!",+ m.deleted_at::timestamptz AS "deleted_at?",+ COALESCE(+ ARRAY(+ SELECT entity_type || ':' || entity_id+ FROM comms_entity_mentions em+ WHERE em.source_entity_type = 'message'+ AND em.source_entity_id = m.id::text+ ),+ '{}'::text[]+ ) AS "mentions!"+ FROM comms_messages m+ WHERE m.channel_id = $1+ AND m.deleted_at IS NULL+ ORDER BY m.created_at DESC+ LIMIT $2+ "#,+ channel_id,+ i64::from(limit)+ )+ .map(|row| RecentChannelMessage {+ message_id: row.message_id,+ thread_id: row.thread_id,+ sender_id: row.sender_id,+ content: row.content,+ created_at: row.created_at,+ updated_at: row.updated_at,+ deleted_at: row.deleted_at,+ mentions: row.mentions,+ })+ .fetch_all(&self.pool)+ .await?)+ }+}+impl ChannelRepo for PgChannelsRepo {type Err = anyhow::Error;diff --git a/rust/cloud-storage/comms/Cargo.toml b/rust/cloud-storage/comms/Cargo.tomldeleted file mode 100644index 31f76356f6..0000000000--- a/rust/cloud-storage/comms/Cargo.toml+++ /dev/null@@ -1,51 +0,0 @@-[package]-edition = "2024"-name = "comms"-publish = false-version = "0.1.0"--[features]-attachment = [- "dep:anyhow",- "dep:attachment",- "dep:entity_access",- "dep:futures",- "dep:non_empty",-]-inbound = ["dep:axum", "dep:model_user", "dep:utoipa"]-outbound = ["dep:readonly_pool", "dep:sqlx"]---[dependencies]-anyhow = { workspace = true, optional = true }-attachment = { path = "../attachment", optional = true }-entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["ports"] }-futures = { workspace = true, optional = true }-non_empty = { path = "../non_empty", optional = true }-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" }-model-entity = { path = "../model-entity" }-model_user = { path = "../model_user", optional = true, features = ["axum"] }-models_comms = { path = "../models_comms" }-models_pagination = { path = "../models_pagination" }-readonly_pool = { path = "../readonly_pool", optional = true }-recursion = { workspace = true }-rootcause = { workspace = true }-serde = { workspace = true }-serde_json = { workspace = true }-sqlx = { workspace = true, optional = true }-thiserror = { workspace = true }-tokio = { workspace = true }-tracing = { workspace = true }-utoipa = { workspace = true, optional = true }-uuid = { workspace = true }-workspace-hack = { version = "0.1", path = "../workspace-hack" }--[dev-dependencies]-anyhow = { workspace = true }-macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/rust/cloud-storage/comms/justfile b/rust/cloud-storage/comms/justfiledeleted file mode 100644index fad4a0c048..0000000000--- a/rust/cloud-storage/comms/justfile+++ /dev/null@@ -1,6 +0,0 @@-import '../database.just'--mod sqlx '../sqlx.just'--prepare_db:- just sqlx::prepare_db {{ DATABASE_URL }}diff --git a/rust/cloud-storage/comms/src/domain.rs b/rust/cloud-storage/comms/src/domain.rsdeleted file mode 100644index 901e625fda..0000000000--- a/rust/cloud-storage/comms/src/domain.rs+++ /dev/null@@ -1,3 +0,0 @@-pub mod models;-pub mod ports;-pub mod service;diff --git a/rust/cloud-storage/comms/src/domain/models.rs b/rust/cloud-storage/comms/src/domain/models.rsdeleted file mode 100644index 952bb514c0..0000000000--- a/rust/cloud-storage/comms/src/domain/models.rs+++ /dev/null@@ -1,77 +0,0 @@-use item_filters::ast::{LiteralTree, channel::ChannelLiteral};-use macro_user_id::user_id::MacroUserIdStr;-pub use models_comms::channel;-use models_pagination::{Query, SimpleSortMethod};-use serde::Deserialize;-use uuid::Uuid;--pub mod channel_name;--pub struct ChannelPreviewsRequest<'a> {- pub channel_ids: &'a [Uuid],- pub user: MacroUserIdStr<'a>,- pub organization_id: Option<channel::OrganizationId>,-}--#[derive(Debug, Deserialize)]-pub struct UserName {- pub id: MacroUserIdStr<'static>,- pub first_name: Option<String>,- pub last_name: Option<String>,-}--impl UserName {- /// attempt to create the "pretty" name for this user- /// this can return None if the first name and last name dont exist- /// or if they are set to "N/A" which is apparrently something that can happen- pub fn display_name(&self) -> Option<String> {- const NA: &str = "N/A";- match (- self.first_name.as_deref().filter(|v| *v != NA),- self.last_name.as_deref().filter(|v| *v != NA),- ) {- (None, None) => None,- (None, Some(last)) => Some(last.to_string()),- (Some(first), None) => Some(first.to_string()),- (Some(first), Some(last)) => Some(format!("{first} {last}")),- }- }-}--#[derive(Debug)]-pub struct GetChannelsRequest {- pub macro_id: MacroUserIdStr<'static>,- pub limit: Option<u32>,- pub query: Query<Uuid, SimpleSortMethod, LiteralTree<ChannelLiteral>>,-}--impl GetChannelsRequest {- pub fn into_params(self) -> GetChannelsParams {- GetChannelsParams {- macro_id: self.macro_id,- limit: self.limit,- query: self.query,- }- }-}--#[derive(Debug)]-pub struct GetChannelsParams {- macro_id: MacroUserIdStr<'static>,- limit: Option<u32>,- query: Query<Uuid, SimpleSortMethod, LiteralTree<ChannelLiteral>>,-}--impl GetChannelsParams {- pub fn user(&self) -> &MacroUserIdStr<'static> {- &self.macro_id- }-- pub fn limit(&self) -> Option<u32> {- self.limit- }-- pub fn query(&self) -> &Query<Uuid, SimpleSortMethod, LiteralTree<ChannelLiteral>> {- &self.query- }-}diff --git a/rust/cloud-storage/comms/src/domain/models/channel_name.rs b/rust/cloud-storage/comms/src/domain/models/channel_name.rsdeleted file mode 100644index 5a7909afc5..0000000000--- a/rust/cloud-storage/comms/src/domain/models/channel_name.rs+++ /dev/null@@ -1,104 +0,0 @@-use macro_user_id::{cowlike::CowLike, email::ReadEmailParts, user_id::MacroUserIdStr};-use models_comms::channel::{ChannelId, ChannelParticipant, ChannelType};-use std::collections::HashMap;-use uuid::Uuid;--pub type ChannelName = String;-pub type NameLookup = HashMap<MacroUserIdStr<'static>, String>;--#[cfg(test)]-mod tests;--#[tracing::instrument(skip_all)]-pub fn resolve_channel_name(- channel_type: &ChannelType,- channel_name: Option<&str>,- participants: &[ChannelParticipant],- channel_id: &ChannelId,- user_id: MacroUserIdStr<'_>,- name_lookup: &NameLookup,-) -> ChannelName {- match channel_type {- ChannelType::Public => channel_name- .map(|name| name.to_string())- .unwrap_or_else(|| {- tracing::warn!(channel_id=?channel_id, "public channel should have a name");- "Public".to_string()- }),- ChannelType::Private => {- resolve_private_channel_name(channel_name, participants, name_lookup)- }- ChannelType::DirectMessage => match resolve_direct_message_channel_name(- channel_name,- participants,- &channel_id.0,- user_id,- name_lookup,- ) {- Ok(c) | Err(c) => c,- },- ChannelType::Team => channel_name- .map(|name| name.to_string())- .unwrap_or_else(|| {- tracing::warn!(channel_id=?channel_id, "team channel should have a name");- "Team".to_string()- }),- }-}--pub fn resolve_private_channel_name(- channel_name: Option<&str>,- participants: &[ChannelParticipant],- name_lookup: &NameLookup,-) -> ChannelName {- if let Some(name) = &channel_name- && !name.trim().is_empty()- {- return name.to_string();- }-- participants- .iter()- .map(|p| id_to_display_name(p.user_id.copied(), name_lookup))- .collect::<Vec<String>>()- .join(", ")-}--#[tracing::instrument(err)]-pub fn resolve_direct_message_channel_name(- channel_name: Option<&str>,- participants: &[ChannelParticipant],- channel_id: &Uuid,- user_id: MacroUserIdStr<'_>,- name_lookup: &NameLookup,-) -> Result<ChannelName, ChannelName> {- // Direct Message Channels should not have a name- if channel_name.is_some() {- tracing::warn!(channel_id=?channel_id, "direct message channel should not have a name");- }-- if !participants.iter().any(|p| p.user_id == user_id) {- return Ok(resolve_private_channel_name(- channel_name,- participants,- name_lookup,- ));- }-- let other_participant = participants.iter().find(|p| p.user_id != user_id);-- if let Some(other) = other_participant {- Ok(id_to_display_name(other.user_id.copied(), name_lookup))- } else {- tracing::warn!("{participants:?}");-- Err("Unknown".to_string())- }-}--fn id_to_display_name(id: MacroUserIdStr<'_>, name_lookup: &NameLookup) -> String {- match name_lookup.get(&id) {- Some(name) if !name.trim().is_empty() => name.clone(),- _ => id.email_part().local_part().to_string(),- }-}diff --git a/rust/cloud-storage/comms/src/domain/models/channel_name/tests.rs b/rust/cloud-storage/comms/src/domain/models/channel_name/tests.rsdeleted file mode 100644index 5ea6921629..0000000000--- a/rust/cloud-storage/comms/src/domain/models/channel_name/tests.rs+++ /dev/null@@ -1,187 +0,0 @@-use super::*;-use macro_user_id::user_id::MacroUserIdStr;-use models_comms::channel::{Channel, ChannelId, ChannelType};-use uuid::Uuid;--fn make_participants(channel_id: &Uuid) -> Vec<ChannelParticipant> {- vec![- ChannelParticipant {- channel_id: ChannelId(channel_id.to_owned()),- user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- role: models_comms::channel::ParticipantRole::Owner,- joined_at: chrono::Utc::now(),- left_at: None,- },- ChannelParticipant {- channel_id: ChannelId(channel_id.to_owned()),- user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- role: models_comms::channel::ParticipantRole::Member,- joined_at: chrono::Utc::now(),- left_at: None,- },- ]-}--#[test]-fn test_resolve_private_channel_name() {- let channel_with_name = Channel {- id: ChannelId(Uuid::default()),- name: Some("test".to_string()),- channel_type: ChannelType::Private,- org_id: None,- team_id: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- };-- let channel_without_name = Channel {- id: ChannelId(Uuid::default()),- name: None,- channel_type: ChannelType::Private,- org_id: None,- team_id: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- };-- let participants_with_name = make_participants(&channel_with_name.id.0);- let participants_without_name = make_participants(&channel_without_name.id.0);-- assert_eq!(- resolve_private_channel_name(- channel_with_name.name.as_deref(),- &participants_with_name,- &Default::default()- ),- "test"- );- assert_eq!(- resolve_private_channel_name(- channel_without_name.name.as_deref(),- &participants_without_name,- &Default::default()- ),- "user1, user2"- );-}--#[test]-fn test_resolve_direct_message_channel_name() {- let direct_message_channel = Channel {- id: ChannelId(Default::default()),- name: None,- channel_type: ChannelType::DirectMessage,- org_id: None,- team_id: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- };-- let participants = make_participants(&direct_message_channel.id.0);-- assert_eq!(- resolve_direct_message_channel_name(- direct_message_channel.name.as_deref(),- &participants,- &direct_message_channel.id.0,- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- &Default::default()- )- .as_deref(),- Ok("user2")- );-}--#[test]-fn test_resolve_direct_message_channel_name_for_other() {- let direct_message_channel = Channel {- id: ChannelId(Default::default()),- name: None,- channel_type: ChannelType::DirectMessage,- org_id: None,- team_id: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- };-- // Test the preview for a user who is not in the channel- let participants = make_participants(&direct_message_channel.id.0);-- assert_eq!(- resolve_direct_message_channel_name(- direct_message_channel.name.as_deref(),- &participants,- &direct_message_channel.id.0,- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- &Default::default()- )- .as_deref(),- Ok("user1, user2")- );-}--#[test]-fn test_resolve_direct_message_channel_name_whitespace_only_display_name() {- let channel = Channel {- id: ChannelId(Default::default()),- name: None,- channel_type: ChannelType::DirectMessage,- org_id: None,- team_id: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- };-- let participants = make_participants(&channel.id.0);-- let mut name_lookup = NameLookup::new();- name_lookup.insert(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- " ".to_string(),- );-- assert_eq!(- resolve_direct_message_channel_name(- channel.name.as_deref(),- &participants,- &channel.id.0,- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- &name_lookup- )- .as_deref(),- Ok("user2")- );-}--#[test]-fn test_resolve_public_channel_name() {- let public_channel = Channel {- id: ChannelId(Default::default()),- name: Some("public_channel".to_string()),- channel_type: ChannelType::Public,- org_id: None,- team_id: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- };-- let participants = make_participants(&public_channel.id.0);-- assert_eq!(- resolve_channel_name(- &public_channel.channel_type,- public_channel.name.as_deref(),- &participants,- &public_channel.id,- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- &Default::default()- ),- "public_channel"- );-}diff --git a/rust/cloud-storage/comms/src/domain/ports.rs b/rust/cloud-storage/comms/src/domain/ports.rsdeleted file mode 100644index 7d595d04aa..0000000000--- a/rust/cloud-storage/comms/src/domain/ports.rs+++ /dev/null@@ -1,61 +0,0 @@-use std::collections::{HashMap, HashSet};--use macro_user_id::user_id::MacroUserIdStr;-use models_comms::channel::{- Activity, ChannelId, ChannelMessage, ChannelWithLatest, ChannelWithParticipants, LatestMessage,-};-use rootcause::Report;--use crate::domain::models::{GetChannelsParams, GetChannelsRequest, UserName};--pub trait CommsRepo: Send + Sync + 'static {- fn get_user_channels_with_participants(- &self,- req: GetChannelsParams,- ) -> impl Future<Output = Result<Vec<ChannelWithParticipants>, Report>> + Send;-- fn get_latest_channel_messages_batch(- &self,- channels: &[ChannelId],- ) -> impl Future<Output = Result<HashMap<ChannelId, LatestMessage>, Report>> + Send;-- fn get_activities(- &self,- user_id: MacroUserIdStr<'_>,- ) -> impl Future<Output = Result<Vec<Activity>, Report>> + Send;-- fn get_channel_name(- &self,- channel_id: ChannelId,- ) -> impl Future<Output = Result<Option<String>, Report>> + Send;-- fn get_recent_messages(- &self,- channel_id: ChannelId,- limit: u32,- ) -> impl Future<Output = Result<Vec<ChannelMessage>, Report>> + Send;-}--pub trait UserRepo: Send + Sync + 'static {- fn get_names_for_ids(- &self,- names: HashSet<MacroUserIdStr<'_>>,- ) -> impl Future<Output = Result<Vec<UserName>, Report>> + Send;-}--pub trait ChannelsService: Send + Sync + 'static {- fn get_channels(- &self,- req: GetChannelsRequest,- ) -> impl Future<Output = Result<Vec<ChannelWithLatest>, Report>> + Send;-- fn get_activities(- &self,- user: MacroUserIdStr<'_>,- ) -> impl Future<Output = Result<Vec<Activity>, Report>> + Send;-- fn get_names(- &self,- names: HashSet<MacroUserIdStr<'_>>,- ) -> impl Future<Output = Result<Vec<UserName>, Report>> + Send;-}diff --git a/rust/cloud-storage/comms/src/domain/service.rs b/rust/cloud-storage/comms/src/domain/service.rsdeleted file mode 100644index 1398355f53..0000000000--- a/rust/cloud-storage/comms/src/domain/service.rs+++ /dev/null@@ -1,145 +0,0 @@-use std::{- collections::{HashMap, HashSet},- str::FromStr,-};--use frecency::domain::{models::AggregateFrecency, ports::AggregateFrecencyStorage};-use macro_user_id::cowlike::CowLike;-use model_entity::EntityType;-use models_comms::channel::{Activity, ChannelId, ChannelWithLatest};-use uuid::Uuid;--use crate::domain::{- models::{GetChannelsRequest, channel_name::resolve_channel_name},- ports::{ChannelsService, CommsRepo, UserRepo},-};--pub struct ChannelServiceImpl<Comms, Auth, Frec> {- comms: Comms,- auth: Auth,- frecency: Frec,-}--impl<Comms, Auth, Frec> ChannelServiceImpl<Comms, Auth, Frec>-where- Comms: CommsRepo,- Auth: UserRepo,- Frec: AggregateFrecencyStorage,-{- pub fn new(comms: Comms, auth: Auth, frecency: Frec) -> Self {- ChannelServiceImpl {- comms,- auth,- frecency,- }- }-}--impl<Comms, Auth, Frec> ChannelsService for ChannelServiceImpl<Comms, Auth, Frec>-where- Comms: CommsRepo,- Auth: UserRepo,- Frec: AggregateFrecencyStorage,-{- #[tracing::instrument(err, skip(self))]- async fn get_channels(- &self,- req: GetChannelsRequest,- ) -> Result<Vec<models_comms::channel::ChannelWithLatest>, rootcause::Report> {- let params = req.into_params();- let user = params.user().clone();-- let channels = self- .comms- .get_user_channels_with_participants(params)- .await?;-- let channel_entities: Vec<_> = channels- .iter()- .map(|chan| EntityType::Channel.with_entity_string(chan.channel.id.0.to_string()))- .collect();-- let channel_ids: Vec<_> = channels.iter().map(|chan| chan.channel.id).collect();-- let participant_ids: HashSet<_> = channels- .iter()- .flat_map(|chan| chan.participants.iter().map(|p| p.user_id.copied()))- .collect();-- let (names, latest_messages, activities, frecency) = tokio::join!(- self.auth.get_names_for_ids(participant_ids),- self.comms.get_latest_channel_messages_batch(&channel_ids),- self.comms.get_activities(user.copied()),- self.frecency- .get_aggregate_for_user_entities(user.clone(), channel_entities.as_slice())- );-- let mut activity_lookup: HashMap<ChannelId, Activity> = activities- .unwrap_or_default()- .into_iter()- .map(|a| (a.channel_id, a))- .collect();-- let mut frecency_map: HashMap<ChannelId, AggregateFrecency> = frecency- .unwrap_or_default()- .into_iter()- .filter_map(|f| Some((ChannelId(Uuid::from_str(&f.id.entity.entity_id).ok()?), f)))- .collect();-- let name_lookup = names.map(|n| {- n.into_iter()- .filter_map(|n| {- let display = n.display_name()?;- Some((n.id, display))- })- .collect::<HashMap<_, _>>()- })?;-- let mut latest_messages = latest_messages?;-- // Map a channel to its correct name and latest message- let channels: Vec<ChannelWithLatest> = channels- .into_iter()- .map(|mut channel| {- let resolved_name = resolve_channel_name(- &channel.channel.channel_type,- channel.channel.name.as_deref(),- &channel.participants,- &channel.channel.id,- user.copied(),- &name_lookup,- );- channel.channel.name = Some(resolved_name);- let activity = activity_lookup.remove(&channel.channel.id);- let viewed_at = activity.as_ref().and_then(|a| a.viewed_at);- let interacted_at = activity.as_ref().and_then(|a| a.interacted_at);- let channel_with_latest = ChannelWithLatest {- channel: channel.clone(),- latest_message: latest_messages.remove(&channel.channel.id).unwrap_or_default(),- viewed_at,- interacted_at,- frecency_score: frecency_map.remove(&channel.channel.id)- };-- tracing::trace!(channel_type=?channel.channel.channel_type,channel_name=?channel.channel.name, "resolved channel name");- channel_with_latest- })- .collect();-- Ok(channels)- }-- fn get_activities(- &self,- user: macro_user_id::user_id::MacroUserIdStr<'_>,- ) -> impl Future<Output = Result<Vec<Activity>, rootcause::Report>> + Send {- self.comms.get_activities(user)- }-- fn get_names(- &self,- names: HashSet<macro_user_id::user_id::MacroUserIdStr<'_>>,- ) -> impl Future<Output = Result<Vec<super::models::UserName>, rootcause::Report>> + Send {- self.auth.get_names_for_ids(names)- }-}diff --git a/rust/cloud-storage/comms/src/inbound.rs b/rust/cloud-storage/comms/src/inbound.rsdeleted file mode 100644index 3ad0edd2ca..0000000000--- a/rust/cloud-storage/comms/src/inbound.rs+++ /dev/null@@ -1,4 +0,0 @@-#[cfg(feature = "attachment")]-pub mod attachment;-#[cfg(feature = "inbound")]-pub mod router;diff --git a/rust/cloud-storage/comms/src/inbound/router.rs b/rust/cloud-storage/comms/src/inbound/router.rsdeleted file mode 100644index a2356f452b..0000000000--- a/rust/cloud-storage/comms/src/inbound/router.rs+++ /dev/null@@ -1,231 +0,0 @@-use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::get};-use doppleganger::{Doppleganger, Mirror};-use frecency::domain::models::AggregateFrecency;-use macro_user_id::user_id::MacroUserIdStr;-use model_user::axum_extractor::MacroUserExtractor;-use models_comms::channel::{ChannelId, OrganizationId};-use serde::Serialize;-use std::sync::Arc;-use thiserror::Error;-use utoipa::ToSchema;-use uuid::Uuid;--use crate::domain::{models::GetChannelsRequest, ports::ChannelsService};--pub struct CommsRouterState<S> {- pub inner: Arc<S>,-}--impl<S> Clone for CommsRouterState<S> {- fn clone(&self) -> Self {- Self {- inner: Arc::clone(&self.inner),- }- }-}--impl<S: ChannelsService> CommsRouterState<S> {- pub fn new(s: S) -> Self {- CommsRouterState { inner: Arc::new(s) }- }-}--pub fn comms_router<S: ChannelsService, T: Send + Sync + 'static>(- s: CommsRouterState<S>,-) -> Router<T> {- Router::new()- .route("/channels", get(get_channels_handler))- .route("/activity", get(get_activity_handler))- .with_state(s)-}--#[derive(Debug, Error)]-pub enum CommsErr {- #[error("Internal server error")]- Internal,-}--impl IntoResponse for CommsErr {- fn into_response(self) -> axum::response::Response {- let status = match self {- CommsErr::Internal => StatusCode::INTERNAL_SERVER_ERROR,- };-- (status, self.to_string()).into_response()- }-}--#[utoipa::path(- get,- path = "/channels",- tag = "channels",- operation_id = "get_channels",- responses(- (status = 200, body=Vec<ApiChannelWithLatest>),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String),- )-)]-async fn get_channels_handler<S: ChannelsService>(- State(service): State<CommsRouterState<S>>,- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,-) -> Result<Json<Vec<ApiChannelWithLatest>>, CommsErr> {- let res = service- .inner- .get_channels(GetChannelsRequest {- macro_id: macro_user_id,- limit: None,- query: models_pagination::Query::Sort(- models_pagination::SimpleSortMethod::UpdatedAt,- None,- ),- })- .await- .map_err(|_| CommsErr::Internal)?;-- Ok(Json(<Vec<ApiChannelWithLatest>>::mirror(res)))-}--#[tracing::instrument(skip(service))]-#[utoipa::path(get,- tag = "activity",- operation_id = "get_activity",- path = "/activity", responses(- (status = 200, body=Vec<ApiActivity>),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String),-))]-pub async fn get_activity_handler<S: ChannelsService>(- State(service): State<CommsRouterState<S>>,- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,-) -> Result<Json<Vec<ApiActivity>>, CommsErr> {- let res = service- .inner- .get_activities(macro_user_id)- .await- .map_err(|_| CommsErr::Internal)?;-- Ok(Json(<Vec<ApiActivity>>::mirror(res)))-}--#[derive(Debug, Clone, Copy, Serialize, ToSchema, Doppleganger)]-#[serde(rename_all = "snake_case")]-#[dg(backward = models_comms::channel::ParticipantRole)]-pub enum ParticipantRole {- Owner,- Admin,- Member,-}--#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]-#[dg(backward = models_comms::channel::ChannelParticipant)]-pub struct ChannelParticipant {- /// id of the channel- #[schema(value_type = Uuid)]- pub channel_id: ChannelId,- /// id of the user- #[schema(value_type = String)]- pub user_id: MacroUserIdStr<'static>,- /// type of the participant- pub role: ParticipantRole,- /// timestamp of when the user joined the channel- pub joined_at: chrono::DateTime<chrono::Utc>,- /// timestamp of when the user left the channel- pub left_at: Option<chrono::DateTime<chrono::Utc>>,-}--#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]-#[dg(backward = models_comms::channel::ChannelWithParticipants)]-pub struct ChannelWithParticipants {- #[serde(flatten)]- pub channel: Channel,- pub participants: Vec<ChannelParticipant>,-}--#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]-#[dg(backward = models_comms::channel::ChannelWithLatest)]-pub struct ApiChannelWithLatest {- #[serde(flatten)]- pub channel: ChannelWithParticipants,- #[serde(flatten)]- pub latest_message: LatestMessage,- pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,- pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,- #[dg(map = map_frecency)]- pub frecency_score: Option<f64>,-}--fn map_frecency(f: Option<AggregateFrecency>) -> Option<f64> {- f.map(|f| f.data.frecency_score)-}--#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]-#[dg(backward = models_comms::channel::Channel)]-pub struct Channel {- /// uuid of the channel- #[schema(value_type = Uuid)]- pub id: ChannelId,- /// string name of the channel- pub name: Option<String>,- /// type of the channel- pub channel_type: ChannelType,- /// id of the organization this channel belongs too- #[schema(value_type = Option<u32>)]- pub org_id: Option<OrganizationId>,- /// timestamp of when the channel was created- pub created_at: chrono::DateTime<chrono::Utc>,- /// timestamp of when the channel was last updated- pub updated_at: chrono::DateTime<chrono::Utc>,- /// id of the user who created the channel- #[schema(value_type = String)]- pub owner_id: MacroUserIdStr<'static>,-}--#[derive(Debug, Clone, ToSchema, Serialize, Doppleganger)]-#[dg(backward = models_comms::channel::LatestMessage)]-pub struct LatestMessage {- pub latest_message: Option<ChannelMessage>,- pub latest_non_thread_message: Option<ChannelMessage>,-}--#[derive(Debug, Clone, Copy, Serialize, Doppleganger, ToSchema)]-#[dg(backward = models_comms::channel::ChannelType)]-#[serde(rename_all = "snake_case")]-pub enum ChannelType {- Public,- Private,- DirectMessage,- Team,-}--#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]-#[dg(backward = models_comms::channel::ChannelMessage)]-pub struct ChannelMessage {- pub message_id: Uuid,- pub thread_id: Option<Uuid>,- pub sender_id: String,- pub content: String,- pub created_at: chrono::DateTime<chrono::Utc>,- pub updated_at: chrono::DateTime<chrono::Utc>,- pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,- /// message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`- pub mentions: Vec<String>,-}--#[derive(Debug, ToSchema, Doppleganger, Serialize)]-#[dg(backward = models_comms::channel::Activity)]-pub struct ApiActivity {- pub id: Uuid,- pub user_id: String,- #[schema(value_type = Uuid)]- pub channel_id: ChannelId,- pub created_at: chrono::DateTime<chrono::Utc>,- pub updated_at: chrono::DateTime<chrono::Utc>,- /// the last time the user viewed the channel- pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,- /// the last time the user intereacted with the channel- /// eg. reacting, replying, sending a message- pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,-}diff --git a/rust/cloud-storage/comms/src/lib.rs b/rust/cloud-storage/comms/src/lib.rsdeleted file mode 100644index 5702002c94..0000000000--- a/rust/cloud-storage/comms/src/lib.rs+++ /dev/null@@ -1,5 +0,0 @@-pub mod domain;-#[cfg(any(feature = "inbound", feature = "attachment"))]-pub mod inbound;-#[cfg(feature = "outbound")]-pub mod outbound;diff --git a/rust/cloud-storage/comms/src/outbound.rs b/rust/cloud-storage/comms/src/outbound.rsdeleted file mode 100644index 26e9103cd5..0000000000--- a/rust/cloud-storage/comms/src/outbound.rs+++ /dev/null@@ -1 +0,0 @@-pub mod postgres;diff --git a/rust/cloud-storage/comms/src/outbound/fixtures/channels.sql b/rust/cloud-storage/comms/src/outbound/fixtures/channels.sqldeleted file mode 100644index f1242b9145..0000000000--- a/rust/cloud-storage/comms/src/outbound/fixtures/channels.sql+++ /dev/null@@ -1,55 +0,0 @@--- Channels for dynamic query tests-INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id, created_at, updated_at)-VALUES- ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Private Channel A', 'private', NULL, 'macro|[email protected]', '2024-01-01 10:00:00', '2024-01-10 10:00:00'),- ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Private Channel B', 'private', NULL, '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');---- Notifications for channel notification filter tests-INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)-VALUES- ('eeeeeeea-0000-0000-0000-000000000001', 'test', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'channel', 'test', '{}'::jsonb, 'macro|[email protected]'),- ('eeeeeeeb-0000-0000-0000-000000000002', 'test', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'channel', 'test', '{}'::jsonb, 'macro|[email protected]');--INSERT INTO user_notification (user_id, notification_id, created_at, seen_at, done)-VALUES- -- Channel A: not done + unread- ('macro|[email protected]', 'eeeeeeea-0000-0000-0000-000000000001', '2024-01-05 10:00:00', NULL, false),- -- Channel B: done + seen- ('macro|[email protected]', 'eeeeeeeb-0000-0000-0000-000000000002', '2024-01-05 10:01:00', '2024-01-05 11:00:00', true);---- 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/fixtures/users.sql b/rust/cloud-storage/comms/src/outbound/fixtures/users.sqldeleted file mode 100644index 2b1499f73e..0000000000--- a/rust/cloud-storage/comms/src/outbound/fixtures/users.sql+++ /dev/null@@ -1,20 +0,0 @@--- Test fixture for PgUserRepo tests--- Inserts test users with associated user info---- First insert into macro_user (parent table for both User and macro_user_info)-INSERT INTO "macro_user" (id, username, email, stripe_customer_id) VALUES- ('11111111-1111-1111-1111-111111111111', 'user1', '[email protected]', 'stripe_1'),- ('22222222-2222-2222-2222-222222222222', 'user2', '[email protected]', 'stripe_2'),- ('33333333-3333-3333-3333-333333333333', 'user3', '[email protected]', 'stripe_3');---- Insert user info (first_name, last_name)-INSERT INTO "macro_user_info" (macro_user_id, first_name, last_name) VALUES- ('11111111-1111-1111-1111-111111111111', 'John', 'Doe'),- ('22222222-2222-2222-2222-222222222222', NULL, NULL),- ('33333333-3333-3333-3333-333333333333', 'Jane', 'Smith');---- Insert User records (id format: macro|{EMAIL})-INSERT INTO "User" (id, email, macro_user_id) VALUES- ('macro|[email protected]', '[email protected]', '11111111-1111-1111-1111-111111111111'),- ('macro|[email protected]', '[email protected]', '22222222-2222-2222-2222-222222222222'),- ('macro|[email protected]', '[email protected]', '33333333-3333-3333-3333-333333333333');diff --git a/rust/cloud-storage/comms/src/outbound/http.rs b/rust/cloud-storage/comms/src/outbound/http.rsdeleted file mode 100644index cf6231f423..0000000000--- a/rust/cloud-storage/comms/src/outbound/http.rs+++ /dev/null@@ -1 +0,0 @@-pub mod user_repo;diff --git a/rust/cloud-storage/comms/src/outbound/postgres.rs b/rust/cloud-storage/comms/src/outbound/postgres.rsdeleted file mode 100644index 0e4d55e7da..0000000000--- a/rust/cloud-storage/comms/src/outbound/postgres.rs+++ /dev/null@@ -1,3 +0,0 @@-pub mod channel_name;-pub mod comms_repo;-pub mod user_repo;diff --git a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rsdeleted file mode 100644index bd09e5af28..0000000000--- a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs+++ /dev/null@@ -1,431 +0,0 @@-use crate::domain::models::GetChannelsParams;-use crate::domain::ports::CommsRepo;-use chrono::DateTime;-use chrono::Utc;-use doppleganger::{Doppleganger, Mirror};-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use models_comms::channel::{- Activity, Channel, ChannelId, ChannelMessage, ChannelParticipant, ChannelWithParticipants,- LatestMessage, OrganizationId,-};-use rootcause::Report;-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)]-pub enum ChannelType {- Public,- Private,- DirectMessage,- Team,-}--#[tracing::instrument(skip(db))]-pub async fn get_user_channels_with_participants(- db: &PgPool,- user_id: &str,-) -> Result<Vec<ChannelWithParticipants>, sqlx::Error> {- sqlx::query!(- 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- ),- 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!: ChannelType",- uc.team_id,- uc.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- ORDER BY uc.created_at DESC- "#,- user_id- )- .try_map(|row| {- let channel = Channel {- id: ChannelId(row.id),- name: row.name,- channel_type: ChannelType::mirror(row.channel_type),- org_id: row.org_id.map(|id| OrganizationId(id as u32)),- team_id: row.team_id,- created_at: row.created_at,- updated_at: row.updated_at,- owner_id: MacroUserIdStr::parse_from_str(&row.owner_id)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),- };-- let participants = row- .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,- })- })- .fetch_all(db)- .await-}--#[tracing::instrument(err)]-pub async fn get_latest_channel_messages_batch(- pool: &PgPool,- channel_ids: &[ChannelId],-) -> Result<HashMap<ChannelId, LatestMessage>, Report> {- if channel_ids.is_empty() {- return Ok(HashMap::new());- }-- let ids: Vec<Uuid> = channel_ids.iter().map(|x| x.0).collect();-- let rows = sqlx::query!(- r#"- WITH input_ids AS (- SELECT UNNEST($1::uuid[]) AS channel_id- )- SELECT- i.channel_id AS "channel_id!",- l.message_id AS "l_message_id?: uuid::Uuid",- l.thread_id AS "l_thread_id?: uuid::Uuid",- l.sender_id AS "l_sender_id?: String",- l.content AS "l_content?: String",- l.created_at AS "l_created_at?: chrono::DateTime<chrono::Utc>",- l.updated_at AS "l_updated_at?: chrono::DateTime<chrono::Utc>",- l.deleted_at AS "l_deleted_at?: chrono::DateTime<chrono::Utc>",- l.mentions AS "l_mentions?: Vec<String>",- n.message_id AS "n_message_id?: uuid::Uuid",- n.thread_id AS "n_thread_id?: uuid::Uuid",- n.sender_id AS "n_sender_id?: String",- n.content AS "n_content?: String",- n.created_at AS "n_created_at?: chrono::DateTime<chrono::Utc>",- n.updated_at AS "n_updated_at?: chrono::DateTime<chrono::Utc>",- n.deleted_at AS "n_deleted_at?: chrono::DateTime<chrono::Utc>",- n.mentions AS "n_mentions?: Vec<String>"- FROM input_ids i- LEFT JOIN LATERAL (- SELECT- m.id AS message_id,- m.thread_id,- m.sender_id,- m.content,- m.created_at,- m.updated_at,- m.deleted_at::timestamptz AS deleted_at,- COALESCE(- ARRAY(- SELECT entity_type || ':' || entity_id- FROM comms_entity_mentions em- WHERE em.source_entity_type = 'message'- AND em.source_entity_id = m.id::text- ),- '{}'::text[]- ) AS mentions- FROM comms_messages m- WHERE m.channel_id = i.channel_id- AND m.deleted_at IS NULL- ORDER BY m.created_at DESC- LIMIT 1- ) l ON TRUE- LEFT JOIN LATERAL (- SELECT- m.id AS message_id,- m.thread_id,- m.sender_id,- m.content,- m.created_at,- m.updated_at,- m.deleted_at::timestamptz AS deleted_at,- COALESCE(- ARRAY(- SELECT entity_type || ':' || entity_id- FROM comms_entity_mentions em- WHERE em.source_entity_type = 'message'- AND em.source_entity_id = m.id::text- ),- '{}'::text[]- ) AS mentions- FROM comms_messages m- WHERE m.channel_id = i.channel_id- AND m.deleted_at IS NULL- AND m.thread_id IS NULL- ORDER BY m.created_at DESC- LIMIT 1- ) n ON TRUE- "#,- &ids- )- .fetch_all(pool)- .await?;-- let mut result = HashMap::with_capacity(rows.len());-- let build_message = |message_id: Option<Uuid>,- thread_id: Option<Uuid>,- sender_id: Option<String>,- content: Option<String>,- created_at: Option<chrono::DateTime<chrono::Utc>>,- updated_at: Option<chrono::DateTime<chrono::Utc>>,- deleted_at: Option<chrono::DateTime<chrono::Utc>>,- mentions: Option<Vec<String>>| {- match (message_id, sender_id, content, created_at, updated_at) {- (- Some(message_id),- Some(sender_id),- Some(content),- Some(created_at),- Some(updated_at),- ) => Some(ChannelMessage {- message_id,- thread_id,- sender_id,- content,- created_at,- updated_at,- deleted_at,- mentions: mentions.unwrap_or_default(),- }),- (None, _, _, _, _) => None,- _ => {- tracing::warn!("incomplete latest message row; skipping");- None- }- }- };-- for row in rows {- let latest_message = build_message(- row.l_message_id,- row.l_thread_id,- row.l_sender_id,- row.l_content,- row.l_created_at,- row.l_updated_at,- row.l_deleted_at,- row.l_mentions,- );-- let latest_non_thread_message = build_message(- row.n_message_id,- row.n_thread_id,- row.n_sender_id,- row.n_content,- row.n_created_at,- row.n_updated_at,- row.n_deleted_at,- row.n_mentions,- );-- result.insert(- ChannelId(row.channel_id),- LatestMessage {- latest_message,- latest_non_thread_message,- },- );- }-- Ok(result)-}--pub async fn get_latest_channel_message(- pool: &PgPool,- channel_id: ChannelId,-) -> Result<LatestMessage, Report> {- let res = get_latest_channel_messages_batch(pool, &[channel_id]).await?;- Ok(res.get(&channel_id).cloned().unwrap_or(LatestMessage {- latest_message: None,- latest_non_thread_message: None,- }))-}-#[tracing::instrument(skip(db), err)]-pub async fn get_activities(- db: &PgPool,- user_id: MacroUserIdStr<'_>,-) -> Result<Vec<Activity>, Report> {- Ok(sqlx::query!(- r#"- SELECT- a.id as "id!: Uuid",- a.user_id as "user_id!: String",- a.channel_id as "channel_id!: Uuid",- a.viewed_at as "viewed_at?: DateTime<Utc>",- a.interacted_at as "interacted_at?: DateTime<Utc>",- a.created_at as "created_at!: DateTime<Utc>",- a.updated_at as "updated_at!: DateTime<Utc>"- FROM comms_activity a- WHERE a.user_id = $1- ORDER BY- GREATEST(- COALESCE(a.viewed_at, '1970-01-01'::timestamp),- COALESCE(a.interacted_at, '1970-01-01'::timestamp)- ) DESC,- a.created_at DESC- LIMIT 100- "#,- user_id.as_ref()- )- .map(|row| Activity {- id: row.id,- user_id: row.user_id,- channel_id: ChannelId(row.channel_id),- created_at: row.created_at,- updated_at: row.updated_at,- viewed_at: row.viewed_at,- interacted_at: row.interacted_at,- })- .fetch_all(db)- .await?)-}--#[tracing::instrument(skip(db), err)]-pub async fn get_channel_name(- db: &PgPool,- channel_id: ChannelId,-) -> Result<Option<String>, sqlx::Error> {- sqlx::query_scalar!(- "SELECT name FROM comms_channels WHERE id = $1",- channel_id.0- )- .fetch_optional(db)- .await- .map(|row| row.flatten())-}--#[tracing::instrument(skip(db), err)]-pub async fn get_recent_messages(- db: &PgPool,- channel_id: ChannelId,- limit: u32,-) -> Result<Vec<ChannelMessage>, sqlx::Error> {- sqlx::query!(- r#"- SELECT- m.id AS "message_id!",- m.thread_id,- m.sender_id AS "sender_id!",- m.content AS "content!",- m.created_at AS "created_at!",- m.updated_at AS "updated_at!",- m.deleted_at::timestamptz AS "deleted_at?",- COALESCE(- ARRAY(- SELECT entity_type || ':' || entity_id- FROM comms_entity_mentions em- WHERE em.source_entity_type = 'message'- AND em.source_entity_id = m.id::text- ),- '{}'::text[]- ) AS "mentions!"- FROM comms_messages m- WHERE m.channel_id = $1- AND m.deleted_at IS NULL- ORDER BY m.created_at DESC- LIMIT $2- "#,- channel_id.0,- i64::from(limit)- )- .map(|row| ChannelMessage {- message_id: row.message_id,- thread_id: row.thread_id,- sender_id: row.sender_id,- content: row.content,- created_at: row.created_at,- updated_at: row.updated_at,- deleted_at: row.deleted_at,- mentions: row.mentions,- })- .fetch_all(db)- .await-}--pub struct PgCommsRepo {- pool: readonly_pool::ReadOnlyPool,-}--impl PgCommsRepo {- pub fn new(pool: readonly_pool::ReadOnlyPool) -> Self {- Self { pool }- }-}--impl CommsRepo for PgCommsRepo {- async fn get_user_channels_with_participants(- &self,- req: GetChannelsParams,- ) -> Result<Vec<ChannelWithParticipants>, rootcause::Report> {- Ok(get_user_channels_dynamic(&self.pool.0, &req).await?)- }-- async fn get_latest_channel_messages_batch(- &self,- channels: &[ChannelId],- ) -> Result<- std::collections::HashMap<ChannelId, models_comms::channel::LatestMessage>,- rootcause::Report,- > {- get_latest_channel_messages_batch(&self.pool.0, channels).await- }-- async fn get_activities(- &self,- user_id: MacroUserIdStr<'_>,- ) -> Result<Vec<models_comms::channel::Activity>, rootcause::Report> {- get_activities(&self.pool.0, user_id).await- }-- async fn get_channel_name(- &self,- channel_id: ChannelId,- ) -> Result<Option<String>, rootcause::Report> {- Ok(get_channel_name(&self.pool.0, channel_id).await?)- }-- async fn get_recent_messages(- &self,- channel_id: ChannelId,- limit: u32,- ) -> Result<Vec<ChannelMessage>, rootcause::Report> {- Ok(get_recent_messages(&self.pool.0, channel_id, limit).await?)- }-}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.rsdeleted file mode 100644index c062f48ba2..0000000000--- a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/dynamic.rs+++ /dev/null@@ -1,262 +0,0 @@-//! 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.team_id as "team_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_notification_exists_clause(- entity_id_sql: &str,- entity_type: &str,- predicate_sql: &str,-) -> String {- format!(- r#"EXISTS (- SELECT 1- FROM notification n- JOIN user_notification un ON un.notification_id = n.id- WHERE un.user_id = $1- AND un.deleted_at IS NULL- AND n.event_item_type = '{entity_type}'- AND n.event_item_id = ({entity_id_sql})::text- AND {predicate_sql}- )"#- )-}--fn build_notification_done_clause(entity_id_sql: &str, entity_type: &str, done: bool) -> String {- build_notification_exists_clause(- entity_id_sql,- entity_type,- if done {- "un.done = true"- } else {- "un.done = false"- },- )-}--fn build_notification_seen_clause(entity_id_sql: &str, entity_type: &str, seen: bool) -> String {- build_notification_exists_clause(- entity_id_sql,- entity_type,- if seen {- "un.seen_at IS NOT NULL"- } else {- "un.seen_at IS NULL"- },- )-}--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}")- }- filter_ast::ExprFrame::Literal(ChannelLiteral::TeamId(team_id)) => {- format!("c.team_id = '{team_id}'")- }- filter_ast::ExprFrame::Literal(ChannelLiteral::ChannelType(ct)) => {- format!("c.channel_type = '{ct}'")- }- // 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(),- filter_ast::ExprFrame::Literal(ChannelLiteral::Importance(true)) => String::new(),- // all channels are important, so if importance is false, exclude them- filter_ast::ExprFrame::Literal(ChannelLiteral::Importance(false)) => "1=0".to_string(),- filter_ast::ExprFrame::Literal(ChannelLiteral::NotificationDone(done)) => {- build_notification_done_clause("c.id", "channel", done)- }- filter_ast::ExprFrame::Literal(ChannelLiteral::NotificationSeen(seen)) => {- build_notification_seen_clause("c.id", "channel", seen)- }- });- 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>,- team_id: Option<uuid::Uuid>,- 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)),- team_id: self.team_id,- 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(Debug))]-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().map(|l| l 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")?,- team_id: row.try_get("team_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.rsdeleted file mode 100644index 4e3c08cca9..0000000000--- a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/dynamic/tests.rs+++ /dev/null@@ -1,538 +0,0 @@-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, ¶ms).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, ¶ms).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_matches_no_channels(- 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_filters = ChannelFilters {- org_id: Some(1),- ..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, ¶ms).await.unwrap();-- assert!(- channels.is_empty(),- "Legacy org filters should not match channel fixtures"- );-}--/// 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, ¶ms).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"- );-}--// Test filtering channels by importance-// importance=true is a no-op (returns all channels)-// importance=false short-circuits to match nothing (1=0)-#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("channels"))-)]-async fn test_get_user_channels_dynamic_filter_by_importance(pool: Pool<sqlx::Postgres>) {- use filter_ast::ExpandFrame;- use item_filters::ChannelFilters;-- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();-- // importance=true: no-op, should return all channels- {- let channel_filters = ChannelFilters {- importance: Some(true),- ..Default::default()- };-- let filter_ast = ChannelFilters::expand_ast(channel_filters)- .unwrap()- .map(std::sync::Arc::new);-- let params = GetChannelsRequest {- macro_id: user_id.clone(),- limit: Some(20),- query: Query::Sort(SimpleSortMethod::UpdatedAt, filter_ast),- }- .into_params();-- let channels = get_user_channels_dynamic(&pool, ¶ms).await.unwrap();- assert_eq!(- channels.len(),- 4,- "importance=true should return all 4 channels"- );- }-- // importance=false: 1=0, should return no channels- {- let channel_filters = ChannelFilters {- importance: Some(false),- ..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, ¶ms).await.unwrap();- assert_eq!(- channels.len(),- 0,- "importance=false should return no channels"- );- }-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("channels"))-)]-async fn test_get_user_channels_dynamic_filter_by_notification_done(pool: Pool<sqlx::Postgres>) {- use filter_ast::ExpandFrame;- use item_filters::{ChannelFilters, NotificationFilters};-- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();-- let channel_filters = ChannelFilters {- notification_filters: NotificationFilters {- done: Some(false),- seen: None,- },- ..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, ¶ms).await.unwrap();-- assert_eq!(- channels.len(),- 1,- "done=false should return exactly one channel"- );- assert_eq!(- channels[0].channel.id.0.to_string(),- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"- );-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("channels"))-)]-async fn test_get_user_channels_dynamic_filter_by_notification_seen_and_done(- pool: Pool<sqlx::Postgres>,-) {- use filter_ast::ExpandFrame;- use item_filters::{ChannelFilters, NotificationFilters};-- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();-- let channel_filters = ChannelFilters {- notification_filters: NotificationFilters {- done: Some(true),- seen: Some(true),- },- ..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, ¶ms).await.unwrap();-- assert_eq!(- channels.len(),- 1,- "done=true + seen=true should return exactly one channel"- );- assert_eq!(- channels[0].channel.id.0.to_string(),- "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"- );-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("channels"))-)]-async fn test_get_user_channels_dynamic_filter_by_private_channel_type(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_filters = ChannelFilters {- channel_types: vec!["private".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, ¶ms).await.unwrap();-- // Channels A and B are private type.- assert_eq!(channels.len(), 2, "Should return 2 private channels");-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("channels"))-)]-async fn test_get_user_channels_dynamic_filter_by_multiple_channel_types(- pool: Pool<sqlx::Postgres>,-) {- use filter_ast::ExpandFrame;- use item_filters::ChannelFilters;-- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();-- // Filter for public and direct_message channels- let channel_filters = ChannelFilters {- channel_types: vec!["public".to_string(), "direct_message".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, ¶ms).await.unwrap();-- // Channel C is public, Channel D is direct_message- assert_eq!(- channels.len(),- 2,- "Should return 2 channels (public + direct_message)"- );-}--#[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/user_repo/mod.rs b/rust/cloud-storage/comms/src/outbound/postgres/user_repo/mod.rsdeleted file mode 100644index 7cfde71a89..0000000000--- a/rust/cloud-storage/comms/src/outbound/postgres/user_repo/mod.rs+++ /dev/null@@ -1,72 +0,0 @@-//! Database-backed implementation of UserRepo that queries MacroDB directly.--use std::collections::HashSet;--use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use rootcause::Report;-use sqlx::PgPool;--use crate::domain::models::UserName;-use crate::domain::ports::UserRepo;--#[cfg(test)]-mod test;--/// Fetches user names from the database for the given user profile IDs.-///-/// This queries the `macro_user_info` table joined with the `User` table-/// to retrieve first and last names for users.-#[tracing::instrument(skip(db), err)]-async fn get_names_for_ids(- db: &PgPool,- ids: &[MacroUserIdStr<'_>],-) -> Result<Vec<UserName>, Report> {- let rows = sqlx::query!(- r#"- SELECT- u.id as user_profile_id,- mui.first_name,- mui.last_name- FROM macro_user_info mui- JOIN "User" u ON mui.macro_user_id = u.macro_user_id- WHERE u.id = ANY($1)- "#,- &ids.iter().map(|s| s.to_string()).collect::<Vec<String>>()- )- .fetch_all(db)- .await?;-- let names = rows- .into_iter()- .map(|row| UserName {- id: MacroUserIdStr::parse_from_str(&row.user_profile_id)- .expect("valid macro user id from db")- .into_owned(),- first_name: row.first_name,- last_name: row.last_name,- })- .collect();-- Ok(names)-}--/// Database-backed implementation of UserRepo.-pub struct PgUserRepo {- pool: PgPool,-}--impl PgUserRepo {- /// Creates a new PgUserRepo with the given database connection pool.- pub fn new(pool: PgPool) -> Self {- Self { pool }- }-}--impl UserRepo for PgUserRepo {- async fn get_names_for_ids(- &self,- ids: HashSet<MacroUserIdStr<'_>>,- ) -> Result<Vec<UserName>, Report> {- get_names_for_ids(&self.pool, &ids.into_iter().collect::<Vec<_>>()).await- }-}diff --git a/rust/cloud-storage/comms/src/outbound/postgres/user_repo/test.rs b/rust/cloud-storage/comms/src/outbound/postgres/user_repo/test.rsdeleted file mode 100644index fa90093a3b..0000000000--- a/rust/cloud-storage/comms/src/outbound/postgres/user_repo/test.rs+++ /dev/null@@ -1,102 +0,0 @@-use macro_db_migrator::MACRO_DB_MIGRATIONS;-use macro_user_id::user_id::MacroUserIdStr;-use sqlx::Pool;--use super::get_names_for_ids;--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("users"))-)]-async fn test_get_single_user_name(pool: Pool<sqlx::Postgres>) {- let ids = vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()];-- let names = get_names_for_ids(&pool, &ids).await.unwrap();-- assert_eq!(names.len(), 1);- assert_eq!(names[0].id.as_ref(), "macro|[email protected]");- assert_eq!(names[0].first_name.as_deref(), Some("John"));- assert_eq!(names[0].last_name.as_deref(), Some("Doe"));-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("users"))-)]-async fn test_get_multiple_user_names(pool: Pool<sqlx::Postgres>) {- let ids = vec![- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- ];-- let names = get_names_for_ids(&pool, &ids).await.unwrap();-- assert_eq!(names.len(), 3);-- // Find each user in the results (order not guaranteed)- let user1 = names- .iter()- .find(|n| n.id.as_ref() == "macro|[email protected]")- .expect("user1 should be present");- assert_eq!(user1.first_name.as_deref(), Some("John"));- assert_eq!(user1.last_name.as_deref(), Some("Doe"));-- let user2 = names- .iter()- .find(|n| n.id.as_ref() == "macro|[email protected]")- .expect("user2 should be present");- assert_eq!(user2.first_name, None);- assert_eq!(user2.last_name, None);-- let user3 = names- .iter()- .find(|n| n.id.as_ref() == "macro|[email protected]")- .expect("user3 should be present");- assert_eq!(user3.first_name.as_deref(), Some("Jane"));- assert_eq!(user3.last_name.as_deref(), Some("Smith"));-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("users"))-)]-async fn test_get_user_names_with_nonexistent_ids(pool: Pool<sqlx::Postgres>) {- let ids = vec![- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- ];-- let names = get_names_for_ids(&pool, &ids).await.unwrap();-- // Should only return the one that exists- assert_eq!(names.len(), 1);- assert_eq!(names[0].id.as_ref(), "macro|[email protected]");-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("users"))-)]-async fn test_get_user_names_empty_input(pool: Pool<sqlx::Postgres>) {- let ids: Vec<MacroUserIdStr<'_>> = vec![];-- let names = get_names_for_ids(&pool, &ids).await.unwrap();-- assert!(names.is_empty());-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("users"))-)]-async fn test_get_user_names_all_nonexistent(pool: Pool<sqlx::Postgres>) {- let ids = vec![- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- ];-- let names = get_names_for_ids(&pool, &ids).await.unwrap();-- assert!(names.is_empty());-}diff --git a/rust/cloud-storage/comms_db_client/Cargo.toml b/rust/cloud-storage/comms_db_client/Cargo.tomlindex 2bb9469b20..482178301d 100644--- a/rust/cloud-storage/comms_db_client/Cargo.toml+++ b/rust/cloud-storage/comms_db_client/Cargo.toml@@ -13,7 +13,6 @@ futures = { workspace = true }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }model = { path = "../model" }-models_comms = { path = "../models_comms" }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }diff --git a/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs b/rust/cloud-storage/comms_db_client/src/participants/get_participants.rsindex 9948d1ea55..e4330d1c34 100644--- a/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs+++ b/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs@@ -3,13 +3,13 @@ use doppleganger::Doppleganger;use doppleganger::Mirror;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;-use model::comms::ChannelId;+use model::comms::{ChannelId, ChannelParticipant};use sqlx::Transaction;use sqlx::{Pool, Postgres};use uuid::Uuid;#[derive(sqlx::Type, Doppleganger, Debug)]-#[dg(forward = models_comms::channel::ParticipantRole)]+#[dg(forward = model::comms::ParticipantRole)]#[sqlx(rename_all = "lowercase")]pub enum DbParticipantRole {Admin,@@ -21,7 +21,7 @@ pub enum DbParticipantRole {pub async fn get_participants_tsx<'t>(tsx: &mut Transaction<'t, Postgres>,channel_id: &Uuid,-) -> Result<Vec<models_comms::channel::ChannelParticipant>, sqlx::Error> {+) -> Result<Vec<ChannelParticipant>, sqlx::Error> {let participants = sqlx::query!(r#"SELECT@@ -37,7 +37,7 @@ pub async fn get_participants_tsx<'t>(channel_id).try_map(|row| {- Ok(models_comms::channel::ChannelParticipant {+ Ok(ChannelParticipant {channel_id: ChannelId(row.channel_id),user_id: macro_user_id::user_id::MacroUserIdStr::parse_from_str(&row.user_id).map_err(|e| sqlx::Error::Decode(Box::new(e)))?@@ -57,7 +57,7 @@ pub async fn get_participants_tsx<'t>(pub async fn get_participants(db: &Pool<Postgres>,channel_id: &Uuid,-) -> Result<Vec<models_comms::channel::ChannelParticipant>, sqlx::Error> {+) -> Result<Vec<ChannelParticipant>, sqlx::Error> {let participants = sqlx::query!(r#"SELECT@@ -73,7 +73,7 @@ pub async fn get_participants(channel_id).try_map(|row| {- Ok(models_comms::channel::ChannelParticipant {+ Ok(ChannelParticipant {channel_id: ChannelId(row.channel_id),user_id: macro_user_id::user_id::MacroUserIdStr::parse_from_str(&row.user_id).map_err(|e| sqlx::Error::Decode(Box::new(e)))?diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex 956bb2e46c..15b3fd2096 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -42,8 +42,8 @@ aws-sdk-sqs = { workspace = true }axum = { workspace = true, features = ["tower-log", "ws"] }call = { path = "../call", default-features = false, features = ["ports"] }chat = { path = "../chat", features = ["attachment"] }+channels = { path = "../channels", features = ["outbound", "attachment"] }chrono = { workspace = true }-comms = { path = "../comms", features = ["outbound", "attachment"] }connection_gateway = { path = "../connection_gateway" }cookie = { workspace = true }crm = { path = "../crm" }diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rsindex f00991991b..682f792f55 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs@@ -7,11 +7,11 @@ use ai_tools::{};use attachment::provider::AttachmentProvider;use axum::extract::FromRef;+use channels::inbound::attachment::ChannelAttachmentService;+use channels::outbound::pg_channels_repo::PgChannelsRepo;use chat::domain::service::MessageServiceImpl;use chat::inbound::attachment::ChatAttachmentService;use chat::outbound::postgres::PgChatRepo;-use comms::inbound::attachment::CommsAttachmentService;-use comms::outbound::postgres::comms_repo::PgCommsRepo;use connection_gateway::service::connection::ConnectionRepo;use document_storage_service_client::DocumentStorageServiceClient;use documents::inbound::attachment::DocumentAttachmentService;@@ -38,7 +38,7 @@ pub type DcsAttachmentProvider = AttachmentProvider<DocumentAttachmentService<ToolDocumentService, ToolEntityAccessService>,EmailAttachmentService<ToolEmailService, ToolEntityAccessService>,ChatAttachmentService<PgChatRepo, ToolEntityAccessService>,- CommsAttachmentService<PgCommsRepo, ToolEntityAccessService>,+ ChannelAttachmentService<PgChannelsRepo, ToolEntityAccessService>,StaticFileAttachmentService<CdnStaticFileRepo>,>;diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex ad7d9d7ef6..4e6c54f81e 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -108,9 +108,9 @@ impl StreamRepo for MockStreamRepo {pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arc<ApiContext> {use aws_sdk_sqs;- use comms::domain::service::ChannelServiceImpl;- use comms::outbound::postgres::comms_repo::PgCommsRepo;- use comms::outbound::postgres::user_repo::PgUserRepo;+ use channels::{+ domain::list_service::ChannelListServiceImpl, outbound::pg_channels_repo::PgChannelsRepo,+ };use document_storage_service_client::DocumentStorageServiceClient;use email::domain::ports::ReadonlyEmailPreviewAdapter;use email::domain::service::EmailServiceImpl;@@ -172,10 +172,9 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arcrm_service.clone(),0,);- let user_repo = PgUserRepo::new(pool.clone());- let channels_service = ChannelServiceImpl::new(- PgCommsRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),- user_repo,+ let channels_service = ChannelListServiceImpl::new(+ PgChannelsRepo::new(pool.clone()),+ PgChannelsRepo::new(pool.clone()),frecency_storage,);let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());@@ -394,8 +393,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::ArArc::new(chat::outbound::postgres::PgChatRepo::new(pool.clone())),entity_access_service.clone(),),- channel: comms::inbound::attachment::CommsAttachmentService::new(- Arc::new(PgCommsRepo::new(readonly_pool::ReadOnlyPool(pool.clone()))),+ channel: channels::inbound::attachment::ChannelAttachmentService::new(+ Arc::new(PgChannelsRepo::new(pool.clone())),entity_access_service.clone(),),static_file: static_file::inbound::attachment::StaticFileAttachmentService::new(diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 93af1ed7ec..83ea1310f3 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -6,9 +6,9 @@ use call::domain::service::{CallRecordQueryServiceImpl, CallServiceImpl};use call::inbound::toolset::CallToolContext;use call::outbound::pg_call_repo::PgCallRepo;use call::outbound::s3_recording_storage::S3RecordingStorage;-use comms::domain::service::ChannelServiceImpl;-use comms::outbound::postgres::comms_repo::PgCommsRepo;-use comms::outbound::postgres::user_repo::PgUserRepo;+use channels::{+ domain::list_service::ChannelListServiceImpl, outbound::pg_channels_repo::PgChannelsRepo,+};use config::{Config, EnvVars, Environment};use document_storage_service_client::DocumentStorageServiceClient;use documents::{@@ -215,9 +215,9 @@ async fn main() -> anyhow::Result<()> {crm_service.clone(),0,);- let channels_service = ChannelServiceImpl::new(- PgCommsRepo::new(ReadOnlyPool(db.clone())),- PgUserRepo::new(db.clone()),+ let channels_service = ChannelListServiceImpl::new(+ PgChannelsRepo::new(db.clone()),+ PgChannelsRepo::new(db.clone()),frecency_storage,);let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());@@ -297,8 +297,8 @@ async fn main() -> anyhow::Result<()> {Arc::new(chat::outbound::postgres::PgChatRepo::new(db.clone())),entity_access_service.clone(),),- channel: comms::inbound::attachment::CommsAttachmentService::new(- Arc::new(PgCommsRepo::new(ReadOnlyPool(db.clone()))),+ channel: channels::inbound::attachment::ChannelAttachmentService::new(+ Arc::new(PgChannelsRepo::new(db.clone())),entity_access_service.clone(),),static_file: static_file::inbound::attachment::StaticFileAttachmentService::new(Arc::new(diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 8433d67ea4..baf408c418 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -45,7 +45,6 @@ channels = { path = "../channels", features = ["inbound", "outbound"] }chrono = { workspace = true }clap = { workspace = true }cloudfront_sign = { workspace = true }-comms = { path = "../comms", features = ["inbound", "outbound"] }comms_db_client = { path = "../comms_db_client" }contacts = { path = "../contacts" }connection = { path = "../connection", default-features = false, features = [diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex e6a024b6d7..e2b28ef42a 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -19,10 +19,11 @@ use call::{};use channels::{domain::{+ list_service::ChannelListServiceImpl,service::ChannelServiceImpl,side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher},},- inbound::axum_router::ChannelsRouterState,+ inbound::{axum_router::ChannelsRouterState, list_router::ChannelListRouterState},outbound::{connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher,contacts_dispatcher::ContactsChannelDispatcher,@@ -32,11 +33,6 @@ use channels::{sqs_search_indexer::SqsChannelSearchIndexer,},};-use comms::{- domain::service::ChannelServiceImpl as CommsChannelServiceImpl,- inbound::router::CommsRouterState,- outbound::postgres::{comms_repo::PgCommsRepo, user_repo::PgUserRepo},-};use connection::{domain::service::ConnectionServiceImpl,outbound::connection_gateway_client::ConnectionGatewayImpl,@@ -112,7 +108,7 @@ type DssSoupState = SoupRouterState<PgSoupRepo,FrecencyQueryServiceImpl<FrecencyPgStorage>,ReadonlyEmailPreviewAdapter<DssEmailService>,- CommsChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>,+ ChannelListServiceImpl<PgChannelsRepo, PgChannelsRepo, FrecencyPgStorage>,call::domain::service::CallRecordQueryServiceImpl<call::outbound::pg_call_repo::PgCallRepo>,DssCrmService,ForeignEntityServiceType,@@ -208,12 +204,12 @@ pub(crate) type DocumentService = DocumentServiceImpl</// Type alias for the documents router state.pub(crate) type DocumentsState = DocumentRouterState<DocumentService, EntityAccessService>;-/// Type alias for the ChannelServiceImpl used by comms-pub(crate) type CommsChannelService =- CommsChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>;+/// Type alias for the legacy channel list service.+pub(crate) type DssChannelListService =+ ChannelListServiceImpl<PgChannelsRepo, PgChannelsRepo, FrecencyPgStorage>;-/// Type alias for the CommsRouterState-pub(crate) type CommsState = CommsRouterState<CommsChannelService>;+/// Type alias for the legacy channel list router state.+pub(crate) type DssChannelListState = ChannelListRouterState<DssChannelListService>;/// Type alias for the channels service wired into DSS.pub(crate) type DssChannelService = ChannelServiceImpl<@@ -322,9 +318,10 @@ pub(crate) struct ApiContext {pub jwt_validation_args: JwtValidationArgs,pub config: Arc<Config>,pub dss_auth_key: DocumentStorageServiceAuthKey,- // Comms service fields+ // Shared frecency storage.pub frecency_storage: FrecencyPgStorage,- pub comms_state: CommsState,+ /// Legacy channel list router state.+ pub channel_list_state: DssChannelListState,pub entity_access_service: Arc<EntityAccessService>,pub documents_state: DocumentsState,pub channels_state: DssChannelsState,diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rsindex d8b3fbcff8..89e51a430c 100644--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs@@ -202,7 +202,7 @@ fn api_router(state: ApiContext) -> Router {).nest("/comms",- comms::inbound::router::comms_router(state.comms_state.clone()),+ channels::inbound::list_router::channel_list_router(state.channel_list_state.clone()),).nest("/entity", entity::router()).nest(diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex bc3c27cde7..a6c3aaaf2b 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -24,10 +24,11 @@ use call::{};use channels::{domain::{+ list_service::ChannelListServiceImpl,service::ChannelServiceImpl,side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher},},- inbound::axum_router::ChannelsRouterState,+ inbound::{axum_router::ChannelsRouterState, list_router::ChannelListRouterState},outbound::{connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher,contacts_dispatcher::ContactsChannelDispatcher,@@ -37,11 +38,6 @@ use channels::{sqs_search_indexer::SqsChannelSearchIndexer,},};-use comms::{- domain::service::ChannelServiceImpl as CommsChannelServiceImpl,- inbound::router::CommsRouterState,- outbound::postgres::{comms_repo::PgCommsRepo, user_repo::PgUserRepo},-};use config::{Config, Environment};use connection::{domain::service::ConnectionServiceImpl,@@ -286,20 +282,18 @@ async fn main() -> anyhow::Result<()> {Some(notification_service),));- // Create the comms ChannelServiceImpl instances.- let channel_service_for_soup = CommsChannelServiceImpl::new(- PgCommsRepo::new(readonly_pool::ReadOnlyPool(readonly_db.clone())),- PgUserRepo::new(readonly_db.clone()),+ // Create the channel list service used by soup.+ let channel_service_for_soup = ChannelListServiceImpl::new(+ PgChannelsRepo::new(readonly_db.clone()),+ PgChannelsRepo::new(readonly_db.clone()),frecency_storage.clone(),);- let channel_service_for_comms = CommsChannelServiceImpl::new(- PgCommsRepo::new(readonly_pool::ReadOnlyPool(db.clone())),- PgUserRepo::new(db.clone()),+ // Create the legacy channel list router state for routes mounted under /comms.+ let channel_list_state = ChannelListRouterState::new(ChannelListServiceImpl::new(+ PgChannelsRepo::new(db.clone()),+ PgChannelsRepo::new(db.clone()),frecency_storage.clone(),- );-- // Create the CommsRouterState for the comms hex routes mounted under /comms.- let comms_state = CommsRouterState::new(channel_service_for_comms);+ ));let s3 = Arc::new(S3::new(s3_client,@@ -645,9 +639,9 @@ async fn main() -> anyhow::Result<()> {config: Arc::new(config),jwt_validation_args,dss_auth_key,- // Comms service fields+ // Shared frecency storage and legacy channel list routes.frecency_storage,- comms_state,+ channel_list_state,entity_access_service: entity_access_service.clone(),documents_state: DocumentRouterState {service: document_service.clone(),diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex c8ccae1a67..860dcb042c 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -74,7 +74,6 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./email_db_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./email_refresh_handler/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./comms_db_client/.env- echo "DATABASE_URL={{ DATABASE_URL }}" >> ./comms/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./document_cognition_service/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./document_text_extractor/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./organization_retention_handler/.envdiff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.tomlindex 49f2beeb36..8bd1328946 100644--- a/rust/cloud-storage/mcp_service/Cargo.toml+++ b/rust/cloud-storage/mcp_service/Cargo.toml@@ -15,7 +15,7 @@ aws-sdk-sqs = { workspace = true }axum = { workspace = true, features = ["tower-log"] }call = { path = "../call", default-features = false, features = ["ports"] }chat = { path = "../chat", features = ["ai_tools", "outbound"] }-comms = { path = "../comms", features = ["outbound"] }+channels = { path = "../channels", features = ["outbound"] }crm = { path = "../crm" }documents = { path = "../documents", features = ["ai_tools"] }email = { path = "../email", features = ["outbound"] }diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rsindex 5ea2c15632..a6e2c35258 100644--- a/rust/cloud-storage/mcp_service/src/context.rs+++ b/rust/cloud-storage/mcp_service/src/context.rs@@ -5,9 +5,9 @@ use ai_tools::{NoOpSnsEndpointManager, ToolNotificationQueue, ToolServiceContext,};use anyhow::Context;-use comms::domain::service::ChannelServiceImpl;-use comms::outbound::postgres::comms_repo::PgCommsRepo;-use comms::outbound::postgres::user_repo::PgUserRepo;+use channels::{+ domain::list_service::ChannelListServiceImpl, outbound::pg_channels_repo::PgChannelsRepo,+};use documents::{domain::models::CloudFrontConfig,inbound::toolset::DocumentToolContext,@@ -183,9 +183,9 @@ async fn build_tool_context(crm_service.clone(),0,);- let channels_service = ChannelServiceImpl::new(- PgCommsRepo::new(readonly_pool::ReadOnlyPool(db.clone())),- PgUserRepo::new(db.clone()),+ let channels_service = ChannelListServiceImpl::new(+ PgChannelsRepo::new(db.clone()),+ PgChannelsRepo::new(db.clone()),frecency_storage,);let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.tomlindex 64c307ca81..a6038a667f 100644--- a/rust/cloud-storage/memory/Cargo.toml+++ b/rust/cloud-storage/memory/Cargo.toml@@ -30,7 +30,7 @@ tracing = { workspace = true }utoipa = { workspace = true }# For building ToolServiceContext-comms = { path = "../comms" }+channels = { path = "../channels", features = ["outbound"] }crm = { path = "../crm" }documents = { path = "../documents" }email = { path = "../email" }diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rsindex f8b5641502..0358321ca1 100644--- a/rust/cloud-storage/memory/src/context.rs+++ b/rust/cloud-storage/memory/src/context.rs@@ -1,9 +1,9 @@use ai_tools::{NoOpConnectionService, NoOpSnsEndpointManager, ToolNotificationQueue, ToolServiceContext,};-use comms::domain::service::ChannelServiceImpl;-use comms::outbound::postgres::comms_repo::PgCommsRepo;-use comms::outbound::postgres::user_repo::PgUserRepo;+use channels::{+ domain::list_service::ChannelListServiceImpl, outbound::pg_channels_repo::PgChannelsRepo,+};use documents::domain::models::CloudFrontConfig;use documents::inbound::toolset::DocumentToolContext;use documents::outbound::pg_document_repo::PgDocumentRepo;@@ -87,9 +87,9 @@ pub async fn build_tool_service_context(crm_service.clone(),0,);- let channels_service = ChannelServiceImpl::new(- PgCommsRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),- PgUserRepo::new(pool.clone()),+ let channels_service = ChannelListServiceImpl::new(+ PgChannelsRepo::new(pool.clone()),+ PgChannelsRepo::new(pool.clone()),frecency_storage,);let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());diff --git a/rust/cloud-storage/model/Cargo.toml b/rust/cloud-storage/model/Cargo.tomlindex 17d4e0224a..7227f09ba6 100644--- a/rust/cloud-storage/model/Cargo.toml+++ b/rust/cloud-storage/model/Cargo.toml@@ -17,7 +17,6 @@ model-error-response = { path = "../model-error-response" }model_file_type = { path = "../model_file_type", features = ["utoipa"] }model_user = { path = "../model_user", features = ["axum"] }models_bulk_upload = { path = "../models_bulk_upload" }-models_comms = { path = "../models_comms" }models_pagination = { path = "../models_pagination" }models_permissions = { path = "../models_permissions" }schemars = { workspace = true }diff --git a/rust/cloud-storage/model/src/comms/mod.rs b/rust/cloud-storage/model/src/comms/mod.rsindex 4b761df2bb..4eb93b728b 100644--- a/rust/cloud-storage/model/src/comms/mod.rs+++ b/rust/cloud-storage/model/src/comms/mod.rs@@ -1,7 +1,6 @@use chrono::{DateTime, Utc};-use doppleganger::Doppleganger;+use doppleganger::Primitive;use macro_user_id::user_id::MacroUserIdStr;-pub use models_comms::channel::{ChannelId, OrganizationId};use serde::{Deserialize, Serialize};use sqlx::Type;use std::collections::HashMap;@@ -12,6 +11,18 @@ use uuid::Uuid;/// Ugly place to store the models that are used by service client./// it's ugly to promot someone else moving it as I am lazy -- Hutch.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(transparent)]+pub struct OrganizationId(pub u32);++impl Primitive for OrganizationId {}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]+#[serde(transparent)]+pub struct ChannelId(pub Uuid);++impl Primitive for ChannelId {}+#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct AddUserToOrgChannelsRequest {pub user_id: String,@@ -47,12 +58,9 @@ pub struct UserActivityForChannel {pub updated_at: chrono::NaiveDateTime,}-#[derive(- Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type, ToSchema, Default, Doppleganger,-)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type, ToSchema, Default)]#[sqlx(type_name = "comms_participant_role", rename_all = "lowercase")]#[serde(rename_all = "snake_case")]-#[dg(backward = models_comms::channel::ParticipantRole)]pub enum ParticipantRole {Owner,Admin,@@ -60,8 +68,7 @@ pub enum ParticipantRole {Member,}-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]-#[dg(backward = models_comms::channel::ChannelParticipant)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct ChannelParticipant {/// id of the channel#[schema(value_type = Uuid)]@@ -85,7 +92,6 @@ pub struct ChannelParticipant {Eq,Display,ToSchema,- Doppleganger,Serialize,Deserialize,sqlx::Type,@@ -94,7 +100,6 @@ pub struct ChannelParticipant {#[strum(serialize_all = "snake_case")]#[serde(rename_all = "snake_case")]#[sqlx(type_name = "comms_channel_type", rename_all = "snake_case")]-#[dg(backward = models_comms::channel::ChannelType)]pub enum ChannelType {Public,Private,@@ -102,8 +107,7 @@ pub enum ChannelType {Team,}-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq, Doppleganger)]-#[dg(backward = models_comms::channel::Channel)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]pub struct Channel {/// uuid of the channel#[schema(value_type = Uuid)]@@ -115,6 +119,9 @@ pub struct Channel {/// id of the organization this channel belongs too#[schema(value_type = Option<u32>)]pub org_id: Option<OrganizationId>,+ /// id of the team this channel belongs to+ #[serde(default)]+ pub team_id: Option<Uuid>,/// timestamp of when the channel was createdpub created_at: chrono::DateTime<chrono::Utc>,/// timestamp of when the channel was last updated@@ -124,16 +131,14 @@ pub struct Channel {pub owner_id: MacroUserIdStr<'static>,}-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]-#[dg(backward = models_comms::channel::ChannelWithParticipants)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct ChannelWithParticipants {#[serde(flatten)]pub channel: Channel,pub participants: Vec<ChannelParticipant>,}-#[derive(Debug, Clone, Default, ToSchema, Serialize, Deserialize, Doppleganger)]-#[dg(backward = models_comms::channel::LatestMessage)]+#[derive(Debug, Clone, Default, ToSchema, Serialize, Deserialize)]pub struct LatestMessage {pub latest_message: Option<ChannelMessage>,pub latest_non_thread_message: Option<ChannelMessage>,@@ -172,8 +177,7 @@ pub struct CreateWelcomeMessageRequest {pub to_user_id: MacroUserIdStr<'static>,}-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]-#[dg(backward = models_comms::channel::ChannelMessage)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct ChannelMessage {pub message_id: Uuid,pub thread_id: Option<Uuid>,diff --git a/rust/cloud-storage/model_notifications/Cargo.toml b/rust/cloud-storage/model_notifications/Cargo.tomlindex 20d9ea5bf8..7ad15e6c0b 100644--- a/rust/cloud-storage/model_notifications/Cargo.toml+++ b/rust/cloud-storage/model_notifications/Cargo.toml@@ -7,11 +7,9 @@ version = "0.1.0"[dependencies]anyhow = { workspace = true }chrono = { workspace = true }-doppleganger = { workspace = true }macro_user_id = { path = "../macro_user_id" }mention_utils = { path = "../mention_utils" }model-entity = { path = "../model-entity" }-models_comms = { path = "../models_comms" }models_pagination = { path = "../models_pagination" }notification = { path = "../notification" }paste = { workspace = true }diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rsindex d7b6fb193c..4f98404078 100644--- a/rust/cloud-storage/model_notifications/src/metadata.rs+++ b/rust/cloud-storage/model_notifications/src/metadata.rs@@ -1,5 +1,4 @@use chrono::{DateTime, Utc};-use doppleganger::Doppleganger;pub use invite_email::{ChannelInviteMetadata, InviteToTeamMetadata};use macro_user_id::cowlike::CowLike;use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};@@ -485,8 +484,7 @@ impl NotificationTitle for GithubPrReview {}}-#[derive(Debug, Clone, Copy, ToSchema, Doppleganger, Serialize, Deserialize)]-#[dg(backward = models_comms::channel::ChannelType)]+#[derive(Debug, Clone, Copy, ToSchema, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub enum ChannelType {#[serde(alias = "Public", alias = "public")]@@ -499,17 +497,6 @@ pub enum ChannelType {Team,}-impl ChannelType {- pub fn to_model_comms(self) -> models_comms::channel::ChannelType {- match self {- ChannelType::Public => models_comms::channel::ChannelType::Public,- ChannelType::Private => models_comms::channel::ChannelType::Private,- ChannelType::DirectMessage => models_comms::channel::ChannelType::DirectMessage,- ChannelType::Team => models_comms::channel::ChannelType::Team,- }- }-}-/// Common metadata for notifications on channels#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]diff --git a/rust/cloud-storage/models_comms/Cargo.toml b/rust/cloud-storage/models_comms/Cargo.tomldeleted file mode 100644index 63bb3d686e..0000000000--- a/rust/cloud-storage/models_comms/Cargo.toml+++ /dev/null@@ -1,17 +0,0 @@-[package]-edition = "2024"-name = "models_comms"-publish = false-version = "0.1.0"--[dependencies]-anyhow = { workspace = true }-chrono = { workspace = true }-doppleganger = { workspace = true }-frecency = { path = "../frecency" }-macro_user_id = { path = "../macro_user_id" }-serde = { workspace = true }-strum = { workspace = true }-thiserror = { workspace = true }-uuid = { workspace = true }-workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/rust/cloud-storage/models_comms/src/channel.rs b/rust/cloud-storage/models_comms/src/channel.rsdeleted file mode 100644index 1193e3ebf4..0000000000--- a/rust/cloud-storage/models_comms/src/channel.rs+++ /dev/null@@ -1,118 +0,0 @@-use chrono::{DateTime, Utc};-use doppleganger::Primitive;-use frecency::domain::models::AggregateFrecency;-use macro_user_id::user_id::MacroUserIdStr;-use serde::{Deserialize, Serialize};-use strum::Display;-use uuid::Uuid;--#[derive(Debug, Clone, Copy, Display, Deserialize)]-#[strum(serialize_all = "snake_case")]-#[serde(rename_all = "snake_case")]-pub enum ChannelType {- Public,- Private,- DirectMessage,- Team,-}--#[derive(Debug, Clone)]-pub struct ChannelMetadata {- pub name: String,- pub channel_type: ChannelType,-}--#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]-#[serde(transparent)]-pub struct OrganizationId(pub u32);--impl Primitive for OrganizationId {}--#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]-#[serde(transparent)]-pub struct ChannelId(pub Uuid);--impl Primitive for ChannelId {}--#[derive(Debug, Clone, Copy, Default, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum ParticipantRole {- Owner,- Admin,- #[default]- Member,-}--#[derive(Debug, Clone, Deserialize)]-pub struct ChannelParticipant {- pub channel_id: ChannelId,- pub user_id: MacroUserIdStr<'static>,- pub role: ParticipantRole,- pub joined_at: DateTime<Utc>,- pub left_at: Option<DateTime<Utc>>,-}--#[derive(Debug, Clone)]-pub struct Channel {- pub id: ChannelId,- pub name: Option<String>,- pub channel_type: ChannelType,- pub org_id: Option<OrganizationId>,- pub team_id: Option<uuid::Uuid>,- pub created_at: DateTime<Utc>,- pub updated_at: DateTime<Utc>,- pub owner_id: MacroUserIdStr<'static>,-}--#[derive(Debug, Clone)]-pub struct ChannelWithParticipants {- pub channel: Channel,- pub participants: Vec<ChannelParticipant>,-}--#[derive(Debug, Clone, Default)]-pub struct LatestMessage {- pub latest_message: Option<ChannelMessage>,- pub latest_non_thread_message: Option<ChannelMessage>,-}--#[derive(Debug, Clone)]-pub struct ChannelWithLatest {- pub channel: ChannelWithParticipants,- pub latest_message: LatestMessage,- pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,- pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,- pub frecency_score: Option<AggregateFrecency>,-}--#[derive(Debug, Clone)]-pub struct ChannelMessage {- pub message_id: Uuid,- pub thread_id: Option<Uuid>,- pub sender_id: String,- pub content: String,- pub created_at: chrono::DateTime<chrono::Utc>,- pub updated_at: chrono::DateTime<chrono::Utc>,- pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,- /// message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`- pub mentions: Vec<String>,-}--pub struct EnrichedChannel {- pub channel: ChannelWithParticipants,- pub latest_message: LatestMessage,-}--/// Represents a user's activity in a channel-pub struct Activity {- pub id: Uuid,- pub user_id: String,- pub channel_id: ChannelId,- pub created_at: chrono::DateTime<chrono::Utc>,- pub updated_at: chrono::DateTime<chrono::Utc>,- /// the last time the user viewed the channel- pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,- /// the last time the user intereacted with the channel- /// eg. reacting, replying, sending a message- pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,-}diff --git a/rust/cloud-storage/models_comms/src/lib.rs b/rust/cloud-storage/models_comms/src/lib.rsdeleted file mode 100644index ff02972763..0000000000--- a/rust/cloud-storage/models_comms/src/lib.rs+++ /dev/null@@ -1 +0,0 @@-pub mod channel;diff --git a/rust/cloud-storage/models_soup/Cargo.toml b/rust/cloud-storage/models_soup/Cargo.tomlindex 50ffe451e9..f8c29733a4 100644--- a/rust/cloud-storage/models_soup/Cargo.toml+++ b/rust/cloud-storage/models_soup/Cargo.toml@@ -12,13 +12,13 @@ schema = ["dep:utoipa", "item_filters/schema"]anyhow = { workspace = true }call = { path = "../call", default-features = false }chrono = { workspace = true }-comms = { path = "../comms" }crm = { path = "../crm", default-features = false }document_sub_type = { path = "../document_sub_type" }doppleganger = { workspace = true, features = ["chrono", "uuid"] }email = { path = "../email" }item_filters = { path = "../item_filters" }macro_user_id = { path = "../macro_user_id" }+model = { path = "../model" }model-entity = { path = "../model-entity" }models_pagination = { path = "../models_pagination" }models_properties = { path = "../models_properties/" }diff --git a/rust/cloud-storage/models_soup/src/comms.rs b/rust/cloud-storage/models_soup/src/comms.rsindex 5b8a792a9b..5fc3cf2941 100644--- a/rust/cloud-storage/models_soup/src/comms.rs+++ b/rust/cloud-storage/models_soup/src/comms.rs@@ -1,13 +1,12 @@-use chrono::{DateTime, Utc};-use comms::domain::models::channel::{ChannelId, OrganizationId};-use doppleganger::Doppleganger;-use macro_user_id::user_id::MacroUserIdStr;+use model::comms;use serde::{Deserialize, Serialize};-use uuid::Uuid;-#[derive(Debug, Doppleganger, Serialize, Deserialize)]+pub use comms::{+ Channel, ChannelId, ChannelMessage, ChannelType, LatestMessage, OrganizationId, ParticipantRole,+};++#[derive(Debug, Serialize, Deserialize)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-#[dg(backward = comms::domain::models::channel::ChannelWithLatest)]pub struct SoupChannel {#[serde(flatten)]pub channel: ChannelWithParticipants,@@ -17,85 +16,21 @@ pub struct SoupChannel {pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,}-#[derive(Debug, Doppleganger, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-#[dg(backward = comms::domain::models::channel::ChannelWithParticipants)]pub struct ChannelWithParticipants {pub channel: Channel,pub participants: Vec<ChannelParticipant>,}-#[derive(Debug, Doppleganger, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-#[dg(backward = comms::domain::models::channel::LatestMessage)]-pub struct LatestMessage {- pub latest_message: Option<ChannelMessage>,- pub latest_non_thread_message: Option<ChannelMessage>,-}--#[derive(Debug, Doppleganger, Serialize, Deserialize)]-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-#[dg(backward = comms::domain::models::channel::ChannelMessage)]-pub struct ChannelMessage {- pub message_id: Uuid,- pub thread_id: Option<Uuid>,- pub sender_id: String,- pub content: String,- pub created_at: chrono::DateTime<chrono::Utc>,- pub updated_at: chrono::DateTime<chrono::Utc>,- pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,- /// message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`- pub mentions: Vec<String>,-}--#[derive(Debug, Doppleganger, Serialize, Deserialize)]-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-#[dg(backward = comms::domain::models::channel::Channel)]-pub struct Channel {- #[cfg_attr(feature = "schema", schema(value_type = Uuid))]- pub id: ChannelId,- pub name: Option<String>,- pub channel_type: ChannelType,- #[cfg_attr(feature = "schema", schema(value_type = Option<u32>))]- pub org_id: Option<OrganizationId>,- #[cfg_attr(feature = "schema", schema(value_type = Option<uuid::Uuid>))]- pub team_id: Option<uuid::Uuid>,- pub created_at: DateTime<Utc>,- pub updated_at: DateTime<Utc>,- #[cfg_attr(feature = "schema", schema(value_type = String))]- pub owner_id: MacroUserIdStr<'static>,-}--#[derive(Debug, Clone, Copy, Serialize, Deserialize, Doppleganger)]-#[serde(rename_all = "snake_case")]-#[dg(backward = comms::domain::models::channel::ChannelType)]-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-pub enum ChannelType {- Public,- Private,- DirectMessage,- Team,-}--#[derive(Debug, Doppleganger, Serialize, Deserialize)]-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-#[dg(backward = comms::domain::models::channel::ChannelParticipant)]pub struct ChannelParticipant {- #[cfg_attr(feature = "schema", schema(value_type = Uuid))]+ #[cfg_attr(feature = "schema", schema(value_type = uuid::Uuid))]pub channel_id: ChannelId,#[cfg_attr(feature = "schema", schema(value_type = String))]- pub user_id: MacroUserIdStr<'static>,+ pub user_id: macro_user_id::user_id::MacroUserIdStr<'static>,pub role: ParticipantRole,- pub joined_at: DateTime<Utc>,- pub left_at: Option<DateTime<Utc>>,-}--#[derive(Debug, Clone, Copy, Serialize, Deserialize, Doppleganger)]-#[serde(rename_all = "snake_case")]-#[dg(backward = comms::domain::models::channel::ParticipantRole)]-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-pub enum ParticipantRole {- Owner,- Admin,- Member,+ pub joined_at: chrono::DateTime<chrono::Utc>,+ pub left_at: Option<chrono::DateTime<chrono::Utc>>,}diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.tomlindex 106bcf3f27..c60430a30b 100644--- a/rust/cloud-storage/notification_service/Cargo.toml+++ b/rust/cloud-storage/notification_service/Cargo.toml@@ -53,7 +53,6 @@ model-error-response = { path = "../model-error-response" }model_file_type = { path = "../model_file_type" }model_notifications = { path = "../model_notifications" }model_user = { path = "../model_user", features = ["axum"] }-models_comms = { path = "../models_comms" }models_pagination = { path = "../models_pagination", features = ["axum"] }notification = { path = "../notification", features = ["axum"] }notification_db_client = { path = "../notification_db_client" }diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.tomlindex b7381b1dd6..6dc73fa1cf 100644--- a/rust/cloud-storage/search_service/Cargo.toml+++ b/rust/cloud-storage/search_service/Cargo.toml@@ -18,7 +18,7 @@ aws-sdk-secretsmanager = { workspace = true }macro_aws_config = { path = "../macro_aws_config" }axum = { workspace = true }chrono = { workspace = true }-comms = { path = "../comms", default-features = false, features = ["outbound"] }+channels = { path = "../channels", default-features = false, features = ["outbound"] }comms_db_client = { path = "../comms_db_client" }crm = { path = "../crm", default-features = false, features = ["search"] }document_sub_type = { path = "../document_sub_type" }diff --git a/rust/cloud-storage/search_service/src/api/search/call_record.rs b/rust/cloud-storage/search_service/src/api/search/call_record.rsindex c182a6f5dc..3857a745a4 100644--- a/rust/cloud-storage/search_service/src/api/search/call_record.rs+++ b/rust/cloud-storage/search_service/src/api/search/call_record.rs@@ -1,4 +1,4 @@-use comms::outbound::postgres::channel_name::batch_resolve_channel_names;+use channels::outbound::channel_name::batch_resolve_channel_names;use indexmap::IndexMap;use item_filters::CallStatus;use macro_user_id::user_id::MacroUserIdStr;diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex c8156172f9..8bf9e033a0 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -6,7 +6,6 @@ version = "0.1.0"[features]ai_tools = [- "comms/outbound","dep:ai_toolset","dep:async-trait","dep:schemars",@@ -43,7 +42,7 @@ axum = { workspace = true, optional = true }axum-extra = { workspace = true, optional = true }call = { path = "../call", default-features = false, features = ["ports"] }chrono = { workspace = true }-comms = { path = "../comms", default-features = false }+channels = { path = "../channels", default-features = false, features = ["list"] }cowlike = { path = "../cowlike" }crm = { path = "../crm", default-features = false }document_sub_type = { path = "../document_sub_type" }diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rsindex 1b1b736494..b48793b3c4 100644--- a/rust/cloud-storage/soup/src/domain/models.rs+++ b/rust/cloud-storage/soup/src/domain/models.rs@@ -6,7 +6,7 @@ pub use grouping::{};use call::domain::models::GetCallRecordsRequest;-use comms::domain::models::GetChannelsRequest;+use channels::domain::models::GetChannelsRequest;use crm::domain::auth::CrmTeamReceipt;use crm::domain::companies_repo::{CrmCompanyListSort, CrmCompanySoupCursor};use email::domain::models::{GetEmailsRequest, PreviewView};diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex 803771fe01..92e4caf815 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -7,7 +7,10 @@ use crate::domain::{ports::{SoupOutput, SoupRepo, SoupService},};use call::domain::{models::GetCallRecordsRequest, ports::CallRecordQueryService};-use comms::domain::{models::GetChannelsRequest, ports::ChannelsService};+use channels::domain::{+ models::{ChannelType, GetChannelsRequest, ParticipantRole, RecentChannelMessage},+ ports::ChannelListService,+};use cowlike::CowLike;use crm::domain::service::CrmService;use doppleganger::Mirror;@@ -48,6 +51,89 @@ use uuid::Uuid;#[cfg(test)]mod tests;+fn channel_type_to_soup(channel_type: ChannelType) -> models_soup::comms::ChannelType {+ match channel_type {+ ChannelType::Public => models_soup::comms::ChannelType::Public,+ ChannelType::Private => models_soup::comms::ChannelType::Private,+ ChannelType::DirectMessage => models_soup::comms::ChannelType::DirectMessage,+ ChannelType::Team => models_soup::comms::ChannelType::Team,+ }+}++fn participant_role_to_soup(role: ParticipantRole) -> models_soup::comms::ParticipantRole {+ match role {+ ParticipantRole::Owner => models_soup::comms::ParticipantRole::Owner,+ ParticipantRole::Admin => models_soup::comms::ParticipantRole::Admin,+ ParticipantRole::Member => models_soup::comms::ParticipantRole::Member,+ }+}++fn recent_channel_message_to_soup(+ message: RecentChannelMessage,+) -> models_soup::comms::ChannelMessage {+ models_soup::comms::ChannelMessage {+ message_id: message.message_id,+ thread_id: message.thread_id,+ sender_id: message.sender_id,+ content: message.content,+ created_at: message.created_at,+ updated_at: message.updated_at,+ deleted_at: message.deleted_at,+ mentions: message.mentions,+ }+}++fn channel_to_soup_channel(+ channel: channels::domain::models::ChannelWithLatest,+) -> Option<SoupChannel> {+ let channel_item = channel.channel.channel;+ Some(SoupChannel {+ channel: models_soup::comms::ChannelWithParticipants {+ channel: models_soup::comms::Channel {+ id: models_soup::comms::ChannelId(channel_item.id),+ name: channel_item.name,+ channel_type: channel_type_to_soup(channel_item.channel_type),+ org_id: channel_item+ .org_id+ .and_then(|org_id| u32::try_from(org_id).ok())+ .map(models_soup::comms::OrganizationId),+ team_id: channel_item.team_id,+ created_at: channel_item.created_at,+ updated_at: channel_item.updated_at,+ owner_id: channel_item.owner_id,+ },+ participants: channel+ .channel+ .participants+ .into_iter()+ .filter_map(|participant| {+ Some(models_soup::comms::ChannelParticipant {+ channel_id: models_soup::comms::ChannelId(participant.channel_id),+ user_id: MacroUserIdStr::parse_from_str(&participant.user_id)+ .ok()?+ .into_owned(),+ role: participant_role_to_soup(participant.role),+ joined_at: participant.joined_at,+ left_at: participant.left_at,+ })+ })+ .collect(),+ },+ latest_message: models_soup::comms::LatestMessage {+ latest_message: channel+ .latest_message+ .latest_message+ .map(recent_channel_message_to_soup),+ latest_non_thread_message: channel+ .latest_message+ .latest_non_thread_message+ .map(recent_channel_message_to_soup),+ },+ viewed_at: channel.viewed_at,+ interacted_at: channel.interacted_at,+ })+}+fn foreign_entity_to_soup_item(entity: ForeignEntity) -> SoupItem {SoupItem::ForeignEntity(SoupForeignEntity {id: entity.id,@@ -69,7 +155,7 @@ pub struct SoupImpl<T, U, V, C, K, Crm, F> {frecency: U,/// the interface for interacting with emailemail_service: V,- /// the interface for interacting with comms+ /// the interface for interacting with channelscomms_service: C,/// the interface for interacting with call recordscall_record_service: K,@@ -85,7 +171,7 @@ whereanyhow::Error: From<T::Err>,U: FrecencyQueryService,V: EmailPreviewServiceReadOnly,- C: ChannelsService,+ C: ChannelListService,K: CallRecordQueryService,Crm: CrmService,F: ForeignEntityService,@@ -387,13 +473,13 @@ where.await.map_err(|_| SoupErr::CommsErr).map(|r| {- r.into_iter().map(|mut c| {+ r.into_iter().filter_map(|mut c| {let frecency_score = c.frecency_score.take();- let soup_channel = SoupChannel::mirror(c);- FrecencySoupItem {+ let soup_channel = channel_to_soup_channel(c)?;+ Some(FrecencySoupItem {item: SoupItem::Channel(soup_channel),frecency_score,- }+ })})})?,))@@ -498,7 +584,7 @@ whereanyhow::Error: From<T::Err>,U: FrecencyQueryService,V: EmailPreviewServiceReadOnly,- C: ChannelsService,+ C: ChannelListService,K: CallRecordQueryService,Crm: CrmService,F: ForeignEntityService,diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex 754eb7fcb7..191da8460e 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -1,8 +1,8 @@use crate::domain::models::FrecencySoupItem;use crate::domain::ports::MockSoupRepo;+use channels::domain::{models::GetChannelsRequest, ports::ChannelListService};use chrono::Days;use chrono::{DateTime, Utc};-use comms::domain::models::GetChannelsRequest;use cool_asserts::assert_matches;use email::domain::models::{EnrichedEmailThreadPreview, PreviewView};use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};@@ -52,25 +52,25 @@ impl EmailPreviewServiceReadOnly for NoopEmailPreviewService {struct NoopCommsService;-impl ChannelsService for NoopCommsService {+impl ChannelListService for NoopCommsService {async fn get_channels(&self,_req: GetChannelsRequest,- ) -> Result<Vec<comms::domain::models::channel::ChannelWithLatest>, Report> {+ ) -> Result<Vec<channels::domain::models::ChannelWithLatest>, Report> {Ok(Vec::new())}async fn get_activities(&self,_user: MacroUserIdStr<'_>,- ) -> Result<Vec<comms::domain::models::channel::Activity>, Report> {+ ) -> Result<Vec<channels::domain::models::Activity>, Report> {Ok(Vec::new())}async fn get_names(&self,_names: std::collections::HashSet<MacroUserIdStr<'_>>,- ) -> Result<Vec<comms::domain::models::UserName>, Report> {+ ) -> Result<Vec<channels::domain::models::UserName>, Report> {Ok(Vec::new())}}