Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(channels)!: hex channels crate, notif,realtime,contacts dispatch improvements (#3453)

teod12086cf31d4
diff --git a/docker-compose.local-e2e.yml b/docker-compose.local-e2e.yml
index 6e057c0834..745d931670 100644
--- a/docker-compose.local-e2e.yml
+++ b/docker-compose.local-e2e.yml
@@ -38,13 +38,14 @@ x-local-e2e-env: &local-e2e-env
GMAIL_OPS_QUEUE: email-service-gmail-ops-queue
GMAIL_OPS_RETRY_QUEUE: email-service-gmail-ops-retry-queue
LINK_MANAGER_QUEUE: email-service-refresh-queue
- NOTIFICATION_QUEUE: notification-queue
+ NOTIFICATION_QUEUE: http://localstack:4566/000000000000/notification-queue
NOTIFICATION_INGRESS_QUEUE: http://localstack:4566/000000000000/notification-ingress-queue
PUSH_NOTIFICATION_EVENT_HANDLER_QUEUE: push-delivery-queue
SEARCH_EVENT_QUEUE: search-event-queue
SFS_DELETE_QUEUE: email-sfs-delete-queue
SFS_UPLOADER_QUEUE: email-service-sfs-mapper-queue
STATIC_FILE_SERVICE_S3_EVENT_QUEUE_URL: http://localstack:4566/000000000000/static-file-s3-event-notification-queue
+ EMAIL_BACKFILL_QUEUE: http://localstack:4566/000000000000/email-service-backfill-queue
services:
authentication-service:
diff --git a/justfile b/justfile
index a4defa293d..1d43dde461 100644
--- a/justfile
+++ b/justfile
@@ -120,7 +120,7 @@ local-e2e-seed:
# Start only the services needed by the local E2E suites. Avoid unrelated
# local services with extra env/dependency requirements blocking E2E.
-local-e2e-services := "authentication-service connection_gateway contacts_service document_storage_service email_service static_file_service static_file_cdn sync_service websocket_service"
+local-e2e-services := "authentication-service connection_gateway contacts_service document_storage_service email_service notification_service static_file_service static_file_cdn sync_service websocket_service"
# Start the local stack, seed deterministic data, and run the Playwright smoke suite.
local-e2e *ARGS:
diff --git a/rust/cloud-storage/.sqlx/query-0710b66e8a6608c340848ad6295fc012f06f1c298d1b287eebd7be0b89766702.json b/rust/cloud-storage/.sqlx/query-0710b66e8a6608c340848ad6295fc012f06f1c298d1b287eebd7be0b89766702.json
new file mode 100644
index 0000000000..40ba2008c6
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-0710b66e8a6608c340848ad6295fc012f06f1c298d1b287eebd7be0b89766702.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM comms_channel_participants\n WHERE channel_id = $1 AND user_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0710b66e8a6608c340848ad6295fc012f06f1c298d1b287eebd7be0b89766702"
+}
diff --git a/rust/cloud-storage/.sqlx/query-096cff82c1f50ae5f4a5699ba9e1f35280fefe178bfc01701fc09b8962def475.json b/rust/cloud-storage/.sqlx/query-096cff82c1f50ae5f4a5699ba9e1f35280fefe178bfc01701fc09b8962def475.json
new file mode 100644
index 0000000000..e4fd6f14ab
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-096cff82c1f50ae5f4a5699ba9e1f35280fefe178bfc01701fc09b8962def475.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COUNT(id) AS \"count!\"\n FROM comms_messages\n WHERE channel_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "096cff82c1f50ae5f4a5699ba9e1f35280fefe178bfc01701fc09b8962def475"
+}
diff --git a/rust/cloud-storage/.sqlx/query-107c7ff9f46c80e689a642b15b85ea8978acaeba5aa4a264639b2a5c8c741a62.json b/rust/cloud-storage/.sqlx/query-107c7ff9f46c80e689a642b15b85ea8978acaeba5aa4a264639b2a5c8c741a62.json
new file mode 100644
index 0000000000..514fa3d797
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-107c7ff9f46c80e689a642b15b85ea8978acaeba5aa4a264639b2a5c8c741a62.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT id AS \"user_id!: MacroUserIdStr\" FROM (\n SELECT m.sender_id AS id\n FROM comms_channel_participants cp\n JOIN comms_channels c ON c.id = cp.channel_id\n JOIN comms_messages m ON m.channel_id = c.id\n WHERE (m.id = $1 OR m.thread_id = $1) AND cp.left_at IS NULL\n UNION\n SELECT em.entity_id AS id\n FROM comms_entity_mentions em\n JOIN comms_messages m ON m.id::text = em.source_entity_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = m.channel_id AND cp.user_id = em.entity_id\n WHERE (m.id = $1 OR m.thread_id = $1)\n AND em.source_entity_type = 'message'\n AND em.entity_type = 'user'\n AND cp.left_at IS NULL\n ) AS combined\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id!: MacroUserIdStr",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "107c7ff9f46c80e689a642b15b85ea8978acaeba5aa4a264639b2a5c8c741a62"
+}
diff --git a/rust/cloud-storage/.sqlx/query-10843b4044bca618301e755b0b6b5aeca5fd398adc48ed9f755490fa25e7f3f9.json b/rust/cloud-storage/.sqlx/query-10843b4044bca618301e755b0b6b5aeca5fd398adc48ed9f755490fa25e7f3f9.json
new file mode 100644
index 0000000000..1317474022
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-10843b4044bca618301e755b0b6b5aeca5fd398adc48ed9f755490fa25e7f3f9.json
@@ -0,0 +1,32 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_channels (id, name, owner_id, org_id, team_id, channel_type)\n VALUES ($1, $2, $3, $4, $5, $6)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Varchar",
+ "Text",
+ "Int8",
+ "Uuid",
+ {
+ "Custom": {
+ "name": "comms_channel_type",
+ "kind": {
+ "Enum": [
+ "public",
+ "organization",
+ "private",
+ "direct_message",
+ "team"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "10843b4044bca618301e755b0b6b5aeca5fd398adc48ed9f755490fa25e7f3f9"
+}
diff --git a/rust/cloud-storage/.sqlx/query-11cffac7d14e962aa00fd0a9a0ca290ad6e8bbce98fe53cd4079791734567928.json b/rust/cloud-storage/.sqlx/query-11cffac7d14e962aa00fd0a9a0ca290ad6e8bbce98fe53cd4079791734567928.json
new file mode 100644
index 0000000000..cc0d105dbd
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-11cffac7d14e962aa00fd0a9a0ca290ad6e8bbce98fe53cd4079791734567928.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id\n FROM comms_channel_participants\n WHERE channel_id = $1 AND left_at IS NULL\n ORDER BY joined_at ASC, user_id ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "11cffac7d14e962aa00fd0a9a0ca290ad6e8bbce98fe53cd4079791734567928"
+}
diff --git a/rust/cloud-storage/.sqlx/query-1a8ff2838fcde3373b6cb6e0886cf5c20932ec3e9fe9eb8f5812f75f641b40b2.json b/rust/cloud-storage/.sqlx/query-1a8ff2838fcde3373b6cb6e0886cf5c20932ec3e9fe9eb8f5812f75f641b40b2.json
new file mode 100644
index 0000000000..1ff2e97f41
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-1a8ff2838fcde3373b6cb6e0886cf5c20932ec3e9fe9eb8f5812f75f641b40b2.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT sender_id AS \"sender_id: MacroUserIdStr\"\n FROM comms_messages\n WHERE id = $1\n ORDER BY created_at ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sender_id: MacroUserIdStr",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "1a8ff2838fcde3373b6cb6e0886cf5c20932ec3e9fe9eb8f5812f75f641b40b2"
+}
diff --git a/rust/cloud-storage/.sqlx/query-1c651bb11edabc6aceff14663b7a1e722ca09640bdae70dad37a017fafd16206.json b/rust/cloud-storage/.sqlx/query-1c651bb11edabc6aceff14663b7a1e722ca09640bdae70dad37a017fafd16206.json
new file mode 100644
index 0000000000..dc7641635e
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-1c651bb11edabc6aceff14663b7a1e722ca09640bdae70dad37a017fafd16206.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT pp.\"sharePermissionId\" as \"share_permission_id!\"\n FROM \"ProjectPermission\" pp\n WHERE pp.\"projectId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "share_permission_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "1c651bb11edabc6aceff14663b7a1e722ca09640bdae70dad37a017fafd16206"
+}
diff --git a/rust/cloud-storage/.sqlx/query-2247a3c9b543df2bdf1150a7148956f0c3c8287e3863893eb7e8761af066a46f.json b/rust/cloud-storage/.sqlx/query-2247a3c9b543df2bdf1150a7148956f0c3c8287e3863893eb7e8761af066a46f.json
new file mode 100644
index 0000000000..92694142b3
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2247a3c9b543df2bdf1150a7148956f0c3c8287e3863893eb7e8761af066a46f.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM comms_attachments\n WHERE id = ANY($1)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2247a3c9b543df2bdf1150a7148956f0c3c8287e3863893eb7e8761af066a46f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-2323566d1f90b640bf6cbd83beb86be825ff271d9a18921835dfd1864a78ebfb.json b/rust/cloud-storage/.sqlx/query-2323566d1f90b640bf6cbd83beb86be825ff271d9a18921835dfd1864a78ebfb.json
new file mode 100644
index 0000000000..19bcc6aa4e
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2323566d1f90b640bf6cbd83beb86be825ff271d9a18921835dfd1864a78ebfb.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"SharePermission\" (\"isPublic\", \"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES (false, NULL, NOW(), NOW())\n RETURNING id as \"id!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "2323566d1f90b640bf6cbd83beb86be825ff271d9a18921835dfd1864a78ebfb"
+}
diff --git a/rust/cloud-storage/.sqlx/query-25ecb2c575d0ba90bea0d500ac8522346fb8bc6aa9bf669219c300cc398a1108.json b/rust/cloud-storage/.sqlx/query-25ecb2c575d0ba90bea0d500ac8522346fb8bc6aa9bf669219c300cc398a1108.json
new file mode 100644
index 0000000000..19945e3ba5
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-25ecb2c575d0ba90bea0d500ac8522346fb8bc6aa9bf669219c300cc398a1108.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH message AS (\n SELECT id\n FROM comms_messages\n WHERE id = $2 AND channel_id = $1\n ),\n inserted AS (\n INSERT INTO comms_reactions (message_id, emoji, user_id)\n SELECT id, $3, $4\n FROM message\n ON CONFLICT DO NOTHING\n )\n SELECT EXISTS (SELECT 1 FROM message) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Varchar",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "25ecb2c575d0ba90bea0d500ac8522346fb8bc6aa9bf669219c300cc398a1108"
+}
diff --git a/rust/cloud-storage/.sqlx/query-2849c75501e874a2056d63e028c97cece3f7605b12f4c6f904c7ba8c718844f7.json b/rust/cloud-storage/.sqlx/query-2849c75501e874a2056d63e028c97cece3f7605b12f4c6f904c7ba8c718844f7.json
new file mode 100644
index 0000000000..1207987257
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2849c75501e874a2056d63e028c97cece3f7605b12f4c6f904c7ba8c718844f7.json
@@ -0,0 +1,74 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_messages (id, channel_id, sender_id, content, thread_id)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING\n id,\n channel_id,\n sender_id AS \"sender_id: MacroUserIdStr\",\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id: MacroUserIdStr",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ null,
+ null
+ ]
+ },
+ "hash": "2849c75501e874a2056d63e028c97cece3f7605b12f4c6f904c7ba8c718844f7"
+}
diff --git a/rust/cloud-storage/.sqlx/query-2f25b7a9ef03d53404c384af4763ec5ce5f48079d5b040724b62f1964e49c932.json b/rust/cloud-storage/.sqlx/query-2f25b7a9ef03d53404c384af4763ec5ce5f48079d5b040724b62f1964e49c932.json
new file mode 100644
index 0000000000..bf7d0c2a17
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2f25b7a9ef03d53404c384af4763ec5ce5f48079d5b040724b62f1964e49c932.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH message AS (\n SELECT id\n FROM comms_messages\n WHERE id = $2 AND channel_id = $1\n ),\n deleted AS (\n DELETE FROM comms_reactions r\n USING message m\n WHERE r.message_id = m.id\n AND r.emoji = $3\n AND r.user_id = $4\n )\n SELECT EXISTS (SELECT 1 FROM message) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "2f25b7a9ef03d53404c384af4763ec5ce5f48079d5b040724b62f1964e49c932"
+}
diff --git a/rust/cloud-storage/.sqlx/query-304363603c60b5894a3e692b394aa320b6d72a5851a596cec6dc37b6ef5f80e6.json b/rust/cloud-storage/.sqlx/query-304363603c60b5894a3e692b394aa320b6d72a5851a596cec6dc37b6ef5f80e6.json
new file mode 100644
index 0000000000..c120389544
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-304363603c60b5894a3e692b394aa320b6d72a5851a596cec6dc37b6ef5f80e6.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT l.macro_id as \"macro_id!\"\n FROM email_threads t\n JOIN email_links l ON t.link_id = l.id\n WHERE t.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "304363603c60b5894a3e692b394aa320b6d72a5851a596cec6dc37b6ef5f80e6"
+}
diff --git a/rust/cloud-storage/.sqlx/query-37c8b721c4a8e35b8cbecf02ca434d2095a2b2dbfc9d3a64e595f9725bbb0b8c.json b/rust/cloud-storage/.sqlx/query-37c8b721c4a8e35b8cbecf02ca434d2095a2b2dbfc9d3a64e595f9725bbb0b8c.json
new file mode 100644
index 0000000000..b5dcd6e28f
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-37c8b721c4a8e35b8cbecf02ca434d2095a2b2dbfc9d3a64e595f9725bbb0b8c.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH message_channel AS (\n SELECT channel_id FROM comms_messages WHERE id = $1\n ),\n mentions_to_insert AS (\n SELECT t.entity_type, t.entity_id\n FROM UNNEST($2::text[], $3::text[]) AS t(entity_type, entity_id)\n ),\n inserted_mentions AS (\n INSERT INTO comms_entity_mentions (\n id,\n source_entity_type,\n source_entity_id,\n entity_type,\n entity_id,\n user_id\n )\n SELECT gen_random_uuid(), 'message', $4::text, m.entity_type, m.entity_id, NULL\n FROM mentions_to_insert m\n WHERE NOT EXISTS (\n SELECT 1\n FROM comms_entity_mentions em\n WHERE em.source_entity_type = 'message'\n AND em.source_entity_id = $4::text\n AND em.entity_type = m.entity_type\n AND em.entity_id = m.entity_id\n )\n )\n SELECT DISTINCT cp.user_id\n FROM mentions_to_insert m\n CROSS JOIN message_channel mc\n JOIN comms_channel_participants cp ON m.entity_id = cp.user_id\n WHERE m.entity_type = 'user'\n AND cp.channel_id = mc.channel_id\n AND cp.left_at IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray",
+ "TextArray",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "37c8b721c4a8e35b8cbecf02ca434d2095a2b2dbfc9d3a64e595f9725bbb0b8c"
+}
diff --git a/rust/cloud-storage/.sqlx/query-3ada2f8355f9c5ecd4072938c3243296615904f9af24c4e18dda50992b47d5af.json b/rust/cloud-storage/.sqlx/query-3ada2f8355f9c5ecd4072938c3243296615904f9af24c4e18dda50992b47d5af.json
new file mode 100644
index 0000000000..c07d958fd5
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-3ada2f8355f9c5ecd4072938c3243296615904f9af24c4e18dda50992b47d5af.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_activity (id, user_id, channel_id, created_at, updated_at)\n VALUES ($1, $2, $3, NOW(), NOW())\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3ada2f8355f9c5ecd4072938c3243296615904f9af24c4e18dda50992b47d5af"
+}
diff --git a/rust/cloud-storage/.sqlx/query-45ad79d68456546519948ee22ab123c807c6ebc97bf5d6b523ef00b40beeb70e.json b/rust/cloud-storage/.sqlx/query-45ad79d68456546519948ee22ab123c807c6ebc97bf5d6b523ef00b40beeb70e.json
new file mode 100644
index 0000000000..22a8b4e775
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-45ad79d68456546519948ee22ab123c807c6ebc97bf5d6b523ef00b40beeb70e.json
@@ -0,0 +1,71 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE comms_messages\n SET content = '', updated_at = NOW(), deleted_at = NOW()\n WHERE id = $1 AND channel_id = $2\n RETURNING\n id,\n channel_id,\n sender_id AS \"sender_id: MacroUserIdStr\",\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id: MacroUserIdStr",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ null,
+ null
+ ]
+ },
+ "hash": "45ad79d68456546519948ee22ab123c807c6ebc97bf5d6b523ef00b40beeb70e"
+}
diff --git a/rust/cloud-storage/.sqlx/query-46529d3ed1fd86a194a7e99458b4f95a0dc0ae92127693240ce9dc0acc3b7467.json b/rust/cloud-storage/.sqlx/query-46529d3ed1fd86a194a7e99458b4f95a0dc0ae92127693240ce9dc0acc3b7467.json
new file mode 100644
index 0000000000..348c31b38b
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-46529d3ed1fd86a194a7e99458b4f95a0dc0ae92127693240ce9dc0acc3b7467.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"ChannelSharePermission\" (\"share_permission_id\", \"channel_id\", \"access_level\")\n VALUES ($1, $2, $3)\n ON CONFLICT (\"share_permission_id\", \"channel_id\") DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "46529d3ed1fd86a194a7e99458b4f95a0dc0ae92127693240ce9dc0acc3b7467"
+}
diff --git a/rust/cloud-storage/.sqlx/query-4962707d2bc90c036ab1540db476ad45483ad784af4908660342b1c57f045095.json b/rust/cloud-storage/.sqlx/query-4962707d2bc90c036ab1540db476ad45483ad784af4908660342b1c57f045095.json
new file mode 100644
index 0000000000..ac1dfe7b9e
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-4962707d2bc90c036ab1540db476ad45483ad784af4908660342b1c57f045095.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, message_id, channel_id, entity_type, entity_id, width, height, created_at\n FROM comms_attachments\n WHERE message_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "entity_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "entity_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "width",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 6,
+ "name": "height",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ false
+ ]
+ },
+ "hash": "4962707d2bc90c036ab1540db476ad45483ad784af4908660342b1c57f045095"
+}
diff --git a/rust/cloud-storage/.sqlx/query-56f380911d1ece3f1a04ad73ffdf724d132c32f4971d533f7dbe0a42e283ebce.json b/rust/cloud-storage/.sqlx/query-56f380911d1ece3f1a04ad73ffdf724d132c32f4971d533f7dbe0a42e283ebce.json
new file mode 100644
index 0000000000..c55fe1a69c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-56f380911d1ece3f1a04ad73ffdf724d132c32f4971d533f7dbe0a42e283ebce.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id\n FROM comms_channels\n WHERE channel_type = 'direct_message'::comms_channel_type\n AND EXISTS (\n SELECT 1\n FROM comms_channel_participants cp\n WHERE cp.channel_id = comms_channels.id\n AND cp.user_id = $1\n )\n AND EXISTS (\n SELECT 1\n FROM comms_channel_participants cp\n WHERE cp.channel_id = comms_channels.id\n AND cp.user_id = $2\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "56f380911d1ece3f1a04ad73ffdf724d132c32f4971d533f7dbe0a42e283ebce"
+}
diff --git a/rust/cloud-storage/.sqlx/query-5c7aee79058a9904924fdd338d6823a3b0caf86fa2ff09ea307703a57ed72c68.json b/rust/cloud-storage/.sqlx/query-5c7aee79058a9904924fdd338d6823a3b0caf86fa2ff09ea307703a57ed72c68.json
new file mode 100644
index 0000000000..452c6fa17c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-5c7aee79058a9904924fdd338d6823a3b0caf86fa2ff09ea307703a57ed72c68.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_activity (id, user_id, channel_id, interacted_at)\n VALUES ($1, $2, $3, NOW())\n ON CONFLICT (user_id, channel_id) DO UPDATE\n SET interacted_at = NOW(), updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5c7aee79058a9904924fdd338d6823a3b0caf86fa2ff09ea307703a57ed72c68"
+}
diff --git a/rust/cloud-storage/.sqlx/query-5ff5a0e3731dc62354f69e26961fee699c6de82cfa14ba2a403486731366d664.json b/rust/cloud-storage/.sqlx/query-5ff5a0e3731dc62354f69e26961fee699c6de82cfa14ba2a403486731366d664.json
new file mode 100644
index 0000000000..e22db21cde
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-5ff5a0e3731dc62354f69e26961fee699c6de82cfa14ba2a403486731366d664.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT r.emoji, r.user_id, r.created_at\n FROM comms_reactions r\n JOIN comms_messages m ON m.id = r.message_id\n WHERE r.message_id = $1 AND m.channel_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "emoji",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "5ff5a0e3731dc62354f69e26961fee699c6de82cfa14ba2a403486731366d664"
+}
diff --git a/rust/cloud-storage/.sqlx/query-607eecc4c046c7bae3bdcdc4e20a5bfa78673bf04979c01365b9e9a35398125f.json b/rust/cloud-storage/.sqlx/query-607eecc4c046c7bae3bdcdc4e20a5bfa78673bf04979c01365b9e9a35398125f.json
new file mode 100644
index 0000000000..29844bb1d6
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-607eecc4c046c7bae3bdcdc4e20a5bfa78673bf04979c01365b9e9a35398125f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"sharePermissionId\" as \"share_permission_id!\"\n FROM \"EmailThreadPermission\"\n WHERE \"threadId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "share_permission_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "607eecc4c046c7bae3bdcdc4e20a5bfa78673bf04979c01365b9e9a35398125f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-643b149e8a3c616d39850f156f37cdc1a007500afdc7c8e232a59a8b60824962.json b/rust/cloud-storage/.sqlx/query-643b149e8a3c616d39850f156f37cdc1a007500afdc7c8e232a59a8b60824962.json
new file mode 100644
index 0000000000..70b89288cf
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-643b149e8a3c616d39850f156f37cdc1a007500afdc7c8e232a59a8b60824962.json
@@ -0,0 +1,57 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n channel_id,\n user_id,\n role AS \"role: ParticipantRole\",\n joined_at,\n left_at::timestamptz AS \"left_at?\"\n FROM comms_channel_participants\n WHERE channel_id = $1 AND left_at IS NULL\n ORDER BY joined_at ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "role: ParticipantRole",
+ "type_info": {
+ "Custom": {
+ "name": "comms_participant_role",
+ "kind": {
+ "Enum": [
+ "owner",
+ "admin",
+ "member"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "joined_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "left_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "643b149e8a3c616d39850f156f37cdc1a007500afdc7c8e232a59a8b60824962"
+}
diff --git a/rust/cloud-storage/.sqlx/query-6b9cf167af68aad294c96f81d6bc995ead4fd6f968ef17176a770ffa46b44f64.json b/rust/cloud-storage/.sqlx/query-6b9cf167af68aad294c96f81d6bc995ead4fd6f968ef17176a770ffa46b44f64.json
new file mode 100644
index 0000000000..531266f154
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-6b9cf167af68aad294c96f81d6bc995ead4fd6f968ef17176a770ffa46b44f64.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM comms_channel_participants\n WHERE channel_id = $1\n AND user_id = $2\n AND role IN (\n 'admin'::comms_participant_role,\n 'owner'::comms_participant_role\n )\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "6b9cf167af68aad294c96f81d6bc995ead4fd6f968ef17176a770ffa46b44f64"
+}
diff --git a/rust/cloud-storage/.sqlx/query-75843bf211e0811b398d636fe6c8b05005afb77be95bc434a924e53c17cd6033.json b/rust/cloud-storage/.sqlx/query-75843bf211e0811b398d636fe6c8b05005afb77be95bc434a924e53c17cd6033.json
new file mode 100644
index 0000000000..67426125ba
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-75843bf211e0811b398d636fe6c8b05005afb77be95bc434a924e53c17cd6033.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT tp.\"sharePermissionId\" as \"share_permission_id!\"\n FROM \"EmailThreadPermission\" tp\n WHERE tp.\"threadId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "share_permission_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "75843bf211e0811b398d636fe6c8b05005afb77be95bc434a924e53c17cd6033"
+}
diff --git a/rust/cloud-storage/.sqlx/query-783fb2d2833135d5bf8aa7eb5983b773d4b7c9b508388987155815d8c7e1db3b.json b/rust/cloud-storage/.sqlx/query-783fb2d2833135d5bf8aa7eb5983b773d4b7c9b508388987155815d8c7e1db3b.json
new file mode 100644
index 0000000000..07229f5fe0
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-783fb2d2833135d5bf8aa7eb5983b773d4b7c9b508388987155815d8c7e1db3b.json
@@ -0,0 +1,59 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, name, channel_type AS \"channel_type: ChannelType\", org_id, team_id\n FROM comms_channels\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "channel_type: ChannelType",
+ "type_info": {
+ "Custom": {
+ "name": "comms_channel_type",
+ "kind": {
+ "Enum": [
+ "public",
+ "organization",
+ "private",
+ "direct_message",
+ "team"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "org_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 4,
+ "name": "team_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "783fb2d2833135d5bf8aa7eb5983b773d4b7c9b508388987155815d8c7e1db3b"
+}
diff --git a/rust/cloud-storage/.sqlx/query-7e64280ac5918582d61bf6573e0f9b83180c03d2f0d5a9c8574217f9dbd02cbe.json b/rust/cloud-storage/.sqlx/query-7e64280ac5918582d61bf6573e0f9b83180c03d2f0d5a9c8574217f9dbd02cbe.json
new file mode 100644
index 0000000000..3b0a31710e
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-7e64280ac5918582d61bf6573e0f9b83180c03d2f0d5a9c8574217f9dbd02cbe.json
@@ -0,0 +1,72 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE comms_messages\n SET content = $1, updated_at = NOW(), edited_at = NOW()\n WHERE id = $2 AND channel_id = $3\n RETURNING\n id,\n channel_id,\n sender_id AS \"sender_id: MacroUserIdStr\",\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id: MacroUserIdStr",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ null,
+ null
+ ]
+ },
+ "hash": "7e64280ac5918582d61bf6573e0f9b83180c03d2f0d5a9c8574217f9dbd02cbe"
+}
diff --git a/rust/cloud-storage/.sqlx/query-869087208a0e921c85a4de60ef9037f0121d673203126052c384ccca95d472db.json b/rust/cloud-storage/.sqlx/query-869087208a0e921c85a4de60ef9037f0121d673203126052c384ccca95d472db.json
new file mode 100644
index 0000000000..e67077cf7b
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-869087208a0e921c85a4de60ef9037f0121d673203126052c384ccca95d472db.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT cp.\"sharePermissionId\" as \"share_permission_id!\"\n FROM \"ChatPermission\" cp\n WHERE cp.\"chatId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "share_permission_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "869087208a0e921c85a4de60ef9037f0121d673203126052c384ccca95d472db"
+}
diff --git a/rust/cloud-storage/.sqlx/query-88eef0eafe13e4e4f3c0f9c0792cb7e8e2f73c4f87ca77a32c64d99ac28a4b12.json b/rust/cloud-storage/.sqlx/query-88eef0eafe13e4e4f3c0f9c0792cb7e8e2f73c4f87ca77a32c64d99ac28a4b12.json
new file mode 100644
index 0000000000..7c59ecbefe
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-88eef0eafe13e4e4f3c0f9c0792cb7e8e2f73c4f87ca77a32c64d99ac28a4b12.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT u.id AS user_profile_id, mui.first_name, mui.last_name\n FROM macro_user_info mui\n JOIN \"User\" u ON mui.macro_user_id = u.macro_user_id\n WHERE u.id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_profile_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "first_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "last_name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "88eef0eafe13e4e4f3c0f9c0792cb7e8e2f73c4f87ca77a32c64d99ac28a4b12"
+}
diff --git a/rust/cloud-storage/.sqlx/query-9c2fa9459318bdf3adfd77ae07e0aa74c7b53c39640602546483c6509c94fa8d.json b/rust/cloud-storage/.sqlx/query-9c2fa9459318bdf3adfd77ae07e0aa74c7b53c39640602546483c6509c94fa8d.json
new file mode 100644
index 0000000000..3c1fac2605
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-9c2fa9459318bdf3adfd77ae07e0aa74c7b53c39640602546483c6509c94fa8d.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT sender_id AS \"sender_id: MacroUserIdStr\"\n FROM comms_messages\n WHERE id = $1 AND channel_id = $2\n ORDER BY created_at ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sender_id: MacroUserIdStr",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "9c2fa9459318bdf3adfd77ae07e0aa74c7b53c39640602546483c6509c94fa8d"
+}
diff --git a/rust/cloud-storage/.sqlx/query-9c40820250bebc60feaa2af6d84138690f54dc428ebef57f72b13d4542a984be.json b/rust/cloud-storage/.sqlx/query-9c40820250bebc60feaa2af6d84138690f54dc428ebef57f72b13d4542a984be.json
new file mode 100644
index 0000000000..8b0f84192f
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-9c40820250bebc60feaa2af6d84138690f54dc428ebef57f72b13d4542a984be.json
@@ -0,0 +1,71 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE comms_messages\n SET\n updated_at = NOW(),\n edited_at = NOW(),\n deleted_at = CASE\n WHEN $2 = false AND (content IS NULL OR content ~ '^[\\s]*$') THEN NOW()\n ELSE deleted_at\n END\n WHERE id = $1\n RETURNING\n id,\n channel_id,\n sender_id AS \"sender_id: MacroUserIdStr\",\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id: MacroUserIdStr",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ null,
+ null
+ ]
+ },
+ "hash": "9c40820250bebc60feaa2af6d84138690f54dc428ebef57f72b13d4542a984be"
+}
diff --git a/rust/cloud-storage/.sqlx/query-a080f5686385b0b8f5b10542781756629b2a2571db10a385a0d3559f64481f59.json b/rust/cloud-storage/.sqlx/query-a080f5686385b0b8f5b10542781756629b2a2571db10a385a0d3559f64481f59.json
new file mode 100644
index 0000000000..f2cc72d282
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-a080f5686385b0b8f5b10542781756629b2a2571db10a385a0d3559f64481f59.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"EmailThreadPermission\" (\"threadId\", \"sharePermissionId\", \"userId\")\n VALUES ($1, $2, $3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a080f5686385b0b8f5b10542781756629b2a2571db10a385a0d3559f64481f59"
+}
diff --git a/rust/cloud-storage/.sqlx/query-ac1973d97ddd4dcb5cacb138b9321138cea6141d03301b03f7c7e0d509663dc4.json b/rust/cloud-storage/.sqlx/query-ac1973d97ddd4dcb5cacb138b9321138cea6141d03301b03f7c7e0d509663dc4.json
new file mode 100644
index 0000000000..b3e494ac89
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-ac1973d97ddd4dcb5cacb138b9321138cea6141d03301b03f7c7e0d509663dc4.json
@@ -0,0 +1,70 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_attachments (\n id,\n message_id,\n channel_id,\n entity_type,\n entity_id,\n width,\n height\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n RETURNING id, message_id, channel_id, entity_type, entity_id, width, height, created_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "entity_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "entity_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "width",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 6,
+ "name": "height",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Varchar",
+ "Varchar",
+ "Int4",
+ "Int4"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ false
+ ]
+ },
+ "hash": "ac1973d97ddd4dcb5cacb138b9321138cea6141d03301b03f7c7e0d509663dc4"
+}
diff --git a/rust/cloud-storage/.sqlx/query-af05f3b0d0796a3cb2eed49cd562776fd1abde1cea7f0f5057fede45c2312223.json b/rust/cloud-storage/.sqlx/query-af05f3b0d0796a3cb2eed49cd562776fd1abde1cea7f0f5057fede45c2312223.json
new file mode 100644
index 0000000000..1ad2601550
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-af05f3b0d0796a3cb2eed49cd562776fd1abde1cea7f0f5057fede45c2312223.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM team_user\n WHERE user_id = $1 AND team_id = $2\n ) AS \"has_team!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "has_team!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "af05f3b0d0796a3cb2eed49cd562776fd1abde1cea7f0f5057fede45c2312223"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b96181ce30beea5d5067c9e8177d9feca7891cdf00ad560cc522121ee8d6b4ec.json b/rust/cloud-storage/.sqlx/query-b96181ce30beea5d5067c9e8177d9feca7891cdf00ad560cc522121ee8d6b4ec.json
new file mode 100644
index 0000000000..76f2bd9360
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b96181ce30beea5d5067c9e8177d9feca7891cdf00ad560cc522121ee8d6b4ec.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id\n FROM comms_channels\n WHERE channel_type = 'private'::comms_channel_type\n AND (\n (\n SELECT COUNT(*)\n FROM comms_channel_participants cp\n WHERE cp.channel_id = comms_channels.id\n AND cp.user_id = ANY($1)\n ) = CARDINALITY($1)\n AND (\n SELECT COUNT(*)\n FROM comms_channel_participants\n WHERE channel_id = comms_channels.id\n ) = CARDINALITY($1)\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "b96181ce30beea5d5067c9e8177d9feca7891cdf00ad560cc522121ee8d6b4ec"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b9a4ad717639aa71706e8476ac7eb030794f34cd8e05cc7dff262602d12ddcba.json b/rust/cloud-storage/.sqlx/query-b9a4ad717639aa71706e8476ac7eb030794f34cd8e05cc7dff262602d12ddcba.json
deleted file mode 100644
index 8bb9e6f828..0000000000
--- a/rust/cloud-storage/.sqlx/query-b9a4ad717639aa71706e8476ac7eb030794f34cd8e05cc7dff262602d12ddcba.json
+++ /dev/null
@@ -1,46 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT channel_id, user_id, role::text AS \"role!\", joined_at,\n left_at AS \"left_at?\"\n FROM comms_channel_participants\n WHERE channel_id = $1 AND left_at IS NULL\n ORDER BY joined_at ASC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "channel_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "user_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "role!",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "joined_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 4,
- "name": "left_at?",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false,
- null,
- false,
- true
- ]
- },
- "hash": "b9a4ad717639aa71706e8476ac7eb030794f34cd8e05cc7dff262602d12ddcba"
-}
diff --git a/rust/cloud-storage/.sqlx/query-bdca4a82e47757c7c1434555612b4f81dad7d0c3ec2cef1eda3afa66897081e7.json b/rust/cloud-storage/.sqlx/query-bdca4a82e47757c7c1434555612b4f81dad7d0c3ec2cef1eda3afa66897081e7.json
new file mode 100644
index 0000000000..a9084e5079
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-bdca4a82e47757c7c1434555612b4f81dad7d0c3ec2cef1eda3afa66897081e7.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT dp.\"sharePermissionId\" as \"share_permission_id!\"\n FROM \"DocumentPermission\" dp\n WHERE dp.\"documentId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "share_permission_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "bdca4a82e47757c7c1434555612b4f81dad7d0c3ec2cef1eda3afa66897081e7"
+}
diff --git a/rust/cloud-storage/.sqlx/query-bfd05323023ae02d10ecd01f6432a0b25cce4d43b63f05fd04b52860c482ffa3.json b/rust/cloud-storage/.sqlx/query-bfd05323023ae02d10ecd01f6432a0b25cce4d43b63f05fd04b52860c482ffa3.json
new file mode 100644
index 0000000000..d7418fde11
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-bfd05323023ae02d10ecd01f6432a0b25cce4d43b63f05fd04b52860c482ffa3.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE comms_channels\n SET updated_at = $2\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "bfd05323023ae02d10ecd01f6432a0b25cce4d43b63f05fd04b52860c482ffa3"
+}
diff --git a/rust/cloud-storage/.sqlx/query-c7499a6777186567833a23df8df39fd871328de140968ba50c3db3a30cd3f520.json b/rust/cloud-storage/.sqlx/query-c7499a6777186567833a23df8df39fd871328de140968ba50c3db3a30cd3f520.json
new file mode 100644
index 0000000000..bdc0ab08a8
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-c7499a6777186567833a23df8df39fd871328de140968ba50c3db3a30cd3f520.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT mui.profile_picture as \"profile_picture!\"\n FROM \"User\" u\n JOIN macro_user mu ON mu.id = u.macro_user_id\n JOIN macro_user_info mui ON mui.macro_user_id = mu.id\n WHERE u.id = $1\n AND mui.profile_picture IS NOT NULL\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "profile_picture!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "c7499a6777186567833a23df8df39fd871328de140968ba50c3db3a30cd3f520"
+}
diff --git a/rust/cloud-storage/.sqlx/query-d672dff677cfcb21b6f90672e2d79b6d56ccda8789dd737a8cb2d89eb6858b03.json b/rust/cloud-storage/.sqlx/query-d672dff677cfcb21b6f90672e2d79b6d56ccda8789dd737a8cb2d89eb6858b03.json
new file mode 100644
index 0000000000..748fb52c0c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-d672dff677cfcb21b6f90672e2d79b6d56ccda8789dd737a8cb2d89eb6858b03.json
@@ -0,0 +1,27 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_channel_participants (channel_id, role, user_id)\n VALUES ($1, $2, $3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ {
+ "Custom": {
+ "name": "comms_participant_role",
+ "kind": {
+ "Enum": [
+ "owner",
+ "admin",
+ "member"
+ ]
+ }
+ }
+ },
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d672dff677cfcb21b6f90672e2d79b6d56ccda8789dd737a8cb2d89eb6858b03"
+}
diff --git a/rust/cloud-storage/.sqlx/query-d9ad977df73e6a2e5cf561edfb41d5ab7728a12ca7245876c3ede0c3adc69647.json b/rust/cloud-storage/.sqlx/query-d9ad977df73e6a2e5cf561edfb41d5ab7728a12ca7245876c3ede0c3adc69647.json
new file mode 100644
index 0000000000..921f441cd6
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-d9ad977df73e6a2e5cf561edfb41d5ab7728a12ca7245876c3ede0c3adc69647.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT share_permission_id as \"share_permission_id!\"\n FROM (\n SELECT share_permission_id FROM calls WHERE id = $1\n UNION ALL\n SELECT share_permission_id FROM call_records WHERE id = $1\n ) t\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "share_permission_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d9ad977df73e6a2e5cf561edfb41d5ab7728a12ca7245876c3ede0c3adc69647"
+}
diff --git a/rust/cloud-storage/.sqlx/query-e2c696b916af0f7591d95a280d75c01e2e6e9dee46a74504fde48b78587934b6.json b/rust/cloud-storage/.sqlx/query-e2c696b916af0f7591d95a280d75c01e2e6e9dee46a74504fde48b78587934b6.json
new file mode 100644
index 0000000000..aadf5b33e9
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-e2c696b916af0f7591d95a280d75c01e2e6e9dee46a74504fde48b78587934b6.json
@@ -0,0 +1,27 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role)\n VALUES ($1, $2, $3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ {
+ "Custom": {
+ "name": "comms_participant_role",
+ "kind": {
+ "Enum": [
+ "owner",
+ "admin",
+ "member"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e2c696b916af0f7591d95a280d75c01e2e6e9dee46a74504fde48b78587934b6"
+}
diff --git a/rust/cloud-storage/.sqlx/query-e6a3bb4ea73a16bb6664ecb2adda3573d0cb043fee8aeb7c46a61bcd534357e3.json b/rust/cloud-storage/.sqlx/query-e6a3bb4ea73a16bb6664ecb2adda3573d0cb043fee8aeb7c46a61bcd534357e3.json
new file mode 100644
index 0000000000..a06abc2bc4
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-e6a3bb4ea73a16bb6664ecb2adda3573d0cb043fee8aeb7c46a61bcd534357e3.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.name AS document_name,\n d.owner AS \"owner: MacroUserIdStr\",\n d.\"fileType\" AS file_type,\n dst.sub_type::text AS sub_type\n FROM \"Document\" d\n LEFT JOIN document_sub_type dst ON dst.document_id = d.id\n WHERE d.id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner: MacroUserIdStr",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "file_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "sub_type",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ null
+ ]
+ },
+ "hash": "e6a3bb4ea73a16bb6664ecb2adda3573d0cb043fee8aeb7c46a61bcd534357e3"
+}
diff --git a/rust/cloud-storage/.sqlx/query-e757b0ff97cdde3e3742a24ca0efe796c255daff9e95ca53b7dcc6f824d0c942.json b/rust/cloud-storage/.sqlx/query-e757b0ff97cdde3e3742a24ca0efe796c255daff9e95ca53b7dcc6f824d0c942.json
new file mode 100644
index 0000000000..d249a31a8d
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-e757b0ff97cdde3e3742a24ca0efe796c255daff9e95ca53b7dcc6f824d0c942.json
@@ -0,0 +1,57 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n user_id,\n channel_id,\n joined_at,\n left_at::timestamptz AS \"left_at?\",\n role AS \"role: ParticipantRole\"\n FROM comms_channel_participants\n WHERE channel_id = $1\n ORDER BY joined_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "joined_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "left_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "role: ParticipantRole",
+ "type_info": {
+ "Custom": {
+ "name": "comms_participant_role",
+ "kind": {
+ "Enum": [
+ "owner",
+ "admin",
+ "member"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "e757b0ff97cdde3e3742a24ca0efe796c255daff9e95ca53b7dcc6f824d0c942"
+}
diff --git a/rust/cloud-storage/.sqlx/query-eaef3f030f89336b4530560c11b502fd1ef001d1247a155814df5c4510170aaa.json b/rust/cloud-storage/.sqlx/query-eaef3f030f89336b4530560c11b502fd1ef001d1247a155814df5c4510170aaa.json
new file mode 100644
index 0000000000..40b5070db6
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-eaef3f030f89336b4530560c11b502fd1ef001d1247a155814df5c4510170aaa.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT u.id\n FROM \"User\" u\n WHERE u.id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "eaef3f030f89336b4530560c11b502fd1ef001d1247a155814df5c4510170aaa"
+}
diff --git a/rust/cloud-storage/.sqlx/query-f04a97eb13684a35daf6c5ff52890da499864d7f8e97a390a11b384d6429fa13.json b/rust/cloud-storage/.sqlx/query-f04a97eb13684a35daf6c5ff52890da499864d7f8e97a390a11b384d6429fa13.json
new file mode 100644
index 0000000000..5b722afbd3
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-f04a97eb13684a35daf6c5ff52890da499864d7f8e97a390a11b384d6429fa13.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM comms_channels\n WHERE id = $1\n AND EXISTS (\n SELECT 1\n FROM comms_channel_participants\n WHERE channel_id = $1\n AND user_id = $2\n AND role = 'owner'::comms_participant_role\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f04a97eb13684a35daf6c5ff52890da499864d7f8e97a390a11b384d6429fa13"
+}
diff --git a/rust/cloud-storage/.sqlx/query-fd9545dca362a8cdf1b3189af6277d724c16d6068b7ab828c2eb604617227113.json b/rust/cloud-storage/.sqlx/query-fd9545dca362a8cdf1b3189af6277d724c16d6068b7ab828c2eb604617227113.json
new file mode 100644
index 0000000000..a9456acc75
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-fd9545dca362a8cdf1b3189af6277d724c16d6068b7ab828c2eb604617227113.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM comms_entity_mentions\n WHERE entity_id = ANY($1) AND source_entity_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fd9545dca362a8cdf1b3189af6277d724c16d6068b7ab828c2eb604617227113"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 02c688c8b9..8106012144 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1957,18 +1957,28 @@ dependencies = [
"async-trait",
"axum",
"chrono",
+ "connection_gateway_client",
+ "contacts",
"entity_access",
+ "entity_access_db_utils",
"http-body-util",
"macro_db_migrator",
"macro_user_id",
+ "macro_uuid",
"mockall",
+ "model-entity",
"model-error-response",
+ "model_notifications",
"model_user",
"models_pagination",
+ "models_permissions",
+ "notification",
"schemars 1.2.1",
"serde",
"serde_json",
+ "share_permission_db_utils",
"sqlx",
+ "sqs_client",
"thiserror 2.0.18",
"tokio",
"tower 0.5.3",
@@ -6243,8 +6253,10 @@ dependencies = [
"reqwest 0.13.3",
"serde",
"serde_json",
+ "sqlx",
"tokio",
"tokio-tungstenite 0.28.0",
+ "uuid",
]
[[package]]
@@ -6574,6 +6586,7 @@ dependencies = [
"doppleganger",
"nom 8.0.0",
"serde",
+ "sqlx",
"thiserror 2.0.18",
"tracing",
"utoipa",
@@ -10622,6 +10635,18 @@ dependencies = [
"lazy_static",
]
+[[package]]
+name = "share_permission_db_utils"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "entity_access_db_utils",
+ "macro_user_id",
+ "macro_uuid",
+ "models_permissions",
+ "sqlx",
+]
+
[[package]]
name = "shlex"
version = "1.3.0"
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 478be89e08..78ad8c9a48 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.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 channels::domain::service::ChannelMessagesServiceImpl;
+use channels::domain::service::ChannelServiceImpl;
use channels::inbound::toolset::ChannelToolContext;
-use channels::outbound::pg_channels_repo::PgChannelMessagesRepo;
+use channels::outbound::pg_channels_repo::PgChannelsRepo;
use chat::domain::service::ChatServiceImpl;
use chat::inbound::toolset::ChatToolContext;
use chat::outbound::postgres::PgChatRepo;
@@ -62,7 +62,7 @@ pub type ToolCommsService = comms::domain::service::ChannelServiceImpl<
>;
/// Type alias for the channel messages service implementation used by AI tools.
-pub type ToolChannelMessagesService = ChannelMessagesServiceImpl<PgChannelMessagesRepo>;
+pub type ToolChannelMessagesService = ChannelServiceImpl<PgChannelsRepo>;
/// Type alias for the channel AI tool context.
pub type ToolChannelToolContext =
@@ -71,7 +71,7 @@ pub type ToolChannelToolContext =
/// Build the channel AI tool context from a Postgres pool.
pub fn build_channel_tool_context(pool: sqlx::PgPool) -> ToolChannelToolContext {
ChannelToolContext::new(
- ChannelMessagesServiceImpl::new(PgChannelMessagesRepo::new(pool.clone())),
+ ChannelServiceImpl::new(PgChannelsRepo::new(pool.clone())),
entity_access::domain::service::EntityAccessServiceImpl::new(
entity_access::outbound::PgAccessRepository::new(pool),
),
diff --git a/rust/cloud-storage/channels/Cargo.toml b/rust/cloud-storage/channels/Cargo.toml
index 5e1102e392..99b29c1a2b 100644
--- a/rust/cloud-storage/channels/Cargo.toml
+++ b/rust/cloud-storage/channels/Cargo.toml
@@ -23,20 +23,48 @@ inbound = [
"models_pagination/axum",
"ports",
]
-outbound = ["ports"]
+outbound = [
+ "ports",
+ "dep:connection_gateway_client",
+ "dep:contacts",
+ "dep:entity_access",
+ "entity_access/ports",
+ "dep:entity_access_db_utils",
+ "dep:macro_uuid",
+ "dep:model-entity",
+ "dep:model_notifications",
+ "dep:models_permissions",
+ "dep:notification_hex",
+ "dep:serde_json",
+ "dep:share_permission_db_utils",
+ "dep:sqs_client",
+ "dep:sqlx",
+ "macro_user_id/sqlx",
+]
ports = ["dep:tokio"]
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
chrono = { workspace = true }
+connection_gateway_client = { path = "../connection_gateway_client", optional = true }
+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 }
model-error-response = { path = "../model-error-response", optional = true }
macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid", optional = true }
+model-entity = { path = "../model-entity", optional = true }
+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 }
+notification_hex = { path = "../notification", package = "notification", optional = true }
serde = { workspace = true }
-sqlx = { 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 }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["macros"], optional = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/channels/src/domain/events.rs b/rust/cloud-storage/channels/src/domain/events.rs
new file mode 100644
index 0000000000..d8a09b0f6c
--- /dev/null
+++ b/rust/cloud-storage/channels/src/domain/events.rs
@@ -0,0 +1,137 @@
+//! Domain events emitted by channel mutation workflows.
+
+use crate::domain::models::{
+ ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, MutatedAttachment,
+ MutatedMessage, SimpleMention, TypingAction,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+/// Events emitted after durable channel state changes.
+#[derive(Debug, Clone)]
+pub enum ChannelEvent {
+ /// A channel was created.
+ ChannelCreated {
+ /// Created channel id.
+ channel_id: Uuid,
+ /// Type of channel that was created.
+ channel_type: ChannelType,
+ /// Active participants after creation.
+ participant_user_ids: Vec<MacroUserIdStr<'static>>,
+ },
+ /// A channel was deleted.
+ ChannelDeleted {
+ /// Deleted channel id.
+ channel_id: Uuid,
+ },
+ /// A message was posted.
+ MessagePosted {
+ /// Channel containing the message.
+ channel_id: Uuid,
+ /// Resolved channel metadata for downstream side effects.
+ metadata: ChannelMetadata,
+ /// Active channel participants at publish time.
+ participants: Vec<ChannelParticipant>,
+ /// Persisted message payload.
+ message: MutatedMessage,
+ /// Mentions attached to the message.
+ mentions: Vec<SimpleMention>,
+ /// Whether the message contains attachments.
+ has_attachments: bool,
+ /// Attachments persisted with the message.
+ attachments: Vec<MutatedAttachment>,
+ /// Client mutation nonce echoed to realtime listeners.
+ nonce: Option<String>,
+ },
+ /// Message attachments changed.
+ AttachmentsChanged {
+ /// Channel containing the message.
+ channel_id: Uuid,
+ /// Message whose attachments changed.
+ message_id: Uuid,
+ /// Current attachment set for the message.
+ attachments: Vec<MutatedAttachment>,
+ /// Realtime recipients at mutation time.
+ recipients: Vec<MacroUserIdStr<'static>>,
+ /// Client mutation nonce echoed to realtime listeners.
+ nonce: Option<String>,
+ },
+ /// Message content changed.
+ MessageChanged {
+ /// Channel containing the message.
+ channel_id: Uuid,
+ /// Persisted message payload after mutation.
+ message: MutatedMessage,
+ /// Realtime recipients at mutation time.
+ recipients: Vec<MacroUserIdStr<'static>>,
+ /// Client mutation nonce echoed to realtime listeners.
+ nonce: Option<String>,
+ },
+ /// Message tombstone state changed.
+ MessageDeleted {
+ /// Channel containing the message.
+ channel_id: Uuid,
+ /// Persisted message payload after deletion.
+ message: MutatedMessage,
+ /// Realtime recipients at mutation time.
+ recipients: Vec<MacroUserIdStr<'static>>,
+ /// Client mutation nonce echoed to realtime listeners.
+ nonce: Option<String>,
+ },
+ /// Message reactions changed.
+ ReactionChanged {
+ /// Channel containing the message.
+ channel_id: Uuid,
+ /// Message whose reactions changed.
+ message_id: Uuid,
+ /// Current grouped reaction state for the message.
+ reactions: Vec<CountedReaction>,
+ /// Realtime recipients at mutation time.
+ recipients: Vec<MacroUserIdStr<'static>>,
+ /// Client mutation nonce echoed to realtime listeners.
+ nonce: Option<String>,
+ },
+ /// A user typing state changed.
+ TypingChanged {
+ /// Channel containing the typing update.
+ channel_id: Uuid,
+ /// User whose typing state changed.
+ user_id: String,
+ /// Typing action.
+ action: TypingAction,
+ /// Optional thread id for thread-scoped typing.
+ thread_id: Option<Uuid>,
+ /// Realtime recipients at mutation time.
+ recipients: Vec<MacroUserIdStr<'static>>,
+ /// Client mutation nonce echoed to realtime listeners.
+ nonce: Option<String>,
+ },
+ /// Participants were explicitly added to a channel.
+ ParticipantsAdded {
+ /// Channel receiving new participants.
+ channel_id: Uuid,
+ /// Type of channel that received participants.
+ channel_type: ChannelType,
+ /// Active participants after the addition.
+ active_participant_user_ids: Vec<MacroUserIdStr<'static>>,
+ /// User who initiated the add.
+ invited_by_user_id: MacroUserIdStr<'static>,
+ /// Newly added recipients.
+ recipient_user_ids: Vec<MacroUserIdStr<'static>>,
+ /// Resolved channel metadata for notification copy.
+ metadata: ChannelMetadata,
+ /// Optional message content associated with the invite.
+ message_content: Option<String>,
+ },
+ /// A user joined a channel.
+ ParticipantJoined {
+ /// Channel that was joined.
+ channel_id: Uuid,
+ /// Type of channel that was joined.
+ channel_type: ChannelType,
+ /// User that joined the channel.
+ user_id: MacroUserIdStr<'static>,
+ /// Active participants after the join.
+ active_participant_user_ids: Vec<MacroUserIdStr<'static>>,
+ },
+}
diff --git a/rust/cloud-storage/channels/src/domain/mod.rs b/rust/cloud-storage/channels/src/domain/mod.rs
index 2a2e74f008..0524cd6faa 100644
--- a/rust/cloud-storage/channels/src/domain/mod.rs
+++ b/rust/cloud-storage/channels/src/domain/mod.rs
@@ -1,3 +1,5 @@
+/// Domain events emitted by channel workflows.
+pub mod events;
/// Domain models for channel messages.
pub mod models;
#[cfg(feature = "ports")]
@@ -6,3 +8,6 @@ pub mod ports;
#[cfg(feature = "ports")]
/// Service orchestration for channel messages.
pub mod service;
+#[cfg(feature = "ports")]
+/// Domain orchestration for channel side effects.
+pub mod side_effects;
diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rs
index a30361fb67..94ed9c0674 100644
--- a/rust/cloud-storage/channels/src/domain/models.rs
+++ b/rust/cloud-storage/channels/src/domain/models.rs
@@ -1,4 +1,5 @@
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -186,7 +187,7 @@ pub struct ThreadReply {
}
/// A reaction emoji with the list of users who reacted.
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Serialize)]
pub struct CountedReaction {
/// The emoji string.
pub emoji: String,
@@ -252,7 +253,12 @@ impl SortOn<CreatedAt> for ChannelAttachment {
}
/// Role of a channel participant.
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "outbound", derive(sqlx::Type))]
+#[cfg_attr(
+ feature = "outbound",
+ sqlx(type_name = "comms_participant_role", rename_all = "lowercase")
+)]
pub enum ParticipantRole {
/// Channel owner.
Owner,
@@ -340,3 +346,372 @@ pub struct ThreadReplyRow {
/// Edited timestamp.
pub edited_at: Option<DateTime<Utc>>,
}
+
+/// Type of channel.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[cfg_attr(feature = "outbound", derive(sqlx::Type))]
+#[cfg_attr(
+ feature = "outbound",
+ sqlx(type_name = "comms_channel_type", rename_all = "snake_case")
+)]
+#[serde(rename_all = "snake_case")]
+pub enum ChannelType {
+ /// Public channel.
+ Public,
+ /// Organization-wide channel.
+ Organization,
+ /// Private group channel.
+ Private,
+ /// One-to-one direct message channel.
+ DirectMessage,
+ /// Team channel.
+ Team,
+}
+
+/// Result of a get-or-create channel operation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum GetOrCreateAction {
+ /// An existing channel was returned.
+ Get,
+ /// A new channel was created.
+ Create,
+}
+
+/// Typing indicator action.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "lowercase")]
+pub enum TypingAction {
+ /// User started typing.
+ Start,
+ /// User stopped typing.
+ Stop,
+}
+
+/// Reaction mutation action.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub enum ReactionAction {
+ /// Add a reaction.
+ Add,
+ /// Remove a reaction.
+ Remove,
+}
+
+/// Request to create a channel.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct CreateChannelRequest {
+ /// Optional channel name.
+ pub name: Option<String>,
+ /// Channel type.
+ pub channel_type: ChannelType,
+ /// Team id for team channels.
+ pub team_id: Option<Uuid>,
+ /// Participants to add, excluding the owner.
+ pub participants: Vec<String>,
+}
+
+/// Response returned after creating a channel.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct CreateChannelResponse {
+ /// Created channel id.
+ pub id: String,
+}
+
+/// Request to get or create a direct message channel.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct GetOrCreateDmRequest {
+ /// Recipient user id.
+ pub recipient_id: String,
+}
+
+/// Request to get or create a private channel.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct GetOrCreatePrivateRequest {
+ /// Recipient user ids.
+ pub recipients: Vec<String>,
+}
+
+/// Response for get-or-create channel operations.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct GetOrCreateChannelResponse {
+ /// Channel id.
+ pub channel_id: String,
+ /// Whether the channel was fetched or created.
+ pub action: GetOrCreateAction,
+}
+
+/// Request to patch a channel.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct PatchChannelRequest {
+ /// New channel name.
+ pub channel_name: Option<String>,
+}
+
+/// New attachment to add to a channel message.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct NewChannelAttachment {
+ /// Attachment entity type.
+ pub entity_type: String,
+ /// Attachment entity id.
+ pub entity_id: String,
+ /// Optional rendered width.
+ pub width: Option<i32>,
+ /// Optional rendered height.
+ pub height: Option<i32>,
+}
+
+/// Simple entity mention attached to a message.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct SimpleMention {
+ /// Mentioned entity type.
+ pub entity_type: String,
+ /// Mentioned entity id.
+ pub entity_id: String,
+}
+
+/// Shareable entity type referenced by a channel message.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum ReferencedShareItemType {
+ /// Document entity.
+ Document,
+ /// Chat entity.
+ Chat,
+ /// Project entity.
+ Project,
+ /// Email thread entity.
+ EmailThread,
+ /// Call entity.
+ Call,
+}
+
+impl ReferencedShareItemType {
+ /// Parse a raw entity type from the transport/storage representation.
+ pub fn from_raw(raw: &str) -> Option<Self> {
+ match raw {
+ "document" => Some(Self::Document),
+ "chat" => Some(Self::Chat),
+ "project" => Some(Self::Project),
+ "thread" => Some(Self::EmailThread),
+ "call" => Some(Self::Call),
+ _ => None,
+ }
+ }
+
+ /// Return the storage representation of this item type.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Document => "document",
+ Self::Chat => "chat",
+ Self::Project => "project",
+ Self::EmailThread => "thread",
+ Self::Call => "call",
+ }
+ }
+}
+
+/// Shareable item referenced by a channel message.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct ReferencedShareItem {
+ entity_id: String,
+ entity_type: ReferencedShareItemType,
+}
+
+impl ReferencedShareItem {
+ /// Build a typed referenced share item.
+ pub fn new(entity_id: impl Into<String>, entity_type: ReferencedShareItemType) -> Self {
+ Self {
+ entity_id: entity_id.into(),
+ entity_type,
+ }
+ }
+
+ /// Build a typed referenced share item from raw entity data.
+ pub fn from_raw(entity_id: impl Into<String>, entity_type: &str) -> Option<Self> {
+ Some(Self::new(
+ entity_id,
+ ReferencedShareItemType::from_raw(entity_type)?,
+ ))
+ }
+
+ /// Referenced entity id.
+ pub fn entity_id(&self) -> &str {
+ &self.entity_id
+ }
+
+ /// Referenced entity type.
+ pub fn entity_type(&self) -> ReferencedShareItemType {
+ self.entity_type
+ }
+}
+
+/// Request to send a channel message.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct PostMessageRequest {
+ /// Message body.
+ pub content: String,
+ /// Message mentions.
+ pub mentions: Vec<SimpleMention>,
+ /// Optional thread parent id.
+ pub thread_id: Option<Uuid>,
+ /// Attachments to add after message creation.
+ pub attachments: Vec<NewChannelAttachment>,
+ /// Optional optimistic-update nonce.
+ pub nonce: Option<String>,
+}
+
+/// Response returned after sending a message.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct PostMessageResponse {
+ /// Created message id.
+ pub id: String,
+ /// Optional optimistic-update nonce.
+ pub nonce: Option<String>,
+}
+
+/// Request to patch a channel message.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct PatchMessageRequest {
+ /// Optional replacement message body.
+ pub content: Option<String>,
+ /// Optional replacement mentions.
+ pub mentions: Option<Vec<SimpleMention>>,
+ /// Attachment ids to remove.
+ pub attachment_ids_to_delete: Option<Vec<String>>,
+ /// Attachments to add.
+ pub attachments_to_add: Option<Vec<NewChannelAttachment>>,
+ /// Optional optimistic-update nonce.
+ pub nonce: Option<String>,
+}
+
+/// Query parameters for deleting a message.
+#[derive(Debug, Clone, Default, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct DeleteMessageQuery {
+ /// Optional optimistic-update nonce.
+ pub nonce: Option<String>,
+}
+
+/// Request to mutate a reaction.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct PostReactionRequest {
+ /// Reaction emoji.
+ pub emoji: String,
+ /// Message id to react to.
+ pub message_id: String,
+ /// Reaction action.
+ pub action: ReactionAction,
+ /// Optional optimistic-update nonce.
+ pub nonce: Option<String>,
+}
+
+/// Request to emit a typing event.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct PostTypingRequest {
+ /// Typing action.
+ pub action: TypingAction,
+ /// Optional thread id.
+ pub thread_id: Option<String>,
+ /// Optional optimistic-update nonce.
+ pub nonce: Option<String>,
+}
+
+/// Request to add participants.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct AddParticipantsRequest {
+ /// User ids to add.
+ pub participants: Vec<String>,
+}
+
+/// Request to remove participants.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct RemoveParticipantsRequest {
+ /// User ids to remove.
+ pub participants: Vec<String>,
+}
+
+/// Channel metadata needed for notifications.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ChannelMetadata {
+ /// Channel type.
+ pub channel_type: ChannelType,
+ /// Resolved display name.
+ pub channel_name: String,
+}
+
+/// Persisted channel message returned by mutation operations.
+#[derive(Debug, Clone, Serialize)]
+pub struct MutatedMessage {
+ /// Message id.
+ pub id: Uuid,
+ /// Channel id.
+ pub channel_id: Uuid,
+ /// Thread parent id.
+ pub thread_id: Option<Uuid>,
+ /// Sender user id.
+ pub sender_id: MacroUserIdStr<'static>,
+ /// Message body.
+ pub content: String,
+ /// Created timestamp.
+ pub created_at: DateTime<Utc>,
+ /// Updated timestamp.
+ pub updated_at: DateTime<Utc>,
+ /// Edited timestamp.
+ pub edited_at: Option<DateTime<Utc>>,
+ /// Deleted timestamp.
+ pub deleted_at: Option<DateTime<Utc>>,
+}
+
+/// Persisted attachment returned by mutation operations.
+#[derive(Debug, Clone, Serialize)]
+pub struct MutatedAttachment {
+ /// Attachment id.
+ pub id: Uuid,
+ /// Channel id.
+ pub channel_id: Uuid,
+ /// Message id.
+ pub message_id: Uuid,
+ /// Attachment entity type.
+ pub entity_type: String,
+ /// Attachment entity id.
+ pub entity_id: String,
+ /// Optional rendered width.
+ pub width: Option<i32>,
+ /// Optional rendered height.
+ pub height: Option<i32>,
+ /// Created timestamp.
+ pub created_at: DateTime<Utc>,
+}
+
+/// Channel info row used by mutation logic.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ChannelInfo {
+ /// Channel id.
+ pub id: Uuid,
+ /// Stored channel 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>,
+}
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index 528e6cde59..9abc26930d 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -1,19 +1,29 @@
+use crate::domain::events::ChannelEvent;
use crate::domain::models::{
- ChannelAttachment, ChannelAttachmentType, ChannelMessageFilters, ChannelParticipant,
- CountedReaction, MessageAttachment, MessagePageDirection, ResolvedChannelMessage, ThreadData,
- ThreadReply, ThreadReplyRow, TopLevelMessageRow,
+ AddParticipantsRequest, ChannelAttachment, ChannelAttachmentType, ChannelInfo,
+ ChannelMessageFilters, ChannelMetadata, ChannelParticipant, CountedReaction,
+ CreateChannelRequest, CreateChannelResponse, DeleteMessageQuery, GetOrCreateChannelResponse,
+ GetOrCreateDmRequest, GetOrCreatePrivateRequest, MessageAttachment, MessagePageDirection,
+ MutatedAttachment, MutatedMessage, NewChannelAttachment, PatchChannelRequest,
+ PatchMessageRequest, PostMessageRequest, PostMessageResponse, PostReactionRequest,
+ PostTypingRequest, ReferencedShareItem, RemoveParticipantsRequest, ResolvedChannelMessage,
+ SimpleMention, ThreadData, ThreadReply, ThreadReplyRow, TopLevelMessageRow,
+};
+use crate::domain::side_effects::{
+ ChannelDocumentMention, ChannelNotificationEffect, ChannelRealtimeEffect,
+ ThreadNotificationContext,
};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Query};
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use uuid::Uuid;
-/// Repository for fetching channel message data.
+/// Repository for channel persistence and query data.
#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
-pub trait ChannelMessagesRepo: Send + Sync + 'static {
+pub trait ChannelRepo: Send + Sync + 'static {
/// Error type for repo operations.
- type Err: Send;
+ type Err: Into<anyhow::Error> + Send;
/// Fetch top-level messages (thread_id IS NULL). Cursor-paginated on created_at DESC.
///
@@ -92,10 +102,210 @@ pub trait ChannelMessagesRepo: Send + Sync + 'static {
anchor_id: Uuid,
limit: u16,
) -> impl Future<Output = Result<(Vec<TopLevelMessageRow>, Vec<TopLevelMessageRow>), Self::Err>> + Send;
+
+ /// Fetch channel metadata.
+ fn get_channel_info(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<ChannelInfo, Self::Err>> + Send;
+
+ /// Resolve channel metadata from a user's perspective.
+ fn get_channel_metadata(
+ &self,
+ channel_id: Uuid,
+ viewer_user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<ChannelMetadata, Self::Err>> + Send;
+
+ /// Check whether a user belongs to a team.
+ fn user_has_team(
+ &self,
+ user_id: String,
+ team_id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// Create a channel.
+ fn create_channel(
+ &self,
+ owner_id: String,
+ org_id: Option<i64>,
+ req: CreateChannelRequest,
+ ) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;
+
+ /// Fetch an existing direct message channel.
+ fn maybe_get_dm(
+ &self,
+ user_id: String,
+ recipient_id: String,
+ ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;
+
+ /// Fetch an existing private channel.
+ fn maybe_get_private_channel(
+ &self,
+ participants: Vec<String>,
+ ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;
+
+ /// Patch a channel.
+ fn patch_channel(
+ &self,
+ channel_id: Uuid,
+ user_id: String,
+ req: PatchChannelRequest,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Delete a channel.
+ fn delete_channel(
+ &self,
+ channel_id: Uuid,
+ user_id: String,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Add a participant.
+ fn add_participant(
+ &self,
+ channel_id: Uuid,
+ user_id: String,
+ role: super::models::ParticipantRole,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Remove a participant.
+ fn remove_participant(
+ &self,
+ channel_id: Uuid,
+ user_id: String,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Create a message.
+ fn create_message(
+ &self,
+ channel_id: Uuid,
+ sender_id: String,
+ content: String,
+ thread_id: Option<Uuid>,
+ ) -> impl Future<Output = Result<MutatedMessage, Self::Err>> + Send;
+
+ /// Update the channel activity timestamp.
+ fn touch_channel_updated_at(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Create message mentions.
+ fn create_message_mentions(
+ &self,
+ message_id: Uuid,
+ mentions: Vec<SimpleMention>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Sync message mentions by deleting old mentions and creating new ones.
+ fn sync_message_mentions(
+ &self,
+ message_id: Uuid,
+ mentions: Vec<SimpleMention>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Add attachments to a message.
+ fn add_attachments(
+ &self,
+ message_id: Uuid,
+ channel_id: Uuid,
+ attachments: Vec<NewChannelAttachment>,
+ ) -> impl Future<Output = Result<Vec<MutatedAttachment>, Self::Err>> + Send;
+
+ /// Get all attachments for a message.
+ fn get_message_attachments(
+ &self,
+ message_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<MutatedAttachment>, Self::Err>> + Send;
+
+ /// Delete attachments by id.
+ fn delete_attachments(
+ &self,
+ attachment_ids: Vec<Uuid>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Delete entity mentions for detached attachment entity ids.
+ fn delete_entity_mentions_for_entities(
+ &self,
+ entity_ids: Vec<String>,
+ source_entity_id: String,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Patch message attachment state.
+ fn patch_message_attachments(
+ &self,
+ message_id: Uuid,
+ attachments: Vec<MutatedAttachment>,
+ ) -> impl Future<Output = Result<MutatedMessage, Self::Err>> + Send;
+
+ /// Patch message content within a channel.
+ fn patch_message(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ content: String,
+ ) -> impl Future<Output = Result<MutatedMessage, Self::Err>> + Send;
+
+ /// Delete a message within a channel.
+ fn delete_message(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> impl Future<Output = Result<MutatedMessage, Self::Err>> + Send;
+
+ /// Fetch the owner of a message within a channel.
+ fn get_message_owner(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
+
+ /// Fetch active participants.
+ fn get_participants(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<ChannelParticipant>, Self::Err>> + Send;
+
+ /// Fetch notification recipients for a thread.
+ fn get_thread_participants(
+ &self,
+ thread_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, Self::Err>> + Send;
+
+ /// Upsert activity for the user in the channel.
+ fn upsert_activity(
+ &self,
+ user_id: String,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Add a reaction to a message within a channel.
+ fn add_reaction(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ emoji: String,
+ user_id: String,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Remove a reaction from a message within a channel.
+ fn remove_reaction(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ emoji: String,
+ user_id: String,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Get grouped reactions for a message within a channel.
+ fn get_message_reactions(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<CountedReaction>, Self::Err>> + Send;
}
-/// Service for fetching paginated channel messages.
-pub trait ChannelMessagesService: Send + Sync + 'static {
+/// Service for channel reads and mutations.
+pub trait ChannelService: Send + Sync + 'static {
/// Fetch a page of channel messages with thread previews, reactions, and attachments.
///
/// `notification_user_id` is used only when `filters.notification_filters` is non-empty.
@@ -153,6 +363,202 @@ pub trait ChannelMessagesService: Send + Sync + 'static {
let _ = channel_id;
async move { Err(ChannelMessagesErr::MessageNotFound(message_id)) }
}
+
+ // Channel mutation operations.
+
+ /// Create a channel.
+ fn create_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _actor_org_id: Option<i64>,
+ _req: CreateChannelRequest,
+ ) -> impl Future<Output = Result<CreateChannelResponse, ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Get or create a direct message channel.
+ fn get_or_create_dm(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _req: GetOrCreateDmRequest,
+ ) -> impl Future<Output = Result<GetOrCreateChannelResponse, ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Get or create a private channel.
+ fn get_or_create_private(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _req: GetOrCreatePrivateRequest,
+ ) -> impl Future<Output = Result<GetOrCreateChannelResponse, ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Patch a channel.
+ fn patch_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _req: PatchChannelRequest,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Delete a channel.
+ fn delete_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Send a message.
+ fn post_message(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _req: PostMessageRequest,
+ ) -> impl Future<Output = Result<PostMessageResponse, ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Patch a message.
+ fn patch_message(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _actor_role: super::models::ParticipantRole,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _req: PatchMessageRequest,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Delete a message.
+ fn delete_message(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _actor_role: super::models::ParticipantRole,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _query: DeleteMessageQuery,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Mutate a reaction.
+ fn post_reaction(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _req: PostReactionRequest,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Emit a typing update.
+ fn post_typing(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _req: PostTypingRequest,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Add participants to a channel.
+ fn add_participants(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _req: AddParticipantsRequest,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Remove participants from a channel.
+ fn remove_participants(
+ &self,
+ _channel_id: Uuid,
+ _req: RemoveParticipantsRequest,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Join a channel.
+ fn join_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
+ /// Leave a channel.
+ fn leave_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
}
/// A paginated page of channel messages.
@@ -190,3 +596,142 @@ pub enum ChannelMessagesErr {
#[error("message {0} not found")]
MessageNotFound(Uuid),
}
+
+/// Publisher for realtime channel side-effect commands.
+pub trait ChannelRealtimePublisher: Send + Sync + 'static {
+ /// Error type for publishing operations.
+ type Err: Into<anyhow::Error> + Send;
+
+ /// Publish an explicit realtime effect.
+ fn publish(
+ &self,
+ effect: ChannelRealtimeEffect,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Sender for notification side-effect commands.
+pub trait ChannelNotificationSender: Send + Sync + 'static {
+ /// Error type for notification operations.
+ type Err: Into<anyhow::Error> + Send;
+
+ /// Send an explicit notification effect.
+ fn send(
+ &self,
+ notification: ChannelNotificationEffect,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Read model for data needed while deriving side effects.
+pub trait ChannelSideEffectContext: Send + Sync + 'static {
+ /// Error type for context lookups.
+ type Err: Into<anyhow::Error> + Send;
+
+ /// Count persisted channel messages.
+ fn get_channel_message_count(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<i64, Self::Err>> + Send;
+
+ /// Return user ids that exist in the application.
+ fn get_existing_user_ids(
+ &self,
+ user_ids: Vec<MacroUserIdStr<'static>>,
+ ) -> impl Future<Output = Result<HashSet<String>, Self::Err>> + Send;
+
+ /// Load display metadata for mentioned documents.
+ fn get_document_mentions(
+ &self,
+ document_ids: Vec<String>,
+ ) -> impl Future<Output = Result<Vec<ChannelDocumentMention>, Self::Err>> + Send;
+
+ /// Load notification context for a thread reply.
+ fn get_thread_notification_context(
+ &self,
+ thread_id: Uuid,
+ ) -> impl Future<Output = Result<ThreadNotificationContext, Self::Err>> + Send;
+
+ /// Load a user's profile picture URL for notification copy.
+ fn get_sender_profile_picture_url(
+ &self,
+ sender_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Option<String>> + Send;
+}
+
+/// Handler for durable channel events.
+pub trait ChannelEventHandler: Clone + Send + Sync + 'static {
+ /// Handle a durable channel event.
+ fn handle(&self, event: ChannelEvent) -> impl Future<Output = ()> + Send;
+}
+
+/// Dispatcher for channel side effects emitted after durable state changes.
+pub trait ChannelEventDispatcher: Send + Sync + 'static {
+ /// Fire-and-forget dispatch of a channel event.
+ fn dispatch(&self, event: ChannelEvent);
+}
+
+/// Dispatcher for contact graph updates.
+pub trait ChannelContactsDispatcher: Send + Sync + 'static {
+ /// Error type for contacts operations.
+ type Err: Into<anyhow::Error> + Send;
+
+ /// Enqueue a complete contact graph update for the provided users.
+ fn enqueue_contacts(
+ &self,
+ users: HashSet<MacroUserIdStr<'static>>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Indexer for channel search updates.
+pub trait ChannelSearchIndexer: Send + Sync + 'static {
+ /// Enqueue a message upsert.
+ fn index_message(&self, channel_id: Uuid, message_id: Uuid) -> impl Future<Output = ()> + Send;
+
+ /// Enqueue a message or channel removal.
+ fn remove_message(
+ &self,
+ channel_id: Uuid,
+ message_id: Option<Uuid>,
+ ) -> impl Future<Output = ()> + Send;
+}
+
+/// Share-permission updater for items referenced by channel messages.
+pub trait ChannelReferenceSharePermissions: Send + Sync + 'static {
+ /// Error type for reference share-permission operations.
+ type Err: Into<anyhow::Error> + Send;
+
+ /// Update channel share permissions for referenced items that `actor` can view.
+ ///
+ /// Implementations must not grant access for an item the actor cannot already view.
+ fn update_channel_share_permissions_for_referenced_items(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ items: Vec<ReferencedShareItem>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Errors that can occur while mutating channels.
+#[derive(Debug, thiserror::Error)]
+pub enum ChannelMutationErr {
+ /// Bad request.
+ #[error("{0}")]
+ BadRequest(String),
+ /// Unauthorized mutation attempt.
+ #[error("{0}")]
+ Unauthorized(String),
+ /// Not found.
+ #[error("{0}")]
+ NotFound(String),
+ /// Repository error.
+ #[error(transparent)]
+ Repo(#[from] anyhow::Error),
+ /// Realtime gateway error.
+ #[error(transparent)]
+ Gateway(anyhow::Error),
+ /// Notification dispatch error.
+ #[error(transparent)]
+ Notification(anyhow::Error),
+ /// Contacts dispatch error.
+ #[error(transparent)]
+ Contacts(anyhow::Error),
+}
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index c6a4a86dcf..5cbd745a76 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -1,11 +1,18 @@
use crate::domain::{
+ events::ChannelEvent,
models::{
- ChannelAttachmentType, ChannelMessage, ChannelMessageFilters, ChannelParticipant,
- MessagePageDirection, ResolvedChannelMessage, ThreadInfo, ThreadReply, TopLevelMessageRow,
+ AddParticipantsRequest, ChannelAttachmentType, ChannelMessage, ChannelMessageFilters,
+ ChannelParticipant, ChannelType, DeleteMessageQuery, GetOrCreateAction,
+ GetOrCreateChannelResponse, GetOrCreateDmRequest, GetOrCreatePrivateRequest,
+ MessagePageDirection, NewChannelAttachment, ParticipantRole, PatchChannelRequest,
+ PatchMessageRequest, PostMessageRequest, PostMessageResponse, PostReactionRequest,
+ PostTypingRequest, ReactionAction, ReferencedShareItem, RemoveParticipantsRequest,
+ ResolvedChannelMessage, SimpleMention, ThreadInfo, ThreadReply, TopLevelMessageRow,
},
ports::{
- ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult,
- ChannelMessagesRepo, ChannelMessagesService,
+ ChannelAttachmentsPage, ChannelEventDispatcher, ChannelMessagesErr,
+ ChannelMessagesQueryResult, ChannelMutationErr, ChannelReferenceSharePermissions,
+ ChannelRepo, ChannelService,
},
};
use macro_user_id::user_id::MacroUserIdStr;
@@ -18,21 +25,73 @@ mod test;
/// Default number of preview replies per thread.
const THREAD_PREVIEW_COUNT: u16 = 3;
-/// Service implementation backed by a [`ChannelMessagesRepo`].
-pub struct ChannelMessagesServiceImpl<R> {
+/// Service implementation backed by a [`ChannelRepo`].
+#[derive(Clone)]
+pub struct ChannelServiceImpl<
+ R,
+ E = NoopChannelEventDispatcher,
+ P = NoopChannelReferenceSharePermissions,
+> {
repo: R,
+ events: E,
+ reference_share_permissions: P,
}
-impl<R> ChannelMessagesServiceImpl<R>
+/// No-op event dispatcher used by read-only contexts.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoopChannelEventDispatcher;
+
+impl ChannelEventDispatcher for NoopChannelEventDispatcher {
+ fn dispatch(&self, _event: ChannelEvent) {}
+}
+
+/// No-op reference-sharing service used by read-only contexts.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoopChannelReferenceSharePermissions;
+
+impl ChannelReferenceSharePermissions for NoopChannelReferenceSharePermissions {
+ type Err = anyhow::Error;
+
+ async fn update_channel_share_permissions_for_referenced_items(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _items: Vec<ReferencedShareItem>,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+}
+
+impl<R> ChannelServiceImpl<R, NoopChannelEventDispatcher, NoopChannelReferenceSharePermissions>
where
- R: ChannelMessagesRepo,
- anyhow::Error: From<R::Err>,
+ R: ChannelRepo,
{
- /// Create a new service with the given repository.
+ /// Create a new read-only service with no-op side-effect dependencies.
pub fn new(repo: R) -> Self {
- Self { repo }
+ Self {
+ repo,
+ events: NoopChannelEventDispatcher,
+ reference_share_permissions: NoopChannelReferenceSharePermissions,
+ }
}
+}
+impl<R, E, P> ChannelServiceImpl<R, E, P> {
+ /// Create a new service with outbound dependencies wired.
+ pub fn with_dependencies(repo: R, events: E, reference_share_permissions: P) -> Self {
+ Self {
+ repo,
+ events,
+ reference_share_permissions,
+ }
+ }
+}
+
+impl<R, E, P> ChannelServiceImpl<R, E, P>
+where
+ R: ChannelRepo,
+ anyhow::Error: From<R::Err>,
+{
/// Hydrate top-level message rows with thread data, reactions, and attachments.
async fn hydrate_messages(
&self,
@@ -107,6 +166,899 @@ where
}
}
+fn lower_macro_users(users: &[String]) -> Vec<String> {
+ users
+ .iter()
+ .map(|u| u.to_lowercase())
+ .filter(|u| u.starts_with("macro|"))
+ .collect()
+}
+
+fn parse_macro_user_id(
+ user_id: impl Into<String>,
+) -> Result<MacroUserIdStr<'static>, ChannelMutationErr> {
+ MacroUserIdStr::try_from(user_id.into())
+ .map_err(|_| ChannelMutationErr::BadRequest("invalid user id".to_string()))
+}
+
+fn participant_ids(participants: &[ChannelParticipant]) -> Vec<MacroUserIdStr<'static>> {
+ participants
+ .iter()
+ .filter_map(|p| MacroUserIdStr::try_from(p.user_id.clone()).ok())
+ .collect()
+}
+
+fn extract_share_items(
+ attachments: &[NewChannelAttachment],
+ mentions: &[SimpleMention],
+) -> Vec<ReferencedShareItem> {
+ attachments
+ .iter()
+ .filter_map(|a| ReferencedShareItem::from_raw(a.entity_id.clone(), &a.entity_type))
+ .chain(
+ mentions
+ .iter()
+ .filter_map(|m| ReferencedShareItem::from_raw(m.entity_id.clone(), &m.entity_type)),
+ )
+ .collect()
+}
+
+fn is_admin_or_owner(role: ParticipantRole) -> bool {
+ matches!(role, ParticipantRole::Owner | ParticipantRole::Admin)
+}
+
+fn parse_user_ids(
+ users: impl IntoIterator<Item = String>,
+) -> Result<Vec<MacroUserIdStr<'static>>, ChannelMutationErr> {
+ users
+ .into_iter()
+ .map(parse_macro_user_id)
+ .collect::<Result<Vec<_>, _>>()
+}
+
+fn created_channel_participant_ids(
+ owner_id: &str,
+ participants: &[String],
+) -> Result<Vec<MacroUserIdStr<'static>>, ChannelMutationErr> {
+ let mut users = participants.to_vec();
+ if !users.iter().any(|user| user == owner_id) {
+ users.push(owner_id.to_string());
+ }
+ parse_user_ids(users)
+}
+
+impl<R, E, P> ChannelServiceImpl<R, E, P>
+where
+ R: ChannelRepo,
+ E: ChannelEventDispatcher,
+ P: ChannelReferenceSharePermissions,
+{
+ #[tracing::instrument(err, skip(self, req))]
+ async fn create_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ actor_org_id: Option<i64>,
+ req: crate::domain::models::CreateChannelRequest,
+ ) -> Result<crate::domain::models::CreateChannelResponse, ChannelMutationErr> {
+ if req.channel_type == ChannelType::Team {
+ let team_id = req.team_id.ok_or_else(|| {
+ ChannelMutationErr::BadRequest("team id missing for team channel type".to_string())
+ })?;
+ let has_team = self
+ .repo
+ .user_has_team(actor.as_ref().to_string(), team_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ if !has_team {
+ return Err(ChannelMutationErr::Unauthorized(
+ "you do not have access to that team".to_string(),
+ ));
+ }
+ }
+
+ if req.team_id.is_some() && req.channel_type != ChannelType::Team {
+ return Err(ChannelMutationErr::BadRequest(
+ "team channels need team channel type".to_string(),
+ ));
+ }
+
+ let org_id = match req.channel_type {
+ ChannelType::Organization => actor_org_id,
+ _ => None,
+ };
+ let participants = lower_macro_users(&req.participants);
+ if participants.is_empty() {
+ return Err(ChannelMutationErr::BadRequest(
+ "participants must be a non-empty list of 'macro|<email>'".to_string(),
+ ));
+ }
+ let create_req = crate::domain::models::CreateChannelRequest {
+ participants: participants.clone(),
+ ..req.clone()
+ };
+
+ let channel_id = self
+ .create_channel_record(actor.as_ref().to_string(), org_id, create_req)
+ .await?;
+
+ self.events.dispatch(ChannelEvent::ChannelCreated {
+ channel_id,
+ channel_type: req.channel_type,
+ participant_user_ids: created_channel_participant_ids(actor.as_ref(), &participants)?,
+ });
+
+ Ok(crate::domain::models::CreateChannelResponse {
+ id: channel_id.to_string(),
+ })
+ }
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn get_or_create_dm(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ req: GetOrCreateDmRequest,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ let recipient_id = req.recipient_id.to_lowercase();
+ let user_id = actor.as_ref().to_lowercase();
+
+ if recipient_id.is_empty() {
+ return Err(ChannelMutationErr::BadRequest(
+ "recipient_id must be a non-empty string".to_string(),
+ ));
+ }
+ if !recipient_id.starts_with("macro|") {
+ return Err(ChannelMutationErr::BadRequest(
+ "recipient_id must be 'macro|<email>'".to_string(),
+ ));
+ }
+ if recipient_id == user_id {
+ return Err(ChannelMutationErr::BadRequest(
+ "recipient_id cannot be the same as the user_id".to_string(),
+ ));
+ }
+
+ let existing_channel_id = self
+ .repo
+ .maybe_get_dm(user_id.clone(), recipient_id.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ self.get_or_create_channel(
+ existing_channel_id,
+ user_id.clone(),
+ None,
+ crate::domain::models::CreateChannelRequest {
+ name: None,
+ channel_type: ChannelType::DirectMessage,
+ team_id: None,
+ participants: vec![user_id.clone(), recipient_id.clone()],
+ },
+ )
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn get_or_create_private(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ mut req: GetOrCreatePrivateRequest,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ req.recipients = lower_macro_users(&req.recipients);
+ if req.recipients.is_empty() {
+ return Err(ChannelMutationErr::BadRequest(
+ "recipients must be a non-empty list of 'macro|<email>'".to_string(),
+ ));
+ }
+
+ let user_id = actor.as_ref().to_lowercase();
+ let mut lookup = req.recipients.clone();
+ lookup.push(user_id.clone());
+ let existing_channel_id = self
+ .repo
+ .maybe_get_private_channel(lookup)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ self.get_or_create_channel(
+ existing_channel_id,
+ user_id,
+ None,
+ crate::domain::models::CreateChannelRequest {
+ name: None,
+ channel_type: ChannelType::Private,
+ team_id: None,
+ participants: req.recipients,
+ },
+ )
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn patch_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: PatchChannelRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ let info = self
+ .repo
+ .get_channel_info(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ if matches!(info.channel_type, ChannelType::DirectMessage) && req.channel_name.is_some() {
+ return Err(ChannelMutationErr::BadRequest(
+ "cannot change channel_name for direct message channels".to_string(),
+ ));
+ }
+ self.repo
+ .patch_channel(channel_id, actor.as_ref().to_string(), req)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn delete_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ self.repo
+ .delete_channel(channel_id, actor.as_ref().to_string())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ self.events
+ .dispatch(ChannelEvent::ChannelDeleted { channel_id });
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn post_message(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: PostMessageRequest,
+ ) -> Result<PostMessageResponse, ChannelMutationErr> {
+ let message = self
+ .repo
+ .create_message(
+ channel_id,
+ actor.as_ref().to_string(),
+ req.content.clone(),
+ req.thread_id,
+ )
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ if let Err(err) = self.repo.touch_channel_updated_at(channel_id).await {
+ tracing::error!(error=?err.into(), "unable to update channel updated_at");
+ }
+
+ if let Err(err) = self
+ .repo
+ .create_message_mentions(message.id, req.mentions.clone())
+ .await
+ {
+ tracing::error!(error=?err.into(), "unable to create mentions");
+ }
+
+ let items = extract_share_items(&req.attachments, &req.mentions);
+ if !items.is_empty()
+ && let Err(err) = self
+ .reference_share_permissions
+ .update_channel_share_permissions_for_referenced_items(
+ actor.clone(),
+ channel_id,
+ items,
+ )
+ .await
+ {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to update channel share permissions");
+ }
+
+ let channel_metadata = self
+ .repo
+ .get_channel_metadata(channel_id, actor.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let participants = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ if let Err(err) = self
+ .repo
+ .upsert_activity(actor.as_ref().to_string(), channel_id)
+ .await
+ {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to upsert activity for message");
+ }
+
+ let has_attachments = !req.attachments.is_empty();
+ let attachments = self
+ .repo
+ .add_attachments(message.id, channel_id, req.attachments.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ self.events.dispatch(ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: channel_metadata,
+ participants,
+ message: message.clone(),
+ mentions: req.mentions,
+ has_attachments,
+ attachments,
+ nonce: req.nonce.clone(),
+ });
+
+ Ok(PostMessageResponse {
+ id: message.id.to_string(),
+ nonce: req.nonce,
+ })
+ }
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn patch_message(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ actor_role: ParticipantRole,
+ channel_id: Uuid,
+ message_id: Uuid,
+ mut req: PatchMessageRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ let owner = self
+ .repo
+ .get_message_owner(channel_id, message_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ .ok_or_else(|| ChannelMutationErr::NotFound("message not found".to_string()))?;
+ if owner != actor.as_ref() && !is_admin_or_owner(actor_role) {
+ return Err(ChannelMutationErr::Unauthorized(
+ "user is not authorized to edit this message".to_string(),
+ ));
+ }
+
+ let attachments_to_delete = req.attachment_ids_to_delete.clone().unwrap_or_default();
+ let attachments_to_add = req.attachments_to_add.clone().unwrap_or_default();
+ let attachments_changed =
+ !attachments_to_delete.is_empty() || !attachments_to_add.is_empty();
+
+ if attachments_changed {
+ self.patch_message_attachments(
+ actor.clone(),
+ channel_id,
+ message_id,
+ attachments_to_delete,
+ attachments_to_add,
+ req.nonce.clone(),
+ )
+ .await?;
+ }
+
+ if let Some(content) = req.content.clone() {
+ let message = self
+ .repo
+ .patch_message(channel_id, message_id, content)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ if let Some(mentions) = req.mentions.take() {
+ self.repo
+ .sync_message_mentions(message_id, mentions.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ let items = extract_share_items(&[], &mentions);
+ if !items.is_empty()
+ && let Err(err) = self
+ .reference_share_permissions
+ .update_channel_share_permissions_for_referenced_items(
+ actor.clone(),
+ channel_id,
+ items,
+ )
+ .await
+ {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to update channel share permissions");
+ }
+ }
+
+ let participants = if let Some(thread_id) = message.thread_id {
+ self.repo
+ .get_thread_participants(thread_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ } else {
+ participant_ids(
+ &self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?,
+ )
+ };
+
+ self.events.dispatch(ChannelEvent::MessageChanged {
+ channel_id,
+ message: message.clone(),
+ recipients: participants,
+ nonce: req.nonce.clone(),
+ });
+
+ if let Err(err) = self
+ .repo
+ .upsert_activity(actor.as_ref().to_string(), channel_id)
+ .await
+ {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to upsert activity for message");
+ }
+ }
+
+ if attachments_changed
+ && req.content.is_none()
+ && let Err(err) = self
+ .repo
+ .upsert_activity(actor.as_ref().to_string(), channel_id)
+ .await
+ {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to upsert activity for attachment patch");
+ }
+
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self, query))]
+ async fn delete_message(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ actor_role: ParticipantRole,
+ channel_id: Uuid,
+ message_id: Uuid,
+ query: DeleteMessageQuery,
+ ) -> Result<(), ChannelMutationErr> {
+ let owner = self
+ .repo
+ .get_message_owner(channel_id, message_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ .ok_or_else(|| ChannelMutationErr::NotFound("message not found".to_string()))?;
+ if owner != actor.as_ref() && !is_admin_or_owner(actor_role) {
+ return Err(ChannelMutationErr::Unauthorized(
+ "user is not authorized to delete this message".to_string(),
+ ));
+ }
+
+ let message = self
+ .repo
+ .delete_message(channel_id, message_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let participants = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ self.events.dispatch(ChannelEvent::MessageDeleted {
+ channel_id,
+ message,
+ recipients: participant_ids(&participants),
+ nonce: query.nonce,
+ });
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn post_reaction(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: PostReactionRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ let message_id = Uuid::parse_str(&req.message_id)
+ .map_err(|err| ChannelMutationErr::BadRequest(err.to_string()))?;
+ self.repo
+ .get_message_owner(channel_id, message_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ .ok_or_else(|| ChannelMutationErr::NotFound("message not found".to_string()))?;
+ match req.action {
+ ReactionAction::Add => {
+ self.repo
+ .add_reaction(
+ channel_id,
+ message_id,
+ req.emoji,
+ actor.as_ref().to_string(),
+ )
+ .await
+ }
+ ReactionAction::Remove => {
+ self.repo
+ .remove_reaction(
+ channel_id,
+ message_id,
+ req.emoji,
+ actor.as_ref().to_string(),
+ )
+ .await
+ }
+ }
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ let reactions = self
+ .repo
+ .get_message_reactions(channel_id, message_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let participants = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ self.events.dispatch(ChannelEvent::ReactionChanged {
+ channel_id,
+ message_id,
+ reactions,
+ recipients: participant_ids(&participants),
+ nonce: req.nonce,
+ });
+
+ if let Err(err) = self
+ .repo
+ .upsert_activity(actor.as_ref().to_string(), channel_id)
+ .await
+ {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to upsert activity for reaction");
+ }
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn post_typing(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: PostTypingRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ let thread_id = req
+ .thread_id
+ .as_deref()
+ .map(Uuid::parse_str)
+ .transpose()
+ .map_err(|err| ChannelMutationErr::BadRequest(err.to_string()))?;
+ let participants = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ self.events.dispatch(ChannelEvent::TypingChanged {
+ channel_id,
+ user_id: actor.as_ref().to_string(),
+ action: req.action,
+ thread_id,
+ recipients: participant_ids(&participants),
+ nonce: req.nonce,
+ });
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn add_participants(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: AddParticipantsRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ let info = self
+ .repo
+ .get_channel_info(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ if info.channel_type == ChannelType::DirectMessage {
+ return Err(ChannelMutationErr::BadRequest(
+ "cannot add/remove participants from direct message channels".to_string(),
+ ));
+ }
+
+ let participants_to_add = lower_macro_users(&req.participants);
+ for participant in &participants_to_add {
+ self.repo
+ .add_participant(channel_id, participant.clone(), ParticipantRole::Member)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ }
+
+ let active_participants = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ let recipients = participants_to_add
+ .iter()
+ .filter_map(|id| MacroUserIdStr::try_from(id.clone()).ok())
+ .collect();
+ let channel_metadata = self
+ .repo
+ .get_channel_metadata(channel_id, actor.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let active_participant_user_ids = parse_user_ids(
+ active_participants
+ .into_iter()
+ .map(|participant| participant.user_id),
+ )?;
+ self.events.dispatch(ChannelEvent::ParticipantsAdded {
+ channel_id,
+ channel_type: info.channel_type,
+ active_participant_user_ids,
+ invited_by_user_id: actor.clone(),
+ recipient_user_ids: recipients,
+ metadata: channel_metadata,
+ message_content: None,
+ });
+
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn remove_participants(
+ &self,
+ channel_id: Uuid,
+ req: RemoveParticipantsRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ let info = self
+ .repo
+ .get_channel_info(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ if info.channel_type == ChannelType::DirectMessage {
+ return Err(ChannelMutationErr::BadRequest(
+ "cannot add or remove participants from direct message channel".to_string(),
+ ));
+ }
+ for participant in req.participants {
+ self.repo
+ .remove_participant(channel_id, participant)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ }
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn join_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ let info = self
+ .repo
+ .get_channel_info(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ if info.channel_type == ChannelType::DirectMessage {
+ return Err(ChannelMutationErr::BadRequest(
+ "cannot join direct message channel".to_string(),
+ ));
+ }
+ let before = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ self.repo
+ .add_participant(
+ channel_id,
+ actor.as_ref().to_string(),
+ ParticipantRole::Member,
+ )
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ let active_participant_user_ids = parse_user_ids(
+ before
+ .into_iter()
+ .map(|participant| participant.user_id)
+ .chain(std::iter::once(actor.as_ref().to_string())),
+ )?;
+ self.events.dispatch(ChannelEvent::ParticipantJoined {
+ channel_id,
+ channel_type: info.channel_type,
+ user_id: actor,
+ active_participant_user_ids,
+ });
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn leave_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ let info = self
+ .repo
+ .get_channel_info(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let participants = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ match (info.channel_type, participants.len()) {
+ (ChannelType::Organization, _) => {
+ return Err(ChannelMutationErr::BadRequest(
+ "cannot leave organization channel".to_string(),
+ ));
+ }
+ (ChannelType::Private, 2) | (ChannelType::DirectMessage, _) => {
+ return Err(ChannelMutationErr::BadRequest(
+ "cannot leave channel with only 2 participants".to_string(),
+ ));
+ }
+ _ => {}
+ }
+ self.repo
+ .remove_participant(channel_id, actor.as_ref().to_string())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))
+ }
+}
+
+impl<R, E, P> ChannelServiceImpl<R, E, P>
+where
+ R: ChannelRepo,
+ E: ChannelEventDispatcher,
+ P: ChannelReferenceSharePermissions,
+{
+ async fn create_channel_record(
+ &self,
+ owner_id: String,
+ org_id: Option<i64>,
+ req: crate::domain::models::CreateChannelRequest,
+ ) -> Result<Uuid, ChannelMutationErr> {
+ self.repo
+ .create_channel(owner_id, org_id, req)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))
+ }
+
+ async fn get_or_create_channel(
+ &self,
+ existing_channel_id: Option<Uuid>,
+ owner_id: String,
+ org_id: Option<i64>,
+ create_req: crate::domain::models::CreateChannelRequest,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ if let Some(channel_id) = existing_channel_id {
+ return Ok(GetOrCreateChannelResponse {
+ channel_id: channel_id.to_string(),
+ action: GetOrCreateAction::Get,
+ });
+ }
+
+ let channel_type = create_req.channel_type;
+ let participant_user_ids =
+ created_channel_participant_ids(&owner_id, &create_req.participants)?;
+ let channel_id = self
+ .create_channel_record(owner_id, org_id, create_req)
+ .await?;
+ self.events.dispatch(ChannelEvent::ChannelCreated {
+ channel_id,
+ channel_type,
+ participant_user_ids,
+ });
+ Ok(GetOrCreateChannelResponse {
+ channel_id: channel_id.to_string(),
+ action: GetOrCreateAction::Create,
+ })
+ }
+
+ async fn patch_message_attachments(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ message_id: Uuid,
+ attachment_ids_to_delete: Vec<String>,
+ attachments_to_add: Vec<NewChannelAttachment>,
+ nonce: Option<String>,
+ ) -> Result<(), ChannelMutationErr> {
+ let attachment_uuids = attachment_ids_to_delete
+ .iter()
+ .map(|id| Uuid::parse_str(id))
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|err| ChannelMutationErr::BadRequest(err.to_string()))?;
+
+ let existing = self
+ .repo
+ .get_message_attachments(message_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let attachments_to_delete = existing
+ .iter()
+ .filter(|a| attachment_uuids.contains(&a.id))
+ .cloned()
+ .collect::<Vec<_>>();
+ if attachments_to_delete.len() != attachment_uuids.len() {
+ tracing::error!(attachment_ids=?attachment_uuids, "some attachments were not found");
+ }
+
+ let fetched_attachment_ids = attachments_to_delete
+ .iter()
+ .map(|a| a.id)
+ .collect::<Vec<_>>();
+ let fetched_entity_ids = attachments_to_delete
+ .iter()
+ .map(|a| a.entity_id.clone())
+ .collect::<Vec<_>>();
+
+ if !fetched_attachment_ids.is_empty() {
+ self.repo
+ .delete_attachments(fetched_attachment_ids)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ self.repo
+ .delete_entity_mentions_for_entities(fetched_entity_ids, message_id.to_string())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ }
+
+ if !attachments_to_add.is_empty() {
+ self.repo
+ .add_attachments(message_id, channel_id, attachments_to_add.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ }
+
+ let items = extract_share_items(&attachments_to_add, &[]);
+ if !items.is_empty()
+ && let Err(err) = self
+ .reference_share_permissions
+ .update_channel_share_permissions_for_referenced_items(actor, channel_id, items)
+ .await
+ {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to update channel share permissions");
+ }
+
+ let all_attachments = self
+ .repo
+ .get_message_attachments(message_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ self.repo
+ .patch_message_attachments(message_id, all_attachments.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
+ let participants = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ self.events.dispatch(ChannelEvent::AttachmentsChanged {
+ channel_id,
+ message_id,
+ attachments: all_attachments,
+ recipients: participant_ids(&participants),
+ nonce,
+ });
+
+ Ok(())
+ }
+}
+
/// Build a centered window of messages around an anchor.
///
/// - `before`: older messages in DESC order (closest to anchor first).
@@ -173,9 +1125,11 @@ fn center_window(
}
}
-impl<R> ChannelMessagesService for ChannelMessagesServiceImpl<R>
+impl<R, E, P> ChannelService for ChannelServiceImpl<R, E, P>
where
- R: ChannelMessagesRepo,
+ R: ChannelRepo,
+ E: ChannelEventDispatcher,
+ P: ChannelReferenceSharePermissions,
anyhow::Error: From<R::Err>,
{
#[tracing::instrument(err, skip(self))]
@@ -370,4 +1324,130 @@ where
.map_err(anyhow::Error::from)?
.ok_or(ChannelMessagesErr::MessageNotFound(message_id))
}
+
+ async fn create_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ actor_org_id: Option<i64>,
+ req: crate::domain::models::CreateChannelRequest,
+ ) -> Result<crate::domain::models::CreateChannelResponse, ChannelMutationErr> {
+ ChannelServiceImpl::create_channel(self, actor, actor_org_id, req).await
+ }
+
+ async fn get_or_create_dm(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ req: GetOrCreateDmRequest,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ ChannelServiceImpl::get_or_create_dm(self, actor, req).await
+ }
+
+ async fn get_or_create_private(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ req: GetOrCreatePrivateRequest,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ ChannelServiceImpl::get_or_create_private(self, actor, req).await
+ }
+
+ async fn patch_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: PatchChannelRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::patch_channel(self, actor, channel_id, req).await
+ }
+
+ async fn delete_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::delete_channel(self, actor, channel_id).await
+ }
+
+ async fn post_message(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: PostMessageRequest,
+ ) -> Result<PostMessageResponse, ChannelMutationErr> {
+ ChannelServiceImpl::post_message(self, actor, channel_id, req).await
+ }
+
+ async fn patch_message(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ actor_role: ParticipantRole,
+ channel_id: Uuid,
+ message_id: Uuid,
+ req: PatchMessageRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::patch_message(self, actor, actor_role, channel_id, message_id, req)
+ .await
+ }
+
+ async fn delete_message(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ actor_role: ParticipantRole,
+ channel_id: Uuid,
+ message_id: Uuid,
+ query: DeleteMessageQuery,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::delete_message(self, actor, actor_role, channel_id, message_id, query)
+ .await
+ }
+
+ async fn post_reaction(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: PostReactionRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::post_reaction(self, actor, channel_id, req).await
+ }
+
+ async fn post_typing(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: PostTypingRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::post_typing(self, actor, channel_id, req).await
+ }
+
+ async fn add_participants(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: AddParticipantsRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::add_participants(self, actor, channel_id, req).await
+ }
+
+ async fn remove_participants(
+ &self,
+ channel_id: Uuid,
+ req: RemoveParticipantsRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::remove_participants(self, channel_id, req).await
+ }
+
+ async fn join_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::join_channel(self, actor, channel_id).await
+ }
+
+ async fn leave_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::leave_channel(self, actor, channel_id).await
+ }
}
diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rs
index 45c60b981d..acd28b76a3 100644
--- a/rust/cloud-storage/channels/src/domain/service/test.rs
+++ b/rust/cloud-storage/channels/src/domain/service/test.rs
@@ -1,13 +1,25 @@
use super::*;
use crate::domain::{
+ events::ChannelEvent,
models::{
- ChannelMessageFilters, CountedReaction, MessageAttachment, MessagePageDirection,
- ThreadData, ThreadReplyRow, TopLevelMessageRow,
+ ChannelAttachment, ChannelAttachmentType, ChannelInfo, ChannelMessageFilters,
+ ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, MessageAttachment,
+ MessagePageDirection, MutatedAttachment, MutatedMessage, NewChannelAttachment,
+ ParticipantRole, PatchChannelRequest, PatchMessageRequest, PostMessageRequest,
+ PostReactionRequest, ReactionAction, ReferencedShareItem, ReferencedShareItemType,
+ ResolvedChannelMessage, SimpleMention, ThreadData, ThreadReplyRow, TopLevelMessageRow,
+ },
+ ports::{
+ ChannelEventDispatcher, ChannelReferenceSharePermissions, ChannelRepo, MockChannelRepo,
+ TopLevelMessagesQueryResult,
},
- ports::{MockChannelMessagesRepo, TopLevelMessagesQueryResult},
};
use chrono::Utc;
-use std::collections::HashMap;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+};
fn make_row(id: Uuid, minutes_ago: i64) -> TopLevelMessageRow {
let now = Utc::now();
@@ -23,8 +35,8 @@ fn make_row(id: Uuid, minutes_ago: i64) -> TopLevelMessageRow {
}
}
-fn empty_repo() -> MockChannelMessagesRepo {
- let mut repo = MockChannelMessagesRepo::new();
+fn empty_repo() -> MockChannelRepo {
+ let mut repo = MockChannelRepo::new();
repo.expect_get_top_level_messages()
.returning(|_, _, _, _, _, _| {
Box::pin(async {
@@ -55,7 +67,7 @@ fn empty_repo() -> MockChannelMessagesRepo {
#[tokio::test]
async fn returns_empty_page_for_no_messages() {
- let svc = ChannelMessagesServiceImpl::new(empty_repo());
+ let svc = ChannelServiceImpl::new(empty_repo());
let result = svc
.get_channel_messages(
Uuid::nil(),
@@ -90,7 +102,7 @@ async fn returns_messages_with_thread_info() {
edited_at: None,
};
- let mut repo = MockChannelMessagesRepo::new();
+ let mut repo = MockChannelRepo::new();
let row_clone = row.clone();
repo.expect_get_top_level_messages()
@@ -144,7 +156,7 @@ async fn returns_messages_with_thread_info() {
Box::pin(async move { Ok(map) })
});
- let svc = ChannelMessagesServiceImpl::new(repo);
+ let svc = ChannelServiceImpl::new(repo);
let result = svc
.get_channel_messages(
Uuid::nil(),
@@ -167,9 +179,600 @@ async fn returns_messages_with_thread_info() {
assert!(page.next_cursor.is_none());
}
+#[derive(Clone)]
+struct FakeMutationRepo {
+ state: Arc<Mutex<FakeMutationRepoState>>,
+}
+
+struct FakeMutationRepoState {
+ channel_id: Uuid,
+ message: MutatedMessage,
+ owner: String,
+ participants: Vec<ChannelParticipant>,
+ thread_participants: Vec<MacroUserIdStr<'static>>,
+ attachments: Vec<MutatedAttachment>,
+ patched_content: Option<String>,
+ activity_upserts: usize,
+}
+
+impl FakeMutationRepo {
+ fn new(channel_id: Uuid, sender: &str) -> Self {
+ let now = Utc::now();
+ let message = MutatedMessage {
+ id: Uuid::new_v4(),
+ channel_id,
+ thread_id: None,
+ sender_id: MacroUserIdStr::try_from(sender.to_string()).unwrap(),
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ };
+ Self {
+ state: Arc::new(Mutex::new(FakeMutationRepoState {
+ channel_id,
+ owner: sender.to_string(),
+ message,
+ participants: vec![
+ ChannelParticipant {
+ channel_id,
+ user_id: sender.to_string(),
+ role: ParticipantRole::Owner,
+ joined_at: now,
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id,
+ user_id: "macro|[email protected]".to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ],
+ thread_participants: vec![
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),
+ ],
+ attachments: vec![],
+ patched_content: None,
+ activity_upserts: 0,
+ })),
+ }
+ }
+}
+
+impl ChannelRepo for FakeMutationRepo {
+ type Err = anyhow::Error;
+
+ async fn get_top_level_messages(
+ &self,
+ _channel_id: Uuid,
+ _query: &Query<Uuid, CreatedAt, ()>,
+ _direction: MessagePageDirection,
+ _limit: u16,
+ _filters: &ChannelMessageFilters,
+ _notification_user_id: Option<MacroUserIdStr<'static>>,
+ ) -> Result<TopLevelMessagesQueryResult, Self::Err> {
+ Ok(TopLevelMessagesQueryResult {
+ rows: vec![],
+ has_more_newer: false,
+ })
+ }
+
+ async fn get_thread_data(
+ &self,
+ _parent_ids: &[Uuid],
+ _preview_count: u16,
+ ) -> Result<HashMap<Uuid, ThreadData>, Self::Err> {
+ Ok(HashMap::new())
+ }
+
+ async fn get_thread_replies(&self, _parent_id: Uuid) -> Result<Vec<ThreadReplyRow>, Self::Err> {
+ Ok(vec![])
+ }
+
+ async fn get_reactions_batch(
+ &self,
+ _message_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, Vec<CountedReaction>>, Self::Err> {
+ Ok(HashMap::new())
+ }
+
+ async fn get_attachments_batch(
+ &self,
+ _message_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, Vec<MessageAttachment>>, Self::Err> {
+ Ok(HashMap::new())
+ }
+
+ async fn get_channel_attachments(
+ &self,
+ _channel_id: Uuid,
+ _query: &Query<Uuid, CreatedAt, ()>,
+ _limit: u16,
+ _attachment_type: Option<ChannelAttachmentType>,
+ ) -> Result<Vec<ChannelAttachment>, Self::Err> {
+ Ok(vec![])
+ }
+
+ async fn get_channel_participants(
+ &self,
+ _channel_id: Uuid,
+ ) -> Result<Vec<ChannelParticipant>, Self::Err> {
+ Ok(self.state.lock().unwrap().participants.clone())
+ }
+
+ async fn resolve_top_level_parent(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ ) -> Result<Option<TopLevelMessageRow>, Self::Err> {
+ Ok(None)
+ }
+
+ async fn resolve_message(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ ) -> Result<Option<ResolvedChannelMessage>, Self::Err> {
+ Ok(None)
+ }
+
+ async fn get_top_level_messages_around(
+ &self,
+ _channel_id: Uuid,
+ _anchor_created_at: chrono::DateTime<chrono::Utc>,
+ _anchor_id: Uuid,
+ _limit: u16,
+ ) -> Result<(Vec<TopLevelMessageRow>, Vec<TopLevelMessageRow>), Self::Err> {
+ Ok((vec![], vec![]))
+ }
+
+ async fn get_channel_info(&self, channel_id: Uuid) -> Result<ChannelInfo, Self::Err> {
+ Ok(ChannelInfo {
+ id: channel_id,
+ name: Some("Project".to_string()),
+ channel_type: ChannelType::Private,
+ org_id: None,
+ team_id: None,
+ })
+ }
+
+ async fn get_channel_metadata(
+ &self,
+ _channel_id: Uuid,
+ _viewer_user_id: MacroUserIdStr<'static>,
+ ) -> Result<ChannelMetadata, Self::Err> {
+ Ok(ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ })
+ }
+
+ async fn user_has_team(&self, _user_id: String, _team_id: Uuid) -> Result<bool, Self::Err> {
+ Ok(true)
+ }
+
+ async fn create_channel(
+ &self,
+ _owner_id: String,
+ _org_id: Option<i64>,
+ _req: crate::domain::models::CreateChannelRequest,
+ ) -> Result<Uuid, Self::Err> {
+ Ok(self.state.lock().unwrap().channel_id)
+ }
+
+ async fn maybe_get_dm(
+ &self,
+ _user_id: String,
+ _recipient_id: String,
+ ) -> Result<Option<Uuid>, Self::Err> {
+ Ok(None)
+ }
+
+ async fn maybe_get_private_channel(
+ &self,
+ _participants: Vec<String>,
+ ) -> Result<Option<Uuid>, Self::Err> {
+ Ok(None)
+ }
+
+ async fn patch_channel(
+ &self,
+ _channel_id: Uuid,
+ _user_id: String,
+ _req: PatchChannelRequest,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn delete_channel(&self, _channel_id: Uuid, _user_id: String) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn add_participant(
+ &self,
+ _channel_id: Uuid,
+ _user_id: String,
+ _role: ParticipantRole,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn remove_participant(
+ &self,
+ _channel_id: Uuid,
+ _user_id: String,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn create_message(
+ &self,
+ channel_id: Uuid,
+ sender_id: String,
+ content: String,
+ thread_id: Option<Uuid>,
+ ) -> Result<MutatedMessage, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ state.message.channel_id = channel_id;
+ state.message.sender_id = MacroUserIdStr::try_from(sender_id).unwrap();
+ state.message.content = content;
+ state.message.thread_id = thread_id;
+ Ok(state.message.clone())
+ }
+
+ async fn touch_channel_updated_at(&self, _channel_id: Uuid) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn create_message_mentions(
+ &self,
+ _message_id: Uuid,
+ _mentions: Vec<SimpleMention>,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn sync_message_mentions(
+ &self,
+ _message_id: Uuid,
+ _mentions: Vec<SimpleMention>,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn add_attachments(
+ &self,
+ message_id: Uuid,
+ channel_id: Uuid,
+ attachments: Vec<NewChannelAttachment>,
+ ) -> Result<Vec<MutatedAttachment>, Self::Err> {
+ let now = Utc::now();
+ let created = attachments
+ .into_iter()
+ .map(|a| MutatedAttachment {
+ id: Uuid::new_v4(),
+ channel_id,
+ message_id,
+ entity_type: a.entity_type,
+ entity_id: a.entity_id,
+ width: a.width,
+ height: a.height,
+ created_at: now,
+ })
+ .collect::<Vec<_>>();
+ self.state.lock().unwrap().attachments = created.clone();
+ Ok(created)
+ }
+
+ async fn get_message_attachments(
+ &self,
+ _message_id: Uuid,
+ ) -> Result<Vec<MutatedAttachment>, Self::Err> {
+ Ok(self.state.lock().unwrap().attachments.clone())
+ }
+
+ async fn delete_attachments(&self, _attachment_ids: Vec<Uuid>) -> Result<(), Self::Err> {
+ self.state.lock().unwrap().attachments.clear();
+ Ok(())
+ }
+
+ async fn delete_entity_mentions_for_entities(
+ &self,
+ _entity_ids: Vec<String>,
+ _source_entity_id: String,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn patch_message_attachments(
+ &self,
+ _message_id: Uuid,
+ _attachments: Vec<MutatedAttachment>,
+ ) -> Result<MutatedMessage, Self::Err> {
+ Ok(self.state.lock().unwrap().message.clone())
+ }
+
+ async fn patch_message(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ content: String,
+ ) -> Result<MutatedMessage, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ state.patched_content = Some(content.clone());
+ state.message.content = content;
+ state.message.edited_at = Some(Utc::now());
+ Ok(state.message.clone())
+ }
+
+ async fn delete_message(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ ) -> Result<MutatedMessage, Self::Err> {
+ Ok(self.state.lock().unwrap().message.clone())
+ }
+
+ async fn get_message_owner(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ ) -> Result<Option<String>, Self::Err> {
+ Ok(Some(self.state.lock().unwrap().owner.clone()))
+ }
+
+ async fn get_participants(
+ &self,
+ _channel_id: Uuid,
+ ) -> Result<Vec<ChannelParticipant>, Self::Err> {
+ Ok(self.state.lock().unwrap().participants.clone())
+ }
+
+ async fn get_thread_participants(
+ &self,
+ _thread_id: Uuid,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, Self::Err> {
+ Ok(self.state.lock().unwrap().thread_participants.clone())
+ }
+
+ async fn upsert_activity(&self, _user_id: String, _channel_id: Uuid) -> Result<(), Self::Err> {
+ self.state.lock().unwrap().activity_upserts += 1;
+ Ok(())
+ }
+
+ async fn add_reaction(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _emoji: String,
+ _user_id: String,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn remove_reaction(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _emoji: String,
+ _user_id: String,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn get_message_reactions(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ ) -> Result<Vec<CountedReaction>, Self::Err> {
+ Ok(vec![CountedReaction {
+ emoji: "👍".to_string(),
+ users: vec!["macro|[email protected]".to_string()],
+ }])
+ }
+}
+
+#[derive(Clone, Default)]
+struct FakeEvents {
+ events: Arc<Mutex<Vec<ChannelEvent>>>,
+}
+
+impl ChannelEventDispatcher for FakeEvents {
+ fn dispatch(&self, event: ChannelEvent) {
+ self.events.lock().unwrap().push(event);
+ }
+}
+
+#[derive(Clone, Default)]
+struct FakeReferenceSharing {
+ items: Arc<Mutex<Vec<ReferencedShareItem>>>,
+}
+
+impl ChannelReferenceSharePermissions for FakeReferenceSharing {
+ type Err = anyhow::Error;
+
+ async fn update_channel_share_permissions_for_referenced_items(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ items: Vec<ReferencedShareItem>,
+ ) -> Result<(), Self::Err> {
+ self.items.lock().unwrap().extend(items);
+ Ok(())
+ }
+}
+
+fn mutation_service(
+ repo: FakeMutationRepo,
+ events: FakeEvents,
+ share: FakeReferenceSharing,
+) -> ChannelServiceImpl<FakeMutationRepo, FakeEvents, FakeReferenceSharing> {
+ ChannelServiceImpl::with_dependencies(repo, events, share)
+}
+
+fn macro_id(user_id: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(user_id.to_string()).unwrap()
+}
+
+#[tokio::test]
+async fn post_message_emits_message_posted_event_and_updates_share_permissions() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let events = FakeEvents::default();
+ let share = FakeReferenceSharing::default();
+ let svc = mutation_service(repo.clone(), events.clone(), share.clone());
+
+ let res = svc
+ .post_message(
+ macro_id("macro|[email protected]"),
+ channel_id,
+ PostMessageRequest {
+ content: "hello world".to_string(),
+ mentions: vec![SimpleMention {
+ entity_type: "document".to_string(),
+ entity_id: "doc-1".to_string(),
+ }],
+ thread_id: None,
+ attachments: vec![NewChannelAttachment {
+ entity_type: "chat".to_string(),
+ entity_id: "chat-1".to_string(),
+ width: None,
+ height: None,
+ }],
+ nonce: Some("nonce-1".to_string()),
+ },
+ )
+ .await
+ .unwrap();
+
+ let emitted = events.events.lock().unwrap();
+ assert_eq!(emitted.len(), 1);
+ let ChannelEvent::MessagePosted {
+ metadata,
+ participants,
+ message,
+ has_attachments,
+ attachments,
+ nonce,
+ ..
+ } = &emitted[0]
+ else {
+ panic!("expected MessagePosted event, got {:?}", emitted[0]);
+ };
+ assert_eq!(metadata.channel_name, "Project");
+ assert_eq!(message.id.to_string(), res.id);
+ assert_eq!(nonce.as_deref(), Some("nonce-1"));
+ assert!(*has_attachments);
+ assert_eq!(attachments.len(), 1);
+ assert!(
+ participants
+ .iter()
+ .any(|participant| participant.user_id == "macro|[email protected]")
+ );
+ drop(emitted);
+
+ let shared = share.items.lock().unwrap();
+ assert!(shared.contains(&ReferencedShareItem::new(
+ "chat-1",
+ ReferencedShareItemType::Chat
+ )));
+ assert!(shared.contains(&ReferencedShareItem::new(
+ "doc-1",
+ ReferencedShareItemType::Document
+ )));
+}
+
+#[tokio::test]
+async fn patch_message_content_emits_message_changed_event_to_thread_participants() {
+ let channel_id = Uuid::new_v4();
+ let thread_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().message.thread_id = Some(thread_id);
+ let message_id = repo.state.lock().unwrap().message.id;
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_message(
+ macro_id("macro|[email protected]"),
+ ParticipantRole::Member,
+ channel_id,
+ message_id,
+ PatchMessageRequest {
+ content: Some("edited".to_string()),
+ mentions: None,
+ attachment_ids_to_delete: None,
+ attachments_to_add: None,
+ nonce: Some("edit-nonce".to_string()),
+ },
+ )
+ .await
+ .unwrap();
+
+ let emitted = events.events.lock().unwrap();
+ assert_eq!(emitted.len(), 1);
+ let ChannelEvent::MessageChanged {
+ channel_id: emitted_channel_id,
+ message,
+ recipients,
+ nonce,
+ } = &emitted[0]
+ else {
+ panic!("expected MessageChanged event, got {:?}", emitted[0]);
+ };
+ assert_eq!(*emitted_channel_id, channel_id);
+ assert_eq!(message.id, message_id);
+ assert_eq!(message.content, "edited");
+ assert_eq!(nonce.as_deref(), Some("edit-nonce"));
+ assert_eq!(recipients.len(), 1);
+ assert_eq!(recipients[0].as_ref(), "macro|[email protected]");
+}
+
+#[tokio::test]
+async fn reaction_mutation_emits_grouped_reaction_event() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let message_id = repo.state.lock().unwrap().message.id;
+ let events = FakeEvents::default();
+ let svc = mutation_service(repo, events.clone(), FakeReferenceSharing::default());
+
+ svc.post_reaction(
+ macro_id("macro|[email protected]"),
+ channel_id,
+ PostReactionRequest {
+ emoji: "👍".to_string(),
+ message_id: message_id.to_string(),
+ action: ReactionAction::Add,
+ nonce: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let emitted = events.events.lock().unwrap();
+ assert_eq!(emitted.len(), 1);
+ let ChannelEvent::ReactionChanged {
+ channel_id: emitted_channel_id,
+ message_id: emitted_message_id,
+ reactions,
+ ..
+ } = &emitted[0]
+ else {
+ panic!("expected ReactionChanged event, got {:?}", emitted[0]);
+ };
+ assert_eq!(*emitted_channel_id, channel_id);
+ assert_eq!(*emitted_message_id, message_id);
+ assert_eq!(reactions[0].emoji, "👍");
+}
+
#[tokio::test]
async fn clamps_limit() {
- let mut repo = MockChannelMessagesRepo::new();
+ let mut repo = MockChannelRepo::new();
repo.expect_get_top_level_messages()
.withf(|_, _, _, limit, _, _| *limit == 100)
.returning(|_, _, _, _, _, _| {
@@ -187,7 +790,7 @@ async fn clamps_limit() {
repo.expect_get_attachments_batch()
.returning(|_| Box::pin(async { Ok(HashMap::new()) }));
- let svc = ChannelMessagesServiceImpl::new(repo);
+ let svc = ChannelServiceImpl::new(repo);
let result = svc
.get_channel_messages(
Uuid::nil(),
@@ -206,7 +809,7 @@ async fn clamps_limit() {
#[tokio::test]
async fn returns_empty_attachments_page() {
- let svc = ChannelMessagesServiceImpl::new(empty_repo());
+ let svc = ChannelServiceImpl::new(empty_repo());
let page = svc
.get_channel_attachments(Uuid::nil(), Query::Sort(CreatedAt, ()), 50, None)
.await
@@ -218,7 +821,7 @@ async fn returns_empty_attachments_page() {
#[tokio::test]
async fn returns_empty_participants_list() {
- let svc = ChannelMessagesServiceImpl::new(empty_repo());
+ let svc = ChannelServiceImpl::new(empty_repo());
let participants = svc.get_channel_participants(Uuid::nil()).await.unwrap();
assert!(participants.is_empty());
@@ -313,7 +916,7 @@ fn center_window_limit_one() {
#[tokio::test]
async fn around_message_not_found() {
- let svc = ChannelMessagesServiceImpl::new(empty_repo());
+ let svc = ChannelServiceImpl::new(empty_repo());
let message_id = Uuid::new_v4();
let err = svc
@@ -333,7 +936,7 @@ async fn around_deleted_top_level_without_active_replies_is_not_found() {
let mut anchor = make_row(message_id, 0);
anchor.deleted_at = Some(Utc::now());
- let mut repo = MockChannelMessagesRepo::new();
+ let mut repo = MockChannelRepo::new();
repo.expect_resolve_top_level_parent()
.returning(move |_, _| {
let anchor = anchor.clone();
@@ -342,7 +945,7 @@ async fn around_deleted_top_level_without_active_replies_is_not_found() {
repo.expect_get_thread_data()
.returning(|_, _| Box::pin(async { Ok(HashMap::new()) }));
- let svc = ChannelMessagesServiceImpl::new(repo);
+ let svc = ChannelServiceImpl::new(repo);
let err = svc
.get_channel_messages_around(Uuid::nil(), message_id, 50)
.await
@@ -361,7 +964,7 @@ async fn around_reply_to_deleted_top_level_with_active_replies_still_works() {
anchor.deleted_at = Some(Utc::now());
let anchor_clone = anchor.clone();
- let mut repo = MockChannelMessagesRepo::new();
+ let mut repo = MockChannelRepo::new();
repo.expect_resolve_top_level_parent()
.returning(move |_, _| {
@@ -388,7 +991,7 @@ async fn around_reply_to_deleted_top_level_with_active_replies_still_works() {
repo.expect_get_attachments_batch()
.returning(|_| Box::pin(async { Ok(HashMap::new()) }));
- let svc = ChannelMessagesServiceImpl::new(repo);
+ let svc = ChannelServiceImpl::new(repo);
let result = svc
.get_channel_messages_around(Uuid::nil(), reply_id, 50)
.await
@@ -409,7 +1012,7 @@ async fn around_resolves_and_hydrates() {
let before_clone = before_row.clone();
let after_clone = after_row.clone();
- let mut repo = MockChannelMessagesRepo::new();
+ let mut repo = MockChannelRepo::new();
repo.expect_resolve_top_level_parent()
.returning(move |_, _| {
@@ -429,7 +1032,7 @@ async fn around_resolves_and_hydrates() {
repo.expect_get_attachments_batch()
.returning(|_| Box::pin(async { Ok(HashMap::new()) }));
- let svc = ChannelMessagesServiceImpl::new(repo);
+ let svc = ChannelServiceImpl::new(repo);
let result = svc
.get_channel_messages_around(Uuid::nil(), anchor.id, 50)
.await
@@ -446,7 +1049,7 @@ async fn around_resolves_and_hydrates() {
#[tokio::test]
async fn thread_replies_message_not_found() {
- let svc = ChannelMessagesServiceImpl::new(empty_repo());
+ let svc = ChannelServiceImpl::new(empty_repo());
let message_id = Uuid::new_v4();
let err = svc
@@ -486,7 +1089,7 @@ async fn thread_replies_resolve_and_hydrate() {
let reply_1_clone = reply_1.clone();
let reply_2_clone = reply_2.clone();
- let mut repo = MockChannelMessagesRepo::new();
+ let mut repo = MockChannelRepo::new();
repo.expect_resolve_top_level_parent()
.returning(move |_, _| {
@@ -524,7 +1127,7 @@ async fn thread_replies_resolve_and_hydrate() {
Box::pin(async move { Ok(map) })
});
- let svc = ChannelMessagesServiceImpl::new(repo);
+ let svc = ChannelServiceImpl::new(repo);
let replies = svc
.get_thread_replies(Uuid::nil(), reply_1.id)
.await
diff --git a/rust/cloud-storage/channels/src/domain/side_effects.rs b/rust/cloud-storage/channels/src/domain/side_effects.rs
new file mode 100644
index 0000000000..e20baddb95
--- /dev/null
+++ b/rust/cloud-storage/channels/src/domain/side_effects.rs
@@ -0,0 +1,1280 @@
+//! Domain policies for channel side effects.
+
+use crate::domain::{
+ events::ChannelEvent,
+ models::{
+ ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, MutatedAttachment,
+ MutatedMessage, SimpleMention, TypingAction,
+ },
+ ports::{
+ ChannelContactsDispatcher, ChannelEventDispatcher, ChannelEventHandler,
+ ChannelNotificationSender, ChannelRealtimePublisher, ChannelSearchIndexer,
+ ChannelSideEffectContext,
+ },
+};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use std::collections::HashSet;
+use uuid::Uuid;
+
+/// Realtime update requested by the channel domain.
+#[derive(Debug, Clone)]
+pub enum ChannelRealtimeEffect {
+ /// A message was created or changed.
+ Message {
+ /// Recipients that should receive the update.
+ recipients: Vec<MacroUserIdStr<'static>>,
+ /// Persisted message payload.
+ message: MutatedMessage,
+ /// Client mutation nonce echoed to listeners.
+ nonce: Option<String>,
+ },
+ /// Message attachments changed.
+ Attachments {
+ /// Recipients that should receive the update.
+ recipients: Vec<MacroUserIdStr<'static>>,
+ /// Channel containing the message.
+ channel_id: Uuid,
+ /// Message whose attachments changed.
+ message_id: Uuid,
+ /// Current attachment set.
+ attachments: Vec<MutatedAttachment>,
+ /// Client mutation nonce echoed to listeners.
+ nonce: Option<String>,
+ },
+ /// Message reactions changed.
+ Reaction {
+ /// Recipients that should receive the update.
+ recipients: Vec<MacroUserIdStr<'static>>,
+ /// Channel containing the message.
+ channel_id: Uuid,
+ /// Message whose reactions changed.
+ message_id: Uuid,
+ /// Current grouped reaction state.
+ reactions: Vec<CountedReaction>,
+ /// Client mutation nonce echoed to listeners.
+ nonce: Option<String>,
+ },
+ /// Typing state changed.
+ Typing {
+ /// Recipients that should receive the update.
+ recipients: Vec<MacroUserIdStr<'static>>,
+ /// Channel containing the typing update.
+ channel_id: Uuid,
+ /// User whose typing state changed.
+ user_id: String,
+ /// Typing action.
+ action: TypingAction,
+ /// Optional thread id for thread-scoped typing.
+ thread_id: Option<Uuid>,
+ /// Client mutation nonce echoed to listeners.
+ nonce: Option<String>,
+ },
+}
+
+/// Shared channel-message notification payload.
+#[derive(Debug, Clone)]
+pub struct ChannelMentionNotification {
+ /// Channel containing the message.
+ pub channel_id: Uuid,
+ /// Message body.
+ pub message_content: String,
+ /// Message id.
+ pub message_id: Uuid,
+ /// Whether the message has attachments.
+ pub has_attachments: bool,
+ /// Optional thread parent id.
+ pub thread_id: Option<Uuid>,
+ /// Channel display metadata.
+ pub metadata: ChannelMetadata,
+ /// Optional sender profile picture URL.
+ pub sender_profile_picture_url: Option<String>,
+ /// Sender user id.
+ pub sender_id: MacroUserIdStr<'static>,
+}
+
+/// Metadata for a mentioned document.
+#[derive(Debug, Clone)]
+pub struct ChannelDocumentMention {
+ /// Document display name.
+ pub document_name: String,
+ /// Document owner.
+ pub owner: MacroUserIdStr<'static>,
+ /// Optional document file type.
+ pub file_type: Option<String>,
+ /// Optional document subtype.
+ pub sub_type: Option<String>,
+}
+
+/// Thread context needed for reply notifications.
+#[derive(Debug, Clone, Default)]
+pub struct ThreadNotificationContext {
+ /// Users participating in the thread.
+ pub participants: Vec<MacroUserIdStr<'static>>,
+ /// Sender of the thread parent message.
+ pub parent_sender_id: Option<MacroUserIdStr<'static>>,
+}
+
+/// Notification requested by the channel domain.
+#[derive(Debug, Clone)]
+pub enum ChannelNotificationEffect {
+ /// A user was mentioned in a channel message.
+ UserMention {
+ /// Common mention payload.
+ mention: ChannelMentionNotification,
+ /// Users that should receive the notification.
+ recipient_ids: HashSet<MacroUserIdStr<'static>>,
+ },
+ /// A document was mentioned in a channel message.
+ DocumentMention {
+ /// Common mention payload.
+ mention: ChannelMentionNotification,
+ /// Mentioned document metadata.
+ document: ChannelDocumentMention,
+ /// Users that should receive the notification.
+ recipient_ids: HashSet<MacroUserIdStr<'static>>,
+ },
+ /// A reply was posted in a thread.
+ Reply {
+ /// Channel containing the message.
+ channel_id: Uuid,
+ /// Thread parent id.
+ thread_id: Uuid,
+ /// Reply message id.
+ message_id: Uuid,
+ /// Sender user id.
+ sender_id: MacroUserIdStr<'static>,
+ /// Reply body.
+ message_content: String,
+ /// Whether the reply has attachments.
+ has_attachments: bool,
+ /// Sender of the thread parent message.
+ thread_parent_sender_id: Option<MacroUserIdStr<'static>>,
+ /// Channel display metadata.
+ metadata: ChannelMetadata,
+ /// Optional sender profile picture URL.
+ sender_profile_picture_url: Option<String>,
+ /// Users that should receive the notification.
+ recipient_ids: HashSet<MacroUserIdStr<'static>>,
+ },
+ /// A normal channel message was posted.
+ ChannelMessage {
+ /// Channel containing the message.
+ channel_id: Uuid,
+ /// Message id.
+ message_id: Uuid,
+ /// Sender user id.
+ sender_id: MacroUserIdStr<'static>,
+ /// Message body.
+ message_content: String,
+ /// Whether the message has attachments.
+ has_attachments: bool,
+ /// Channel display metadata.
+ metadata: ChannelMetadata,
+ /// Optional sender profile picture URL.
+ sender_profile_picture_url: Option<String>,
+ /// Users that should receive the notification.
+ recipient_ids: HashSet<MacroUserIdStr<'static>>,
+ },
+ /// Participants were invited to a channel.
+ Invite {
+ /// Channel receiving participants.
+ channel_id: Uuid,
+ /// User that invited the participants.
+ invited_by_user_id: MacroUserIdStr<'static>,
+ /// Existing application users.
+ registered_recipient_ids: HashSet<MacroUserIdStr<'static>>,
+ /// Recipients that do not yet exist as application users.
+ unregistered_recipient_ids: HashSet<MacroUserIdStr<'static>>,
+ /// Optional inviter profile picture URL.
+ sender_profile_picture_url: Option<String>,
+ /// Optional message content associated with the invite.
+ message_content: Option<String>,
+ /// Channel display metadata.
+ metadata: ChannelMetadata,
+ },
+}
+
+/// Domain service that derives and dispatches side effects for channel events.
+#[derive(Clone)]
+pub struct ChannelSideEffectService<C, R, N, S, K> {
+ context: C,
+ realtime: R,
+ notifications: N,
+ search: S,
+ contacts: K,
+}
+
+struct MessagePostedSideEffects {
+ channel_id: Uuid,
+ metadata: ChannelMetadata,
+ participants: Vec<ChannelParticipant>,
+ message: MutatedMessage,
+ mentions: Vec<SimpleMention>,
+ has_attachments: bool,
+ attachments: Vec<MutatedAttachment>,
+ nonce: Option<String>,
+}
+
+struct InviteNotificationRequest {
+ channel_id: Uuid,
+ invited_by_user_id: MacroUserIdStr<'static>,
+ recipient_user_ids: Vec<MacroUserIdStr<'static>>,
+ existing_user_ids: HashSet<String>,
+ sender_profile_picture_url: Option<String>,
+ message_content: Option<String>,
+ metadata: ChannelMetadata,
+}
+
+impl<C, R, N, S, K> ChannelSideEffectService<C, R, N, S, K> {
+ /// Create a channel side-effect service.
+ pub fn new(context: C, realtime: R, notifications: N, search: S, contacts: K) -> Self {
+ Self {
+ context,
+ realtime,
+ notifications,
+ search,
+ contacts,
+ }
+ }
+}
+
+/// Channel event dispatcher that handles events on spawned tasks.
+#[derive(Clone)]
+pub struct SpawnedChannelEventDispatcher<H> {
+ handler: H,
+}
+
+impl<H> SpawnedChannelEventDispatcher<H> {
+ /// Create a spawned event dispatcher.
+ pub fn new(handler: H) -> Self {
+ Self { handler }
+ }
+}
+
+impl<H> ChannelEventDispatcher for SpawnedChannelEventDispatcher<H>
+where
+ H: ChannelEventHandler,
+{
+ fn dispatch(&self, event: ChannelEvent) {
+ let handler = self.handler.clone();
+ tokio::spawn(async move {
+ handler.handle(event).await;
+ });
+ }
+}
+
+impl<C, R, N, S, K> ChannelEventHandler for ChannelSideEffectService<C, R, N, S, K>
+where
+ C: ChannelSideEffectContext + Clone,
+ R: ChannelRealtimePublisher + Clone,
+ N: ChannelNotificationSender + Clone,
+ S: ChannelSearchIndexer + Clone,
+ K: ChannelContactsDispatcher + Clone,
+{
+ async fn handle(&self, event: ChannelEvent) {
+ let contact_sync_users = contact_sync_users_for_event(&event);
+
+ match event {
+ ChannelEvent::ChannelCreated { .. } => {}
+ ChannelEvent::ChannelDeleted { channel_id } => {
+ self.search.remove_message(channel_id, None).await;
+ }
+ ChannelEvent::MessagePosted {
+ channel_id,
+ metadata,
+ participants,
+ message,
+ mentions,
+ has_attachments,
+ attachments,
+ nonce,
+ } => {
+ self.handle_message_posted(MessagePostedSideEffects {
+ channel_id,
+ metadata,
+ participants,
+ message,
+ mentions,
+ has_attachments,
+ attachments,
+ nonce,
+ })
+ .await;
+ }
+ ChannelEvent::AttachmentsChanged {
+ channel_id,
+ message_id,
+ attachments,
+ recipients,
+ nonce,
+ } => {
+ self.publish_realtime(ChannelRealtimeEffect::Attachments {
+ recipients,
+ channel_id,
+ message_id,
+ attachments,
+ nonce,
+ })
+ .await;
+ self.search.index_message(channel_id, message_id).await;
+ }
+ ChannelEvent::MessageChanged {
+ channel_id,
+ message,
+ recipients,
+ nonce,
+ } => {
+ let message_id = message.id;
+ self.publish_realtime(ChannelRealtimeEffect::Message {
+ recipients,
+ message,
+ nonce,
+ })
+ .await;
+ self.search.index_message(channel_id, message_id).await;
+ }
+ ChannelEvent::MessageDeleted {
+ channel_id,
+ message,
+ recipients,
+ nonce,
+ } => {
+ let message_id = message.id;
+ self.publish_realtime(ChannelRealtimeEffect::Message {
+ recipients,
+ message,
+ nonce,
+ })
+ .await;
+ self.search
+ .remove_message(channel_id, Some(message_id))
+ .await;
+ }
+ ChannelEvent::ReactionChanged {
+ channel_id,
+ message_id,
+ reactions,
+ recipients,
+ nonce,
+ } => {
+ self.publish_realtime(ChannelRealtimeEffect::Reaction {
+ recipients,
+ channel_id,
+ message_id,
+ reactions,
+ nonce,
+ })
+ .await;
+ }
+ ChannelEvent::TypingChanged {
+ channel_id,
+ user_id,
+ action,
+ thread_id,
+ recipients,
+ nonce,
+ } => {
+ self.publish_realtime(ChannelRealtimeEffect::Typing {
+ recipients,
+ channel_id,
+ user_id,
+ action,
+ thread_id,
+ nonce,
+ })
+ .await;
+ }
+ ChannelEvent::ParticipantsAdded {
+ channel_id,
+ invited_by_user_id,
+ recipient_user_ids,
+ metadata,
+ message_content,
+ ..
+ } => {
+ self.send_participants_added_notification(
+ channel_id,
+ invited_by_user_id,
+ recipient_user_ids,
+ metadata,
+ message_content,
+ )
+ .await;
+ }
+ ChannelEvent::ParticipantJoined { .. } => {}
+ }
+
+ if let Some(users) = contact_sync_users
+ && let Err(err) = self.contacts.enqueue_contacts(users).await
+ {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to enqueue channel contact sync");
+ }
+ }
+}
+
+impl<C, R, N, S, K> ChannelSideEffectService<C, R, N, S, K>
+where
+ C: ChannelSideEffectContext + Clone,
+ R: ChannelRealtimePublisher + Clone,
+ N: ChannelNotificationSender + Clone,
+ S: ChannelSearchIndexer + Clone,
+ K: ChannelContactsDispatcher + Clone,
+{
+ async fn handle_message_posted(&self, event: MessagePostedSideEffects) {
+ let MessagePostedSideEffects {
+ channel_id,
+ metadata,
+ participants,
+ message,
+ mentions,
+ has_attachments,
+ attachments,
+ nonce,
+ } = event;
+ let recipients = participant_ids(&participants);
+ self.publish_realtime(ChannelRealtimeEffect::Message {
+ recipients: recipients.clone(),
+ message: message.clone(),
+ nonce: nonce.clone(),
+ })
+ .await;
+
+ if !attachments.is_empty() {
+ self.publish_realtime(ChannelRealtimeEffect::Attachments {
+ recipients,
+ channel_id,
+ message_id: message.id,
+ attachments,
+ nonce,
+ })
+ .await;
+ }
+
+ self.search.index_message(channel_id, message.id).await;
+ self.send_message_posted_notifications(
+ channel_id,
+ metadata,
+ participants,
+ message,
+ mentions,
+ has_attachments,
+ )
+ .await;
+ }
+
+ async fn publish_realtime(&self, effect: ChannelRealtimeEffect) {
+ if let Err(err) = self.realtime.publish(effect).await {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to dispatch channel realtime event");
+ }
+ }
+
+ async fn send_notification(&self, effect: ChannelNotificationEffect) {
+ if let Err(err) = self.notifications.send(effect).await {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to dispatch channel notification event");
+ }
+ }
+
+ async fn send_message_posted_notifications(
+ &self,
+ channel_id: Uuid,
+ metadata: ChannelMetadata,
+ participants: Vec<ChannelParticipant>,
+ message: MutatedMessage,
+ mentions: Vec<SimpleMention>,
+ has_attachments: bool,
+ ) {
+ let context = match self
+ .build_posted_message_context(channel_id, metadata, &participants, &message, mentions)
+ .await
+ {
+ Ok(context) => context,
+ Err(err) => {
+ tracing::error!(error=?err, "unable to build channel notification context");
+ return;
+ }
+ };
+
+ self.send_user_mention_notifications(channel_id, &message, has_attachments, &context)
+ .await;
+ self.send_document_mention_notifications(channel_id, &message, has_attachments, &context)
+ .await;
+
+ if let Some(thread_id) = message.thread_id {
+ self.send_reply_notification(
+ thread_id,
+ channel_id,
+ &message,
+ has_attachments,
+ &context,
+ )
+ .await;
+ } else if context.is_first_top_level_message {
+ self.send_first_message_invites(channel_id, &message, context)
+ .await;
+ } else {
+ self.send_channel_message_notification(channel_id, &message, has_attachments, &context)
+ .await;
+ }
+ }
+
+ async fn build_posted_message_context(
+ &self,
+ channel_id: Uuid,
+ metadata: ChannelMetadata,
+ participants: &[ChannelParticipant],
+ message: &MutatedMessage,
+ mentions: Vec<SimpleMention>,
+ ) -> anyhow::Result<PostedMessageNotificationContext> {
+ let message_count = self
+ .context
+ .get_channel_message_count(channel_id)
+ .await
+ .map_err(Into::into)?;
+ let is_first_top_level_message = message_count <= 1 && message.thread_id.is_none();
+ let existing_user_ids = if is_first_top_level_message {
+ let participant_ids: Vec<_> = participants
+ .iter()
+ .filter_map(|participant| MacroUserIdStr::parse_from_str(&participant.user_id).ok())
+ .map(|id| id.into_owned())
+ .collect();
+ self.context
+ .get_existing_user_ids(participant_ids)
+ .await
+ .map_err(Into::into)?
+ } else {
+ HashSet::new()
+ };
+
+ let (user_mentions, document_mention_ids) = mentions.into_iter().fold(
+ (Vec::new(), Vec::new()),
+ |(mut users, mut docs), mention| {
+ match mention.entity_type.as_str() {
+ "user" => users.push(mention.entity_id),
+ "document" => docs.push(mention.entity_id),
+ _ => {}
+ }
+ (users, docs)
+ },
+ );
+ let document_mentions = self.load_document_mentions(document_mention_ids).await;
+ let thread_context = self
+ .load_thread_notification_context(message.thread_id)
+ .await;
+ let sender_profile_picture_url = self
+ .context
+ .get_sender_profile_picture_url(message.sender_id.clone())
+ .await;
+
+ let excluded_user_ids = std::iter::once(message.sender_id.as_ref().to_string())
+ .chain(user_mentions.iter().cloned())
+ .collect::<Vec<_>>();
+ let recipients_without_sender = recipients_excluding(
+ participants
+ .iter()
+ .map(|participant| participant.user_id.as_str()),
+ std::iter::once(message.sender_id.as_ref()),
+ )
+ .collect();
+ let recipients_without_sender_and_mentions = recipients_excluding(
+ participants
+ .iter()
+ .map(|participant| participant.user_id.as_str()),
+ excluded_user_ids.iter().map(String::as_str),
+ )
+ .collect();
+
+ Ok(PostedMessageNotificationContext {
+ metadata,
+ sender_profile_picture_url,
+ user_mentions,
+ document_mentions,
+ thread_context,
+ excluded_user_ids,
+ recipients_without_sender,
+ recipients_without_sender_and_mentions,
+ existing_user_ids,
+ is_first_top_level_message,
+ })
+ }
+
+ async fn load_document_mentions(
+ &self,
+ document_mention_ids: Vec<String>,
+ ) -> Vec<ChannelDocumentMention> {
+ if document_mention_ids.is_empty() {
+ return Vec::new();
+ }
+
+ match self
+ .context
+ .get_document_mentions(document_mention_ids)
+ .await
+ {
+ Ok(document_mentions) => document_mentions,
+ Err(err) => {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to get documents metadata");
+ Vec::new()
+ }
+ }
+ }
+
+ async fn load_thread_notification_context(
+ &self,
+ thread_id: Option<Uuid>,
+ ) -> ThreadNotificationContext {
+ match thread_id {
+ Some(thread_id) => self
+ .context
+ .get_thread_notification_context(thread_id)
+ .await
+ .unwrap_or_default(),
+ None => ThreadNotificationContext::default(),
+ }
+ }
+
+ async fn send_user_mention_notifications(
+ &self,
+ channel_id: Uuid,
+ message: &MutatedMessage,
+ has_attachments: bool,
+ context: &PostedMessageNotificationContext,
+ ) {
+ if context.user_mentions.is_empty() {
+ return;
+ }
+
+ self.send_notification(ChannelNotificationEffect::UserMention {
+ mention: ChannelMentionNotification {
+ channel_id,
+ message_content: message.content.clone(),
+ message_id: message.id,
+ has_attachments,
+ thread_id: message.thread_id,
+ metadata: context.metadata.clone(),
+ sender_profile_picture_url: context.sender_profile_picture_url.clone(),
+ sender_id: message.sender_id.clone(),
+ },
+ recipient_ids: recipients_excluding(
+ context.user_mentions.iter().map(String::as_str),
+ std::iter::once(message.sender_id.as_ref()),
+ )
+ .collect(),
+ })
+ .await;
+ }
+
+ async fn send_document_mention_notifications(
+ &self,
+ channel_id: Uuid,
+ message: &MutatedMessage,
+ has_attachments: bool,
+ context: &PostedMessageNotificationContext,
+ ) {
+ if context.document_mentions.is_empty() {
+ return;
+ }
+
+ for document in &context.document_mentions {
+ self.send_notification(ChannelNotificationEffect::DocumentMention {
+ mention: ChannelMentionNotification {
+ channel_id,
+ message_content: message.content.clone(),
+ message_id: message.id,
+ has_attachments,
+ thread_id: message.thread_id,
+ metadata: context.metadata.clone(),
+ sender_profile_picture_url: context.sender_profile_picture_url.clone(),
+ sender_id: message.sender_id.clone(),
+ },
+ document: document.clone(),
+ recipient_ids: context.recipients_without_sender.clone(),
+ })
+ .await;
+ }
+ }
+
+ async fn send_reply_notification(
+ &self,
+ thread_id: Uuid,
+ channel_id: Uuid,
+ message: &MutatedMessage,
+ has_attachments: bool,
+ context: &PostedMessageNotificationContext,
+ ) {
+ if context.thread_context.participants.is_empty() {
+ tracing::warn!(thread_id = %thread_id, "thread participants is empty, but message has thread id");
+ return;
+ }
+
+ self.send_notification(ChannelNotificationEffect::Reply {
+ channel_id,
+ thread_id,
+ message_id: message.id,
+ sender_id: message.sender_id.clone(),
+ message_content: message.content.clone(),
+ has_attachments,
+ thread_parent_sender_id: context.thread_context.parent_sender_id.clone(),
+ metadata: context.metadata.clone(),
+ sender_profile_picture_url: context.sender_profile_picture_url.clone(),
+ recipient_ids: recipients_excluding(
+ context
+ .thread_context
+ .participants
+ .iter()
+ .map(|participant| participant.as_ref()),
+ context.excluded_user_ids.iter().map(String::as_str),
+ )
+ .collect(),
+ })
+ .await;
+ }
+
+ async fn send_first_message_invites(
+ &self,
+ channel_id: Uuid,
+ message: &MutatedMessage,
+ context: PostedMessageNotificationContext,
+ ) {
+ self.send_invite_notification(InviteNotificationRequest {
+ channel_id,
+ invited_by_user_id: message.sender_id.clone(),
+ recipient_user_ids: context
+ .recipients_without_sender_and_mentions
+ .into_iter()
+ .collect(),
+ existing_user_ids: context.existing_user_ids,
+ sender_profile_picture_url: context.sender_profile_picture_url,
+ message_content: Some(message.content.clone()),
+ metadata: context.metadata,
+ })
+ .await;
+ }
+
+ async fn send_channel_message_notification(
+ &self,
+ channel_id: Uuid,
+ message: &MutatedMessage,
+ has_attachments: bool,
+ context: &PostedMessageNotificationContext,
+ ) {
+ self.send_notification(ChannelNotificationEffect::ChannelMessage {
+ channel_id,
+ message_id: message.id,
+ sender_id: message.sender_id.clone(),
+ message_content: message.content.clone(),
+ has_attachments,
+ metadata: context.metadata.clone(),
+ sender_profile_picture_url: context.sender_profile_picture_url.clone(),
+ recipient_ids: context.recipients_without_sender_and_mentions.clone(),
+ })
+ .await;
+ }
+
+ async fn send_participants_added_notification(
+ &self,
+ channel_id: Uuid,
+ invited_by_user_id: MacroUserIdStr<'static>,
+ recipient_user_ids: Vec<MacroUserIdStr<'static>>,
+ metadata: ChannelMetadata,
+ message_content: Option<String>,
+ ) {
+ let sender_profile_picture_url = self
+ .context
+ .get_sender_profile_picture_url(invited_by_user_id.clone())
+ .await;
+ let existing_user_ids = match self
+ .context
+ .get_existing_user_ids(recipient_user_ids.clone())
+ .await
+ {
+ Ok(existing_user_ids) => existing_user_ids,
+ Err(err) => {
+ let err: anyhow::Error = err.into();
+ tracing::error!(error=?err, "unable to get existing users for invite");
+ HashSet::new()
+ }
+ };
+
+ self.send_invite_notification(InviteNotificationRequest {
+ channel_id,
+ invited_by_user_id,
+ recipient_user_ids,
+ existing_user_ids,
+ sender_profile_picture_url,
+ message_content,
+ metadata,
+ })
+ .await;
+ }
+
+ async fn send_invite_notification(&self, req: InviteNotificationRequest) {
+ let InviteNotificationRequest {
+ channel_id,
+ invited_by_user_id,
+ recipient_user_ids,
+ existing_user_ids,
+ sender_profile_picture_url,
+ message_content,
+ metadata,
+ } = req;
+ let (registered_recipient_ids, unregistered_recipient_ids): (HashSet<_>, HashSet<_>) =
+ recipient_user_ids
+ .into_iter()
+ .partition(|id| existing_user_ids.contains(id.as_ref()));
+
+ self.send_notification(ChannelNotificationEffect::Invite {
+ channel_id,
+ invited_by_user_id,
+ registered_recipient_ids,
+ unregistered_recipient_ids,
+ sender_profile_picture_url,
+ message_content,
+ metadata,
+ })
+ .await;
+ }
+}
+
+struct PostedMessageNotificationContext {
+ metadata: ChannelMetadata,
+ sender_profile_picture_url: Option<String>,
+ user_mentions: Vec<String>,
+ document_mentions: Vec<ChannelDocumentMention>,
+ thread_context: ThreadNotificationContext,
+ excluded_user_ids: Vec<String>,
+ recipients_without_sender: HashSet<MacroUserIdStr<'static>>,
+ recipients_without_sender_and_mentions: HashSet<MacroUserIdStr<'static>>,
+ existing_user_ids: HashSet<String>,
+ is_first_top_level_message: bool,
+}
+
+fn participant_ids(participants: &[ChannelParticipant]) -> Vec<MacroUserIdStr<'static>> {
+ participants
+ .iter()
+ .filter_map(|p| MacroUserIdStr::parse_from_str(&p.user_id).ok())
+ .map(|id| id.into_owned())
+ .collect()
+}
+
+fn recipients_excluding<'a>(
+ recipients: impl IntoIterator<Item = &'a str>,
+ exclude: impl IntoIterator<Item = &'a str>,
+) -> impl Iterator<Item = MacroUserIdStr<'static>> {
+ let exclude_set: HashSet<&str> = exclude.into_iter().collect();
+ recipients
+ .into_iter()
+ .filter(move |id| !exclude_set.contains(id))
+ .filter_map(|id| MacroUserIdStr::parse_from_str(id).ok())
+ .map(|u| u.into_owned())
+}
+
+fn contact_sync_users_for_event(event: &ChannelEvent) -> Option<HashSet<MacroUserIdStr<'static>>> {
+ match event {
+ ChannelEvent::ChannelCreated {
+ channel_type: ChannelType::Private | ChannelType::DirectMessage,
+ participant_user_ids,
+ ..
+ } => Some(participant_user_ids.iter().cloned().collect()),
+ ChannelEvent::ParticipantsAdded {
+ channel_type: ChannelType::Private | ChannelType::Team,
+ active_participant_user_ids,
+ ..
+ } => Some(active_participant_user_ids.iter().cloned().collect()),
+ ChannelEvent::ParticipantJoined {
+ channel_type: ChannelType::Public | ChannelType::Private | ChannelType::Team,
+ active_participant_user_ids,
+ ..
+ } if active_participant_user_ids.len() > 1 => {
+ Some(active_participant_user_ids.iter().cloned().collect())
+ }
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::domain::{
+ models::ParticipantRole,
+ ports::{
+ ChannelEventHandler, ChannelNotificationSender, ChannelRealtimePublisher,
+ ChannelSearchIndexer, ChannelSideEffectContext,
+ },
+ };
+ use chrono::Utc;
+ use std::sync::{Arc, Mutex};
+
+ type IndexedMessages = Arc<Mutex<Vec<(Uuid, Uuid)>>>;
+ type RemovedMessages = Arc<Mutex<Vec<(Uuid, Option<Uuid>)>>>;
+
+ #[derive(Clone)]
+ struct FakeContext {
+ message_count: i64,
+ document_mentions: Vec<ChannelDocumentMention>,
+ }
+
+ impl ChannelSideEffectContext for FakeContext {
+ type Err = anyhow::Error;
+
+ async fn get_channel_message_count(&self, _channel_id: Uuid) -> Result<i64, Self::Err> {
+ Ok(self.message_count)
+ }
+
+ async fn get_existing_user_ids(
+ &self,
+ user_ids: Vec<MacroUserIdStr<'static>>,
+ ) -> Result<HashSet<String>, Self::Err> {
+ Ok(user_ids
+ .into_iter()
+ .map(|user_id| user_id.as_ref().to_string())
+ .collect())
+ }
+
+ async fn get_document_mentions(
+ &self,
+ _document_ids: Vec<String>,
+ ) -> Result<Vec<ChannelDocumentMention>, Self::Err> {
+ Ok(self.document_mentions.clone())
+ }
+
+ async fn get_thread_notification_context(
+ &self,
+ _thread_id: Uuid,
+ ) -> Result<ThreadNotificationContext, Self::Err> {
+ Ok(ThreadNotificationContext::default())
+ }
+
+ async fn get_sender_profile_picture_url(
+ &self,
+ _sender_id: MacroUserIdStr<'static>,
+ ) -> Option<String> {
+ Some("https://example.com/avatar.png".to_string())
+ }
+ }
+
+ #[derive(Clone, Default)]
+ struct FakeRealtime {
+ effects: Arc<Mutex<Vec<ChannelRealtimeEffect>>>,
+ }
+
+ impl ChannelRealtimePublisher for FakeRealtime {
+ type Err = anyhow::Error;
+
+ async fn publish(&self, effect: ChannelRealtimeEffect) -> Result<(), Self::Err> {
+ self.effects.lock().unwrap().push(effect);
+ Ok(())
+ }
+ }
+
+ #[derive(Clone, Default)]
+ struct FakeNotifications {
+ effects: Arc<Mutex<Vec<ChannelNotificationEffect>>>,
+ }
+
+ impl ChannelNotificationSender for FakeNotifications {
+ type Err = anyhow::Error;
+
+ async fn send(&self, notification: ChannelNotificationEffect) -> Result<(), Self::Err> {
+ self.effects.lock().unwrap().push(notification);
+ Ok(())
+ }
+ }
+
+ #[derive(Clone, Default)]
+ struct FakeSearch {
+ indexed: IndexedMessages,
+ removed: RemovedMessages,
+ }
+
+ impl ChannelSearchIndexer for FakeSearch {
+ async fn index_message(&self, channel_id: Uuid, message_id: Uuid) {
+ self.indexed.lock().unwrap().push((channel_id, message_id));
+ }
+
+ async fn remove_message(&self, channel_id: Uuid, message_id: Option<Uuid>) {
+ self.removed.lock().unwrap().push((channel_id, message_id));
+ }
+ }
+
+ #[derive(Clone, Default)]
+ struct FakeContacts {
+ users: Arc<Mutex<Vec<HashSet<MacroUserIdStr<'static>>>>>,
+ }
+
+ impl ChannelContactsDispatcher for FakeContacts {
+ type Err = anyhow::Error;
+
+ async fn enqueue_contacts(
+ &self,
+ users: HashSet<MacroUserIdStr<'static>>,
+ ) -> Result<(), Self::Err> {
+ self.users.lock().unwrap().push(users);
+ Ok(())
+ }
+ }
+
+ fn user(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email(email).unwrap()
+ }
+
+ fn users(emails: &[&str]) -> Vec<MacroUserIdStr<'static>> {
+ emails.iter().map(|email| user(email)).collect()
+ }
+
+ #[tokio::test]
+ async fn message_posted_derives_realtime_search_and_notification_effects() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let sender = user("[email protected]");
+ let recipient = user("[email protected]");
+ let realtime = FakeRealtime::default();
+ let notifications = FakeNotifications::default();
+ let search = FakeSearch::default();
+ let contacts = FakeContacts::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ message_count: 2,
+ document_mentions: Vec::new(),
+ },
+ realtime.clone(),
+ notifications.clone(),
+ search.clone(),
+ contacts,
+ );
+ let now = Utc::now();
+
+ service
+ .handle(ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ },
+ participants: vec![
+ ChannelParticipant {
+ channel_id,
+ user_id: sender.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id,
+ user_id: recipient.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ],
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id: None,
+ sender_id: sender.clone(),
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ },
+ mentions: Vec::new(),
+ has_attachments: false,
+ attachments: Vec::new(),
+ nonce: Some("nonce-1".to_string()),
+ })
+ .await;
+
+ let realtime_effects = realtime.effects.lock().unwrap();
+ assert_eq!(realtime_effects.len(), 1);
+ let ChannelRealtimeEffect::Message {
+ recipients,
+ message,
+ nonce,
+ } = &realtime_effects[0]
+ else {
+ panic!("expected message realtime effect");
+ };
+ assert_eq!(message.id, message_id);
+ assert_eq!(nonce.as_deref(), Some("nonce-1"));
+ assert_eq!(recipients.len(), 2);
+ drop(realtime_effects);
+
+ assert_eq!(
+ *search.indexed.lock().unwrap(),
+ vec![(channel_id, message_id)]
+ );
+
+ let notification_effects = notifications.effects.lock().unwrap();
+ assert_eq!(notification_effects.len(), 1);
+ let ChannelNotificationEffect::ChannelMessage {
+ message_id: notified_message_id,
+ recipient_ids,
+ metadata,
+ ..
+ } = &notification_effects[0]
+ else {
+ panic!("expected channel message notification effect");
+ };
+ assert_eq!(*notified_message_id, message_id);
+ assert_eq!(metadata.channel_name, "Project");
+ assert_eq!(recipient_ids.len(), 1);
+ assert!(recipient_ids.contains(&recipient));
+ }
+
+ #[tokio::test]
+ async fn document_mentions_notify_participants_except_sender() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let sender = user("[email protected]");
+ let mentioned = user("[email protected]");
+ let other = user("[email protected]");
+ let notifications = FakeNotifications::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ message_count: 2,
+ document_mentions: vec![ChannelDocumentMention {
+ document_name: "Spec".to_string(),
+ owner: sender.clone(),
+ file_type: None,
+ sub_type: None,
+ }],
+ },
+ FakeRealtime::default(),
+ notifications.clone(),
+ FakeSearch::default(),
+ FakeContacts::default(),
+ );
+ let now = Utc::now();
+
+ service
+ .handle(ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ },
+ participants: vec![
+ ChannelParticipant {
+ channel_id,
+ user_id: sender.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id,
+ user_id: mentioned.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id,
+ user_id: other.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ],
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id: None,
+ sender_id: sender.clone(),
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ },
+ mentions: vec![
+ SimpleMention {
+ entity_type: "user".to_string(),
+ entity_id: mentioned.as_ref().to_string(),
+ },
+ SimpleMention {
+ entity_type: "document".to_string(),
+ entity_id: "doc-1".to_string(),
+ },
+ ],
+ has_attachments: false,
+ attachments: Vec::new(),
+ nonce: None,
+ })
+ .await;
+
+ let notification_effects = notifications.effects.lock().unwrap();
+ let document_recipients = notification_effects
+ .iter()
+ .find_map(|effect| match effect {
+ ChannelNotificationEffect::DocumentMention { recipient_ids, .. } => {
+ Some(recipient_ids)
+ }
+ _ => None,
+ })
+ .expect("expected document mention notification");
+ assert!(document_recipients.contains(&mentioned));
+ assert!(document_recipients.contains(&other));
+ assert!(!document_recipients.contains(&sender));
+ }
+
+ #[test]
+ fn contact_sync_is_derived_from_private_channel_created() {
+ let event = ChannelEvent::ChannelCreated {
+ channel_id: Uuid::nil(),
+ channel_type: ChannelType::Private,
+ participant_user_ids: users(&["[email protected]", "[email protected]"]),
+ };
+
+ let contact_users = contact_sync_users_for_event(&event).unwrap();
+
+ assert_eq!(contact_users.len(), 2);
+ assert!(contact_users.contains(&user("[email protected]")));
+ assert!(contact_users.contains(&user("[email protected]")));
+ }
+
+ #[test]
+ fn contact_sync_ignores_public_channel_created() {
+ let event = ChannelEvent::ChannelCreated {
+ channel_id: Uuid::nil(),
+ channel_type: ChannelType::Public,
+ participant_user_ids: users(&["[email protected]", "[email protected]"]),
+ };
+
+ assert!(contact_sync_users_for_event(&event).is_none());
+ }
+
+ #[test]
+ fn contact_sync_is_derived_from_team_participants_added() {
+ let event = ChannelEvent::ParticipantsAdded {
+ channel_id: Uuid::nil(),
+ channel_type: ChannelType::Team,
+ active_participant_user_ids: users(&["[email protected]", "[email protected]"]),
+ invited_by_user_id: user("[email protected]"),
+ recipient_user_ids: users(&["[email protected]"]),
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Team,
+ channel_name: "team".to_string(),
+ },
+ message_content: None,
+ };
+
+ assert_eq!(contact_sync_users_for_event(&event).unwrap().len(), 2);
+ }
+
+ #[test]
+ fn contact_sync_ignores_single_user_join() {
+ let event = ChannelEvent::ParticipantJoined {
+ channel_id: Uuid::nil(),
+ channel_type: ChannelType::Public,
+ user_id: user("[email protected]"),
+ active_participant_user_ids: users(&["[email protected]"]),
+ };
+
+ assert!(contact_sync_users_for_event(&event).is_none());
+ }
+}
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index 4a2970f62f..2e3fe569a9 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -1,6 +1,12 @@
#[cfg(test)]
mod test;
+pub use crate::domain::models::{
+ AddParticipantsRequest, CreateChannelRequest, CreateChannelResponse, DeleteMessageQuery,
+ GetOrCreateChannelResponse, GetOrCreateDmRequest, GetOrCreatePrivateRequest,
+ PatchChannelRequest, PatchMessageRequest, PostMessageRequest, PostMessageResponse,
+ PostReactionRequest, PostTypingRequest, RemoveParticipantsRequest,
+};
use crate::domain::models::{
ChannelAttachment, ChannelAttachmentType, ChannelMessage, ChannelMessageKind,
ChannelParticipant, CountedReaction, MessageAttachment, MessagePageDirection, ParticipantRole,
@@ -8,25 +14,30 @@ use crate::domain::models::{
};
pub use crate::domain::models::{ChannelMessageFilters, NotificationFilters};
use crate::domain::ports::{
- ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesQueryResult, ChannelMessagesService,
+ ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesQueryResult, ChannelMutationErr,
+ ChannelService,
};
use axum::{
Json, Router,
- extract::{FromRef, Path, Query, State},
+ extract::{Extension, FromRef, Path, Query, State},
http::StatusCode,
response::IntoResponse,
- routing::get,
+ routing::{delete, get, patch, post},
};
use chrono::{DateTime, Utc};
use entity_access::{
domain::{
- models::{EntityAccessReceipt, MemberParticipantRole, RequiredPermission},
+ models::{
+ AdminParticipantRole, EntityAccessReceipt, EntityPermission, MemberParticipantRole,
+ OwnerParticipantRole, RequiredPermission,
+ },
ports::EntityAccessService,
},
inbound::axum_extractors::ChannelAccessLevelExtractor,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
+use model_user::UserContext;
use models_pagination::{
Base64Str, BidirectionalCursor, CreatedAt, Cursor, CursorOptionExt, CursorVal,
CursorWithValAndFilter, PaginatedOpaqueCursor, Query as PaginationQuery, TypeEraseCursor,
@@ -50,8 +61,8 @@ impl<S, Svc> Clone for ChannelsRouterState<S, Svc> {
}
}
-impl<S: ChannelMessagesService, Svc: EntityAccessService> ChannelsRouterState<S, Svc> {
- /// Create a new router state wrapping the service and entity access service.
+impl<S: ChannelService, Svc: EntityAccessService> ChannelsRouterState<S, Svc> {
+ /// Create a router state wrapping the channel service and entity access service.
pub fn new(service: S, access_service: Svc) -> Self {
Self {
service: Arc::new(service),
@@ -87,6 +98,35 @@ fn notification_user_id_from_receipt<T: RequiredPermission>(
Ok(Some(user.clone()))
}
+fn actor_from_receipt<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+) -> Result<MacroUserIdStr<'static>, ChannelsHandlerErr> {
+ receipt
+ .get_authenticated_user()
+ .cloned()
+ .map_err(|_| ChannelsHandlerErr::BadRequest("authenticated user required"))
+}
+
+fn role_from_receipt<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+) -> Result<ParticipantRole, ChannelsHandlerErr> {
+ match receipt.entity_permission() {
+ EntityPermission::ChannelRole { role } => Ok(match role {
+ entity_access::domain::models::ParticipantRole::Owner => ParticipantRole::Owner,
+ entity_access::domain::models::ParticipantRole::Admin => ParticipantRole::Admin,
+ entity_access::domain::models::ParticipantRole::Member => ParticipantRole::Member,
+ }),
+ _ => Err(ChannelsHandlerErr::BadRequest("channel role required")),
+ }
+}
+
+fn actor_from_user_context(
+ user_context: &UserContext,
+) -> Result<MacroUserIdStr<'static>, ChannelsHandlerErr> {
+ MacroUserIdStr::try_from(user_context.user_id.clone())
+ .map_err(|_| ChannelsHandlerErr::BadRequest("invalid user id"))
+}
+
const MAX_MESSAGE_ID_FILTERS: usize = 100;
/// Query parameters for the messages endpoint.
@@ -113,6 +153,13 @@ pub struct ThreadRepliesPath {
message_id: Uuid,
}
+/// Path params for channel-level endpoints.
+#[derive(Debug, Deserialize)]
+pub struct ChannelPath {
+ /// Channel ID from path.
+ channel_id: Uuid,
+}
+
fn parse_messages_query(
cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
) -> (
@@ -154,14 +201,61 @@ fn cursor_from_first_message(
})
}
+/// Build the channel mutation router.
+pub fn channel_mutation_router<S, Svc>() -> Router<ChannelsRouterState<S, Svc>>
+where
+ S: ChannelService,
+ Svc: EntityAccessService,
+{
+ Router::new()
+ .route("/", post(create_channel_handler::<S, Svc>))
+ .route(
+ "/get_or_create_dm",
+ post(get_or_create_dm_handler::<S, Svc>),
+ )
+ .route(
+ "/get_or_create_private",
+ post(get_or_create_private_handler::<S, Svc>),
+ )
+ .route("/{channel_id}", patch(patch_channel_handler::<S, Svc>))
+ .route("/{channel_id}", delete(delete_channel_handler::<S, Svc>))
+ .route(
+ "/{channel_id}/message",
+ post(post_message_handler::<S, Svc>),
+ )
+ .route("/{channel_id}/typing", post(post_typing_handler::<S, Svc>))
+ .route(
+ "/{channel_id}/reaction",
+ post(post_reaction_handler::<S, Svc>),
+ )
+ .route(
+ "/{channel_id}/message/{message_id}",
+ patch(patch_message_handler::<S, Svc>),
+ )
+ .route(
+ "/{channel_id}/message/{message_id}",
+ delete(delete_message_handler::<S, Svc>),
+ )
+ .route("/{channel_id}/join", post(join_channel_handler::<S, Svc>))
+ .route("/{channel_id}/leave", post(leave_channel_handler::<S, Svc>))
+ .route(
+ "/{channel_id}/participants",
+ post(add_participants_handler::<S, Svc>),
+ )
+ .route(
+ "/{channel_id}/participants",
+ delete(remove_participants_handler::<S, Svc>),
+ )
+}
+
/// Create the channels router.
pub fn channels_router<S, Svc, T>(state: ChannelsRouterState<S, Svc>) -> Router<T>
where
- S: ChannelMessagesService,
+ S: ChannelService,
Svc: EntityAccessService,
T: Send + Sync,
{
- Router::new()
+ channel_mutation_router::<S, Svc>()
.route(
"/{channel_id}/messages",
get(get_channel_messages_handler::<S, Svc>)
@@ -186,6 +280,196 @@ where
.with_state(state)
}
+/// Handler for `POST /channels`.
+#[tracing::instrument(err, skip_all)]
+pub async fn create_channel_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ Extension(user_context): Extension<UserContext>,
+ Json(req): Json<CreateChannelRequest>,
+) -> Result<(StatusCode, Json<CreateChannelResponse>), ChannelsHandlerErr> {
+ let actor = actor_from_user_context(&user_context)?;
+ let res = state
+ .service
+ .create_channel(actor, user_context.organization_id.map(i64::from), req)
+ .await?;
+ Ok((StatusCode::OK, Json(res)))
+}
+
+/// Handler for `POST /channels/get_or_create_dm`.
+#[tracing::instrument(err, skip_all)]
+pub async fn get_or_create_dm_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ Extension(user_context): Extension<UserContext>,
+ Json(req): Json<GetOrCreateDmRequest>,
+) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
+ let actor = actor_from_user_context(&user_context)?;
+ let res = state.service.get_or_create_dm(actor, req).await?;
+ Ok((StatusCode::OK, Json(res)))
+}
+
+/// Handler for `POST /channels/get_or_create_private`.
+#[tracing::instrument(err, skip_all)]
+pub async fn get_or_create_private_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ Extension(user_context): Extension<UserContext>,
+ Json(req): Json<GetOrCreatePrivateRequest>,
+) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
+ let actor = actor_from_user_context(&user_context)?;
+ let res = state.service.get_or_create_private(actor, req).await?;
+ Ok((StatusCode::OK, Json(res)))
+}
+
+/// Handler for `PATCH /channels/{channel_id}`.
+#[tracing::instrument(err, skip_all)]
+pub async fn patch_channel_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc>,
+ Json(req): Json<PatchChannelRequest>,
+) -> Result<(StatusCode, String), ChannelsHandlerErr> {
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ state.service.patch_channel(actor, channel_id, req).await?;
+ Ok((StatusCode::OK, "patched channel".to_string()))
+}
+
+/// Handler for `DELETE /channels/{channel_id}`.
+#[tracing::instrument(err, skip_all)]
+pub async fn delete_channel_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<OwnerParticipantRole, Svc>,
+) -> Result<(StatusCode, String), ChannelsHandlerErr> {
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ state.service.delete_channel(actor, channel_id).await?;
+ Ok((StatusCode::OK, "channel successfully deleted".to_string()))
+}
+
+/// Handler for `POST /channels/{channel_id}/message`.
+#[tracing::instrument(err, skip_all)]
+pub async fn post_message_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+ Json(req): Json<PostMessageRequest>,
+) -> Result<(StatusCode, Json<PostMessageResponse>), ChannelsHandlerErr> {
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ let res = state.service.post_message(actor, channel_id, req).await?;
+ Ok((StatusCode::OK, Json(res)))
+}
+
+/// Handler for `PATCH /channels/{channel_id}/message/{message_id}`.
+#[tracing::instrument(err, skip_all)]
+pub async fn patch_message_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+ Path(path): Path<ThreadRepliesPath>,
+ Json(req): Json<PatchMessageRequest>,
+) -> Result<(StatusCode, String), ChannelsHandlerErr> {
+ let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ let role = role_from_receipt(&access.entity_access_receipt)?;
+ state
+ .service
+ .patch_message(actor, role, path.channel_id, path.message_id, req)
+ .await?;
+ Ok((StatusCode::OK, "message sent".to_string()))
+}
+
+/// Handler for `DELETE /channels/{channel_id}/message/{message_id}`.
+#[tracing::instrument(err, skip_all)]
+pub async fn delete_message_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+ Path(path): Path<ThreadRepliesPath>,
+ Query(query): Query<DeleteMessageQuery>,
+) -> Result<(StatusCode, String), ChannelsHandlerErr> {
+ let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ let role = role_from_receipt(&access.entity_access_receipt)?;
+ state
+ .service
+ .delete_message(actor, role, path.channel_id, path.message_id, query)
+ .await?;
+ Ok((StatusCode::OK, "message sent".to_string()))
+}
+
+/// Handler for `POST /channels/{channel_id}/reaction`.
+#[tracing::instrument(err, skip_all)]
+pub async fn post_reaction_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+ Json(req): Json<PostReactionRequest>,
+) -> Result<(StatusCode, String), ChannelsHandlerErr> {
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ state.service.post_reaction(actor, channel_id, req).await?;
+ Ok((StatusCode::OK, "Reaction added".to_string()))
+}
+
+/// Handler for `POST /channels/{channel_id}/typing`.
+#[tracing::instrument(err, skip_all)]
+pub async fn post_typing_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+ Json(req): Json<PostTypingRequest>,
+) -> Result<(StatusCode, String), ChannelsHandlerErr> {
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ state.service.post_typing(actor, channel_id, req).await?;
+ Ok((StatusCode::OK, "message sent".to_string()))
+}
+
+/// Handler for `POST /channels/{channel_id}/participants`.
+#[tracing::instrument(err, skip_all)]
+pub async fn add_participants_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+ Json(req): Json<AddParticipantsRequest>,
+) -> Result<StatusCode, ChannelsHandlerErr> {
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ state
+ .service
+ .add_participants(actor, channel_id, req)
+ .await?;
+ Ok(StatusCode::OK)
+}
+
+/// Handler for `DELETE /channels/{channel_id}/participants`.
+#[tracing::instrument(err, skip_all)]
+pub async fn remove_participants_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+ Json(req): Json<RemoveParticipantsRequest>,
+) -> Result<StatusCode, ChannelsHandlerErr> {
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ state.service.remove_participants(channel_id, req).await?;
+ Ok(StatusCode::OK)
+}
+
+/// Handler for `POST /channels/{channel_id}/join`.
+#[tracing::instrument(err, skip_all)]
+pub async fn join_channel_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ Path(path): Path<ChannelPath>,
+ Extension(user_context): Extension<UserContext>,
+) -> Result<StatusCode, ChannelsHandlerErr> {
+ let channel_id = path.channel_id;
+ let actor = actor_from_user_context(&user_context)?;
+ state.service.join_channel(actor, channel_id).await?;
+ Ok(StatusCode::OK)
+}
+
+/// Handler for `POST /channels/{channel_id}/leave`.
+#[tracing::instrument(err, skip_all)]
+pub async fn leave_channel_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+) -> Result<StatusCode, ChannelsHandlerErr> {
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ state.service.leave_channel(actor, channel_id).await?;
+ Ok(StatusCode::OK)
+}
+
/// Handler for `GET /channels/{channel_id}/messages`.
#[utoipa::path(
get,
@@ -217,7 +501,7 @@ where
load_around_message_id = tracing::field::Empty
)
)]
-pub async fn get_channel_messages_handler<S: ChannelMessagesService, Svc: EntityAccessService>(
+pub async fn get_channel_messages_handler<S: ChannelService, Svc: EntityAccessService>(
State(state): State<ChannelsRouterState<S, Svc>>,
access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Query(params): Query<Params>,
@@ -260,7 +544,7 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService, Svc: Entity
load_around_message_id = tracing::field::Empty
)
)]
-pub async fn post_channel_messages_handler<S: ChannelMessagesService, Svc: EntityAccessService>(
+pub async fn post_channel_messages_handler<S: ChannelService, Svc: EntityAccessService>(
State(state): State<ChannelsRouterState<S, Svc>>,
access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Query(params): Query<Params>,
@@ -284,7 +568,7 @@ pub async fn post_channel_messages_handler<S: ChannelMessagesService, Svc: Entit
.await
}
-async fn channel_messages_response<S: ChannelMessagesService, Svc>(
+async fn channel_messages_response<S: ChannelService, Svc>(
state: &ChannelsRouterState<S, Svc>,
params: Params,
cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
@@ -378,7 +662,7 @@ async fn channel_messages_response<S: ChannelMessagesService, Svc>(
skip_all,
fields(channel_id = tracing::field::Empty, message_id = tracing::field::Empty)
)]
-pub async fn get_thread_replies_handler<S: ChannelMessagesService, Svc: EntityAccessService>(
+pub async fn get_thread_replies_handler<S: ChannelService, Svc: EntityAccessService>(
State(state): State<ChannelsRouterState<S, Svc>>,
_access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Path(path): Path<ThreadRepliesPath>,
@@ -420,10 +704,7 @@ pub async fn get_thread_replies_handler<S: ChannelMessagesService, Svc: EntityAc
skip_all,
fields(channel_id = tracing::field::Empty, message_id = tracing::field::Empty)
)]
-pub async fn resolve_channel_message_handler<
- S: ChannelMessagesService,
- Svc: EntityAccessService,
->(
+pub async fn resolve_channel_message_handler<S: ChannelService, Svc: EntityAccessService>(
State(state): State<ChannelsRouterState<S, Svc>>,
_access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Path(path): Path<ThreadRepliesPath>,
@@ -470,10 +751,7 @@ pub async fn resolve_channel_message_handler<
attachment_type = tracing::field::Empty
)
)]
-pub async fn get_channel_attachments_handler<
- S: ChannelMessagesService,
- Svc: EntityAccessService,
->(
+pub async fn get_channel_attachments_handler<S: ChannelService, Svc: EntityAccessService>(
State(state): State<ChannelsRouterState<S, Svc>>,
access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Query(params): Query<Params>,
@@ -516,10 +794,7 @@ pub async fn get_channel_attachments_handler<
)
)]
#[tracing::instrument(err, skip_all, fields(channel_id = tracing::field::Empty))]
-pub async fn get_channel_participants_handler<
- S: ChannelMessagesService,
- Svc: EntityAccessService,
->(
+pub async fn get_channel_participants_handler<S: ChannelService, Svc: EntityAccessService>(
State(state): State<ChannelsRouterState<S, Svc>>,
access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
) -> Result<Json<Vec<ApiChannelParticipant>>, ChannelsHandlerErr> {
@@ -861,6 +1136,9 @@ pub enum ChannelsHandlerErr {
/// Internal server error.
#[error("An internal server error occurred")]
Internal(#[from] ChannelMessagesErr),
+ /// Mutation error.
+ #[error(transparent)]
+ Mutation(#[from] ChannelMutationErr),
}
impl IntoResponse for ChannelsHandlerErr {
@@ -873,6 +1151,27 @@ impl IntoResponse for ChannelsHandlerErr {
}),
)
.into_response(),
+ ChannelsHandlerErr::Mutation(err) => {
+ let status = match &err {
+ ChannelMutationErr::BadRequest(_) => StatusCode::BAD_REQUEST,
+ ChannelMutationErr::Unauthorized(_) => StatusCode::UNAUTHORIZED,
+ ChannelMutationErr::NotFound(_) => StatusCode::NOT_FOUND,
+ ChannelMutationErr::Repo(_)
+ | ChannelMutationErr::Gateway(_)
+ | ChannelMutationErr::Notification(_)
+ | ChannelMutationErr::Contacts(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ if status == StatusCode::INTERNAL_SERVER_ERROR {
+ tracing::error!(error=?err, "channel mutation error");
+ }
+ (
+ status,
+ Json(ErrorResponse {
+ message: err.to_string().into(),
+ }),
+ )
+ .into_response()
+ }
ChannelsHandlerErr::Internal(err) => match err {
ChannelMessagesErr::MessageNotFound(id) => {
tracing::warn!(message_id=?id, "message not found");
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
index a36ea70b01..57f7924669 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -1,10 +1,14 @@
use super::*;
use crate::domain::models::{
ChannelAttachment, ChannelMessage, ChannelMessageFilters, ChannelParticipant,
- MessagePageDirection, ParticipantRole,
+ DeleteMessageQuery, GetOrCreateChannelResponse, GetOrCreateDmRequest,
+ GetOrCreatePrivateRequest, MessagePageDirection, ParticipantRole, PatchChannelRequest,
+ PatchMessageRequest, PostMessageRequest, PostMessageResponse, PostReactionRequest,
+ PostTypingRequest, RemoveParticipantsRequest,
};
use crate::domain::ports::{
- ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelMessagesService,
+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelMutationErr,
+ ChannelService,
};
use axum::{
Extension, Router,
@@ -23,6 +27,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use model_user::UserContext;
use models_pagination::{Base64Str, CreatedAt, Cursor, CursorVal, PaginateOn, Query};
+use std::sync::{Arc, Mutex};
use tower::util::ServiceExt;
// --- Access service implementations for tests ---
@@ -172,7 +177,7 @@ impl EntityAccessService for TestAccessService {
struct MockService;
-impl ChannelMessagesService for MockService {
+impl ChannelService for MockService {
async fn get_channel_messages(
&self,
_channel_id: Uuid,
@@ -240,7 +245,7 @@ impl ChannelMessagesService for MockService {
struct ErrorService;
-impl ChannelMessagesService for ErrorService {
+impl ChannelService for ErrorService {
async fn get_channel_messages(
&self,
_channel_id: Uuid,
@@ -290,7 +295,7 @@ impl ChannelMessagesService for ErrorService {
struct ParticipantsService;
-impl ChannelMessagesService for ParticipantsService {
+impl ChannelService for ParticipantsService {
async fn get_channel_messages(
&self,
_channel_id: Uuid,
@@ -371,6 +376,207 @@ impl ChannelMessagesService for ParticipantsService {
}
}
+#[derive(Clone, Default)]
+struct RecordingMutationService {
+ posts: Arc<Mutex<Vec<(MacroUserIdStr<'static>, Uuid, PostMessageRequest)>>>,
+}
+
+impl ChannelService for RecordingMutationService {
+ async fn get_channel_messages(
+ &self,
+ _channel_id: Uuid,
+ _query: models_pagination::Query<Uuid, CreatedAt, ()>,
+ _direction: MessagePageDirection,
+ _limit: u16,
+ _filters: &ChannelMessageFilters,
+ _notification_user_id: Option<MacroUserIdStr<'static>>,
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
+ Ok(ChannelMessagesQueryResult {
+ page: Vec::<ChannelMessage>::new()
+ .into_iter()
+ .paginate_on(50, CreatedAt)
+ .filter_on(())
+ .into_page(),
+ has_more_newer: false,
+ })
+ }
+
+ async fn get_channel_attachments(
+ &self,
+ _channel_id: Uuid,
+ _query: models_pagination::Query<Uuid, CreatedAt, ()>,
+ _limit: u16,
+ _attachment_type: Option<ChannelAttachmentType>,
+ ) -> Result<ChannelAttachmentsPage, ChannelMessagesErr> {
+ Ok(Vec::<ChannelAttachment>::new()
+ .into_iter()
+ .paginate_on(50, CreatedAt)
+ .filter_on(())
+ .into_page())
+ }
+
+ async fn get_channel_participants(
+ &self,
+ _channel_id: Uuid,
+ ) -> Result<Vec<ChannelParticipant>, ChannelMessagesErr> {
+ Ok(vec![])
+ }
+
+ async fn get_channel_messages_around(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _limit: u16,
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
+ Ok(ChannelMessagesQueryResult {
+ page: Vec::<ChannelMessage>::new()
+ .into_iter()
+ .paginate_on(50, CreatedAt)
+ .filter_on(())
+ .into_page(),
+ has_more_newer: false,
+ })
+ }
+
+ async fn get_thread_replies(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ ) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {
+ Ok(vec![])
+ }
+
+ async fn create_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _actor_org_id: Option<i64>,
+ _req: CreateChannelRequest,
+ ) -> Result<CreateChannelResponse, ChannelMutationErr> {
+ Ok(CreateChannelResponse {
+ id: Uuid::new_v4().to_string(),
+ })
+ }
+
+ async fn get_or_create_dm(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _req: GetOrCreateDmRequest,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ Err(ChannelMutationErr::NotFound("unused".to_string()))
+ }
+
+ async fn get_or_create_private(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _req: GetOrCreatePrivateRequest,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ Err(ChannelMutationErr::NotFound("unused".to_string()))
+ }
+
+ async fn patch_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _req: PatchChannelRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+
+ async fn delete_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+
+ async fn post_message(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ req: PostMessageRequest,
+ ) -> Result<PostMessageResponse, ChannelMutationErr> {
+ self.posts.lock().unwrap().push((actor, channel_id, req));
+ Ok(PostMessageResponse {
+ id: Uuid::new_v4().to_string(),
+ nonce: Some("n1".to_string()),
+ })
+ }
+
+ async fn patch_message(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _actor_role: ParticipantRole,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _req: PatchMessageRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+
+ async fn delete_message(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _actor_role: ParticipantRole,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _query: DeleteMessageQuery,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+
+ async fn post_reaction(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _req: PostReactionRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+
+ async fn post_typing(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _req: PostTypingRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+
+ async fn add_participants(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _req: AddParticipantsRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+
+ async fn remove_participants(
+ &self,
+ _channel_id: Uuid,
+ _req: RemoveParticipantsRequest,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+
+ async fn join_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+
+ async fn leave_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ Ok(())
+ }
+}
+
fn user_extension() -> Extension<UserContext> {
Extension(UserContext {
user_id: "macro|[email protected]".to_string(),
@@ -412,6 +618,45 @@ fn not_found_router() -> Router {
.layer(user_extension())
}
+#[tokio::test]
+async fn post_message_route_uses_entity_access_and_mutation_service() {
+ let mutation_service = RecordingMutationService::default();
+ let posts = mutation_service.posts.clone();
+ let router = channels_router(ChannelsRouterState::new(
+ mutation_service,
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension());
+ let channel_id = Uuid::new_v4();
+ let request = Request::builder()
+ .method("POST")
+ .uri(format!("/{channel_id}/message"))
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::json!({
+ "content": "hello",
+ "mentions": [],
+ "thread_id": null,
+ "attachments": [],
+ "nonce": "n1"
+ })
+ .to_string(),
+ ))
+ .unwrap();
+
+ let res = router.oneshot(request).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+ let bytes = res.into_body().collect().await.unwrap().to_bytes();
+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(json["nonce"], "n1");
+
+ let posts = posts.lock().unwrap();
+ assert_eq!(posts.len(), 1);
+ assert_eq!(posts[0].0.as_ref(), "macro|[email protected]");
+ assert_eq!(posts[0].1, channel_id);
+ assert_eq!(posts[0].2.content, "hello");
+}
+
#[tokio::test]
async fn messages_returns_empty_page() {
let router = mock_router();
@@ -594,7 +839,7 @@ async fn participants_returns_500_on_service_error() {
struct NotFoundService;
-impl ChannelMessagesService for NotFoundService {
+impl ChannelService for NotFoundService {
async fn get_channel_messages(
&self,
_channel_id: Uuid,
@@ -657,7 +902,7 @@ struct AroundHasItemsService {
has_more_newer: bool,
}
-impl ChannelMessagesService for AroundHasItemsService {
+impl ChannelService for AroundHasItemsService {
async fn get_channel_messages(
&self,
_channel_id: Uuid,
@@ -857,7 +1102,7 @@ impl CapturingService {
}
}
-impl ChannelMessagesService for std::sync::Arc<CapturingService> {
+impl ChannelService for std::sync::Arc<CapturingService> {
async fn get_channel_messages(
&self,
_channel_id: Uuid,
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/mod.rs b/rust/cloud-storage/channels/src/inbound/toolset/mod.rs
index dcf2b64a70..146c732af6 100644
--- a/rust/cloud-storage/channels/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/channels/src/inbound/toolset/mod.rs
@@ -8,7 +8,7 @@ mod types;
#[cfg(test)]
mod test;
-use crate::domain::ports::ChannelMessagesService;
+use crate::domain::ports::ChannelService;
use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};
use entity_access::domain::{
models::{AccessError, AccessLevel, EntityType},
@@ -26,7 +26,7 @@ pub use read_channel_thread::{ReadChannelThread, ReadChannelThreadResponse};
/// Service context for channel AI tools.
pub struct ChannelToolContext<Svc, AccessSvc>
where
- Svc: ChannelMessagesService,
+ Svc: ChannelService,
AccessSvc: EntityAccessService,
{
/// Channel message service used to read timelines, resolve messages, and fetch threads.
@@ -37,7 +37,7 @@ where
impl<Svc, AccessSvc> Clone for ChannelToolContext<Svc, AccessSvc>
where
- Svc: ChannelMessagesService,
+ Svc: ChannelService,
AccessSvc: EntityAccessService,
{
fn clone(&self) -> Self {
@@ -50,7 +50,7 @@ where
impl<Svc, AccessSvc> ChannelToolContext<Svc, AccessSvc>
where
- Svc: ChannelMessagesService,
+ Svc: ChannelService,
AccessSvc: EntityAccessService,
{
/// Create a new channel tool context.
@@ -101,7 +101,7 @@ fn channel_access_error(err: AccessError) -> ToolCallError {
/// Create the channel AI toolset.
pub fn channel_toolset<Svc, AccessSvc>() -> AsyncToolCollection<ChannelToolContext<Svc, AccessSvc>>
where
- Svc: ChannelMessagesService,
+ Svc: ChannelService,
AccessSvc: EntityAccessService,
{
AsyncToolCollection::new()
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/read_channel_message_context.rs b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_message_context.rs
index 77bb02529f..f6b991f316 100644
--- a/rust/cloud-storage/channels/src/inbound/toolset/read_channel_message_context.rs
+++ b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_message_context.rs
@@ -6,7 +6,7 @@ use super::types::{
clamp_max_chars, content_truncation_omissions,
};
use crate::domain::models::ChannelMessageKind;
-use crate::domain::ports::ChannelMessagesService;
+use crate::domain::ports::ChannelService;
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use entity_access::domain::ports::EntityAccessService;
@@ -111,7 +111,7 @@ pub struct ReadChannelMessageContextResponse {
#[async_trait]
impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for ReadChannelMessageContext
where
- Svc: ChannelMessagesService,
+ Svc: ChannelService,
AccessSvc: EntityAccessService,
{
type Output = ReadChannelMessageContextResponse;
@@ -240,7 +240,7 @@ async fn read_reply_context<Svc>(
args: ReplyContextArgs,
) -> Result<ToolThreadReplyContextWindow, ToolCallError>
where
- Svc: ChannelMessagesService,
+ Svc: ChannelService,
{
let before = usize::from(args.before.unwrap_or(10).min(50));
let after = usize::from(args.after.unwrap_or(10).min(50));
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/read_channel_messages.rs b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_messages.rs
index ba213d16ff..9e651986b9 100644
--- a/rust/cloud-storage/channels/src/inbound/toolset/read_channel_messages.rs
+++ b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_messages.rs
@@ -6,7 +6,7 @@ use super::types::{
clamp_max_chars, content_truncation_omissions,
};
use crate::domain::models::{ChannelMessageFilters, MessagePageDirection};
-use crate::domain::ports::{ChannelMessagesQueryResult, ChannelMessagesService};
+use crate::domain::ports::{ChannelMessagesQueryResult, ChannelService};
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
@@ -163,7 +163,7 @@ pub struct ReadChannelMessagesResponse {
#[async_trait]
impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for ReadChannelMessages
where
- Svc: ChannelMessagesService,
+ Svc: ChannelService,
AccessSvc: EntityAccessService,
{
type Output = ReadChannelMessagesResponse;
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/read_channel_thread.rs b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_thread.rs
index f7ce6afeb2..892b8fde7e 100644
--- a/rust/cloud-storage/channels/src/inbound/toolset/read_channel_thread.rs
+++ b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_thread.rs
@@ -5,7 +5,7 @@ use super::types::{
ToolChannelMessage, ToolOmission, ToolOmissionKind, ToolResolvedMessage, ToolThreadReply,
clamp_limit, clamp_max_chars, content_truncation_omissions,
};
-use crate::domain::ports::ChannelMessagesService;
+use crate::domain::ports::ChannelService;
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
@@ -117,7 +117,7 @@ pub struct ReadChannelThreadResponse {
#[async_trait]
impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for ReadChannelThread
where
- Svc: ChannelMessagesService,
+ Svc: ChannelService,
AccessSvc: EntityAccessService,
{
type Output = ReadChannelThreadResponse;
diff --git a/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs
new file mode 100644
index 0000000000..c7d545e5a1
--- /dev/null
+++ b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs
@@ -0,0 +1,167 @@
+//! Connection-gateway realtime adapter for channel side effects.
+
+use crate::domain::{
+ models::{CountedReaction, MutatedAttachment, TypingAction},
+ ports::ChannelRealtimePublisher,
+ side_effects::ChannelRealtimeEffect,
+};
+use connection_gateway_client::ConnectionGatewayClient;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType as GatewayEntityType;
+use serde::Serialize;
+use std::sync::Arc;
+use uuid::Uuid;
+
+/// Connection-gateway realtime publisher adapter.
+#[derive(Clone)]
+pub struct ConnectionGatewayChannelRealtimePublisher {
+ client: Arc<ConnectionGatewayClient>,
+}
+
+impl ConnectionGatewayChannelRealtimePublisher {
+ /// Create a realtime publisher adapter.
+ pub fn new(client: Arc<ConnectionGatewayClient>) -> Self {
+ Self { client }
+ }
+
+ async fn send_update<T: Serialize + Send>(
+ &self,
+ message_type: &'static str,
+ payload: T,
+ participants: Vec<MacroUserIdStr<'static>>,
+ ) -> anyhow::Result<()> {
+ if participants.is_empty() {
+ return Ok(());
+ }
+ self.client
+ .batch_send_message(
+ message_type.to_string(),
+ serde_json::to_value(payload)?,
+ participants
+ .iter()
+ .map(|p| GatewayEntityType::User.with_entity_str(p.as_ref()))
+ .collect(),
+ )
+ .await?;
+ Ok(())
+ }
+}
+
+impl ChannelRealtimePublisher for ConnectionGatewayChannelRealtimePublisher {
+ type Err = anyhow::Error;
+
+ async fn publish(&self, effect: ChannelRealtimeEffect) -> Result<(), Self::Err> {
+ match effect {
+ ChannelRealtimeEffect::Message {
+ recipients,
+ message,
+ nonce,
+ } => {
+ self.send_update(
+ "comms_message",
+ WithNonce {
+ data: message,
+ nonce,
+ },
+ recipients,
+ )
+ .await
+ }
+ ChannelRealtimeEffect::Attachments {
+ recipients,
+ channel_id,
+ message_id,
+ attachments,
+ nonce,
+ } => {
+ self.send_update(
+ "comms_attachment",
+ WithNonce {
+ data: AttachmentRealtimeData {
+ channel_id,
+ message_id,
+ attachments,
+ },
+ nonce,
+ },
+ recipients,
+ )
+ .await
+ }
+ ChannelRealtimeEffect::Reaction {
+ recipients,
+ channel_id,
+ message_id,
+ reactions,
+ nonce,
+ } => {
+ self.send_update(
+ "comms_reaction",
+ WithNonce {
+ data: ReactionRealtimeData {
+ channel_id,
+ message_id,
+ reactions,
+ },
+ nonce,
+ },
+ recipients,
+ )
+ .await
+ }
+ ChannelRealtimeEffect::Typing {
+ recipients,
+ channel_id,
+ user_id,
+ action,
+ thread_id,
+ nonce,
+ } => {
+ self.send_update(
+ "comms_typing",
+ WithNonce {
+ data: TypingRealtimeData {
+ channel_id,
+ user_id,
+ action,
+ thread_id,
+ },
+ nonce,
+ },
+ recipients,
+ )
+ .await
+ }
+ }
+ }
+}
+
+#[derive(Serialize)]
+struct WithNonce<T: Serialize> {
+ #[serde(flatten)]
+ data: T,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ nonce: Option<String>,
+}
+
+#[derive(Serialize)]
+struct AttachmentRealtimeData {
+ channel_id: Uuid,
+ message_id: Uuid,
+ attachments: Vec<MutatedAttachment>,
+}
+
+#[derive(Serialize)]
+struct ReactionRealtimeData {
+ channel_id: Uuid,
+ message_id: Uuid,
+ reactions: Vec<CountedReaction>,
+}
+
+#[derive(Serialize)]
+struct TypingRealtimeData {
+ channel_id: Uuid,
+ user_id: String,
+ action: TypingAction,
+ thread_id: Option<Uuid>,
+}
diff --git a/rust/cloud-storage/channels/src/outbound/contacts_dispatcher.rs b/rust/cloud-storage/channels/src/outbound/contacts_dispatcher.rs
new file mode 100644
index 0000000000..b7d43ddc8a
--- /dev/null
+++ b/rust/cloud-storage/channels/src/outbound/contacts_dispatcher.rs
@@ -0,0 +1,43 @@
+//! Contacts adapter for channel side effects.
+
+use crate::domain::ports::ChannelContactsDispatcher;
+use contacts::domain::ports::ContactsIngress;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::{collections::HashSet, sync::Arc};
+
+/// Contacts ingress adapter.
+pub struct ContactsChannelDispatcher<I> {
+ ingress: Arc<I>,
+}
+
+impl<I> Clone for ContactsChannelDispatcher<I> {
+ fn clone(&self) -> Self {
+ Self {
+ ingress: self.ingress.clone(),
+ }
+ }
+}
+
+impl<I> ContactsChannelDispatcher<I> {
+ /// Create a contacts adapter.
+ pub fn new(ingress: Arc<I>) -> Self {
+ Self { ingress }
+ }
+}
+
+impl<I> ChannelContactsDispatcher for ContactsChannelDispatcher<I>
+where
+ I: ContactsIngress,
+{
+ type Err = anyhow::Error;
+
+ async fn enqueue_contacts(
+ &self,
+ users: HashSet<MacroUserIdStr<'static>>,
+ ) -> Result<(), Self::Err> {
+ self.ingress
+ .enqueue_contacts(users)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e:?}"))
+ }
+}
diff --git a/rust/cloud-storage/channels/src/outbound/mod.rs b/rust/cloud-storage/channels/src/outbound/mod.rs
index 7e85e2b8a8..1cdfb473f5 100644
--- a/rust/cloud-storage/channels/src/outbound/mod.rs
+++ b/rust/cloud-storage/channels/src/outbound/mod.rs
@@ -1,2 +1,14 @@
-/// Postgres repository for channel messages.
+/// Connection-gateway realtime adapter for channel side effects.
+pub mod connection_gateway_realtime;
+/// Contacts adapter for channel side effects.
+pub mod contacts_dispatcher;
+/// Notification adapter for channel notification side effects.
+pub mod notification_sender;
+/// Postgres adapter for channel reference share-permission side effects.
+pub mod pg_channel_reference_share_permissions;
+/// Postgres repository for channels.
pub mod pg_channels_repo;
+/// Postgres context adapter for channel side-effect policy.
+pub mod pg_side_effect_context;
+/// SQS search-index adapter for channel side effects.
+pub mod sqs_search_indexer;
diff --git a/rust/cloud-storage/channels/src/outbound/notification_sender.rs b/rust/cloud-storage/channels/src/outbound/notification_sender.rs
new file mode 100644
index 0000000000..8928d3e098
--- /dev/null
+++ b/rust/cloud-storage/channels/src/outbound/notification_sender.rs
@@ -0,0 +1,283 @@
+//! Notification adapter for channel notification side effects.
+
+use crate::domain::{
+ models::{ChannelMetadata, ChannelType},
+ ports::ChannelNotificationSender,
+ side_effects::{ChannelMentionNotification, ChannelNotificationEffect},
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_notifications::{
+ ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,
+ ChannelReplyMetadata, CommonChannelMetadata, DocumentMentionMetadata,
+ NotificationDocumentSubType,
+};
+use notification_hex::domain::{
+ models::SendNotificationRequestBuilder, service::NotificationIngress,
+};
+use std::{collections::HashSet, sync::Arc};
+use uuid::Uuid;
+
+/// Notification ingress adapter for channel notification effects.
+#[derive(Clone)]
+pub struct NotificationChannelSender<I> {
+ ingress: Arc<I>,
+}
+
+impl<I> NotificationChannelSender<I> {
+ /// Create a notification sender adapter.
+ pub fn new(ingress: Arc<I>) -> Self {
+ Self { ingress }
+ }
+}
+
+fn to_notification_channel_type(channel_type: ChannelType) -> model_notifications::ChannelType {
+ match channel_type {
+ ChannelType::Public => model_notifications::ChannelType::Public,
+ ChannelType::Organization => model_notifications::ChannelType::Organization,
+ ChannelType::Private => model_notifications::ChannelType::Private,
+ ChannelType::DirectMessage => model_notifications::ChannelType::DirectMessage,
+ ChannelType::Team => model_notifications::ChannelType::Team,
+ }
+}
+
+fn to_common_metadata(metadata: ChannelMetadata) -> CommonChannelMetadata {
+ CommonChannelMetadata {
+ channel_type: to_notification_channel_type(metadata.channel_type),
+ channel_name: metadata.channel_name,
+ }
+}
+
+struct InviteNotificationDelivery {
+ channel_id: Uuid,
+ invited_by_user_id: MacroUserIdStr<'static>,
+ registered_recipient_ids: HashSet<MacroUserIdStr<'static>>,
+ unregistered_recipient_ids: HashSet<MacroUserIdStr<'static>>,
+ sender_profile_picture_url: Option<String>,
+ message_content: Option<String>,
+ common: CommonChannelMetadata,
+}
+
+async fn send_invite_notifications(
+ ingress: &impl NotificationIngress,
+ delivery: InviteNotificationDelivery,
+) -> anyhow::Result<()> {
+ let InviteNotificationDelivery {
+ channel_id,
+ invited_by_user_id,
+ registered_recipient_ids,
+ unregistered_recipient_ids,
+ sender_profile_picture_url,
+ message_content,
+ common,
+ } = delivery;
+ let _ = tokio::try_join!(
+ ingress.send_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: model_entity::EntityType::Channel
+ .with_entity_string(channel_id.to_string()),
+ notification: ChannelInviteMetadata {
+ invited_by: invited_by_user_id.clone(),
+ channel_name: common.channel_name.clone(),
+ sender_profile_picture_url: sender_profile_picture_url.clone(),
+ message_content: message_content.clone(),
+ },
+ sender_id: Some(invited_by_user_id.clone()),
+ recipient_ids: registered_recipient_ids,
+ }
+ .into_request()
+ .with_apns()
+ .with_conn_gateway(),
+ ),
+ ingress.send_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: model_entity::EntityType::Channel
+ .with_entity_string(channel_id.to_string()),
+ notification: ChannelInviteMetadata {
+ invited_by: invited_by_user_id.clone(),
+ channel_name: common.channel_name.clone(),
+ sender_profile_picture_url,
+ message_content,
+ },
+ sender_id: Some(invited_by_user_id.clone()),
+ recipient_ids: unregistered_recipient_ids,
+ }
+ .into_request()
+ .with_email(),
+ )
+ )
+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;
+
+ Ok(())
+}
+
+fn to_channel_mention_metadata(mention: ChannelMentionNotification) -> ChannelMentionMetadata {
+ ChannelMentionMetadata {
+ message_content: mention.message_content,
+ message_id: mention.message_id.to_string(),
+ has_attachments: mention.has_attachments,
+ thread_id: mention.thread_id.map(|thread_id| thread_id.to_string()),
+ common: to_common_metadata(mention.metadata),
+ sender_profile_picture_url: mention.sender_profile_picture_url,
+ }
+}
+
+impl<I> ChannelNotificationSender for NotificationChannelSender<I>
+where
+ I: NotificationIngress + 'static,
+{
+ type Err = anyhow::Error;
+
+ async fn send(&self, notification: ChannelNotificationEffect) -> Result<(), Self::Err> {
+ match notification {
+ ChannelNotificationEffect::UserMention {
+ mention,
+ recipient_ids,
+ } => {
+ let channel_id = mention.channel_id;
+ let sender_id = mention.sender_id.clone();
+ self.ingress
+ .send_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: model_entity::EntityType::Channel
+ .with_entity_string(channel_id.to_string()),
+ notification: to_channel_mention_metadata(mention),
+ sender_id: Some(sender_id),
+ recipient_ids,
+ }
+ .into_request()
+ .with_apns()
+ .with_conn_gateway(),
+ )
+ .await
+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;
+ }
+ ChannelNotificationEffect::DocumentMention {
+ mention,
+ document,
+ recipient_ids,
+ } => {
+ let channel_id = mention.channel_id;
+ let sender_id = mention.sender_id.clone();
+ self.ingress
+ .send_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: model_entity::EntityType::Channel
+ .with_entity_string(channel_id.to_string()),
+ notification: DocumentMentionMetadata {
+ document_name: document.document_name,
+ owner: document.owner,
+ file_type: document.file_type,
+ sub_type: match document.sub_type.as_deref() {
+ Some("task") => Some(NotificationDocumentSubType::Task),
+ _ => None,
+ },
+ channel: to_channel_mention_metadata(mention),
+ },
+ sender_id: Some(sender_id),
+ recipient_ids,
+ }
+ .into_request()
+ .with_apns()
+ .with_conn_gateway(),
+ )
+ .await
+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;
+ }
+ ChannelNotificationEffect::Reply {
+ channel_id,
+ thread_id,
+ message_id,
+ sender_id,
+ message_content,
+ has_attachments,
+ thread_parent_sender_id,
+ metadata,
+ sender_profile_picture_url,
+ recipient_ids,
+ } => {
+ self.ingress
+ .send_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: model_entity::EntityType::Channel
+ .with_entity_string(channel_id.to_string()),
+ notification: ChannelReplyMetadata {
+ thread_id: thread_id.to_string(),
+ message_id: message_id.to_string(),
+ user_id: sender_id.clone(),
+ message_content,
+ has_attachments,
+ thread_parent_sender_id,
+ common: to_common_metadata(metadata),
+ sender_profile_picture_url,
+ },
+ sender_id: Some(sender_id),
+ recipient_ids,
+ }
+ .into_request()
+ .with_apns()
+ .with_conn_gateway(),
+ )
+ .await
+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;
+ }
+ ChannelNotificationEffect::ChannelMessage {
+ channel_id,
+ message_id,
+ sender_id,
+ message_content,
+ has_attachments,
+ metadata,
+ sender_profile_picture_url,
+ recipient_ids,
+ } => {
+ self.ingress
+ .send_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: model_entity::EntityType::Channel
+ .with_entity_string(channel_id.to_string()),
+ notification: ChannelMessageSendMetadata {
+ message_id: message_id.to_string(),
+ sender: sender_id.clone(),
+ message_content,
+ has_attachments,
+ common: to_common_metadata(metadata),
+ sender_profile_picture_url,
+ },
+ sender_id: Some(sender_id),
+ recipient_ids,
+ }
+ .into_request()
+ .with_apns()
+ .with_conn_gateway(),
+ )
+ .await
+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;
+ }
+ ChannelNotificationEffect::Invite {
+ channel_id,
+ invited_by_user_id,
+ registered_recipient_ids,
+ unregistered_recipient_ids,
+ sender_profile_picture_url,
+ message_content,
+ metadata,
+ } => {
+ send_invite_notifications(
+ &*self.ingress,
+ InviteNotificationDelivery {
+ channel_id,
+ invited_by_user_id,
+ registered_recipient_ids,
+ unregistered_recipient_ids,
+ sender_profile_picture_url,
+ message_content,
+ common: to_common_metadata(metadata),
+ },
+ )
+ .await?;
+ }
+ }
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channel_reference_share_permissions.rs b/rust/cloud-storage/channels/src/outbound/pg_channel_reference_share_permissions.rs
new file mode 100644
index 0000000000..a49b13ede3
--- /dev/null
+++ b/rust/cloud-storage/channels/src/outbound/pg_channel_reference_share_permissions.rs
@@ -0,0 +1,152 @@
+//! Postgres adapter for channel reference share-permission side effects.
+
+use crate::domain::{
+ models::{ReferencedShareItem, ReferencedShareItemType},
+ ports::ChannelReferenceSharePermissions,
+};
+use anyhow::Context;
+use entity_access::domain::{models::EntityType, ports::EntityAccessService};
+use macro_user_id::user_id::MacroUserIdStr;
+use models_permissions::share_permission::{
+ access_level::AccessLevel,
+ channel_share_permission::{UpdateChannelSharePermission, UpdateOperation},
+};
+use share_permission_db_utils::InsertChannelSharePermissionResult;
+use sqlx::PgPool;
+use std::sync::Arc;
+use uuid::Uuid;
+
+/// Postgres-backed share-permission adapter for channel message references.
+#[derive(Clone)]
+pub struct PgChannelReferenceSharePermissions<E> {
+ pool: PgPool,
+ entity_access_service: Arc<E>,
+}
+
+impl<E> PgChannelReferenceSharePermissions<E> {
+ /// Create a Postgres-backed reference share-permission adapter.
+ pub fn new(pool: PgPool, entity_access_service: Arc<E>) -> Self {
+ Self {
+ pool,
+ entity_access_service,
+ }
+ }
+}
+
+impl<E> ChannelReferenceSharePermissions for PgChannelReferenceSharePermissions<E>
+where
+ E: EntityAccessService,
+{
+ type Err = anyhow::Error;
+
+ async fn update_channel_share_permissions_for_referenced_items(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ items: Vec<ReferencedShareItem>,
+ ) -> Result<(), Self::Err> {
+ for item in items {
+ ensure_referenced_item_visible_to_channel(
+ &self.pool,
+ &*self.entity_access_service,
+ &actor,
+ channel_id,
+ &item,
+ )
+ .await?;
+ }
+
+ Ok(())
+ }
+}
+
+async fn ensure_referenced_item_visible_to_channel(
+ db: &PgPool,
+ entity_access_service: &impl EntityAccessService,
+ actor: &MacroUserIdStr<'_>,
+ channel_id: Uuid,
+ item: &ReferencedShareItem,
+) -> anyhow::Result<()> {
+ let entity_id = macro_uuid::string_to_uuid(item.entity_id())?;
+
+ if item.entity_type() == ReferencedShareItemType::EmailThread {
+ share_permission_db_utils::ensure_thread_share_permission(db, item.entity_id())
+ .await
+ .context("failed to insert thread share permissions")?;
+ }
+
+ let entity_type = entity_access_type_for(item.entity_type());
+ let user_access_level = entity_access_service
+ .get_access_level(Some(actor), item.entity_id(), entity_type)
+ .await
+ .context("failed to get user access level")?;
+
+ if user_access_level.is_none() {
+ tracing::info!(
+ item_id = item.entity_id(),
+ item_type = item.entity_type().as_str(),
+ "user does not have access to the item, not modifying share permissions"
+ );
+ return Ok(());
+ }
+
+ let share_permission_id = share_permission_db_utils::get_share_permission_id(
+ db,
+ item.entity_id(),
+ item.entity_type().as_str(),
+ )
+ .await
+ .context("failed to get share permission id")?;
+
+ let mut transaction = db.begin().await?;
+ let insert_result = share_permission_db_utils::insert_channel_share_permission(
+ &mut *transaction,
+ &share_permission_id,
+ &channel_id.to_string(),
+ AccessLevel::View,
+ )
+ .await
+ .context("failed to insert channel share permission")?;
+
+ if insert_result == InsertChannelSharePermissionResult::AlreadyExists {
+ return Ok(());
+ }
+
+ entity_access_db_utils::update_entity_access_channel_share_permissions(
+ &mut transaction,
+ &entity_id,
+ entity_access_db_type_for(item.entity_type()),
+ &[UpdateChannelSharePermission {
+ channel_id: channel_id.to_string(),
+ operation: UpdateOperation::Add,
+ access_level: Some(AccessLevel::View),
+ }],
+ )
+ .await
+ .context("failed to update channel entity access")?;
+
+ transaction.commit().await?;
+ Ok(())
+}
+
+fn entity_access_type_for(item_type: ReferencedShareItemType) -> EntityType {
+ match item_type {
+ ReferencedShareItemType::Document => EntityType::Document,
+ ReferencedShareItemType::Chat => EntityType::Chat,
+ ReferencedShareItemType::Project => EntityType::Project,
+ ReferencedShareItemType::EmailThread => EntityType::EmailThread,
+ ReferencedShareItemType::Call => EntityType::Call,
+ }
+}
+
+fn entity_access_db_type_for(
+ item_type: ReferencedShareItemType,
+) -> entity_access_db_utils::EntityType {
+ match item_type {
+ ReferencedShareItemType::Document => entity_access_db_utils::EntityType::Document,
+ ReferencedShareItemType::Chat => entity_access_db_utils::EntityType::Chat,
+ ReferencedShareItemType::Project => entity_access_db_utils::EntityType::Project,
+ ReferencedShareItemType::EmailThread => entity_access_db_utils::EntityType::EmailThread,
+ ReferencedShareItemType::Call => entity_access_db_utils::EntityType::Call,
+ }
+}
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
index a27f5a4659..f63a484c23 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
@@ -3,25 +3,29 @@ mod tests;
use crate::domain::{
models::{
- ChannelAttachment, ChannelAttachmentType, ChannelMessageFilters, ChannelMessageKind,
- ChannelParticipant, CountedReaction, MessageAttachment, MessagePageDirection,
- ParticipantRole, ResolvedChannelMessage, ThreadData, ThreadReplyRow, TopLevelMessageRow,
+ ChannelAttachment, ChannelAttachmentType, ChannelInfo, ChannelMessageFilters,
+ ChannelMessageKind, ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction,
+ CreateChannelRequest, MessageAttachment, MessagePageDirection, MutatedAttachment,
+ MutatedMessage, NewChannelAttachment, ParticipantRole, PatchChannelRequest,
+ ResolvedChannelMessage, SimpleMention, ThreadData, ThreadReplyRow, TopLevelMessageRow,
},
- ports::{ChannelMessagesRepo, TopLevelMessagesQueryResult},
+ ports::{ChannelRepo, TopLevelMessagesQueryResult},
};
+use anyhow::Context;
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Query};
-use sqlx::PgPool;
+use sqlx::{Executor, PgPool, Postgres};
use std::collections::HashMap;
use uuid::Uuid;
-/// Postgres-backed repository for channel messages.
-pub struct PgChannelMessagesRepo {
+/// Postgres-backed repository for channels.
+#[derive(Clone)]
+pub struct PgChannelsRepo {
pool: PgPool,
}
-impl PgChannelMessagesRepo {
+impl PgChannelsRepo {
/// Create a new repo with the given connection pool.
pub fn new(pool: PgPool) -> Self {
Self { pool }
@@ -51,7 +55,7 @@ struct ResolvedMessageRow {
}
/// Intermediate row for the merged thread data query (stats + preview replies).
-#[derive(Debug)]
+#[derive(Debug, sqlx::FromRow)]
struct ThreadDataRow {
id: Uuid,
thread_id: Uuid,
@@ -76,16 +80,24 @@ struct ThreadReplyOnlyRow {
edited_at: Option<chrono::DateTime<chrono::Utc>>,
}
-/// Intermediate row for reactions.
-#[derive(Debug)]
+/// Intermediate row for grouped reactions.
+#[derive(Debug, sqlx::FromRow)]
struct ReactionRow {
message_id: Uuid,
emoji: String,
user_id: String,
}
+/// Intermediate row for reactions including the creation timestamp.
+#[derive(Debug, sqlx::FromRow)]
+struct ReactionWithCreatedAtRow {
+ emoji: String,
+ user_id: String,
+ created_at: chrono::DateTime<chrono::Utc>,
+}
+
/// Intermediate row for attachments.
-#[derive(Debug)]
+#[derive(Debug, sqlx::FromRow)]
struct AttachmentRow {
id: Uuid,
message_id: Uuid,
@@ -97,7 +109,7 @@ struct AttachmentRow {
}
/// Intermediate row for channel-level attachments.
-#[derive(Debug)]
+#[derive(Debug, sqlx::FromRow)]
struct ChannelAttachmentRow {
id: Uuid,
channel_id: Uuid,
@@ -111,16 +123,451 @@ struct ChannelAttachmentRow {
}
/// Intermediate row for channel participants.
-#[derive(Debug)]
+#[derive(Debug, sqlx::FromRow)]
struct ParticipantRow {
channel_id: Uuid,
user_id: String,
- role: String,
+ role: ParticipantRole,
joined_at: chrono::DateTime<chrono::Utc>,
left_at: Option<chrono::DateTime<chrono::Utc>>,
}
-impl ChannelMessagesRepo for PgChannelMessagesRepo {
+/// Intermediate row for mutation-returned messages.
+#[derive(Debug, sqlx::FromRow)]
+struct MutatedMessageRow {
+ id: Uuid,
+ channel_id: Uuid,
+ thread_id: Option<Uuid>,
+ sender_id: MacroUserIdStr<'static>,
+ content: String,
+ created_at: chrono::DateTime<chrono::Utc>,
+ updated_at: chrono::DateTime<chrono::Utc>,
+ edited_at: Option<chrono::DateTime<chrono::Utc>>,
+ deleted_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+/// Intermediate row for mutation-returned attachments.
+#[derive(Debug, sqlx::FromRow)]
+struct MutatedAttachmentRow {
+ id: Uuid,
+ channel_id: Uuid,
+ message_id: Uuid,
+ entity_type: String,
+ entity_id: String,
+ width: Option<i32>,
+ height: Option<i32>,
+ created_at: chrono::DateTime<chrono::Utc>,
+}
+
+/// Intermediate row for channel info.
+#[derive(Debug, sqlx::FromRow)]
+struct ChannelInfoRow {
+ id: Uuid,
+ name: Option<String>,
+ channel_type: ChannelType,
+ org_id: Option<i64>,
+ team_id: Option<Uuid>,
+}
+
+/// Intermediate row for user display-name lookups.
+#[derive(Debug, sqlx::FromRow)]
+struct UserDisplayNameRow {
+ user_profile_id: String,
+ first_name: Option<String>,
+ last_name: Option<String>,
+}
+
+#[derive(Debug, sqlx::FromRow)]
+struct UserIdRow {
+ user_id: String,
+}
+
+#[derive(Debug, sqlx::FromRow)]
+struct MacroUserIdRow {
+ user_id: MacroUserIdStr<'static>,
+}
+
+#[derive(Debug, sqlx::FromRow)]
+struct SenderIdRow {
+ sender_id: MacroUserIdStr<'static>,
+}
+
+#[derive(Debug, sqlx::FromRow)]
+struct ChannelIdRow {
+ id: Uuid,
+}
+
+#[derive(Debug, sqlx::FromRow)]
+struct ExistsRow {
+ exists: bool,
+}
+
+impl From<MutatedMessageRow> for MutatedMessage {
+ fn from(row: MutatedMessageRow) -> Self {
+ Self {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ sender_id: row.sender_id,
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ deleted_at: row.deleted_at,
+ }
+ }
+}
+
+impl From<MutatedAttachmentRow> for MutatedAttachment {
+ fn from(row: MutatedAttachmentRow) -> Self {
+ Self {
+ id: row.id,
+ channel_id: row.channel_id,
+ message_id: row.message_id,
+ entity_type: row.entity_type,
+ entity_id: row.entity_id,
+ width: row.width,
+ height: row.height,
+ created_at: row.created_at,
+ }
+ }
+}
+
+fn group_counted_reactions(
+ reactions: impl IntoIterator<Item = (String, String, DateTime<Utc>)>,
+) -> Vec<CountedReaction> {
+ let mut grouped: HashMap<String, (Vec<String>, DateTime<Utc>)> = HashMap::new();
+ for (emoji, user_id, created_at) in reactions {
+ grouped
+ .entry(emoji)
+ .and_modify(|(users, earliest_at)| {
+ users.push(user_id.clone());
+ *earliest_at = std::cmp::min(*earliest_at, created_at);
+ })
+ .or_insert_with(|| (vec![user_id], created_at));
+ }
+
+ let mut counted: Vec<_> = grouped
+ .into_iter()
+ .map(|(emoji, (users, created_at))| (CountedReaction { emoji, users }, created_at))
+ .collect();
+ counted.sort_by_key(|(_, created_at)| *created_at);
+ counted.into_iter().map(|(reaction, _)| reaction).collect()
+}
+
+async fn create_activity<'e, E>(executor: E, channel_id: Uuid, user_id: &str) -> anyhow::Result<()>
+where
+ E: Executor<'e, Database = Postgres>,
+{
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_activity (id, user_id, channel_id, created_at, updated_at)
+ VALUES ($1, $2, $3, NOW(), NOW())
+ "#,
+ macro_uuid::generate_uuid_v7(),
+ user_id,
+ channel_id,
+ )
+ .execute(executor)
+ .await?;
+ Ok(())
+}
+
+async fn insert_message_mentions<'e, E>(
+ executor: E,
+ message_id: Uuid,
+ mentions: &[SimpleMention],
+) -> anyhow::Result<Vec<String>>
+where
+ E: Executor<'e, Database = Postgres>,
+{
+ if mentions.is_empty() {
+ return Ok(vec![]);
+ }
+
+ let entity_types: Vec<_> = mentions
+ .iter()
+ .map(|mention| mention.entity_type.clone())
+ .collect();
+ let entity_ids: Vec<_> = mentions
+ .iter()
+ .map(|mention| mention.entity_id.clone())
+ .collect();
+
+ let message_id_text = message_id.to_string();
+ let mentioned_users = sqlx::query_as!(
+ UserIdRow,
+ r#"
+ WITH message_channel AS (
+ SELECT channel_id FROM comms_messages WHERE id = $1
+ ),
+ mentions_to_insert AS (
+ SELECT t.entity_type, t.entity_id
+ FROM UNNEST($2::text[], $3::text[]) AS t(entity_type, entity_id)
+ ),
+ inserted_mentions AS (
+ INSERT INTO comms_entity_mentions (
+ id,
+ source_entity_type,
+ source_entity_id,
+ entity_type,
+ entity_id,
+ user_id
+ )
+ SELECT gen_random_uuid(), 'message', $4::text, m.entity_type, m.entity_id, NULL
+ FROM mentions_to_insert m
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM comms_entity_mentions em
+ WHERE em.source_entity_type = 'message'
+ AND em.source_entity_id = $4::text
+ AND em.entity_type = m.entity_type
+ AND em.entity_id = m.entity_id
+ )
+ )
+ SELECT DISTINCT cp.user_id
+ FROM mentions_to_insert m
+ CROSS JOIN message_channel mc
+ JOIN comms_channel_participants cp ON m.entity_id = cp.user_id
+ WHERE m.entity_type = 'user'
+ AND cp.channel_id = mc.channel_id
+ AND cp.left_at IS NULL
+ "#,
+ message_id,
+ &entity_types,
+ &entity_ids,
+ message_id_text,
+ )
+ .fetch_all(executor)
+ .await?;
+
+ Ok(mentioned_users.into_iter().map(|row| row.user_id).collect())
+}
+
+async fn delete_entity_mentions_by_source<'e, E>(
+ executor: E,
+ source_entity_ids: &[String],
+) -> anyhow::Result<u64>
+where
+ E: Executor<'e, Database = Postgres>,
+{
+ let result = sqlx::query!(
+ r#"
+ DELETE FROM comms_entity_mentions
+ WHERE source_entity_id = ANY($1)
+ "#,
+ source_entity_ids,
+ )
+ .execute(executor)
+ .await?;
+ Ok(result.rows_affected())
+}
+
+async fn get_message_owner(
+ pool: &PgPool,
+ channel_id: Uuid,
+ message_id: Uuid,
+) -> anyhow::Result<Option<String>> {
+ let row = sqlx::query_as!(
+ SenderIdRow,
+ r#"
+ SELECT sender_id AS "sender_id: MacroUserIdStr"
+ FROM comms_messages
+ WHERE id = $1 AND channel_id = $2
+ ORDER BY created_at ASC
+ "#,
+ message_id,
+ channel_id,
+ )
+ .fetch_optional(pool)
+ .await
+ .context("unable to get message owner")?;
+ Ok(row.map(|row| row.sender_id.to_string()))
+}
+
+async fn get_channel_participants_for_thread_id(
+ pool: &PgPool,
+ thread_id: Uuid,
+) -> anyhow::Result<Vec<MacroUserIdStr<'static>>> {
+ let rows = sqlx::query_as!(
+ MacroUserIdRow,
+ r#"
+ SELECT DISTINCT id AS "user_id!: MacroUserIdStr" FROM (
+ SELECT m.sender_id AS id
+ FROM comms_channel_participants cp
+ JOIN comms_channels c ON c.id = cp.channel_id
+ JOIN comms_messages m ON m.channel_id = c.id
+ WHERE (m.id = $1 OR m.thread_id = $1) AND cp.left_at IS NULL
+ UNION
+ SELECT em.entity_id AS id
+ FROM comms_entity_mentions em
+ JOIN comms_messages m ON m.id::text = em.source_entity_id
+ JOIN comms_channel_participants cp
+ ON cp.channel_id = m.channel_id AND cp.user_id = em.entity_id
+ WHERE (m.id = $1 OR m.thread_id = $1)
+ AND em.source_entity_type = 'message'
+ AND em.entity_type = 'user'
+ AND cp.left_at IS NULL
+ ) AS combined
+ "#,
+ thread_id,
+ )
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().map(|row| row.user_id).collect())
+}
+
+fn static_channel_name(
+ channel_type: ChannelType,
+ channel_name: Option<&str>,
+ channel_id: Uuid,
+) -> String {
+ if let Some(name) = channel_name {
+ return name.to_string();
+ }
+
+ match channel_type {
+ ChannelType::Organization => {
+ tracing::warn!(channel_id=%channel_id, "organization channel should have a name");
+ "Organization".to_string()
+ }
+ ChannelType::Public => {
+ tracing::warn!(channel_id=%channel_id, "public channel should have a name");
+ "Public".to_string()
+ }
+ ChannelType::Team => {
+ tracing::warn!(channel_id=%channel_id, "team channel should have a name");
+ "Team".to_string()
+ }
+ ChannelType::Private | ChannelType::DirectMessage => String::new(),
+ }
+}
+
+async fn resolve_channel_display_name(
+ pool: &PgPool,
+ info: &ChannelInfo,
+ viewer_user_id: MacroUserIdStr<'_>,
+) -> anyhow::Result<String> {
+ match info.channel_type {
+ ChannelType::Organization | ChannelType::Public | ChannelType::Team => Ok(
+ static_channel_name(info.channel_type, info.name.as_deref(), info.id),
+ ),
+ ChannelType::Private
+ if info
+ .name
+ .as_ref()
+ .is_some_and(|name| !name.trim().is_empty()) =>
+ {
+ Ok(info.name.clone().unwrap_or_default())
+ }
+ ChannelType::Private | ChannelType::DirectMessage => {
+ let participant_ids = load_active_participant_ids(pool, info.id).await?;
+ let name_lookup = load_user_display_names(pool, &participant_ids).await?;
+ if matches!(info.channel_type, ChannelType::DirectMessage)
+ && participant_ids
+ .iter()
+ .any(|participant_id| participant_id == viewer_user_id.as_ref())
+ {
+ if let Some(other_participant_id) = participant_ids
+ .iter()
+ .find(|participant_id| participant_id.as_str() != viewer_user_id.as_ref())
+ {
+ return Ok(user_display_name(other_participant_id, &name_lookup));
+ }
+
+ tracing::warn!(channel_id=%info.id, "direct message channel has no other participant");
+ return Ok("Unknown".to_string());
+ }
+
+ Ok(participant_ids
+ .iter()
+ .map(|participant_id| user_display_name(participant_id, &name_lookup))
+ .collect::<Vec<_>>()
+ .join(", "))
+ }
+ }
+}
+
+async fn load_active_participant_ids(
+ pool: &PgPool,
+ channel_id: Uuid,
+) -> anyhow::Result<Vec<String>> {
+ let rows = sqlx::query_as!(
+ UserIdRow,
+ r#"
+ SELECT user_id
+ FROM comms_channel_participants
+ WHERE channel_id = $1 AND left_at IS NULL
+ ORDER BY joined_at ASC, user_id ASC
+ "#,
+ channel_id,
+ )
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().map(|row| row.user_id).collect())
+}
+
+async fn load_user_display_names(
+ pool: &PgPool,
+ user_ids: &[String],
+) -> anyhow::Result<HashMap<String, String>> {
+ if user_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = sqlx::query_as!(
+ UserDisplayNameRow,
+ 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)
+ "#,
+ user_ids,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let mut lookup = HashMap::with_capacity(rows.len());
+ for row in rows {
+ if let Some(name) = display_name(row.first_name.as_deref(), row.last_name.as_deref()) {
+ lookup.insert(row.user_profile_id, name);
+ }
+ }
+
+ Ok(lookup)
+}
+
+fn display_name(first_name: Option<&str>, last_name: Option<&str>) -> Option<String> {
+ const NA: &str = "N/A";
+ match (
+ first_name.filter(|value| *value != NA),
+ last_name.filter(|value| *value != NA),
+ ) {
+ (None, None) => None,
+ (None, Some(last_name)) => Some(last_name.to_string()),
+ (Some(first_name), None) => Some(first_name.to_string()),
+ (Some(first_name), Some(last_name)) => Some(format!("{first_name} {last_name}")),
+ }
+}
+
+fn user_display_name(user_id: &str, name_lookup: &HashMap<String, String>) -> String {
+ name_lookup
+ .get(user_id)
+ .filter(|name| !name.trim().is_empty())
+ .cloned()
+ .unwrap_or_else(|| fallback_user_name(user_id))
+}
+
+fn fallback_user_name(user_id: &str) -> String {
+ let email = user_id.split_once('|').map_or(user_id, |(_, email)| email);
+ email
+ .split_once('@')
+ .map_or(email, |(local, _)| local)
+ .to_string()
+}
+
+impl ChannelRepo for PgChannelsRepo {
type Err = anyhow::Error;
#[tracing::instrument(err, skip(self))]
@@ -626,8 +1073,12 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
let rows = sqlx::query_as!(
ParticipantRow,
r#"
- SELECT channel_id, user_id, role::text AS "role!", joined_at,
- left_at AS "left_at?"
+ SELECT
+ channel_id,
+ user_id,
+ role AS "role: ParticipantRole",
+ joined_at,
+ left_at::timestamptz AS "left_at?"
FROM comms_channel_participants
WHERE channel_id = $1 AND left_at IS NULL
ORDER BY joined_at ASC
@@ -639,15 +1090,12 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
Ok(rows
.into_iter()
- .map(|r| ChannelParticipant {
- channel_id: r.channel_id,
- user_id: r.user_id,
- role: r
- .role
- .parse::<ParticipantRole>()
- .unwrap_or(ParticipantRole::Member),
- joined_at: r.joined_at,
- left_at: r.left_at,
+ .map(|row| ChannelParticipant {
+ channel_id: row.channel_id,
+ user_id: row.user_id,
+ role: row.role,
+ joined_at: row.joined_at,
+ left_at: row.left_at,
})
.collect())
}
@@ -821,4 +1269,741 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
Ok((before, after))
}
+
+ async fn get_channel_info(&self, channel_id: Uuid) -> Result<ChannelInfo, Self::Err> {
+ let row = sqlx::query_as!(
+ ChannelInfoRow,
+ r#"
+ SELECT id, name, channel_type AS "channel_type: ChannelType", org_id, team_id
+ FROM comms_channels
+ WHERE id = $1
+ "#,
+ channel_id,
+ )
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(ChannelInfo {
+ id: row.id,
+ name: row.name,
+ channel_type: row.channel_type,
+ org_id: row.org_id,
+ team_id: row.team_id,
+ })
+ }
+
+ async fn get_channel_metadata(
+ &self,
+ channel_id: Uuid,
+ viewer_user_id: MacroUserIdStr<'static>,
+ ) -> Result<ChannelMetadata, Self::Err> {
+ let info = self.get_channel_info(channel_id).await?;
+ let channel_name = resolve_channel_display_name(&self.pool, &info, viewer_user_id).await?;
+ Ok(ChannelMetadata {
+ channel_type: info.channel_type,
+ channel_name,
+ })
+ }
+
+ async fn user_has_team(&self, user_id: String, team_id: Uuid) -> Result<bool, Self::Err> {
+ let has_team = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM team_user
+ WHERE user_id = $1 AND team_id = $2
+ ) AS "has_team!"
+ "#,
+ user_id,
+ team_id,
+ )
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(has_team)
+ }
+
+ async fn create_channel(
+ &self,
+ owner_id: String,
+ org_id: Option<i64>,
+ req: CreateChannelRequest,
+ ) -> Result<Uuid, Self::Err> {
+ let channel_id = macro_uuid::generate_uuid_v7();
+ let mut transaction = self.pool.begin().await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channels (id, name, owner_id, org_id, team_id, channel_type)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ "#,
+ channel_id,
+ req.name.as_deref(),
+ &owner_id,
+ org_id,
+ req.team_id,
+ req.channel_type as ChannelType,
+ )
+ .execute(&mut *transaction)
+ .await
+ .context("unable to create channel")?;
+
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, role, user_id)
+ VALUES ($1, $2, $3)
+ "#,
+ channel_id,
+ ParticipantRole::Owner as ParticipantRole,
+ &owner_id,
+ )
+ .execute(&mut *transaction)
+ .await
+ .context("unable to create channel participant for owner")?;
+
+ for participant in req
+ .participants
+ .into_iter()
+ .filter(|participant| participant != &owner_id)
+ {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, role, user_id)
+ VALUES ($1, $2, $3)
+ "#,
+ channel_id,
+ ParticipantRole::Member as ParticipantRole,
+ participant,
+ )
+ .execute(&mut *transaction)
+ .await
+ .context("unable to create channel participant")?;
+ }
+
+ create_activity(&mut *transaction, channel_id, &owner_id)
+ .await
+ .context("unable to create activity for channel")?;
+ transaction
+ .commit()
+ .await
+ .context("unable to commit transaction")?;
+ Ok(channel_id)
+ }
+
+ async fn maybe_get_dm(
+ &self,
+ user_id: String,
+ recipient_id: String,
+ ) -> Result<Option<Uuid>, Self::Err> {
+ let row = sqlx::query_as!(
+ ChannelIdRow,
+ r#"
+ SELECT id
+ FROM comms_channels
+ WHERE channel_type = 'direct_message'::comms_channel_type
+ AND EXISTS (
+ SELECT 1
+ FROM comms_channel_participants cp
+ WHERE cp.channel_id = comms_channels.id
+ AND cp.user_id = $1
+ )
+ AND EXISTS (
+ SELECT 1
+ FROM comms_channel_participants cp
+ WHERE cp.channel_id = comms_channels.id
+ AND cp.user_id = $2
+ )
+ "#,
+ user_id,
+ recipient_id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .context("unable to get direct message channel")?;
+ Ok(row.map(|row| row.id))
+ }
+
+ async fn maybe_get_private_channel(
+ &self,
+ participants: Vec<String>,
+ ) -> Result<Option<Uuid>, Self::Err> {
+ let row = sqlx::query_as!(
+ ChannelIdRow,
+ r#"
+ SELECT id
+ FROM comms_channels
+ WHERE channel_type = 'private'::comms_channel_type
+ AND (
+ (
+ SELECT COUNT(*)
+ FROM comms_channel_participants cp
+ WHERE cp.channel_id = comms_channels.id
+ AND cp.user_id = ANY($1)
+ ) = CARDINALITY($1)
+ AND (
+ SELECT COUNT(*)
+ FROM comms_channel_participants
+ WHERE channel_id = comms_channels.id
+ ) = CARDINALITY($1)
+ )
+ "#,
+ &participants,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .context("unable to get private channel")?;
+ Ok(row.map(|row| row.id))
+ }
+
+ async fn patch_channel(
+ &self,
+ channel_id: Uuid,
+ user_id: String,
+ req: PatchChannelRequest,
+ ) -> Result<(), Self::Err> {
+ let row = sqlx::query_as!(
+ ExistsRow,
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM comms_channel_participants
+ WHERE channel_id = $1
+ AND user_id = $2
+ AND role IN (
+ 'admin'::comms_participant_role,
+ 'owner'::comms_participant_role
+ )
+ ) AS "exists!"
+ "#,
+ channel_id,
+ user_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to check user authorization")?;
+
+ if !row.exists {
+ anyhow::bail!(
+ "User is not authorized to perform this action, to patch a channel you must be an admin or owner"
+ );
+ }
+
+ if let Some(channel_name) = req.channel_name {
+ sqlx::query!(
+ r#"
+ UPDATE comms_channels
+ SET name = $1
+ WHERE id = $2
+ "#,
+ channel_name,
+ channel_id,
+ )
+ .execute(&self.pool)
+ .await?;
+ }
+ Ok(())
+ }
+
+ async fn delete_channel(&self, channel_id: Uuid, user_id: String) -> Result<(), Self::Err> {
+ let result = sqlx::query!(
+ r#"
+ DELETE FROM comms_channels
+ WHERE id = $1
+ AND EXISTS (
+ SELECT 1
+ FROM comms_channel_participants
+ WHERE channel_id = $1
+ AND user_id = $2
+ AND role = 'owner'::comms_participant_role
+ )
+ "#,
+ channel_id,
+ user_id,
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to delete channel")?;
+
+ if result.rows_affected() == 0 {
+ anyhow::bail!(
+ "channel not deleted, either it didn't exist or the user_id provided was not the owner"
+ );
+ }
+ Ok(())
+ }
+
+ async fn add_participant(
+ &self,
+ channel_id: Uuid,
+ user_id: String,
+ role: ParticipantRole,
+ ) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, user_id, role)
+ VALUES ($1, $2, $3)
+ "#,
+ channel_id,
+ user_id,
+ role as ParticipantRole,
+ )
+ .execute(&self.pool)
+ .await
+ .context("unable to add participant to channel")?;
+ Ok(())
+ }
+
+ async fn remove_participant(&self, channel_id: Uuid, user_id: String) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ DELETE FROM comms_channel_participants
+ WHERE channel_id = $1 AND user_id = $2
+ "#,
+ channel_id,
+ user_id,
+ )
+ .execute(&self.pool)
+ .await
+ .context("unable to remove participant from channel")?;
+ Ok(())
+ }
+
+ async fn create_message(
+ &self,
+ channel_id: Uuid,
+ sender_id: String,
+ content: String,
+ thread_id: Option<Uuid>,
+ ) -> Result<MutatedMessage, Self::Err> {
+ let message_id = macro_uuid::generate_uuid_v7();
+ let row = sqlx::query_as!(
+ MutatedMessageRow,
+ r#"
+ INSERT INTO comms_messages (id, channel_id, sender_id, content, thread_id)
+ VALUES ($1, $2, $3, $4, $5)
+ RETURNING
+ id,
+ channel_id,
+ sender_id AS "sender_id: MacroUserIdStr",
+ content,
+ created_at,
+ updated_at,
+ thread_id,
+ edited_at::timestamptz AS "edited_at?",
+ deleted_at::timestamptz AS "deleted_at?"
+ "#,
+ message_id,
+ channel_id,
+ sender_id,
+ content,
+ thread_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("unable to create message")?;
+ Ok(row.into())
+ }
+
+ async fn touch_channel_updated_at(&self, channel_id: Uuid) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ UPDATE comms_channels
+ SET updated_at = $2
+ WHERE id = $1
+ "#,
+ channel_id,
+ Utc::now(),
+ )
+ .execute(&self.pool)
+ .await
+ .context("unable to update the channel updated_at timestamp")?;
+ Ok(())
+ }
+
+ async fn create_message_mentions(
+ &self,
+ message_id: Uuid,
+ mentions: Vec<SimpleMention>,
+ ) -> Result<(), Self::Err> {
+ insert_message_mentions(&self.pool, message_id, &mentions)
+ .await
+ .map(|_| ())
+ }
+
+ async fn sync_message_mentions(
+ &self,
+ message_id: Uuid,
+ mentions: Vec<SimpleMention>,
+ ) -> Result<(), Self::Err> {
+ let mut transaction = self.pool.begin().await?;
+ let source_entity_ids = [message_id.to_string()];
+ delete_entity_mentions_by_source(&mut *transaction, &source_entity_ids).await?;
+ insert_message_mentions(&mut *transaction, message_id, &mentions).await?;
+ transaction.commit().await?;
+ Ok(())
+ }
+
+ async fn add_attachments(
+ &self,
+ message_id: Uuid,
+ channel_id: Uuid,
+ attachments: Vec<NewChannelAttachment>,
+ ) -> Result<Vec<MutatedAttachment>, Self::Err> {
+ if attachments.is_empty() {
+ return Ok(vec![]);
+ }
+
+ let mut inserted = Vec::with_capacity(attachments.len());
+ for attachment in attachments {
+ let row = sqlx::query_as!(
+ MutatedAttachmentRow,
+ r#"
+ INSERT INTO comms_attachments (
+ id,
+ message_id,
+ channel_id,
+ entity_type,
+ entity_id,
+ width,
+ height
+ )
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ RETURNING id, message_id, channel_id, entity_type, entity_id, width, height, created_at
+ "#,
+ macro_uuid::generate_uuid_v7(),
+ message_id,
+ channel_id,
+ attachment.entity_type,
+ attachment.entity_id,
+ attachment.width,
+ attachment.height,
+ )
+ .fetch_one(&self.pool)
+ .await?;
+ inserted.push(row.into());
+ }
+ Ok(inserted)
+ }
+
+ async fn get_message_attachments(
+ &self,
+ message_id: Uuid,
+ ) -> Result<Vec<MutatedAttachment>, Self::Err> {
+ Ok(sqlx::query_as!(
+ MutatedAttachmentRow,
+ r#"
+ SELECT id, message_id, channel_id, entity_type, entity_id, width, height, created_at
+ FROM comms_attachments
+ WHERE message_id = $1
+ "#,
+ message_id,
+ )
+ .fetch_all(&self.pool)
+ .await?
+ .into_iter()
+ .map(Into::into)
+ .collect::<Vec<_>>())
+ }
+
+ async fn delete_attachments(&self, attachment_ids: Vec<Uuid>) -> Result<(), Self::Err> {
+ if attachment_ids.is_empty() {
+ return Ok(());
+ }
+ sqlx::query!(
+ r#"
+ DELETE FROM comms_attachments
+ WHERE id = ANY($1)
+ "#,
+ &attachment_ids,
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to delete attachments by IDs")?;
+ Ok(())
+ }
+
+ async fn delete_entity_mentions_for_entities(
+ &self,
+ entity_ids: Vec<String>,
+ source_entity_id: String,
+ ) -> Result<(), Self::Err> {
+ if entity_ids.is_empty() {
+ return Ok(());
+ }
+ sqlx::query!(
+ r#"
+ DELETE FROM comms_entity_mentions
+ WHERE entity_id = ANY($1) AND source_entity_id = $2
+ "#,
+ &entity_ids,
+ source_entity_id,
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ async fn patch_message_attachments(
+ &self,
+ message_id: Uuid,
+ attachments: Vec<MutatedAttachment>,
+ ) -> Result<MutatedMessage, Self::Err> {
+ let has_attachments = !attachments.is_empty();
+ let row = sqlx::query_as!(
+ MutatedMessageRow,
+ r#"
+ UPDATE comms_messages
+ SET
+ updated_at = NOW(),
+ edited_at = NOW(),
+ deleted_at = CASE
+ WHEN $2 = false AND (content IS NULL OR content ~ '^[\s]*$') THEN NOW()
+ ELSE deleted_at
+ END
+ WHERE id = $1
+ RETURNING
+ id,
+ channel_id,
+ sender_id AS "sender_id: MacroUserIdStr",
+ content,
+ created_at,
+ updated_at,
+ thread_id,
+ edited_at::timestamptz AS "edited_at?",
+ deleted_at::timestamptz AS "deleted_at?"
+ "#,
+ message_id,
+ has_attachments,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("unable to update message")?;
+ Ok(row.into())
+ }
+
+ async fn patch_message(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ content: String,
+ ) -> Result<MutatedMessage, Self::Err> {
+ let row = sqlx::query_as!(
+ MutatedMessageRow,
+ r#"
+ UPDATE comms_messages
+ SET content = $1, updated_at = NOW(), edited_at = NOW()
+ WHERE id = $2 AND channel_id = $3
+ RETURNING
+ id,
+ channel_id,
+ sender_id AS "sender_id: MacroUserIdStr",
+ content,
+ created_at,
+ updated_at,
+ thread_id,
+ edited_at::timestamptz AS "edited_at?",
+ deleted_at::timestamptz AS "deleted_at?"
+ "#,
+ content,
+ message_id,
+ channel_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("unable to update message")?;
+ Ok(row.into())
+ }
+ async fn delete_message(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> Result<MutatedMessage, Self::Err> {
+ let row = sqlx::query_as!(
+ MutatedMessageRow,
+ r#"
+ UPDATE comms_messages
+ SET content = '', updated_at = NOW(), deleted_at = NOW()
+ WHERE id = $1 AND channel_id = $2
+ RETURNING
+ id,
+ channel_id,
+ sender_id AS "sender_id: MacroUserIdStr",
+ content,
+ created_at,
+ updated_at,
+ thread_id,
+ edited_at::timestamptz AS "edited_at?",
+ deleted_at::timestamptz AS "deleted_at?"
+ "#,
+ message_id,
+ channel_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("unable to delete message")?;
+ Ok(row.into())
+ }
+
+ async fn get_message_owner(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> Result<Option<String>, Self::Err> {
+ get_message_owner(&self.pool, channel_id, message_id).await
+ }
+
+ async fn get_participants(
+ &self,
+ channel_id: Uuid,
+ ) -> Result<Vec<ChannelParticipant>, Self::Err> {
+ let rows = sqlx::query_as!(
+ ParticipantRow,
+ r#"
+ SELECT
+ user_id,
+ channel_id,
+ joined_at,
+ left_at::timestamptz AS "left_at?",
+ role AS "role: ParticipantRole"
+ FROM comms_channel_participants
+ WHERE channel_id = $1
+ ORDER BY joined_at DESC
+ "#,
+ channel_id,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| ChannelParticipant {
+ channel_id: row.channel_id,
+ user_id: row.user_id,
+ role: row.role,
+ joined_at: row.joined_at,
+ left_at: row.left_at,
+ })
+ .collect())
+ }
+
+ async fn get_thread_participants(
+ &self,
+ thread_id: Uuid,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, Self::Err> {
+ get_channel_participants_for_thread_id(&self.pool, thread_id).await
+ }
+
+ async fn upsert_activity(&self, user_id: String, channel_id: Uuid) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_activity (id, user_id, channel_id, interacted_at)
+ VALUES ($1, $2, $3, NOW())
+ ON CONFLICT (user_id, channel_id) DO UPDATE
+ SET interacted_at = NOW(), updated_at = NOW()
+ "#,
+ macro_uuid::generate_uuid_v7(),
+ user_id,
+ channel_id,
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ async fn add_reaction(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ emoji: String,
+ user_id: String,
+ ) -> Result<(), Self::Err> {
+ let row = sqlx::query_as!(
+ ExistsRow,
+ r#"
+ WITH message AS (
+ SELECT id
+ FROM comms_messages
+ WHERE id = $2 AND channel_id = $1
+ ),
+ inserted AS (
+ INSERT INTO comms_reactions (message_id, emoji, user_id)
+ SELECT id, $3, $4
+ FROM message
+ ON CONFLICT DO NOTHING
+ )
+ SELECT EXISTS (SELECT 1 FROM message) AS "exists!"
+ "#,
+ channel_id,
+ message_id,
+ emoji,
+ user_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to add reaction")?;
+ if !row.exists {
+ anyhow::bail!("message not found in channel");
+ }
+ Ok(())
+ }
+
+ async fn remove_reaction(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ emoji: String,
+ user_id: String,
+ ) -> Result<(), Self::Err> {
+ let row = sqlx::query_as!(
+ ExistsRow,
+ r#"
+ WITH message AS (
+ SELECT id
+ FROM comms_messages
+ WHERE id = $2 AND channel_id = $1
+ ),
+ deleted AS (
+ DELETE FROM comms_reactions r
+ USING message m
+ WHERE r.message_id = m.id
+ AND r.emoji = $3
+ AND r.user_id = $4
+ )
+ SELECT EXISTS (SELECT 1 FROM message) AS "exists!"
+ "#,
+ channel_id,
+ message_id,
+ emoji,
+ user_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to remove reaction")?;
+ if !row.exists {
+ anyhow::bail!("message not found in channel");
+ }
+ Ok(())
+ }
+
+ async fn get_message_reactions(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> Result<Vec<CountedReaction>, Self::Err> {
+ let reactions = sqlx::query_as!(
+ ReactionWithCreatedAtRow,
+ r#"
+ SELECT r.emoji, r.user_id, r.created_at
+ FROM comms_reactions r
+ JOIN comms_messages m ON m.id = r.message_id
+ WHERE r.message_id = $1 AND m.channel_id = $2
+ "#,
+ message_id,
+ channel_id,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("unable to fetch reactions")?
+ .into_iter()
+ .map(|row| (row.emoji, row.user_id, row.created_at))
+ .collect::<Vec<_>>();
+ Ok(group_counted_reactions(reactions))
+ }
}
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
index 4c49e80c42..0ad6cfe7d9 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
@@ -1,8 +1,8 @@
use crate::domain::models::{
ChannelMessageFilters, MessagePageDirection, NotificationFilters, ParticipantRole,
};
-use crate::domain::ports::ChannelMessagesRepo;
-use crate::outbound::pg_channels_repo::PgChannelMessagesRepo;
+use crate::domain::ports::ChannelRepo;
+use crate::outbound::pg_channels_repo::PgChannelsRepo;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Cursor, CursorVal, Query};
@@ -32,8 +32,8 @@ const DELETED_MSG_ATTACHMENT: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0
const USER_A: &str = "macro|[email protected]";
const USER_B: &str = "macro|[email protected]";
-fn repo(pool: Pool<Postgres>) -> PgChannelMessagesRepo {
- PgChannelMessagesRepo::new(pool)
+fn repo(pool: Pool<Postgres>) -> PgChannelsRepo {
+ PgChannelsRepo::new(pool)
}
fn macro_user_id(user_id: &str) -> MacroUserIdStr<'static> {
diff --git a/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs b/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs
new file mode 100644
index 0000000000..5f175f0936
--- /dev/null
+++ b/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs
@@ -0,0 +1,221 @@
+//! Postgres context adapter for channel side-effect policy.
+
+use crate::domain::{
+ ports::ChannelSideEffectContext,
+ side_effects::{ChannelDocumentMention, ThreadNotificationContext},
+};
+use anyhow::Context;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use sqlx::PgPool;
+use std::collections::HashSet;
+use uuid::Uuid;
+
+struct SenderIdRow {
+ sender_id: MacroUserIdStr<'static>,
+}
+
+struct UserIdRow {
+ user_id: MacroUserIdStr<'static>,
+}
+
+struct DocumentMentionRow {
+ document_name: String,
+ owner: MacroUserIdStr<'static>,
+ file_type: Option<String>,
+ sub_type: Option<String>,
+}
+
+/// Postgres-backed context for channel side-effect policy.
+#[derive(Clone)]
+pub struct PgChannelSideEffectContext {
+ pool: PgPool,
+}
+
+impl PgChannelSideEffectContext {
+ /// Create a Postgres side-effect context adapter.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl ChannelSideEffectContext for PgChannelSideEffectContext {
+ type Err = anyhow::Error;
+
+ async fn get_channel_message_count(&self, channel_id: Uuid) -> Result<i64, Self::Err> {
+ get_channel_message_count(&self.pool, channel_id).await
+ }
+
+ async fn get_existing_user_ids(
+ &self,
+ user_ids: Vec<MacroUserIdStr<'static>>,
+ ) -> Result<HashSet<String>, Self::Err> {
+ if user_ids.is_empty() {
+ return Ok(HashSet::new());
+ }
+
+ let user_ids: Vec<String> = user_ids
+ .into_iter()
+ .map(|user_id| user_id.as_ref().to_string())
+ .collect();
+ let existing = sqlx::query_scalar!(
+ r#"
+ SELECT u.id
+ FROM "User" u
+ WHERE u.id = ANY($1)
+ "#,
+ &user_ids,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(existing.into_iter().collect())
+ }
+
+ async fn get_document_mentions(
+ &self,
+ document_ids: Vec<String>,
+ ) -> Result<Vec<ChannelDocumentMention>, Self::Err> {
+ if document_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let mentions = sqlx::query_as!(
+ DocumentMentionRow,
+ r#"
+ SELECT
+ d.name AS document_name,
+ d.owner AS "owner: MacroUserIdStr",
+ d."fileType" AS file_type,
+ dst.sub_type::text AS sub_type
+ FROM "Document" d
+ LEFT JOIN document_sub_type dst ON dst.document_id = d.id
+ WHERE d.id = ANY($1)
+ "#,
+ &document_ids,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(mentions
+ .into_iter()
+ .map(|mention| ChannelDocumentMention {
+ document_name: mention.document_name,
+ owner: mention.owner,
+ file_type: mention.file_type,
+ sub_type: mention.sub_type,
+ })
+ .collect())
+ }
+
+ async fn get_thread_notification_context(
+ &self,
+ thread_id: Uuid,
+ ) -> Result<ThreadNotificationContext, Self::Err> {
+ let participants = get_channel_participants_for_thread_id(&self.pool, thread_id).await?;
+ let parent_sender_id = get_message_owner(&self.pool, thread_id)
+ .await
+ .ok()
+ .and_then(|id| {
+ MacroUserIdStr::parse_from_str(&id)
+ .ok()
+ .map(|id| id.into_owned())
+ });
+
+ Ok(ThreadNotificationContext {
+ participants,
+ parent_sender_id,
+ })
+ }
+
+ async fn get_sender_profile_picture_url(
+ &self,
+ sender_id: MacroUserIdStr<'static>,
+ ) -> Option<String> {
+ get_sender_profile_picture_url(&self.pool, &sender_id).await
+ }
+}
+
+async fn get_sender_profile_picture_url(
+ db: &PgPool,
+ sender_id: &MacroUserIdStr<'_>,
+) -> Option<String> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT mui.profile_picture as "profile_picture!"
+ FROM "User" u
+ JOIN macro_user mu ON mu.id = u.macro_user_id
+ JOIN macro_user_info mui ON mui.macro_user_id = mu.id
+ WHERE u.id = $1
+ AND mui.profile_picture IS NOT NULL
+ LIMIT 1
+ "#,
+ sender_id.as_ref(),
+ )
+ .fetch_optional(db)
+ .await
+ .ok()
+ .flatten()
+}
+
+async fn get_message_owner(pool: &PgPool, message_id: Uuid) -> anyhow::Result<String> {
+ let row = sqlx::query_as!(
+ SenderIdRow,
+ r#"
+ SELECT sender_id AS "sender_id: MacroUserIdStr"
+ FROM comms_messages
+ WHERE id = $1
+ ORDER BY created_at ASC
+ "#,
+ message_id,
+ )
+ .fetch_one(pool)
+ .await
+ .context("unable to get message owner")?;
+ Ok(row.sender_id.to_string())
+}
+
+async fn get_channel_message_count(pool: &PgPool, channel_id: Uuid) -> anyhow::Result<i64> {
+ let count = sqlx::query_scalar!(
+ r#"
+ SELECT COUNT(id) AS "count!"
+ FROM comms_messages
+ WHERE channel_id = $1
+ "#,
+ channel_id,
+ )
+ .fetch_one(pool)
+ .await?;
+ Ok(count)
+}
+
+async fn get_channel_participants_for_thread_id(
+ pool: &PgPool,
+ thread_id: Uuid,
+) -> anyhow::Result<Vec<MacroUserIdStr<'static>>> {
+ let rows = sqlx::query_as!(
+ UserIdRow,
+ r#"
+ SELECT DISTINCT id AS "user_id!: MacroUserIdStr" FROM (
+ SELECT m.sender_id AS id
+ FROM comms_channel_participants cp
+ JOIN comms_channels c ON c.id = cp.channel_id
+ JOIN comms_messages m ON m.channel_id = c.id
+ WHERE (m.id = $1 OR m.thread_id = $1) AND cp.left_at IS NULL
+ UNION
+ SELECT em.entity_id AS id
+ FROM comms_entity_mentions em
+ JOIN comms_messages m ON m.id::text = em.source_entity_id
+ JOIN comms_channel_participants cp
+ ON cp.channel_id = m.channel_id AND cp.user_id = em.entity_id
+ WHERE (m.id = $1 OR m.thread_id = $1)
+ AND em.source_entity_type = 'message'
+ AND em.entity_type = 'user'
+ AND cp.left_at IS NULL
+ ) AS combined
+ "#,
+ thread_id,
+ )
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().map(|row| row.user_id).collect())
+}
diff --git a/rust/cloud-storage/channels/src/outbound/sqs_search_indexer.rs b/rust/cloud-storage/channels/src/outbound/sqs_search_indexer.rs
new file mode 100644
index 0000000000..2c1d8e184a
--- /dev/null
+++ b/rust/cloud-storage/channels/src/outbound/sqs_search_indexer.rs
@@ -0,0 +1,60 @@
+//! SQS search-index adapter for channel side effects.
+
+use crate::domain::ports::ChannelSearchIndexer;
+use std::sync::Arc;
+use uuid::Uuid;
+
+/// SQS-backed search index adapter.
+#[derive(Clone)]
+pub struct SqsChannelSearchIndexer {
+ sqs: Arc<sqs_client::SQS>,
+}
+
+impl SqsChannelSearchIndexer {
+ /// Create a search index adapter.
+ pub fn new(sqs: Arc<sqs_client::SQS>) -> Self {
+ Self { sqs }
+ }
+}
+
+impl ChannelSearchIndexer for SqsChannelSearchIndexer {
+ async fn index_message(&self, channel_id: Uuid, message_id: Uuid) {
+ let sqs = self.sqs.clone();
+ tokio::spawn(async move {
+ sqs.send_message_to_search_event_queue(
+ sqs_client::search::SearchQueueMessage::ChannelMessageUpdate(
+ sqs_client::search::channel::ChannelMessageUpdate {
+ channel_id: channel_id.to_string(),
+ message_id: message_id.to_string(),
+ index_override: None,
+ },
+ ),
+ )
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "SEARCH_QUEUE unable to enqueue message");
+ })
+ .ok();
+ });
+ }
+
+ async fn remove_message(&self, channel_id: Uuid, message_id: Option<Uuid>) {
+ let sqs = self.sqs.clone();
+ tokio::spawn(async move {
+ sqs.send_message_to_search_event_queue(
+ sqs_client::search::SearchQueueMessage::RemoveChannelMessage(
+ sqs_client::search::channel::RemoveChannelMessage {
+ channel_id: channel_id.to_string(),
+ message_id: message_id.map(|id| id.to_string()),
+ index_override: None,
+ },
+ ),
+ )
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "SEARCH_QUEUE unable to enqueue remove message");
+ })
+ .ok();
+ });
+ }
+}
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index d4a225be26..67e46bf72e 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -13,11 +13,22 @@ use call::{
outbound::{livekit_rtc_client::LivekitRtcClient, pg_call_repo::PgCallRepo},
};
use channels::{
- domain::service::ChannelMessagesServiceImpl, inbound::axum_router::ChannelsRouterState,
- outbound::pg_channels_repo::PgChannelMessagesRepo,
+ domain::{
+ service::ChannelServiceImpl,
+ side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher},
+ },
+ inbound::axum_router::ChannelsRouterState,
+ outbound::{
+ connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher,
+ contacts_dispatcher::ContactsChannelDispatcher,
+ notification_sender::NotificationChannelSender,
+ pg_channel_reference_share_permissions::PgChannelReferenceSharePermissions,
+ pg_channels_repo::PgChannelsRepo, pg_side_effect_context::PgChannelSideEffectContext,
+ sqs_search_indexer::SqsChannelSearchIndexer,
+ },
};
use comms::{
- domain::service::ChannelServiceImpl,
+ domain::service::ChannelServiceImpl as CommsChannelServiceImpl,
inbound::router::CommsRouterState,
outbound::postgres::{comms_repo::PgCommsRepo, user_repo::PgUserRepo},
};
@@ -94,7 +105,7 @@ type DssSoupState = SoupRouterState<
PgSoupRepo,
FrecencyQueryServiceImpl<FrecencyPgStorage>,
ReadonlyEmailPreviewAdapter<DssEmailService>,
- ChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>,
+ CommsChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>,
call::domain::service::CallRecordQueryServiceImpl<call::outbound::pg_call_repo::PgCallRepo>,
>,
DssEmailService,
@@ -189,14 +200,28 @@ pub(crate) type DocumentsState = DocumentRouterState<DocumentService, EntityAcce
/// Type alias for the ChannelServiceImpl used by comms
pub(crate) type CommsChannelService =
- ChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>;
+ CommsChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>;
/// Type alias for the CommsRouterState
pub(crate) type CommsState = CommsRouterState<CommsChannelService>;
+/// Type alias for the channels service wired into DSS.
+pub(crate) type DssChannelService = ChannelServiceImpl<
+ PgChannelsRepo,
+ SpawnedChannelEventDispatcher<
+ ChannelSideEffectService<
+ PgChannelSideEffectContext,
+ ConnectionGatewayChannelRealtimePublisher,
+ NotificationChannelSender<NotificationIngressType>,
+ SqsChannelSearchIndexer,
+ ContactsChannelDispatcher<SqsContactsIngress<SqsContactsQueue>>,
+ >,
+ >,
+ PgChannelReferenceSharePermissions<EntityAccessService>,
+>;
+
/// Type alias for the channels router state.
-pub(crate) type DssChannelsState =
- ChannelsRouterState<ChannelMessagesServiceImpl<PgChannelMessagesRepo>, EntityAccessService>;
+pub(crate) type DssChannelsState = ChannelsRouterState<DssChannelService, EntityAccessService>;
/// Type alias for the call connection service.
pub(crate) type CallConnectionService =
diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rs
index ea76eefc44..53273f93f9 100644
--- a/rust/cloud-storage/document_storage_service/src/config.rs
+++ b/rust/cloud-storage/document_storage_service/src/config.rs
@@ -47,6 +47,7 @@ env_var! {
pub DocumentStorageServiceCloudfrontSignerPublicKeyId,
pub RedisUri,
pub NotificationQueue,
+ pub NotificationIngressQueue,
pub SearchEventQueue,
pub ConnectionGatewayUrl,
pub BulkUploadRequestsTable,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index d4cf314b08..c36b07583c 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -24,11 +24,22 @@ use call::{
},
};
use channels::{
- domain::service::ChannelMessagesServiceImpl, inbound::axum_router::ChannelsRouterState,
- outbound::pg_channels_repo::PgChannelMessagesRepo,
+ domain::{
+ service::ChannelServiceImpl,
+ side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher},
+ },
+ inbound::axum_router::ChannelsRouterState,
+ outbound::{
+ connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher,
+ contacts_dispatcher::ContactsChannelDispatcher,
+ notification_sender::NotificationChannelSender,
+ pg_channel_reference_share_permissions::PgChannelReferenceSharePermissions,
+ pg_channels_repo::PgChannelsRepo, pg_side_effect_context::PgChannelSideEffectContext,
+ sqs_search_indexer::SqsChannelSearchIndexer,
+ },
};
use comms::{
- domain::service::ChannelServiceImpl,
+ domain::service::ChannelServiceImpl as CommsChannelServiceImpl,
inbound::router::CommsRouterState,
outbound::postgres::{comms_repo::PgCommsRepo, user_repo::PgUserRepo},
};
@@ -271,7 +282,7 @@ async fn main() -> anyhow::Result<()> {
SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()));
let ingress_queue = SqsQueue::new(
aws_sdk_sqs::Client::new(&aws_config),
- config.vars.notification_queue.as_ref().to_string(),
+ config.vars.notification_ingress_queue.as_ref().to_string(),
);
let notification_ingress_service = Arc::new(SqsNotificationIngress {
queue: ingress_queue.clone(),
@@ -294,13 +305,13 @@ async fn main() -> anyhow::Result<()> {
Some(notification_service),
));
- // Create the ChannelServiceImpl - we need to create separate instances as it doesn't impl Clone
- let channel_service_for_soup = ChannelServiceImpl::new(
+ // 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()),
frecency_storage.clone(),
);
- let channel_service_for_comms = ChannelServiceImpl::new(
+ let channel_service_for_comms = CommsChannelServiceImpl::new(
PgCommsRepo::new(readonly_pool::ReadOnlyPool(db.clone())),
PgUserRepo::new(db.clone()),
frecency_storage.clone(),
@@ -539,8 +550,24 @@ async fn main() -> anyhow::Result<()> {
PgCallRepo::new(readonly_db.clone()),
);
+ let sqs_client = Arc::new(sqs_client);
+ let conn_gateway_client = Arc::new(conn_gateway_client);
+ let channels_repo = PgChannelsRepo::new(db.clone());
+
+ let channels_service = ChannelServiceImpl::with_dependencies(
+ channels_repo,
+ SpawnedChannelEventDispatcher::new(ChannelSideEffectService::new(
+ PgChannelSideEffectContext::new(db.clone()),
+ ConnectionGatewayChannelRealtimePublisher::new(conn_gateway_client.clone()),
+ NotificationChannelSender::new(notification_ingress_service.clone()),
+ SqsChannelSearchIndexer::new(sqs_client.clone()),
+ ContactsChannelDispatcher::new(contacts_ingress.clone()),
+ )),
+ PgChannelReferenceSharePermissions::new(db.clone(), entity_access_service.clone()),
+ );
+
let api_context = ApiContext {
- contacts_ingress,
+ contacts_ingress: contacts_ingress.clone(),
soup_router_state: SoupRouterState::new(
SoupImpl::new(
PgSoupRepo::new(readonly_pool::ReadOnlyPool(readonly_db.clone())),
@@ -559,9 +586,9 @@ async fn main() -> anyhow::Result<()> {
s3_client: s3,
dynamodb_client: Arc::new(dynamodb_client),
dynamo_db,
- sqs_client: Arc::new(sqs_client),
- notification_ingress_service,
- conn_gateway_client: Arc::new(conn_gateway_client),
+ sqs_client: sqs_client.clone(),
+ notification_ingress_service: notification_ingress_service.clone(),
+ conn_gateway_client: conn_gateway_client.clone(),
sync_service_client: sync_service_client.clone(),
system_properties_service: system_properties_service.clone(),
properties_service: properties_service.clone(),
@@ -584,10 +611,7 @@ async fn main() -> anyhow::Result<()> {
documents_hex::outbound::document_bytes_upload::ReqwestDocumentBytesUploader::default(),
),
},
- channels_state: ChannelsRouterState::new(
- ChannelMessagesServiceImpl::new(PgChannelMessagesRepo::new(db.clone())),
- (*entity_access_service).clone(),
- ),
+ channels_state: ChannelsRouterState::new(channels_service, (*entity_access_service).clone()),
call_state,
call_webhook_state,
call_internal_state,
diff --git a/rust/cloud-storage/integration_tests/local_e2e/Cargo.toml b/rust/cloud-storage/integration_tests/local_e2e/Cargo.toml
index 12574e926d..f0ca44076f 100644
--- a/rust/cloud-storage/integration_tests/local_e2e/Cargo.toml
+++ b/rust/cloud-storage/integration_tests/local_e2e/Cargo.toml
@@ -13,3 +13,5 @@ serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["time"] }
tokio-tungstenite = { workspace = true }
+sqlx = { workspace = true }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/integration_tests/local_e2e/tests/channel_mutations.rs b/rust/cloud-storage/integration_tests/local_e2e/tests/channel_mutations.rs
new file mode 100644
index 0000000000..d594702b85
--- /dev/null
+++ b/rust/cloud-storage/integration_tests/local_e2e/tests/channel_mutations.rs
@@ -0,0 +1,2203 @@
+use std::time::Duration;
+
+use anyhow::{Context, ensure};
+use futures::{
+ SinkExt, StreamExt,
+ stream::{SplitSink, SplitStream},
+};
+use local_e2e_test_support::{
+ LocalE2eConfig, LocalE2eSeed, LocalE2eServices, LocalJwtOptions, SeedUser,
+ encode_local_jwt_with,
+};
+use reqwest::{Client, Method, Response};
+use serde::Deserialize;
+use serde_json::{Value, json};
+use sqlx::{PgPool, postgres::PgPoolOptions};
+use tokio::net::TcpStream;
+use tokio::time::{Instant, timeout};
+use tokio_tungstenite::tungstenite::{Error as WebsocketError, Message as WebsocketMessage};
+use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async};
+use uuid::Uuid;
+
+const WEBSOCKET_TIMEOUT: Duration = Duration::from_secs(10);
+const NOTIFICATION_TIMEOUT: Duration = Duration::from_secs(30);
+const CONTACTS_TIMEOUT: Duration = Duration::from_secs(30);
+const DEFAULT_LOCAL_DATABASE_URL: &str = "postgres://user:password@localhost:5432/macrodb";
+
+#[derive(Clone, Debug)]
+struct ChannelApiClient {
+ label: String,
+ mutation_base_url: String,
+ read_base_url: String,
+}
+
+impl ChannelApiClient {
+ /// Channels API under test.
+ /// Override mutations with `LOCAL_E2E_CHANNELS_BASE_URL=http://.../channels`.
+ /// Override the read-model API with `LOCAL_E2E_CHANNELS_READ_BASE_URL=http://.../comms/channels`.
+ fn from_config(config: &LocalE2eConfig, services: &LocalE2eServices) -> Self {
+ let mutation_base_url = config
+ .get("LOCAL_E2E_CHANNELS_BASE_URL")
+ .or_else(|| config.get("LOCAL_E2E_NEW_CHANNELS_BASE_URL"))
+ .map(str::to_string)
+ .unwrap_or_else(|| format!("{}/channels", services.document_storage_url()));
+ let read_base_url = config
+ .get("LOCAL_E2E_CHANNELS_READ_BASE_URL")
+ .or_else(|| config.get("LOCAL_E2E_NEW_CHANNELS_READ_BASE_URL"))
+ .map(str::to_string)
+ .unwrap_or_else(|| format!("{}/comms/channels", services.document_storage_url()));
+ Self {
+ label: "channels".to_string(),
+ mutation_base_url: trim_trailing_slash(&mutation_base_url),
+ read_base_url: trim_trailing_slash(&read_base_url),
+ }
+ }
+
+ fn label(&self) -> &str {
+ &self.label
+ }
+
+ fn create_channel_url(&self) -> String {
+ self.mutation_base_url.clone()
+ }
+
+ fn get_or_create_dm_url(&self) -> String {
+ format!("{}/get_or_create_dm", self.mutation_base_url)
+ }
+
+ fn get_or_create_private_url(&self) -> String {
+ format!("{}/get_or_create_private", self.mutation_base_url)
+ }
+
+ fn channel_url(&self, channel_id: &str) -> String {
+ format!("{}/{channel_id}", self.mutation_base_url)
+ }
+
+ fn read_channel_url(&self, channel_id: &str) -> String {
+ format!("{}/{channel_id}", self.read_base_url)
+ }
+
+ fn channel_message_url(&self, channel_id: &str, message_id: &str) -> String {
+ format!(
+ "{}/{channel_id}/message/{message_id}",
+ self.mutation_base_url
+ )
+ }
+
+ fn post_channel_message_url(&self, channel_id: &str) -> String {
+ format!("{}/{channel_id}/message", self.mutation_base_url)
+ }
+
+ fn post_channel_reaction_url(&self, channel_id: &str) -> String {
+ format!("{}/{channel_id}/reaction", self.mutation_base_url)
+ }
+
+ fn post_channel_typing_url(&self, channel_id: &str) -> String {
+ format!("{}/{channel_id}/typing", self.mutation_base_url)
+ }
+
+ fn channel_participants_url(&self, channel_id: &str) -> String {
+ format!("{}/{channel_id}/participants", self.mutation_base_url)
+ }
+
+ fn join_channel_url(&self, channel_id: &str) -> String {
+ format!("{}/{channel_id}/join", self.mutation_base_url)
+ }
+
+ fn leave_channel_url(&self, channel_id: &str) -> String {
+ format!("{}/{channel_id}/leave", self.mutation_base_url)
+ }
+}
+
+fn trim_trailing_slash(url: &str) -> String {
+ url.trim_end_matches('/').to_string()
+}
+
+struct ChannelContractContext {
+ world: TestWorld,
+ api: ChannelApiClient,
+ http: Client,
+ pool: PgPool,
+ users: ContractUsers,
+}
+
+struct ContractUsers {
+ actor: SeedUser,
+ actor_token: String,
+ bob: SeedUser,
+ bob_token: String,
+ charlie: SeedUser,
+ charlie_token: String,
+ dana: SeedUser,
+ dana_token: String,
+ eve: SeedUser,
+ eve_token: String,
+}
+
+impl ChannelContractContext {
+ async fn load() -> anyhow::Result<Self> {
+ let world = TestWorld::load()?;
+ let api = ChannelApiClient::from_config(&world.config, &world.services);
+ let http = Client::new();
+ let pool = connect_db(&world.config).await?;
+ let actor = world.seed.smoke_user()?.clone();
+ let actor_token = world.token_for(&actor)?;
+ let bob = world
+ .seed
+ .user_by_email("[email protected]")
+ .context("missing bob fixture")?
+ .clone();
+ let bob_token = world.token_for(&bob)?;
+ let charlie = world
+ .seed
+ .user_by_email("[email protected]")
+ .context("missing charlie fixture")?
+ .clone();
+ let charlie_token = world.token_for(&charlie)?;
+ let dana = world
+ .seed
+ .user_by_email("[email protected]")
+ .context("missing dana fixture")?
+ .clone();
+ let dana_token = world.token_for(&dana)?;
+ let eve = world
+ .seed
+ .user_by_email("[email protected]")
+ .context("missing eve fixture")?
+ .clone();
+ let eve_token = world.token_for(&eve)?;
+
+ Ok(Self {
+ world,
+ api,
+ http,
+ pool,
+ users: ContractUsers {
+ actor,
+ actor_token,
+ bob,
+ bob_token,
+ charlie,
+ charlie_token,
+ dana,
+ dana_token,
+ eve,
+ eve_token,
+ },
+ })
+ }
+
+ fn suffix(&self, prefix: &str) -> String {
+ format!("{prefix}-{}-{}", self.api.label(), unique_suffix())
+ }
+}
+
+type GatewaySocket = WebSocketStream<MaybeTlsStream<TcpStream>>;
+type GatewayWrite = SplitSink<GatewaySocket, WebsocketMessage>;
+type GatewayRead = SplitStream<GatewaySocket>;
+
+struct GatewayEvent {
+ label: &'static str,
+ data: Value,
+}
+
+struct ContractGatewayListeners {
+ actor_write: GatewayWrite,
+ actor_read: GatewayRead,
+ bob_write: GatewayWrite,
+ bob_read: GatewayRead,
+ charlie_write: GatewayWrite,
+ charlie_read: GatewayRead,
+}
+
+impl ContractGatewayListeners {
+ async fn connect(ctx: &ChannelContractContext) -> anyhow::Result<Self> {
+ let actor_ws = ctx
+ .world
+ .services
+ .connection_gateway_ws_url_with_token(&ctx.users.actor_token)?;
+ let bob_ws = ctx
+ .world
+ .services
+ .connection_gateway_ws_url_with_token(&ctx.users.bob_token)?;
+ let charlie_ws = ctx
+ .world
+ .services
+ .connection_gateway_ws_url_with_token(&ctx.users.charlie_token)?;
+ let (actor_socket, _) = connect_async(&actor_ws)
+ .await
+ .context("connect actor websocket")?;
+ let (bob_socket, _) = connect_async(&bob_ws)
+ .await
+ .context("connect bob websocket")?;
+ let (charlie_socket, _) = connect_async(&charlie_ws)
+ .await
+ .context("connect charlie websocket")?;
+ let (mut actor_write, mut actor_read) = actor_socket.split();
+ let (mut bob_write, mut bob_read) = bob_socket.split();
+ let (mut charlie_write, mut charlie_read) = charlie_socket.split();
+ ping_and_wait(&mut actor_write, &mut actor_read).await?;
+ ping_and_wait(&mut bob_write, &mut bob_read).await?;
+ ping_and_wait(&mut charlie_write, &mut charlie_read).await?;
+
+ Ok(Self {
+ actor_write,
+ actor_read,
+ bob_write,
+ bob_read,
+ charlie_write,
+ charlie_read,
+ })
+ }
+
+ async fn wait_for_all<F>(
+ &mut self,
+ expected_type: &str,
+ matches: F,
+ detail: &str,
+ ) -> anyhow::Result<Vec<GatewayEvent>>
+ where
+ F: Fn(&Value) -> bool,
+ {
+ let actor =
+ wait_for_gateway_event(&mut self.actor_read, expected_type, |data| matches(data))
+ .await
+ .with_context(|| format!("actor did not receive {detail}"))?;
+ let bob = wait_for_gateway_event(&mut self.bob_read, expected_type, |data| matches(data))
+ .await
+ .with_context(|| format!("bob did not receive {detail}"))?;
+ let charlie =
+ wait_for_gateway_event(&mut self.charlie_read, expected_type, |data| matches(data))
+ .await
+ .with_context(|| format!("charlie did not receive {detail}"))?;
+
+ Ok(vec![
+ GatewayEvent {
+ label: "actor",
+ data: actor,
+ },
+ GatewayEvent {
+ label: "bob",
+ data: bob,
+ },
+ GatewayEvent {
+ label: "charlie",
+ data: charlie,
+ },
+ ])
+ }
+
+ async fn close(mut self) {
+ self.actor_write
+ .send(WebsocketMessage::Close(None))
+ .await
+ .ok();
+ self.bob_write
+ .send(WebsocketMessage::Close(None))
+ .await
+ .ok();
+ self.charlie_write
+ .send(WebsocketMessage::Close(None))
+ .await
+ .ok();
+ }
+}
+
+struct ContractChannel {
+ id: String,
+ name: String,
+}
+
+async fn create_private_contract_channel(
+ ctx: &ChannelContractContext,
+ prefix: &str,
+) -> anyhow::Result<ContractChannel> {
+ let name = ctx.suffix(prefix);
+ let created = create_channel_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ name.clone(),
+ "private",
+ &[&ctx.users.bob.user_id, &ctx.users.charlie.user_id],
+ )
+ .await
+ .with_context(|| format!("{} create private contract channel", ctx.api.label()))?;
+ Ok(ContractChannel {
+ id: created.id,
+ name,
+ })
+}
+
+async fn create_public_contract_channel(
+ ctx: &ChannelContractContext,
+ prefix: &str,
+) -> anyhow::Result<ContractChannel> {
+ let name = ctx.suffix(prefix);
+ let created = create_channel_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ name.clone(),
+ "public",
+ &[&ctx.users.bob.user_id],
+ )
+ .await
+ .with_context(|| format!("{} create public contract channel", ctx.api.label()))?;
+ Ok(ContractChannel {
+ id: created.id,
+ name,
+ })
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus document_storage_service"]
+async fn get_or_create_dm_returns_existing_dm_and_rejects_self_dm() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_get_or_create_dm_access_control_contract(&ctx).await
+}
+
+async fn assert_get_or_create_dm_access_control_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let dm = get_or_create_dm_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &ctx.users.bob.user_id,
+ )
+ .await
+ .with_context(|| format!("{} get existing DM", ctx.api.label()))?;
+ ensure!(
+ dm.action == "get",
+ "{} expected existing seeded DM, got {dm:?}",
+ ctx.api.label()
+ );
+
+ let invalid_dm = ctx
+ .http
+ .post(ctx.api.get_or_create_dm_url())
+ .bearer_auth(&ctx.users.actor_token)
+ .json(&json!({ "recipient_id": ctx.users.actor.user_id }))
+ .send()
+ .await
+ .with_context(|| format!("{} failed to call invalid self-DM", ctx.api.label()))?;
+ ensure!(
+ invalid_dm.status() == reqwest::StatusCode::BAD_REQUEST,
+ "{} self-DM should be rejected with 400, got {}: {}",
+ ctx.api.label(),
+ invalid_dm.status(),
+ invalid_dm.text().await.unwrap_or_default()
+ );
+
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus document_storage_service"]
+async fn get_or_create_private_persists_expected_participants() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_get_or_create_private_access_control_contract(&ctx).await
+}
+
+async fn assert_get_or_create_private_access_control_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let private = get_or_create_private_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &[&ctx.users.bob.user_id, &ctx.users.eve.user_id],
+ )
+ .await
+ .with_context(|| format!("{} get/create private channel", ctx.api.label()))?;
+ ensure!(
+ !private.channel_id.is_empty(),
+ "{} private channel id was empty",
+ ctx.api.label()
+ );
+ assert_db_participants_include(
+ &ctx.pool,
+ &private.channel_id,
+ &[
+ &ctx.users.actor.user_id,
+ &ctx.users.bob.user_id,
+ &ctx.users.eve.user_id,
+ ],
+ )
+ .await?;
+
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus document_storage_service"]
+async fn public_channel_allows_join_and_leave_for_non_participant() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_public_join_leave_access_control_contract(&ctx).await
+}
+
+async fn assert_public_join_leave_access_control_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let public = create_public_contract_channel(ctx, "access-public").await?;
+
+ require_success(
+ ctx.http
+ .post(ctx.api.join_channel_url(&public.id))
+ .bearer_auth(&ctx.users.eve_token)
+ .send()
+ .await
+ .with_context(|| format!("{} failed to join public channel", ctx.api.label()))?,
+ "join public channel as non-participant",
+ )
+ .await?;
+ let joined = get_channel_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.eve_token,
+ &public.id,
+ )
+ .await?;
+ assert_participant(&joined, &ctx.users.eve.user_id)?;
+ assert_db_participants_include(&ctx.pool, &public.id, &[&ctx.users.eve.user_id]).await?;
+
+ require_success(
+ ctx.http
+ .post(ctx.api.leave_channel_url(&public.id))
+ .bearer_auth(&ctx.users.eve_token)
+ .send()
+ .await
+ .with_context(|| format!("{} failed to leave public channel", ctx.api.label()))?,
+ "leave public channel",
+ )
+ .await?;
+ assert_db_participants_absent(&ctx.pool, &public.id, &[&ctx.users.eve.user_id]).await?;
+ delete_channel_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &public.id,
+ )
+ .await?;
+
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus document_storage_service and contacts_service workers"]
+async fn create_private_channel_persists_channel_participants_and_contacts() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_private_channel_create_side_effect_contract(&ctx).await
+}
+
+async fn assert_private_channel_create_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let contacts_since = db_now(&ctx.pool).await?;
+ let private = create_private_contract_channel(ctx, "membership-private").await?;
+
+ assert_db_channel(&ctx.pool, &private.id, Some(&private.name), "private").await?;
+ assert_db_participants_include(
+ &ctx.pool,
+ &private.id,
+ &[
+ &ctx.users.actor.user_id,
+ &ctx.users.bob.user_id,
+ &ctx.users.charlie.user_id,
+ ],
+ )
+ .await?;
+ wait_for_contacts_connections(
+ &ctx.pool,
+ &[
+ (&ctx.users.actor.user_id, &ctx.users.bob.user_id),
+ (&ctx.users.actor.user_id, &ctx.users.charlie.user_id),
+ (&ctx.users.bob.user_id, &ctx.users.charlie.user_id),
+ ],
+ &contacts_since,
+ )
+ .await
+ .with_context(|| format!("{} create private contacts", ctx.api.label()))?;
+
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus document_storage_service, contacts_service, and notification_service workers"]
+async fn adding_and_removing_participant_updates_membership_notifications_and_contacts()
+-> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_participant_invite_remove_side_effect_contract(&ctx).await
+}
+
+async fn assert_participant_invite_remove_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let private = create_private_contract_channel(ctx, "membership-invite").await?;
+ let contacts_since = db_now(&ctx.pool).await?;
+
+ add_participants_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &private.id,
+ &[&ctx.users.dana.user_id],
+ )
+ .await
+ .with_context(|| format!("{} add participant", ctx.api.label()))?;
+ assert_db_participants_include(&ctx.pool, &private.id, &[&ctx.users.dana.user_id]).await?;
+
+ let invite = wait_for_notification(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.users.dana_token,
+ |notification| notification_matches(notification, "channel_invite", &private.id),
+ )
+ .await
+ .with_context(|| format!("{} invite notification", ctx.api.label()))?;
+ assert_sender(&invite, &ctx.users.actor.user_id)?;
+ wait_for_contacts_connections(
+ &ctx.pool,
+ &[
+ (&ctx.users.actor.user_id, &ctx.users.dana.user_id),
+ (&ctx.users.bob.user_id, &ctx.users.dana.user_id),
+ (&ctx.users.charlie.user_id, &ctx.users.dana.user_id),
+ ],
+ &contacts_since,
+ )
+ .await
+ .with_context(|| format!("{} invite contacts", ctx.api.label()))?;
+
+ remove_participants_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &private.id,
+ &[&ctx.users.dana.user_id],
+ )
+ .await
+ .with_context(|| format!("{} remove participant", ctx.api.label()))?;
+ assert_db_participants_absent(&ctx.pool, &private.id, &[&ctx.users.dana.user_id]).await?;
+
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus document_storage_service and contacts_service workers"]
+async fn public_join_and_leave_updates_membership_and_contacts() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_public_join_leave_side_effect_contract(&ctx).await
+}
+
+async fn assert_public_join_leave_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let public = create_public_contract_channel(ctx, "membership-public").await?;
+ assert_db_channel(&ctx.pool, &public.id, Some(&public.name), "public").await?;
+
+ let contacts_since = db_now(&ctx.pool).await?;
+ require_success(
+ ctx.http
+ .post(ctx.api.join_channel_url(&public.id))
+ .bearer_auth(&ctx.users.charlie_token)
+ .send()
+ .await
+ .context("failed to join public channel")?,
+ "join public channel",
+ )
+ .await?;
+ assert_db_participants_include(&ctx.pool, &public.id, &[&ctx.users.charlie.user_id]).await?;
+ wait_for_contacts_connections(
+ &ctx.pool,
+ &[
+ (&ctx.users.actor.user_id, &ctx.users.charlie.user_id),
+ (&ctx.users.bob.user_id, &ctx.users.charlie.user_id),
+ ],
+ &contacts_since,
+ )
+ .await
+ .with_context(|| format!("{} join contacts", ctx.api.label()))?;
+
+ require_success(
+ ctx.http
+ .post(ctx.api.leave_channel_url(&public.id))
+ .bearer_auth(&ctx.users.charlie_token)
+ .send()
+ .await
+ .context("failed to leave public channel")?,
+ "leave public channel",
+ )
+ .await?;
+ assert_db_participants_absent(&ctx.pool, &public.id, &[&ctx.users.charlie.user_id]).await?;
+
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus document_storage_service"]
+async fn delete_channel_removes_channel() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_channel_delete_side_effect_contract(&ctx).await
+}
+
+async fn assert_channel_delete_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let private = create_private_contract_channel(ctx, "membership-delete").await?;
+ delete_channel_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &private.id,
+ )
+ .await?;
+ assert_db_channel_absent(&ctx.pool, &private.id).await?;
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus document_storage_service"]
+async fn channel_rename_persists_name() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_channel_rename_side_effect_contract(&ctx).await
+}
+
+async fn assert_channel_rename_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let channel = create_public_contract_channel(ctx, "rename-channel").await?;
+ let renamed = ctx.suffix("renamed-channel");
+ patch_channel_name_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &renamed,
+ )
+ .await?;
+ assert_db_channel(&ctx.pool, &channel.id, Some(&renamed), "public").await?;
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus connection_gateway, document_storage_service, and notification_service workers"]
+async fn message_with_document_attachment_updates_channel_share_permissions_and_side_effects()
+-> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_document_attachment_share_permission_side_effect_contract(&ctx).await
+}
+
+async fn assert_document_attachment_share_permission_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let document = ctx.world.seed.project_roadmap_document()?;
+ let channel = create_private_contract_channel(ctx, "message-first").await?;
+ let mut listeners = ContractGatewayListeners::connect(ctx).await?;
+ let suffix = ctx.suffix("first-message");
+ let content = format!("root {suffix}");
+ let nonce = format!("root-nonce-{suffix}");
+
+ let root = post_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &PostMessageBody {
+ content: &content,
+ mentions: Vec::new(),
+ thread_id: None,
+ attachments: vec![json!({
+ "entity_type": "document",
+ "entity_id": document.document_id,
+ "width": 320,
+ "height": 240,
+ })],
+ nonce: &nonce,
+ },
+ )
+ .await
+ .with_context(|| format!("{} post root message", ctx.api.label()))?;
+ assert_db_message(
+ &ctx.pool,
+ &root.id,
+ &channel.id,
+ &ctx.users.actor.user_id,
+ &content,
+ None,
+ )
+ .await?;
+ assert_db_attachment_count(&ctx.pool, &root.id, 1).await?;
+ assert_db_document_channel_share_permission(&ctx.pool, &document.document_id, &channel.id)
+ .await?;
+
+ for event in listeners
+ .wait_for_all(
+ "comms_message",
+ |data| {
+ data.get("id").and_then(Value::as_str) == Some(root.id.as_str())
+ && data.get("nonce").and_then(Value::as_str) == Some(nonce.as_str())
+ },
+ "root realtime message",
+ )
+ .await?
+ {
+ ensure!(
+ event.data.get("content").and_then(Value::as_str) == Some(content.as_str()),
+ "{} {} root content mismatch: {}",
+ ctx.api.label(),
+ event.label,
+ event.data
+ );
+ }
+
+ listeners
+ .wait_for_all(
+ "comms_attachment",
+ |data| {
+ data.get("message_id").and_then(Value::as_str) == Some(root.id.as_str())
+ && data.get("nonce").and_then(Value::as_str) == Some(nonce.as_str())
+ },
+ "root attachment realtime event",
+ )
+ .await?;
+
+ let bob_invite = wait_for_notification(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.users.bob_token,
+ |notification| {
+ notification_matches(notification, "channel_invite", &channel.id)
+ && notification_content(notification, "messageContent") == Some(content.as_str())
+ },
+ )
+ .await
+ .with_context(|| format!("{} first message bob invite notification", ctx.api.label()))?;
+ assert_sender(&bob_invite, &ctx.users.actor.user_id)?;
+
+ let charlie_invite = wait_for_notification(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.users.charlie_token,
+ |notification| {
+ notification_matches(notification, "channel_invite", &channel.id)
+ && notification_content(notification, "messageContent") == Some(content.as_str())
+ },
+ )
+ .await
+ .with_context(|| {
+ format!(
+ "{} first message charlie invite notification",
+ ctx.api.label()
+ )
+ })?;
+ assert_sender(&charlie_invite, &ctx.users.actor.user_id)?;
+
+ let actor_notifications =
+ list_notifications(&ctx.http, &ctx.world.services, &ctx.users.actor_token).await?;
+ ensure!(
+ find_notification(&actor_notifications, |notification| {
+ notification_matches(notification, "channel_invite", &channel.id)
+ })
+ .is_none(),
+ "{} sender should not receive channel_invite for {}",
+ ctx.api.label(),
+ channel.id
+ );
+
+ listeners.close().await;
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus connection_gateway, document_storage_service, and notification_service workers"]
+async fn follow_up_message_persists_message_emits_realtime_and_sends_notifications()
+-> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_follow_up_message_side_effect_contract(&ctx).await
+}
+
+async fn assert_follow_up_message_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let channel = create_private_contract_channel(ctx, "message-follow-up").await?;
+ let suffix = ctx.suffix("follow-up-message");
+ post_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &PostMessageBody {
+ content: &format!("invite {suffix}"),
+ mentions: Vec::new(),
+ thread_id: None,
+ attachments: Vec::new(),
+ nonce: &format!("invite-{suffix}"),
+ },
+ )
+ .await?;
+
+ let mut listeners = ContractGatewayListeners::connect(ctx).await?;
+ let content = format!("follow-up {suffix}");
+ let nonce = format!("follow-up-{suffix}");
+ let follow_up = post_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &PostMessageBody {
+ content: &content,
+ mentions: Vec::new(),
+ thread_id: None,
+ attachments: Vec::new(),
+ nonce: &nonce,
+ },
+ )
+ .await
+ .with_context(|| format!("{} follow-up message", ctx.api.label()))?;
+ assert_db_message(
+ &ctx.pool,
+ &follow_up.id,
+ &channel.id,
+ &ctx.users.actor.user_id,
+ &content,
+ None,
+ )
+ .await?;
+
+ listeners
+ .wait_for_all(
+ "comms_message",
+ |data| {
+ data.get("id").and_then(Value::as_str) == Some(follow_up.id.as_str())
+ && data.get("nonce").and_then(Value::as_str) == Some(nonce.as_str())
+ },
+ "follow-up realtime message",
+ )
+ .await?;
+
+ wait_for_notification(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.users.bob_token,
+ |notification| {
+ notification_matches(notification, "channel_message_send", &channel.id)
+ && notification_content(notification, "messageId") == Some(follow_up.id.as_str())
+ && notification_content(notification, "messageContent") == Some(content.as_str())
+ },
+ )
+ .await
+ .with_context(|| format!("{} follow-up bob notification", ctx.api.label()))?;
+ wait_for_notification(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.users.charlie_token,
+ |notification| {
+ notification_matches(notification, "channel_message_send", &channel.id)
+ && notification_content(notification, "messageId") == Some(follow_up.id.as_str())
+ },
+ )
+ .await
+ .with_context(|| format!("{} follow-up charlie notification", ctx.api.label()))?;
+
+ listeners.close().await;
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus connection_gateway and document_storage_service"]
+async fn typing_emits_realtime() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_typing_side_effect_contract(&ctx).await
+}
+
+async fn assert_typing_side_effect_contract(ctx: &ChannelContractContext) -> anyhow::Result<()> {
+ let channel = create_private_contract_channel(ctx, "message-typing").await?;
+ let mut listeners = ContractGatewayListeners::connect(ctx).await?;
+ let nonce = ctx.suffix("typing");
+
+ post_typing_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.bob_token,
+ &channel.id,
+ "start",
+ None,
+ &nonce,
+ )
+ .await
+ .with_context(|| format!("{} typing", ctx.api.label()))?;
+
+ for event in listeners
+ .wait_for_all(
+ "comms_typing",
+ |data| {
+ data.get("user_id").and_then(Value::as_str) == Some(ctx.users.bob.user_id.as_str())
+ && data.get("nonce").and_then(Value::as_str) == Some(nonce.as_str())
+ },
+ "typing realtime event",
+ )
+ .await?
+ {
+ ensure!(
+ event.data.get("action").and_then(Value::as_str) == Some("start"),
+ "{} {} typing action mismatch: {}",
+ ctx.api.label(),
+ event.label,
+ event.data
+ );
+ }
+
+ listeners.close().await;
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus connection_gateway and document_storage_service"]
+async fn reaction_persists_reaction_and_emits_realtime() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_reaction_side_effect_contract(&ctx).await
+}
+
+async fn assert_reaction_side_effect_contract(ctx: &ChannelContractContext) -> anyhow::Result<()> {
+ let channel = create_private_contract_channel(ctx, "message-reaction").await?;
+ let suffix = ctx.suffix("reaction-message");
+ let root = post_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &PostMessageBody {
+ content: &format!("reaction root {suffix}"),
+ mentions: Vec::new(),
+ thread_id: None,
+ attachments: Vec::new(),
+ nonce: &format!("reaction-root-{suffix}"),
+ },
+ )
+ .await?;
+
+ let mut listeners = ContractGatewayListeners::connect(ctx).await?;
+ let nonce = format!("reaction-{suffix}");
+ post_reaction_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.bob_token,
+ &channel.id,
+ &root.id,
+ "👍",
+ "Add",
+ &nonce,
+ )
+ .await
+ .with_context(|| format!("{} reaction", ctx.api.label()))?;
+ assert_db_reaction(&ctx.pool, &root.id, "👍", &ctx.users.bob.user_id).await?;
+
+ for event in listeners
+ .wait_for_all(
+ "comms_reaction",
+ |data| {
+ data.get("message_id").and_then(Value::as_str) == Some(root.id.as_str())
+ && data.get("nonce").and_then(Value::as_str) == Some(nonce.as_str())
+ },
+ "reaction realtime event",
+ )
+ .await?
+ {
+ ensure!(
+ reaction_payload_contains_user(&event.data, "👍", &ctx.users.bob.user_id),
+ "{} {} reaction payload missing bob: {}",
+ ctx.api.label(),
+ event.label,
+ event.data
+ );
+ }
+
+ listeners.close().await;
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus connection_gateway, document_storage_service, and notification_service workers"]
+async fn thread_reply_persists_thread_id_emits_realtime_and_notifies_parent_author()
+-> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_thread_reply_side_effect_contract(&ctx).await
+}
+
+async fn assert_thread_reply_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let channel = create_private_contract_channel(ctx, "message-reply").await?;
+ let suffix = ctx.suffix("reply-message");
+ let root = post_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &PostMessageBody {
+ content: &format!("reply root {suffix}"),
+ mentions: Vec::new(),
+ thread_id: None,
+ attachments: Vec::new(),
+ nonce: &format!("reply-root-{suffix}"),
+ },
+ )
+ .await?;
+
+ let mut listeners = ContractGatewayListeners::connect(ctx).await?;
+ let content = format!("reply {suffix}");
+ let nonce = format!("reply-{suffix}");
+ let reply = post_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.bob_token,
+ &channel.id,
+ &PostMessageBody {
+ content: &content,
+ mentions: Vec::new(),
+ thread_id: Some(root.id.as_str()),
+ attachments: Vec::new(),
+ nonce: &nonce,
+ },
+ )
+ .await
+ .with_context(|| format!("{} reply", ctx.api.label()))?;
+ assert_db_message(
+ &ctx.pool,
+ &reply.id,
+ &channel.id,
+ &ctx.users.bob.user_id,
+ &content,
+ Some(&root.id),
+ )
+ .await?;
+
+ for event in listeners
+ .wait_for_all(
+ "comms_message",
+ |data| {
+ data.get("id").and_then(Value::as_str) == Some(reply.id.as_str())
+ && data.get("nonce").and_then(Value::as_str) == Some(nonce.as_str())
+ },
+ "reply realtime message",
+ )
+ .await?
+ {
+ ensure!(
+ event.data.get("thread_id").and_then(Value::as_str) == Some(root.id.as_str()),
+ "{} {} reply thread mismatch: {}",
+ ctx.api.label(),
+ event.label,
+ event.data
+ );
+ }
+ wait_for_notification(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.users.actor_token,
+ |notification| {
+ notification_matches(notification, "channel_message_reply", &channel.id)
+ && notification_content(notification, "messageId") == Some(reply.id.as_str())
+ && notification_content(notification, "threadId") == Some(root.id.as_str())
+ && notification_content(notification, "messageContent") == Some(content.as_str())
+ },
+ )
+ .await
+ .with_context(|| format!("{} reply notification", ctx.api.label()))?;
+
+ listeners.close().await;
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus connection_gateway and document_storage_service"]
+async fn message_edit_persists_content_and_emits_realtime() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_message_edit_side_effect_contract(&ctx).await
+}
+
+async fn assert_message_edit_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let channel = create_private_contract_channel(ctx, "message-edit").await?;
+ let suffix = ctx.suffix("edit-message");
+ let root = post_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &PostMessageBody {
+ content: &format!("edit root {suffix}"),
+ mentions: Vec::new(),
+ thread_id: None,
+ attachments: Vec::new(),
+ nonce: &format!("edit-root-{suffix}"),
+ },
+ )
+ .await?;
+
+ let mut listeners = ContractGatewayListeners::connect(ctx).await?;
+ let content = format!("edited {suffix}");
+ let nonce = format!("edit-{suffix}");
+ patch_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &root.id,
+ &json!({
+ "content": content,
+ "mentions": [],
+ "attachment_ids_to_delete": [],
+ "attachments_to_add": [],
+ "nonce": nonce,
+ }),
+ )
+ .await
+ .with_context(|| format!("{} edit", ctx.api.label()))?;
+ assert_db_message_content(&ctx.pool, &root.id, &content).await?;
+
+ for event in listeners
+ .wait_for_all(
+ "comms_message",
+ |data| {
+ data.get("id").and_then(Value::as_str) == Some(root.id.as_str())
+ && data.get("nonce").and_then(Value::as_str) == Some(nonce.as_str())
+ },
+ "edit realtime message",
+ )
+ .await?
+ {
+ ensure!(
+ event.data.get("content").and_then(Value::as_str) == Some(content.as_str()),
+ "{} {} edit content mismatch: {}",
+ ctx.api.label(),
+ event.label,
+ event.data
+ );
+ }
+
+ listeners.close().await;
+ Ok(())
+}
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus connection_gateway and document_storage_service"]
+async fn message_delete_persists_tombstone_and_emits_realtime() -> anyhow::Result<()> {
+ let ctx = ChannelContractContext::load().await?;
+ assert_message_delete_side_effect_contract(&ctx).await
+}
+
+async fn assert_message_delete_side_effect_contract(
+ ctx: &ChannelContractContext,
+) -> anyhow::Result<()> {
+ let channel = create_private_contract_channel(ctx, "message-delete").await?;
+ let suffix = ctx.suffix("delete-message");
+ let root = post_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &PostMessageBody {
+ content: &format!("delete root {suffix}"),
+ mentions: Vec::new(),
+ thread_id: None,
+ attachments: Vec::new(),
+ nonce: &format!("delete-root-{suffix}"),
+ },
+ )
+ .await?;
+
+ let mut listeners = ContractGatewayListeners::connect(ctx).await?;
+ let nonce = format!("delete-{suffix}");
+ delete_message_via(
+ &ctx.http,
+ &ctx.world.services,
+ &ctx.api,
+ &ctx.users.actor_token,
+ &channel.id,
+ &root.id,
+ &nonce,
+ )
+ .await
+ .with_context(|| format!("{} delete", ctx.api.label()))?;
+ assert_db_message_deleted(&ctx.pool, &root.id).await?;
+
+ for event in listeners
+ .wait_for_all(
+ "comms_message",
+ |data| {
+ data.get("id").and_then(Value::as_str) == Some(root.id.as_str())
+ && data.get("nonce").and_then(Value::as_str) == Some(nonce.as_str())
+ },
+ "delete realtime message",
+ )
+ .await?
+ {
+ ensure!(
+ !event
+ .data
+ .get("deleted_at")
+ .unwrap_or(&Value::Null)
+ .is_null(),
+ "{} {} delete payload missing deleted_at: {}",
+ ctx.api.label(),
+ event.label,
+ event.data
+ );
+ }
+
+ listeners.close().await;
+ Ok(())
+}
+
+#[derive(Debug, Deserialize)]
+struct CreateChannelResponse {
+ id: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct MessageMutationResponse {
+ id: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct GetOrCreateResponse {
+ channel_id: String,
+ action: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct GatewayMessage {
+ #[serde(rename = "type")]
+ message_type: String,
+ data: String,
+}
+
+struct TestWorld {
+ config: LocalE2eConfig,
+ seed: LocalE2eSeed,
+ services: LocalE2eServices,
+}
+
+impl TestWorld {
+ fn load() -> anyhow::Result<Self> {
+ let config = LocalE2eConfig::load()?;
+ let seed = LocalE2eSeed::from_config(&config)?;
+ let services = LocalE2eServices::from_config(&config)?;
+ Ok(Self {
+ config,
+ seed,
+ services,
+ })
+ }
+
+ fn token_for(&self, user: &SeedUser) -> anyhow::Result<String> {
+ encode_local_jwt_with(&self.config, LocalJwtOptions::new(user))
+ }
+}
+
+struct PostMessageBody<'a> {
+ content: &'a str,
+ mentions: Vec<Value>,
+ thread_id: Option<&'a str>,
+ attachments: Vec<Value>,
+ nonce: &'a str,
+}
+
+async fn create_channel_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ name: String,
+ channel_type: &str,
+ participants: &[&str],
+) -> anyhow::Result<CreateChannelResponse> {
+ let response = http
+ .post(api.create_channel_url())
+ .bearer_auth(token)
+ .json(&json!({
+ "name": name,
+ "channel_type": channel_type,
+ "team_id": null,
+ "participants": participants,
+ }))
+ .send()
+ .await
+ .context("failed to create channel")?;
+ require_success(response, "create channel")
+ .await?
+ .json()
+ .await
+ .context("failed to decode create channel response")
+}
+
+async fn patch_channel_name_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+ channel_name: &str,
+) -> anyhow::Result<()> {
+ require_success(
+ http.patch(api.channel_url(channel_id))
+ .bearer_auth(token)
+ .json(&json!({ "channel_name": channel_name }))
+ .send()
+ .await
+ .context("failed to patch channel name")?,
+ "patch channel",
+ )
+ .await?;
+ Ok(())
+}
+
+async fn add_participants_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+ participants: &[&str],
+) -> anyhow::Result<()> {
+ require_success(
+ http.post(api.channel_participants_url(channel_id))
+ .bearer_auth(token)
+ .json(&json!({ "participants": participants }))
+ .send()
+ .await
+ .context("failed to add participants")?,
+ "add participants",
+ )
+ .await?;
+ Ok(())
+}
+
+async fn remove_participants_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+ participants: &[&str],
+) -> anyhow::Result<()> {
+ require_success(
+ http.request(Method::DELETE, api.channel_participants_url(channel_id))
+ .bearer_auth(token)
+ .json(&json!({ "participants": participants }))
+ .send()
+ .await
+ .context("failed to remove participants")?,
+ "remove participants",
+ )
+ .await?;
+ Ok(())
+}
+
+async fn delete_channel_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+) -> anyhow::Result<()> {
+ require_success(
+ http.delete(api.channel_url(channel_id))
+ .bearer_auth(token)
+ .send()
+ .await
+ .context("failed to delete channel")?,
+ "delete channel",
+ )
+ .await?;
+ Ok(())
+}
+
+async fn post_message_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+ body: &PostMessageBody<'_>,
+) -> anyhow::Result<MessageMutationResponse> {
+ let response = http
+ .post(api.post_channel_message_url(channel_id))
+ .bearer_auth(token)
+ .json(&json!({
+ "content": body.content,
+ "mentions": body.mentions,
+ "thread_id": body.thread_id,
+ "attachments": body.attachments,
+ "nonce": body.nonce,
+ }))
+ .send()
+ .await
+ .context("failed to post channel message")?;
+ require_success(response, "post channel message")
+ .await?
+ .json()
+ .await
+ .context("failed to decode post message response")
+}
+
+async fn patch_message_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+ message_id: &str,
+ body: &Value,
+) -> anyhow::Result<()> {
+ require_success(
+ http.patch(api.channel_message_url(channel_id, message_id))
+ .bearer_auth(token)
+ .json(body)
+ .send()
+ .await
+ .context("failed to patch message")?,
+ "patch message",
+ )
+ .await?;
+ Ok(())
+}
+
+async fn post_reaction_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+ message_id: &str,
+ emoji: &str,
+ action: &str,
+ nonce: &str,
+) -> anyhow::Result<()> {
+ require_success(
+ http.post(api.post_channel_reaction_url(channel_id))
+ .bearer_auth(token)
+ .json(&json!({
+ "emoji": emoji,
+ "message_id": message_id,
+ "action": action,
+ "nonce": nonce,
+ }))
+ .send()
+ .await
+ .context("failed to post reaction")?,
+ "post reaction",
+ )
+ .await?;
+ Ok(())
+}
+
+async fn post_typing_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+ action: &str,
+ thread_id: Option<&str>,
+ nonce: &str,
+) -> anyhow::Result<()> {
+ require_success(
+ http.post(api.post_channel_typing_url(channel_id))
+ .bearer_auth(token)
+ .json(&json!({
+ "action": action,
+ "thread_id": thread_id,
+ "nonce": nonce,
+ }))
+ .send()
+ .await
+ .context("failed to post typing")?,
+ "post typing",
+ )
+ .await?;
+ Ok(())
+}
+
+async fn delete_message_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+ message_id: &str,
+ nonce: &str,
+) -> anyhow::Result<()> {
+ require_success(
+ http.delete(format!(
+ "{}?nonce={nonce}",
+ api.channel_message_url(channel_id, message_id)
+ ))
+ .bearer_auth(token)
+ .send()
+ .await
+ .context("failed to delete message")?,
+ "delete message",
+ )
+ .await?;
+ Ok(())
+}
+
+async fn get_or_create_dm_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ recipient_id: &str,
+) -> anyhow::Result<GetOrCreateResponse> {
+ let response = http
+ .post(api.get_or_create_dm_url())
+ .bearer_auth(token)
+ .json(&json!({ "recipient_id": recipient_id }))
+ .send()
+ .await
+ .context("failed to get or create DM")?;
+ require_success(response, "get or create DM")
+ .await?
+ .json()
+ .await
+ .context("failed to decode DM response")
+}
+
+async fn get_or_create_private_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ recipients: &[&str],
+) -> anyhow::Result<GetOrCreateResponse> {
+ let response = http
+ .post(api.get_or_create_private_url())
+ .bearer_auth(token)
+ .json(&json!({ "recipients": recipients }))
+ .send()
+ .await
+ .context("failed to get or create private channel")?;
+ require_success(response, "get or create private")
+ .await?
+ .json()
+ .await
+ .context("failed to decode private-channel response")
+}
+
+async fn get_channel_via(
+ http: &Client,
+ _services: &LocalE2eServices,
+ api: &ChannelApiClient,
+ token: &str,
+ channel_id: &str,
+) -> anyhow::Result<Value> {
+ let response = http
+ .get(format!("{}?limit=50", api.read_channel_url(channel_id)))
+ .bearer_auth(token)
+ .send()
+ .await
+ .with_context(|| format!("failed to GET channel {channel_id}"))?;
+ require_success(response, "get channel")
+ .await?
+ .json()
+ .await
+ .with_context(|| format!("failed to decode channel {channel_id}"))
+}
+
+async fn connect_db(config: &LocalE2eConfig) -> anyhow::Result<PgPool> {
+ let database_url = config
+ .get("LOCAL_E2E_DATABASE_URL")
+ .unwrap_or(DEFAULT_LOCAL_DATABASE_URL)
+ .replace("@postgres:", "@localhost:");
+ PgPoolOptions::new()
+ .max_connections(2)
+ .connect(&database_url)
+ .await
+ .context("failed to connect to postgres for verification")
+}
+
+async fn db_now(pool: &PgPool) -> anyhow::Result<String> {
+ sqlx::query_scalar::<_, String>("SELECT now()::text")
+ .fetch_one(pool)
+ .await
+ .context("failed to read database clock")
+}
+
+async fn assert_db_channel(
+ pool: &PgPool,
+ channel_id: &str,
+ expected_name: Option<&str>,
+ expected_type: &str,
+) -> anyhow::Result<()> {
+ let channel_id = Uuid::parse_str(channel_id).context("failed to parse channel id")?;
+ let row = sqlx::query_as::<_, (Option<String>, String)>(
+ r#"
+ SELECT name, channel_type::text
+ FROM comms_channels
+ WHERE id = $1
+ "#,
+ )
+ .bind(channel_id)
+ .fetch_optional(pool)
+ .await
+ .context("failed to query channel row")?;
+ let Some((actual_name, actual_type)) = row else {
+ anyhow::bail!("channel {channel_id} was not found in db");
+ };
+ ensure!(
+ actual_name.as_deref() == expected_name && actual_type == expected_type,
+ "channel {channel_id} persisted as name {actual_name:?}, type {actual_type}; expected name {expected_name:?}, type {expected_type}"
+ );
+ Ok(())
+}
+
+async fn assert_db_channel_absent(pool: &PgPool, channel_id: &str) -> anyhow::Result<()> {
+ let channel_id = Uuid::parse_str(channel_id).context("failed to parse channel id")?;
+ let exists =
+ sqlx::query_scalar::<_, bool>("SELECT EXISTS (SELECT 1 FROM comms_channels WHERE id = $1)")
+ .bind(channel_id)
+ .fetch_one(pool)
+ .await
+ .context("failed to query deleted channel row")?;
+ ensure!(!exists, "channel {channel_id} still exists in db");
+ Ok(())
+}
+
+async fn assert_db_participants_include(
+ pool: &PgPool,
+ channel_id: &str,
+ user_ids: &[&str],
+) -> anyhow::Result<()> {
+ for user_id in user_ids {
+ assert_db_participant(pool, channel_id, user_id, true).await?;
+ }
+ Ok(())
+}
+
+async fn assert_db_participants_absent(
+ pool: &PgPool,
+ channel_id: &str,
+ user_ids: &[&str],
+) -> anyhow::Result<()> {
+ for user_id in user_ids {
+ assert_db_participant(pool, channel_id, user_id, false).await?;
+ }
+ Ok(())
+}
+
+async fn assert_db_participant(
+ pool: &PgPool,
+ channel_id: &str,
+ user_id: &str,
+ expected_present: bool,
+) -> anyhow::Result<()> {
+ let channel_id = Uuid::parse_str(channel_id).context("failed to parse channel id")?;
+ let exists = sqlx::query_scalar::<_, bool>(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM comms_channel_participants
+ WHERE channel_id = $1 AND user_id = $2
+ )
+ "#,
+ )
+ .bind(channel_id)
+ .bind(user_id)
+ .fetch_one(pool)
+ .await
+ .context("failed to query channel participant")?;
+ ensure!(
+ exists == expected_present,
+ "participant {user_id} presence for channel {channel_id} was {exists}, expected {expected_present}"
+ );
+ Ok(())
+}
+
+async fn assert_db_message(
+ pool: &PgPool,
+ message_id: &str,
+ channel_id: &str,
+ sender_id: &str,
+ content: &str,
+ thread_id: Option<&str>,
+) -> anyhow::Result<()> {
+ let message_id = Uuid::parse_str(message_id).context("failed to parse message id")?;
+ let channel_id = Uuid::parse_str(channel_id).context("failed to parse channel id")?;
+ let thread_id = thread_id
+ .map(Uuid::parse_str)
+ .transpose()
+ .context("failed to parse thread id")?;
+ let exists = sqlx::query_scalar::<_, bool>(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM comms_messages
+ WHERE id = $1
+ AND channel_id = $2
+ AND sender_id = $3
+ AND content = $4
+ AND thread_id IS NOT DISTINCT FROM $5
+ AND deleted_at IS NULL
+ )
+ "#,
+ )
+ .bind(message_id)
+ .bind(channel_id)
+ .bind(sender_id)
+ .bind(content)
+ .bind(thread_id)
+ .fetch_one(pool)
+ .await
+ .context("failed to query message row")?;
+ ensure!(
+ exists,
+ "message {message_id} did not match expected persisted state"
+ );
+ Ok(())
+}
+
+async fn assert_db_message_content(
+ pool: &PgPool,
+ message_id: &str,
+ content: &str,
+) -> anyhow::Result<()> {
+ let message_id = Uuid::parse_str(message_id).context("failed to parse message id")?;
+ let exists = sqlx::query_scalar::<_, bool>(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM comms_messages
+ WHERE id = $1 AND content = $2 AND edited_at IS NOT NULL AND deleted_at IS NULL
+ )
+ "#,
+ )
+ .bind(message_id)
+ .bind(content)
+ .fetch_one(pool)
+ .await
+ .context("failed to query edited message row")?;
+ ensure!(
+ exists,
+ "message {message_id} did not persist edited content"
+ );
+ Ok(())
+}
+
+async fn assert_db_message_deleted(pool: &PgPool, message_id: &str) -> anyhow::Result<()> {
+ let message_id = Uuid::parse_str(message_id).context("failed to parse message id")?;
+ let exists = sqlx::query_scalar::<_, bool>(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM comms_messages
+ WHERE id = $1 AND content = '' AND deleted_at IS NOT NULL
+ )
+ "#,
+ )
+ .bind(message_id)
+ .fetch_one(pool)
+ .await
+ .context("failed to query deleted message row")?;
+ ensure!(
+ exists,
+ "message {message_id} did not persist tombstone state"
+ );
+ Ok(())
+}
+
+async fn assert_db_attachment_count(
+ pool: &PgPool,
+ message_id: &str,
+ expected_count: i64,
+) -> anyhow::Result<()> {
+ let message_id = Uuid::parse_str(message_id).context("failed to parse message id")?;
+ let count = sqlx::query_scalar::<_, i64>(
+ "SELECT COUNT(*) FROM comms_attachments WHERE message_id = $1",
+ )
+ .bind(message_id)
+ .fetch_one(pool)
+ .await
+ .context("failed to query attachment count")?;
+ ensure!(
+ count == expected_count,
+ "message {message_id} attachment count was {count}, expected {expected_count}"
+ );
+ Ok(())
+}
+
+async fn assert_db_document_channel_share_permission(
+ pool: &PgPool,
+ document_id: &str,
+ channel_id: &str,
+) -> anyhow::Result<()> {
+ let share_permission_id = sqlx::query_scalar::<_, String>(
+ r#"
+ SELECT dp."sharePermissionId"
+ FROM "DocumentPermission" dp
+ WHERE dp."documentId" = $1
+ "#,
+ )
+ .bind(document_id)
+ .fetch_one(pool)
+ .await
+ .with_context(|| {
+ format!("failed to query document share permission for document {document_id}")
+ })?;
+
+ let channel_share_permission_exists = sqlx::query_scalar::<_, bool>(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM "ChannelSharePermission"
+ WHERE "share_permission_id" = $1
+ AND "channel_id" = $2
+ AND "access_level"::text = 'view'
+ )
+ "#,
+ )
+ .bind(&share_permission_id)
+ .bind(channel_id)
+ .fetch_one(pool)
+ .await
+ .context("failed to query channel share permission row")?;
+ ensure!(
+ channel_share_permission_exists,
+ "document {document_id} share permission {share_permission_id} was not granted to channel {channel_id}"
+ );
+
+ let document_uuid = Uuid::parse_str(document_id).context("failed to parse document id")?;
+ let entity_access_exists = sqlx::query_scalar::<_, bool>(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM entity_access
+ WHERE entity_id = $1
+ AND entity_type = 'document'
+ AND source_id = $2
+ AND source_type::text = 'channel'
+ AND access_level::text = 'view'
+ AND granted_from_project_id IS NULL
+ )
+ "#,
+ )
+ .bind(document_uuid)
+ .bind(channel_id)
+ .fetch_one(pool)
+ .await
+ .context("failed to query document channel entity access row")?;
+ ensure!(
+ entity_access_exists,
+ "document {document_id} did not receive view entity_access from channel {channel_id}"
+ );
+
+ Ok(())
+}
+
+async fn assert_db_reaction(
+ pool: &PgPool,
+ message_id: &str,
+ emoji: &str,
+ user_id: &str,
+) -> anyhow::Result<()> {
+ let message_id = Uuid::parse_str(message_id).context("failed to parse message id")?;
+ let exists = sqlx::query_scalar::<_, bool>(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM comms_reactions
+ WHERE message_id = $1 AND emoji = $2 AND user_id = $3
+ )
+ "#,
+ )
+ .bind(message_id)
+ .bind(emoji)
+ .bind(user_id)
+ .fetch_one(pool)
+ .await
+ .context("failed to query reaction row")?;
+ ensure!(
+ exists,
+ "reaction {emoji} by {user_id} missing for message {message_id}"
+ );
+ Ok(())
+}
+
+async fn wait_for_contacts_connections(
+ pool: &PgPool,
+ pairs: &[(&str, &str)],
+ updated_after: &str,
+) -> anyhow::Result<()> {
+ let deadline = Instant::now() + CONTACTS_TIMEOUT;
+ loop {
+ let mut missing = Vec::new();
+ for (a, b) in pairs {
+ if !contact_connection_updated_after(pool, a, b, updated_after).await? {
+ missing.push(format!("{a}<->{b}"));
+ }
+ }
+ if missing.is_empty() {
+ return Ok(());
+ }
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ ensure!(
+ !remaining.is_zero(),
+ "timed out waiting for contacts connections updated after {updated_after}; missing {}",
+ missing.join(", ")
+ );
+ tokio::time::sleep(remaining.min(Duration::from_millis(500))).await;
+ }
+}
+
+async fn contact_connection_updated_after(
+ pool: &PgPool,
+ a: &str,
+ b: &str,
+ updated_after: &str,
+) -> anyhow::Result<bool> {
+ sqlx::query_scalar::<_, bool>(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM contacts_connections
+ WHERE (
+ (user1 = $1 AND user2 = $2)
+ OR (user1 = $2 AND user2 = $1)
+ )
+ AND updated_at >= $3::timestamptz
+ )
+ "#,
+ )
+ .bind(a)
+ .bind(b)
+ .bind(updated_after)
+ .fetch_one(pool)
+ .await
+ .context("failed to query contacts connection")
+}
+
+async fn require_success(response: Response, context: &str) -> anyhow::Result<Response> {
+ if response.status().is_success() {
+ return Ok(response);
+ }
+
+ let status = response.status();
+ let body = response.text().await.unwrap_or_default();
+ anyhow::bail!("{context} failed with {status}: {body}")
+}
+
+fn assert_participant(channel: &Value, user_id: &str) -> anyhow::Result<()> {
+ ensure!(
+ participant_ids(channel)?.any(|id| id == user_id),
+ "expected participant {user_id} in channel response: {channel}"
+ );
+ Ok(())
+}
+
+fn participant_ids(channel: &Value) -> anyhow::Result<impl Iterator<Item = &str>> {
+ let participants = channel
+ .get("participants")
+ .and_then(Value::as_array)
+ .context("channel response did not include participants array")?;
+ Ok(participants
+ .iter()
+ .filter_map(|participant| participant.get("user_id").and_then(Value::as_str)))
+}
+
+fn reaction_payload_contains_user(payload: &Value, emoji: &str, user_id: &str) -> bool {
+ payload
+ .get("reactions")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .find(|reaction| reaction.get("emoji").and_then(Value::as_str) == Some(emoji))
+ .and_then(|reaction| reaction.get("users").and_then(Value::as_array))
+ .map(|users| users.iter().any(|user| user.as_str() == Some(user_id)))
+ .unwrap_or(false)
+}
+
+async fn list_notifications(
+ http: &Client,
+ services: &LocalE2eServices,
+ token: &str,
+) -> anyhow::Result<Value> {
+ let response = http
+ .get(format!("{}?limit=100", services.user_notifications_url()))
+ .bearer_auth(token)
+ .send()
+ .await
+ .context("failed to list notifications")?;
+ require_success(response, "list notifications")
+ .await?
+ .json()
+ .await
+ .context("failed to decode notification list")
+}
+
+async fn wait_for_notification<F>(
+ http: &Client,
+ services: &LocalE2eServices,
+ token: &str,
+ matches: F,
+) -> anyhow::Result<Value>
+where
+ F: Fn(&Value) -> bool,
+{
+ let deadline = Instant::now() + NOTIFICATION_TIMEOUT;
+ loop {
+ let notifications = list_notifications(http, services, token).await?;
+ if let Some(notification) = find_notification(&notifications, &matches) {
+ return Ok(notification.clone());
+ }
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ ensure!(!remaining.is_zero(), "timed out waiting for notification");
+ tokio::time::sleep(remaining.min(Duration::from_millis(500))).await;
+ }
+}
+
+fn find_notification<'a, F>(notifications: &'a Value, matches: F) -> Option<&'a Value>
+where
+ F: Fn(&Value) -> bool,
+{
+ notifications
+ .get("items")
+ .and_then(Value::as_array)?
+ .iter()
+ .find(|notification| matches(notification))
+}
+
+fn notification_matches(notification: &Value, tag: &str, channel_id: &str) -> bool {
+ notification
+ .get("notification_metadata")
+ .and_then(|metadata| metadata.get("tag"))
+ .and_then(Value::as_str)
+ == Some(tag)
+ && notification.get("entity_id").and_then(Value::as_str) == Some(channel_id)
+}
+
+fn notification_content<'a>(notification: &'a Value, key: &str) -> Option<&'a str> {
+ notification
+ .get("notification_metadata")
+ .and_then(|metadata| metadata.get("content"))
+ .and_then(|content| content.get(key))
+ .and_then(Value::as_str)
+}
+
+fn assert_sender(notification: &Value, expected_sender: &str) -> anyhow::Result<()> {
+ ensure!(
+ notification.get("sender_id").and_then(Value::as_str) == Some(expected_sender),
+ "notification sender mismatch: {notification}"
+ );
+ Ok(())
+}
+
+async fn ping_and_wait<W, R>(websocket_write: &mut W, websocket_read: &mut R) -> anyhow::Result<()>
+where
+ W: SinkExt<WebsocketMessage> + Unpin,
+ <W as futures::Sink<WebsocketMessage>>::Error: std::error::Error + Send + Sync + 'static,
+ R: StreamExt<Item = Result<WebsocketMessage, WebsocketError>> + Unpin,
+{
+ websocket_write
+ .send(WebsocketMessage::Text("ping".into()))
+ .await
+ .context("failed to send websocket ping")?;
+ wait_for_pong(websocket_read).await
+}
+
+async fn wait_for_pong<S>(websocket_read: &mut S) -> anyhow::Result<()>
+where
+ S: StreamExt<Item = Result<WebsocketMessage, WebsocketError>> + Unpin,
+{
+ loop {
+ let message = next_websocket_message(websocket_read, WEBSOCKET_TIMEOUT).await?;
+ if let WebsocketMessage::Text(text) = message
+ && text == "pong"
+ {
+ return Ok(());
+ }
+ }
+}
+
+async fn wait_for_gateway_event<S, F>(
+ websocket_read: &mut S,
+ expected_type: &str,
+ matches: F,
+) -> anyhow::Result<Value>
+where
+ S: StreamExt<Item = Result<WebsocketMessage, WebsocketError>> + Unpin,
+ F: Fn(&Value) -> bool,
+{
+ let deadline = Instant::now() + WEBSOCKET_TIMEOUT;
+ loop {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ ensure!(
+ !remaining.is_zero(),
+ "timed out waiting for websocket event {expected_type}"
+ );
+
+ let message = next_websocket_message(websocket_read, remaining).await?;
+ let WebsocketMessage::Text(text) = message else {
+ continue;
+ };
+ if text == "pong" {
+ continue;
+ }
+ let Some((message_type, data)) = parse_gateway_message(&text) else {
+ continue;
+ };
+ if message_type == expected_type && matches(&data) {
+ return Ok(data);
+ }
+ }
+}
+
+async fn next_websocket_message<S>(
+ websocket_read: &mut S,
+ duration: Duration,
+) -> anyhow::Result<WebsocketMessage>
+where
+ S: StreamExt<Item = Result<WebsocketMessage, WebsocketError>> + Unpin,
+{
+ timeout(duration, websocket_read.next())
+ .await
+ .context("timed out waiting for websocket message")?
+ .context("websocket closed before expected message")?
+ .context("websocket returned an error")
+}
+
+fn parse_gateway_message(text: &str) -> Option<(String, Value)> {
+ let gateway: GatewayMessage = serde_json::from_str(text).ok()?;
+ let data = serde_json::from_str(&gateway.data).ok()?;
+ Some((gateway.message_type, data))
+}
+
+fn unique_suffix() -> String {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("system clock before unix epoch")
+ .as_nanos()
+ .to_string()
+}
diff --git a/rust/cloud-storage/local_e2e_test_support/src/services.rs b/rust/cloud-storage/local_e2e_test_support/src/services.rs
index e91ac58d55..bcfff06c49 100644
--- a/rust/cloud-storage/local_e2e_test_support/src/services.rs
+++ b/rust/cloud-storage/local_e2e_test_support/src/services.rs
@@ -5,12 +5,14 @@ use crate::LocalE2eConfig;
const DEFAULT_DOCUMENT_STORAGE_URL: &str = "http://localhost:8086";
const DEFAULT_CONNECTION_GATEWAY_WS_URL: &str = "ws://localhost:8082/";
+const DEFAULT_NOTIFICATION_URL: &str = "http://localhost:8089";
/// Host URLs for services used by local E2E tests.
#[derive(Clone, Debug)]
pub struct LocalE2eServices {
document_storage_url: String,
connection_gateway_ws_url: String,
+ notification_url: String,
}
impl LocalE2eServices {
@@ -25,6 +27,11 @@ impl LocalE2eServices {
.get("LOCAL_E2E_CONNECTION_GATEWAY_WS_URL")
.unwrap_or(DEFAULT_CONNECTION_GATEWAY_WS_URL)
.to_owned();
+ let notification_url = trim_trailing_slash(
+ config
+ .get("LOCAL_E2E_NOTIFICATION_URL")
+ .unwrap_or(DEFAULT_NOTIFICATION_URL),
+ );
validate_local_service_url(
&document_storage_url,
@@ -36,10 +43,16 @@ impl LocalE2eServices {
"connection gateway websocket",
&["ws", "wss"],
)?;
+ validate_local_service_url(
+ &notification_url,
+ "notification service",
+ &["http", "https"],
+ )?;
Ok(Self {
document_storage_url,
connection_gateway_ws_url,
+ notification_url,
})
}
@@ -54,10 +67,62 @@ impl LocalE2eServices {
&self.document_storage_url
}
- /// URL for posting a channel message through document storage's comms API.
+ /// Base URL for notification service HTTP endpoints.
+ pub fn notification_url(&self) -> &str {
+ &self.notification_url
+ }
+
+ /// URL for listing user notifications through notification service.
+ pub fn user_notifications_url(&self) -> String {
+ format!("{}/v1/user_notifications", self.notification_url)
+ }
+
+ /// URL for creating channels through document storage's channels hex API.
+ pub fn create_channel_url(&self) -> String {
+ format!("{}/channels", self.document_storage_url)
+ }
+
+ /// URL for get-or-create direct message channel mutations.
+ pub fn get_or_create_dm_url(&self) -> String {
+ format!("{}/channels/get_or_create_dm", self.document_storage_url)
+ }
+
+ /// URL for get-or-create private channel mutations.
+ pub fn get_or_create_private_url(&self) -> String {
+ format!(
+ "{}/channels/get_or_create_private",
+ self.document_storage_url
+ )
+ }
+
+ /// URL for posting a channel message through document storage's channels hex API.
pub fn post_channel_message_url(&self, channel_id: &str) -> String {
format!(
- "{}/comms/channels/{}/message",
+ "{}/channels/{}/message",
+ self.document_storage_url, channel_id
+ )
+ }
+
+ /// URL for patching or deleting a channel message through document storage's channels hex API.
+ pub fn channel_message_url(&self, channel_id: &str, message_id: &str) -> String {
+ format!(
+ "{}/channels/{}/message/{}",
+ self.document_storage_url, channel_id, message_id
+ )
+ }
+
+ /// URL for posting a channel reaction through document storage's channels hex API.
+ pub fn post_channel_reaction_url(&self, channel_id: &str) -> String {
+ format!(
+ "{}/channels/{}/reaction",
+ self.document_storage_url, channel_id
+ )
+ }
+
+ /// URL for posting a channel typing update through document storage's channels hex API.
+ pub fn post_channel_typing_url(&self, channel_id: &str) -> String {
+ format!(
+ "{}/channels/{}/typing",
self.document_storage_url, channel_id
)
}
@@ -70,6 +135,32 @@ impl LocalE2eServices {
)
}
+ /// URL for patching or deleting a channel through document storage's channels hex API.
+ pub fn channel_url(&self, channel_id: &str) -> String {
+ format!("{}/channels/{}", self.document_storage_url, channel_id)
+ }
+
+ /// URL for mutating channel participants through document storage's channels hex API.
+ pub fn channel_participants_url(&self, channel_id: &str) -> String {
+ format!(
+ "{}/channels/{}/participants",
+ self.document_storage_url, channel_id
+ )
+ }
+
+ /// URL for joining a channel through document storage's channels hex API.
+ pub fn join_channel_url(&self, channel_id: &str) -> String {
+ format!("{}/channels/{}/join", self.document_storage_url, channel_id)
+ }
+
+ /// URL for leaving a channel through document storage's channels hex API.
+ pub fn leave_channel_url(&self, channel_id: &str) -> String {
+ format!(
+ "{}/channels/{}/leave",
+ self.document_storage_url, channel_id
+ )
+ }
+
/// Connection gateway websocket URL with a `macro-api-token` query param.
pub fn connection_gateway_ws_url_with_token(&self, token: &str) -> anyhow::Result<String> {
let mut url = Url::parse(&self.connection_gateway_ws_url)
diff --git a/rust/cloud-storage/macro_user_id/Cargo.toml b/rust/cloud-storage/macro_user_id/Cargo.toml
index 2eb92e33b2..deaac36345 100644
--- a/rust/cloud-storage/macro_user_id/Cargo.toml
+++ b/rust/cloud-storage/macro_user_id/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[features]
schema = ["dep:utoipa"]
+sqlx = ["dep:sqlx"]
[dependencies]
cowlike = { path = "../cowlike" }
@@ -14,4 +15,5 @@ nom = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
+sqlx = { workspace = true, optional = true }
utoipa = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/macro_user_id/src/user_id.rs b/rust/cloud-storage/macro_user_id/src/user_id.rs
index ec02faf8d3..b97456ae56 100644
--- a/rust/cloud-storage/macro_user_id/src/user_id.rs
+++ b/rust/cloud-storage/macro_user_id/src/user_id.rs
@@ -173,6 +173,46 @@ impl<'a> From<MacroUserIdStr<'a>> for String {
}
}
+#[cfg(feature = "sqlx")]
+impl<'a> sqlx::Type<sqlx::Postgres> for MacroUserIdStr<'a> {
+ fn type_info() -> sqlx::postgres::PgTypeInfo {
+ <String as sqlx::Type<sqlx::Postgres>>::type_info()
+ }
+
+ fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
+ <String as sqlx::Type<sqlx::Postgres>>::compatible(ty)
+ }
+}
+
+#[cfg(feature = "sqlx")]
+impl<'a> sqlx::postgres::PgHasArrayType for MacroUserIdStr<'a> {
+ fn array_type_info() -> sqlx::postgres::PgTypeInfo {
+ <String as sqlx::postgres::PgHasArrayType>::array_type_info()
+ }
+}
+
+#[cfg(feature = "sqlx")]
+impl<'q> sqlx::Encode<'q, sqlx::Postgres> for MacroUserIdStr<'q> {
+ fn encode_by_ref(
+ &self,
+ buf: &mut sqlx::postgres::PgArgumentBuffer,
+ ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
+ <&str as sqlx::Encode<sqlx::Postgres>>::encode_by_ref(&self.as_ref(), buf)
+ }
+
+ fn size_hint(&self) -> usize {
+ <&str as sqlx::Encode<sqlx::Postgres>>::size_hint(&self.as_ref())
+ }
+}
+
+#[cfg(feature = "sqlx")]
+impl<'r> sqlx::Decode<'r, sqlx::Postgres> for MacroUserIdStr<'static> {
+ fn decode(value: sqlx::postgres::PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
+ let value = <String as sqlx::Decode<sqlx::Postgres>>::decode(value)?;
+ MacroUserIdStr::try_from(value).map_err(Into::into)
+ }
+}
+
impl<'a> CowLike<'a> for MacroUserIdStr<'a> {
type Owned<'b> = MacroUserIdStr<'b>;
diff --git a/rust/cloud-storage/share_permission_db_utils/Cargo.toml b/rust/cloud-storage/share_permission_db_utils/Cargo.toml
new file mode 100644
index 0000000000..6f7ae89110
--- /dev/null
+++ b/rust/cloud-storage/share_permission_db_utils/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+edition = "2024"
+name = "share_permission_db_utils"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+anyhow = { workspace = true }
+entity_access_db_utils = { path = "../entity_access_db_utils" }
+macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid" }
+models_permissions = { path = "../models_permissions" }
+sqlx = { workspace = true }
diff --git a/rust/cloud-storage/share_permission_db_utils/src/lib.rs b/rust/cloud-storage/share_permission_db_utils/src/lib.rs
new file mode 100644
index 0000000000..46de530b4d
--- /dev/null
+++ b/rust/cloud-storage/share_permission_db_utils/src/lib.rs
@@ -0,0 +1,206 @@
+//! Small SQL helpers for `SharePermission` and `ChannelSharePermission` rows.
+
+use anyhow::Context;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use models_permissions::share_permission::access_level::AccessLevel;
+use sqlx::{Executor, PgPool, Postgres};
+
+/// The result of attempting to insert a channel share permission row.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum InsertChannelSharePermissionResult {
+ /// A new row was inserted.
+ Inserted,
+ /// A row for the same share permission and channel already existed.
+ AlreadyExists,
+}
+
+/// Look up the share permission ID for a supported shareable item.
+pub async fn get_share_permission_id<'e, E>(
+ executor: E,
+ item_id: &str,
+ item_type: &str,
+) -> anyhow::Result<String>
+where
+ E: Executor<'e, Database = Postgres>,
+{
+ let share_permission_id = match item_type {
+ "document" => {
+ sqlx::query_scalar!(
+ r#"
+ SELECT dp."sharePermissionId" as "share_permission_id!"
+ FROM "DocumentPermission" dp
+ WHERE dp."documentId" = $1
+ "#,
+ item_id,
+ )
+ .fetch_one(executor)
+ .await?
+ }
+ "chat" => {
+ sqlx::query_scalar!(
+ r#"
+ SELECT cp."sharePermissionId" as "share_permission_id!"
+ FROM "ChatPermission" cp
+ WHERE cp."chatId" = $1
+ "#,
+ item_id,
+ )
+ .fetch_one(executor)
+ .await?
+ }
+ "thread" => {
+ sqlx::query_scalar!(
+ r#"
+ SELECT tp."sharePermissionId" as "share_permission_id!"
+ FROM "EmailThreadPermission" tp
+ WHERE tp."threadId" = $1
+ "#,
+ item_id,
+ )
+ .fetch_one(executor)
+ .await?
+ }
+ "project" => {
+ sqlx::query_scalar!(
+ r#"
+ SELECT pp."sharePermissionId" as "share_permission_id!"
+ FROM "ProjectPermission" pp
+ WHERE pp."projectId" = $1
+ "#,
+ item_id,
+ )
+ .fetch_one(executor)
+ .await?
+ }
+ "call" => {
+ let item_id = macro_uuid::string_to_uuid(item_id)?;
+ sqlx::query_scalar!(
+ r#"
+ SELECT share_permission_id as "share_permission_id!"
+ FROM (
+ SELECT share_permission_id FROM calls WHERE id = $1
+ UNION ALL
+ SELECT share_permission_id FROM call_records WHERE id = $1
+ ) t
+ LIMIT 1
+ "#,
+ item_id,
+ )
+ .fetch_one(executor)
+ .await?
+ }
+ _ => anyhow::bail!("unsupported item type {item_type}"),
+ };
+
+ Ok(share_permission_id)
+}
+
+/// Insert a channel share permission row without mutating an existing row.
+pub async fn insert_channel_share_permission<'e, E>(
+ executor: E,
+ share_permission_id: &str,
+ channel_id: &str,
+ access_level: AccessLevel,
+) -> Result<InsertChannelSharePermissionResult, sqlx::Error>
+where
+ E: Executor<'e, Database = Postgres>,
+{
+ let result = sqlx::query!(
+ r#"
+ INSERT INTO "ChannelSharePermission" ("share_permission_id", "channel_id", "access_level")
+ VALUES ($1, $2, $3)
+ ON CONFLICT ("share_permission_id", "channel_id") DO NOTHING
+ "#,
+ share_permission_id,
+ channel_id,
+ access_level as _,
+ )
+ .execute(executor)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ Ok(InsertChannelSharePermissionResult::AlreadyExists)
+ } else {
+ Ok(InsertChannelSharePermissionResult::Inserted)
+ }
+}
+
+/// Ensure a thread has a share permission and owner entity-access row.
+pub async fn ensure_thread_share_permission(pool: &PgPool, thread_id: &str) -> anyhow::Result<()> {
+ let existing_share_permission_id = sqlx::query_scalar!(
+ r#"
+ SELECT "sharePermissionId" as "share_permission_id!"
+ FROM "EmailThreadPermission"
+ WHERE "threadId" = $1
+ "#,
+ thread_id,
+ )
+ .fetch_optional(pool)
+ .await
+ .context("failed to get email thread permission")?;
+
+ if existing_share_permission_id.is_some() {
+ return Ok(());
+ }
+
+ let thread_uuid = macro_uuid::string_to_uuid(thread_id).context("invalid thread id")?;
+ let owner_id = sqlx::query_scalar!(
+ r#"
+ SELECT l.macro_id as "macro_id!"
+ FROM email_threads t
+ JOIN email_links l ON t.link_id = l.id
+ WHERE t.id = $1
+ "#,
+ thread_uuid,
+ )
+ .fetch_optional(pool)
+ .await
+ .with_context(|| format!("failed to fetch macro_id for thread ID {thread_id}"))?
+ .context("thread not found")?;
+ let owner_id = MacroUserIdStr::parse_from_str(&owner_id)
+ .context("invalid thread owner macro user id")?
+ .into_owned();
+
+ let mut transaction = pool.begin().await.context("failed to start transaction")?;
+ let share_permission_id = sqlx::query_scalar!(
+ r#"
+ INSERT INTO "SharePermission" ("isPublic", "publicAccessLevel", "createdAt", "updatedAt")
+ VALUES (false, NULL, NOW(), NOW())
+ RETURNING id as "id!"
+ "#,
+ )
+ .fetch_one(transaction.as_mut())
+ .await
+ .context("failed to create thread share permission")?;
+
+ sqlx::query!(
+ r#"
+ INSERT INTO "EmailThreadPermission" ("threadId", "sharePermissionId", "userId")
+ VALUES ($1, $2, $3)
+ "#,
+ thread_id,
+ share_permission_id,
+ owner_id.as_ref(),
+ )
+ .execute(transaction.as_mut())
+ .await
+ .context("failed to create email thread permission")?;
+
+ entity_access_db_utils::insert_entity_access_row(
+ &mut transaction,
+ &thread_uuid,
+ entity_access_db_utils::EntityType::EmailThread,
+ owner_id.as_ref(),
+ entity_access_db_utils::EntityAccessSourceType::User,
+ AccessLevel::Owner,
+ )
+ .await
+ .context("failed to insert owner entity access row for thread")?;
+
+ transaction
+ .commit()
+ .await
+ .context("failed to commit thread share permission")?;
+
+ Ok(())
+}