Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
contacts service refactor (#2920)
Sean Ayeb496bb2c89dc
diff --git a/flake.lock b/flake.lockindex 64efb2c72e..94559a65c0 100644--- a/flake.lock+++ b/flake.lock@@ -8,11 +8,11 @@"rust-analyzer-src": "rust-analyzer-src"},"locked": {- "lastModified": 1777279247,- "narHash": "sha256-xuY2eN11OcD7QOgM2IadfWDR8XIzMbYfbn6gMtF1deE=",+ "lastModified": 1777488689,+ "narHash": "sha256-UYE+SRTDdhXz/y9wmtibVyNapdQF7KCKa1w0Aw3bT7U=","owner": "nix-community","repo": "fenix",- "rev": "6f6f1110eaeafbc9aea16d477c311491d0289977",+ "rev": "ed56ade264bdc3294f457b472cb0482fc36f105c","type": "github"},"original": {@@ -41,11 +41,11 @@},"nixpkgs": {"locked": {- "lastModified": 1776877367,- "narHash": "sha256-EHq1/OX139R1RvBzOJ0aMRT3xnWyqtHBRUBuO1gFzjI=",+ "lastModified": 1777268161,+ "narHash": "sha256-bxrdOn8SCOv8tN4JbTF/TXq7kjo9ag4M+C8yzzIRYbE=","owner": "NixOS","repo": "nixpkgs",- "rev": "0726a0ecb6d4e08f6adced58726b95db924cef57",+ "rev": "1c3fe55ad329cbcb28471bb30f05c9827f724c76","type": "github"},"original": {@@ -65,11 +65,11 @@"rust-analyzer-src": {"flake": false,"locked": {- "lastModified": 1776800521,- "narHash": "sha256-f8YJfwAOsLFpIoqZuX3yF69UvMLrkx7iVzMH1pJU7cM=",+ "lastModified": 1777399820,+ "narHash": "sha256-S9efKWyWdEXBxItqalexMVgcWlcVH52GCu4pw3amb0w=","owner": "rust-lang","repo": "rust-analyzer",- "rev": "8954b66d43225e62c92e8bbcc8500191b5cceb1e",+ "rev": "561d1dd862573b5763064f5402511eecce69fc7a","type": "github"},"original": {diff --git a/js/app/packages/service-clients/service-contacts/generated/client.ts b/js/app/packages/service-clients/service-contacts/generated/client.tsindex 4f15819c30..c6010cafd2 100644--- a/js/app/packages/service-clients/service-contacts/generated/client.ts+++ b/js/app/packages/service-clients/service-contacts/generated/client.ts@@ -1,11 +1,14 @@/*** Generated by orval v7.21.0 🍺* Do not edit manually.- * contacts_service+ * contacts* OpenAPI spec version: 0.1.0*/import type { AddContactRequest, GetContactsResponse } from './schemas';+/**+ * @summary GET /contacts handler.+ */export type getContactsResponse200 = {data: GetContactsResponse;status: 200;@@ -63,6 +66,9 @@ export const getContacts = async (} as getContactsResponse;};+/**+ * @summary POST /contacts handler.+ */export type addContactResponse204 = {data: void;status: 204;diff --git a/js/app/packages/service-clients/service-contacts/generated/schemas/addContactRequest.ts b/js/app/packages/service-clients/service-contacts/generated/schemas/addContactRequest.tsindex b451ea56b7..6dc4251bb4 100644--- a/js/app/packages/service-clients/service-contacts/generated/schemas/addContactRequest.ts+++ b/js/app/packages/service-clients/service-contacts/generated/schemas/addContactRequest.ts@@ -1,10 +1,14 @@/*** Generated by orval v7.21.0 🍺* Do not edit manually.- * contacts_service+ * contacts* OpenAPI spec version: 0.1.0*/+/**+ * Request body for POST /contacts.+ */export interface AddContactRequest {+ /** The user ID to add as a contact. */user_id: string;}diff --git a/js/app/packages/service-clients/service-contacts/generated/schemas/getContactsResponse.ts b/js/app/packages/service-clients/service-contacts/generated/schemas/getContactsResponse.tsindex 94e977a211..0a53c7f3b3 100644--- a/js/app/packages/service-clients/service-contacts/generated/schemas/getContactsResponse.ts+++ b/js/app/packages/service-clients/service-contacts/generated/schemas/getContactsResponse.ts@@ -1,10 +1,14 @@/*** Generated by orval v7.21.0 🍺* Do not edit manually.- * contacts_service+ * contacts* OpenAPI spec version: 0.1.0*/+/**+ * Response body for GET /contacts.+ */export interface GetContactsResponse {+ /** The list of contact user IDs. */contacts: string[];}diff --git a/js/app/packages/service-clients/service-contacts/generated/schemas/index.ts b/js/app/packages/service-clients/service-contacts/generated/schemas/index.tsindex 429efeae8f..1bc239a916 100644--- a/js/app/packages/service-clients/service-contacts/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-contacts/generated/schemas/index.ts@@ -1,7 +1,7 @@/*** Generated by orval v7.21.0 🍺* Do not edit manually.- * contacts_service+ * contacts* OpenAPI spec version: 0.1.0*/diff --git a/js/app/packages/service-clients/service-contacts/openapi.json b/js/app/packages/service-clients/service-contacts/openapi.jsonindex de5529c3c0..9fdaed3c21 100644--- a/js/app/packages/service-clients/service-contacts/openapi.json+++ b/js/app/packages/service-clients/service-contacts/openapi.json@@ -1,7 +1,7 @@{"openapi": "3.1.0","info": {- "title": "contacts_service",+ "title": "contacts","description": "","termsOfService": "https://macro.com/terms","license": {@@ -13,6 +13,7 @@"/contacts": {"get": {"tags": ["contacts"],+ "summary": "GET /contacts handler.","operationId": "get_contacts","responses": {"200": {@@ -59,6 +60,7 @@},"post": {"tags": ["contacts"],+ "summary": "POST /contacts handler.","operationId": "add_contact","requestBody": {"content": {@@ -102,22 +104,26 @@"schemas": {"AddContactRequest": {"type": "object",+ "description": "Request body for POST /contacts.","required": ["user_id"],"properties": {"user_id": {- "type": "string"+ "type": "string",+ "description": "The user ID to add as a contact."}}},"GetContactsResponse": {"type": "object",+ "description": "Response body for GET /contacts.","required": ["contacts"],"properties": {"contacts": {"type": "array","items": {"type": "string"- }+ },+ "description": "The list of contact user IDs."}}}diff --git a/js/bun.lock b/js/bun.lockindex 8dc4083836..9a5034f47f 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -836,7 +836,7 @@"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6152009", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6152009"],+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6152009", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6152009", "sha512-XLN+niDA9BkzrxiZqBjYf+DL4TLoMIcI80ypCowacVfrfAjWt0qLwLkzWVUXjD7k3v0DB/G+BP4OLJNkGygHIw=="],"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],@@ -2624,7 +2624,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/rust/cloud-storage/.sqlx/query-58443a6571e2b390002d7a3ba3954182467bb638a6d399b3ea8212d1a026d4fd.json b/rust/cloud-storage/.sqlx/query-58443a6571e2b390002d7a3ba3954182467bb638a6d399b3ea8212d1a026d4fd.jsonnew file mode 100644index 0000000000..41e02b32b7--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-58443a6571e2b390002d7a3ba3954182467bb638a6d399b3ea8212d1a026d4fd.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE contacts_backfill_outbox SET applied_at = now() WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int4"+ ]+ },+ "nullable": []+ },+ "hash": "58443a6571e2b390002d7a3ba3954182467bb638a6d399b3ea8212d1a026d4fd"+}diff --git a/rust/cloud-storage/.sqlx/query-6cde7e3ff4993fc1a8ed1ae8b9d0cb0d1dde7ec2707d52d5d2211d5569d0a949.json b/rust/cloud-storage/.sqlx/query-6cde7e3ff4993fc1a8ed1ae8b9d0cb0d1dde7ec2707d52d5d2211d5569d0a949.jsonnew file mode 100644index 0000000000..1a4d8c724e--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6cde7e3ff4993fc1a8ed1ae8b9d0cb0d1dde7ec2707d52d5d2211d5569d0a949.json@@ -0,0 +1,32 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id, comms_channel_id, user_ids\n FROM contacts_backfill_outbox\n WHERE applied_at IS NULL\n ORDER BY id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Int4"+ },+ {+ "ordinal": 1,+ "name": "comms_channel_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "user_ids",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "6cde7e3ff4993fc1a8ed1ae8b9d0cb0d1dde7ec2707d52d5d2211d5569d0a949"+}diff --git a/rust/cloud-storage/.sqlx/query-9a75ce409d6381b9573792408e43bb128e1db5454ad95f6cbc39b4aa35458341.json b/rust/cloud-storage/.sqlx/query-9a75ce409d6381b9573792408e43bb128e1db5454ad95f6cbc39b4aa35458341.jsondeleted file mode 100644index 19c32d6b4c..0000000000--- a/rust/cloud-storage/.sqlx/query-9a75ce409d6381b9573792408e43bb128e1db5454ad95f6cbc39b4aa35458341.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT user1 AS contact FROM contacts_connections WHERE user2 = $1\n UNION\n SELECT user2 AS contact from contacts_connections WHERE user1 = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "contact",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "9a75ce409d6381b9573792408e43bb128e1db5454ad95f6cbc39b4aa35458341"-}diff --git a/rust/cloud-storage/.sqlx/query-aab8538835af1c079c4864c1a576b3a51049dd104e2306c4596f1ff99ec329c3.json b/rust/cloud-storage/.sqlx/query-aab8538835af1c079c4864c1a576b3a51049dd104e2306c4596f1ff99ec329c3.jsonnew file mode 100644index 0000000000..a77bb0ab76--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-aab8538835af1c079c4864c1a576b3a51049dd104e2306c4596f1ff99ec329c3.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user1 AS contact FROM contacts_connections WHERE user2 = $1\n UNION\n SELECT user2 AS contact FROM contacts_connections WHERE user1 = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "contact",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "aab8538835af1c079c4864c1a576b3a51049dd104e2306c4596f1ff99ec329c3"+}diff --git a/rust/cloud-storage/.sqlx/query-cb99b956db41571415b60886ba181d8767260559ccb0198eb8b7178448673810.json b/rust/cloud-storage/.sqlx/query-cb99b956db41571415b60886ba181d8767260559ccb0198eb8b7178448673810.jsonnew file mode 100644index 0000000000..042ac07422--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-cb99b956db41571415b60886ba181d8767260559ccb0198eb8b7178448673810.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO contacts_connections(user1, user2)\n SELECT * FROM unnest($1::text[], $2::text[])\n ON CONFLICT(user1, user2) DO UPDATE SET updated_at = now()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "cb99b956db41571415b60886ba181d8767260559ccb0198eb8b7178448673810"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 835893d9e1..2e09f00e08 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -296,9 +296,9 @@ dependencies = [[[package]]name = "anyhow"-version = "1.0.95"+version = "1.0.102"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04"+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"[[package]]name = "aquamarine"@@ -2131,6 +2131,7 @@ dependencies = ["comms","comms_db_client","connection_gateway_client",+ "contacts","doppleganger","entity_access","entity_access_db_utils",@@ -2346,14 +2347,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"[[package]]-name = "contacts_db_client"+name = "contacts"version = "0.1.0"dependencies = [- "anyhow",+ "aws-sdk-sqs",+ "axum",+ "axum-extra",+ "http-body-util",+ "macro_auth","macro_db_migrator",+ "macro_middleware",+ "macro_user_id",+ "model_user",+ "rate_limit",+ "redis",+ "reqwest 0.13.3",+ "rootcause","serde",+ "serde_json","sqlx",+ "sqs_worker",+ "tokio",+ "tower 0.5.2","tracing",+ "utoipa",][[package]]@@ -2361,13 +2378,10 @@ name = "contacts_service"version = "0.1.0"dependencies = ["anyhow",- "async-trait","aws-sdk-secretsmanager","aws-sdk-sqs","axum",- "axum-extra",- "connection_gateway_client",- "contacts_db_client",+ "contacts","http-body-util","macro_auth","macro_aws_config",@@ -2377,10 +2391,8 @@ dependencies = ["macro_middleware","macro_user_id","model",- "model_user","rate_limit","redis",- "rootcause","secretsmanager_client","serde","serde_json",@@ -3199,6 +3211,7 @@ dependencies = ["comms_service","connection","connection_gateway_client",+ "contacts","cool_asserts","cowlike","document_sub_type",@@ -3774,6 +3787,7 @@ dependencies = ["chrono","cloudfront_sign","connection_gateway_client",+ "contacts","document_storage_service_client","doppleganger","ego-tree",@@ -4662,7 +4676,7 @@ dependencies = ["futures-sink","futures-util","http 0.2.12",- "indexmap 2.12.1",+ "indexmap 2.14.0","slab","tokio","tokio-util",@@ -4681,7 +4695,7 @@ dependencies = ["futures-core","futures-sink","http 1.3.1",- "indexmap 2.12.1",+ "indexmap 2.14.0","slab","tokio","tokio-util",@@ -4736,6 +4750,12 @@ dependencies = ["foldhash 0.2.0",]+[[package]]+name = "hashbrown"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"+[[package]]name = "hashlink"version = "0.10.0"@@ -5471,12 +5491,12 @@ dependencies = [[[package]]name = "indexmap"-version = "2.12.1"+version = "2.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2"+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"dependencies = ["equivalent",- "hashbrown 0.16.1",+ "hashbrown 0.17.0","serde","serde_core",]@@ -8148,7 +8168,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"dependencies = ["fixedbitset",- "indexmap 2.12.1",+ "indexmap 2.14.0",][[package]]@@ -9303,12 +9323,12 @@ dependencies = [[[package]]name = "rootcause"-version = "0.11.0"+version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "19b2fa24b30d915f807d1a14eb9eb0947fad76d6e63f165f3969e61a2942a928"+checksum = "4fc4bd36159c7ce180fe2de1e5371ef107a2885f0048430f631e78202e2255d4"dependencies = ["hashbrown 0.16.1",- "indexmap 2.12.1",+ "indexmap 2.14.0","rootcause-internals","rustc-hash 2.1.1","triomphe",@@ -9316,9 +9336,9 @@ dependencies = [[[package]]name = "rootcause-internals"-version = "0.11.0"+version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "15e09e790e6a1ade68d035e081be5054b03b9329a7b568ea5707c4395053b778"+checksum = "4d0df4f84d119d09b5c9c9e8db0fe9bfb5b47b04d0bb95b0763cf81bd9baa559"dependencies = ["triomphe",]@@ -9767,7 +9787,7 @@ dependencies = ["email_db_client","futures","http-body-util",- "indexmap 2.12.1",+ "indexmap 2.14.0","item_filters","macro_auth","macro_aws_config",@@ -10141,7 +10161,7 @@ dependencies = ["chrono","hex","indexmap 1.9.3",- "indexmap 2.12.1",+ "indexmap 2.14.0","serde","serde_derive","serde_json",@@ -10579,7 +10599,7 @@ dependencies = ["futures-util","hashbrown 0.15.2","hashlink",- "indexmap 2.12.1",+ "indexmap 2.14.0","log","memchr","native-tls",@@ -10755,7 +10775,6 @@ dependencies = ["chrono","email","futures",- "macro_user_id","model","models_email","models_opensearch",@@ -11437,7 +11456,7 @@ checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9"dependencies = ["futures-core","futures-util",- "indexmap 2.12.1",+ "indexmap 2.14.0","pin-project-lite","slab","sync_wrapper",@@ -11908,7 +11927,7 @@ version = "5.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2fcc29c80c21c31608227e0912b2d7fddba57ad76b606890627ba8ee7964e993"dependencies = [- "indexmap 2.12.1",+ "indexmap 2.14.0","serde","serde_json","utoipa-gen",@@ -12157,7 +12176,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"dependencies = ["anyhow",- "indexmap 2.12.1",+ "indexmap 2.14.0","wasm-encoder","wasmparser",]@@ -12183,7 +12202,7 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"dependencies = ["bitflags 2.11.1","hashbrown 0.15.2",- "indexmap 2.12.1",+ "indexmap 2.14.0","semver",]@@ -12731,7 +12750,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"dependencies = ["anyhow","heck 0.5.0",- "indexmap 2.12.1",+ "indexmap 2.14.0","prettyplease","syn 2.0.98","wasm-metadata",@@ -12762,7 +12781,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"dependencies = ["anyhow","bitflags 2.11.1",- "indexmap 2.12.1",+ "indexmap 2.14.0","log","serde","serde_derive",@@ -12781,7 +12800,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"dependencies = ["anyhow","id-arena",- "indexmap 2.12.1",+ "indexmap 2.14.0","log","semver","serde",@@ -12992,7 +13011,7 @@ dependencies = ["flate2","getrandom 0.3.1","hmac",- "indexmap 2.12.1",+ "indexmap 2.14.0","lzma-rs","memchr","pbkdf2",@@ -13014,7 +13033,7 @@ dependencies = ["arbitrary","crc32fast","flate2",- "indexmap 2.12.1",+ "indexmap 2.14.0","memchr","zopfli",]diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 26fe047cee..427f9e2c89 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -7,6 +7,7 @@ members = ["ai_toolset","analytics_client","anthropic",+ "attachment","authentication_service","authentication_service_client","backfill_entity_access",@@ -20,7 +21,7 @@ members = ["connection_gateway","connection_gateway_client","connection_gateway_models",- "contacts_db_client",+ "contacts","contacts_service","convert_service","cowlike",@@ -77,6 +78,7 @@ members = ["mcp_service","memory","mention_utils",+ "mobile_welcome_email_db_client","model","model_notifications","model_user",@@ -91,7 +93,6 @@ members = ["models_sfs","models_soup","models_team",- "mobile_welcome_email_db_client","name_search","non_empty","notification",@@ -131,17 +132,17 @@ members = ["sync_service_client","system_properties","teams",+ "tools/native_app_server","unfurl_service","upload_extractor_lambda_handler","upload_extractor_lambda_trigger","user_link_cleanup_handler","user_quota","worker_trigger",- "tools/native_app_server", "attachment",][workspace.dependencies]-anyhow = "1.0.93"+anyhow = "1.0.100"askama = "0.14"async-openai = { version = "0.36.1", features = ["byot", "chat-completion", "completions"] }async-stream = "0.3.6"@@ -201,7 +202,7 @@ recursion = "0.5.4"redis = "1.0.3"regex = "1.11.1"reqwest = { version = "0.13", features = ["form", "hickory-dns", "json"] }-rootcause = "0.11"+rootcause = { version = "0.12" }schemars = { version = "1.0.4", features = ["chrono04", "uuid1"] }semver = { version = "1", features = ["serde"] }serde = { version = "1.0.214", features = ["derive"] }@@ -259,8 +260,8 @@ doppleganger = "0.5"js-sys = "0.3"once_cell = "1.21.3"scraper = "0.18"+serde_urlencoded = "0.7.1"strum_macros = "0.27.1"unicode-segmentation = "1.9.0"-serde_urlencoded = "0.7.1"url = "2.5.0"zip = "=2.4.2"diff --git a/rust/cloud-storage/analytics_client/Cargo.toml b/rust/cloud-storage/analytics_client/Cargo.tomlindex 98f13f5d7d..593fb8173d 100644--- a/rust/cloud-storage/analytics_client/Cargo.toml+++ b/rust/cloud-storage/analytics_client/Cargo.toml@@ -1,8 +1,8 @@[package]-edition = "2021"+edition = "2024"name = "analytics_client"-version = "0.1.0"publish = false+version = "0.1.0"[dependencies]chrono = { workspace = true }diff --git a/rust/cloud-storage/comms_service/Cargo.toml b/rust/cloud-storage/comms_service/Cargo.tomlindex 206452153a..173fc6dc5f 100644--- a/rust/cloud-storage/comms_service/Cargo.toml+++ b/rust/cloud-storage/comms_service/Cargo.toml@@ -65,9 +65,9 @@ serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }sqs_client = { path = "../sqs_client", default-features = false, features = [- "contacts","search",] }+contacts = { path = "../contacts" }thiserror = { workspace = true }tokio = { workspace = true }tower = { workspace = true }diff --git a/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs b/rust/cloud-storage/comms_service/src/api/channels/add_participants.rsindex 87e483dd83..981400d73b 100644--- a/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs+++ b/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs@@ -1,3 +1,7 @@+use std::collections::HashSet;++use contacts::domain::ports::ContactsIngress;+use crate::api::channels::create_channel::to_lowercase;use crate::api::context::{AppState, ChannelImpl};use crate::api::extractors::{@@ -129,13 +133,17 @@ pub async fn handler(.iter().map(|p| p.user_id.to_string()).collect();- let sqs_client = &ctx.sqs_client;- sqs_client- .enqueue_contacts_add_participants(- participants.clone(),- channel_participants,- &channel_id.to_string(),- )+ let contacts_users = [participants.clone(), channel_participants]+ .concat()+ .into_iter()+ .map(MacroUserIdStr::try_from)+ .collect::<Result<HashSet<_>, _>>()+ .map_err(|e| {+ tracing::error!(error=?e, "invalid user id for contacts");+ (StatusCode::BAD_REQUEST, "invalid user id".to_string())+ })?;+ ctx.contacts_ingress+ .enqueue_contacts(contacts_users).await.map_err(|e| {tracing::error!(error=?e, "unable to create 'add participant' SQS message");diff --git a/rust/cloud-storage/comms_service/src/api/channels/create_channel.rs b/rust/cloud-storage/comms_service/src/api/channels/create_channel.rsindex a6afc4c1f3..927dca0dba 100644--- a/rust/cloud-storage/comms_service/src/api/channels/create_channel.rs+++ b/rust/cloud-storage/comms_service/src/api/channels/create_channel.rs@@ -1,3 +1,5 @@+use std::collections::HashSet;+use crate::api::context::AppState;use anyhow::Result;use axum::{@@ -6,6 +8,8 @@ use axum::{http::StatusCode,};use comms_db_client::channels::create_channel::{CreateChannelOptions, create_channel};+use contacts::domain::ports::ContactsIngress;+use macro_user_id::user_id::MacroUserIdStr;use model::comms::ChannelType;use model::user::UserContext;use serde::{Deserialize, Serialize};@@ -139,9 +143,20 @@ pub async fn create_channel_handler(// There should always be participants, but better safe than sorryif !participants.is_empty() && req.channel_type == ChannelType::Private {// Contacts: send message create channel SQS message to Contacts Service- let sqs_client = &ctx.sqs_client;- sqs_client- .enqueue_contacts_create_channel(participants_copy.unwrap(), &id.to_string())+ let mut all_users = participants_copy.unwrap_or_default();+ if !all_users.contains(&user_context.user_id) {+ all_users.push(user_context.user_id.clone());+ }+ let contacts_users = all_users+ .into_iter()+ .map(MacroUserIdStr::try_from)+ .collect::<Result<HashSet<_>, _>>()+ .map_err(|e| {+ tracing::error!(error=?e, "invalid user id for contacts");+ (StatusCode::BAD_REQUEST, "invalid user id".to_string())+ })?;+ ctx.contacts_ingress+ .enqueue_contacts(contacts_users).await.map_err(|e| {tracing::error!(error=?e, "unable to create 'add participant' SQS message");diff --git a/rust/cloud-storage/comms_service/src/api/channels/get_or_create_dm.rs b/rust/cloud-storage/comms_service/src/api/channels/get_or_create_dm.rsindex 736c695044..5f51e26ff9 100644--- a/rust/cloud-storage/comms_service/src/api/channels/get_or_create_dm.rs+++ b/rust/cloud-storage/comms_service/src/api/channels/get_or_create_dm.rs@@ -9,6 +9,8 @@ use comms_db_client::channels::{create_channel::{CreateChannelOptions, create_channel},get_dm,};+use contacts::domain::ports::ContactsIngress;+use macro_user_id::user_id::MacroUserIdStr;use model::{comms::{ChannelType, GetOrCreateAction},user::UserContext,@@ -108,12 +110,16 @@ pub async fn handler()})?;// Contacts: create connections- let sqs_client = &ctx.sqs_client;- sqs_client- .enqueue_contacts_create_channel(- vec![user_id.clone(), recipient_id.clone()],- &id.to_string(),- )+ let contacts_users = vec![user_id.clone(), recipient_id.clone()]+ .into_iter()+ .map(MacroUserIdStr::try_from)+ .collect::<Result<std::collections::HashSet<_>, _>>()+ .map_err(|e| {+ tracing::error!(error=?e, "invalid user id for contacts");+ (StatusCode::BAD_REQUEST, "invalid user id".to_string())+ })?;+ ctx.contacts_ingress+ .enqueue_contacts(contacts_users).await.map_err(|e| {tracing::error!(error=?e, "unable to create 'add participant' SQS message");diff --git a/rust/cloud-storage/comms_service/src/api/channels/get_or_create_private.rs b/rust/cloud-storage/comms_service/src/api/channels/get_or_create_private.rsindex 7ea7fd9b17..d3246681f3 100644--- a/rust/cloud-storage/comms_service/src/api/channels/get_or_create_private.rs+++ b/rust/cloud-storage/comms_service/src/api/channels/get_or_create_private.rs@@ -1,5 +1,7 @@use crate::api::channels::create_channel::to_lowercase;use crate::api::context::AppState;+use contacts::domain::ports::ContactsIngress;+use macro_user_id::user_id::MacroUserIdStr;use std::iter;use anyhow::Result;@@ -110,11 +112,18 @@ pub async fn handler("unable to create private channel".to_string(),)})?;- let sqs_client = &ctx.sqs_client;let mut recipients = recipients.clone();recipients.push(user_id.clone());- sqs_client- .enqueue_contacts_create_channel(recipients, &id.to_string())+ let contacts_users = recipients+ .into_iter()+ .map(MacroUserIdStr::try_from)+ .collect::<Result<std::collections::HashSet<_>, _>>()+ .map_err(|e| {+ tracing::error!(error=?e, "invalid user id for contacts");+ (StatusCode::BAD_REQUEST, "invalid user id".to_string())+ })?;+ ctx.contacts_ingress+ .enqueue_contacts(contacts_users).await.map_err(|e| {tracing::error!(error=?e, "unable to create 'add participant' SQS message");diff --git a/rust/cloud-storage/comms_service/src/api/context.rs b/rust/cloud-storage/comms_service/src/api/context.rsindex fc82306945..f172d1e350 100644--- a/rust/cloud-storage/comms_service/src/api/context.rs+++ b/rust/cloud-storage/comms_service/src/api/context.rs@@ -5,6 +5,8 @@ use comms::{outbound::postgres::{comms_repo::PgCommsRepo, user_repo::PgUserRepo},};use connection_gateway_client::client::ConnectionGatewayClient;+use contacts::domain::service::SqsContactsIngress;+use contacts::outbound::ingress::SqsContactsQueue;use entity_access::domain::service::EntityAccessServiceImpl;use entity_access::outbound::PgAccessRepository;use frecency::outbound::postgres::FrecencyPgStorage;@@ -31,6 +33,7 @@ pub struct AppState {pub connection_gateway_client: Arc<ConnectionGatewayClient>,pub notification_ingress_service: Arc<NotificationIngressType>,pub sqs_client: Arc<sqs_client::SQS>,+ pub contacts_ingress: Arc<SqsContactsIngress<SqsContactsQueue>>,pub permissions_token_secret: LocalOrRemoteSecret<DocumentPermissionJwtSecretKey>,pub frecency_storage: FrecencyPgStorage,pub comms_state: CommsRouterState<ChannelImpl>,diff --git a/rust/cloud-storage/connection_gateway_client/src/client/email.rs b/rust/cloud-storage/connection_gateway_client/src/client/email.rsindex 5782c62c77..56d7d8b374 100644--- a/rust/cloud-storage/connection_gateway_client/src/client/email.rs+++ b/rust/cloud-storage/connection_gateway_client/src/client/email.rs@@ -18,16 +18,4 @@ impl ConnectionGatewayClient {).await}-- /// Invalidate a user's contacts cache- #[tracing::instrument(skip(self), err)]- pub async fn invalidate_contacts(&self, user_id: &str) -> anyhow::Result<Vec<MessageReceipt>> {- self.send_message(- "user",- user_id,- "contacts_invalidation".to_string(),- json!({}),- )- .await- }}diff --git a/rust/cloud-storage/contacts/Cargo.toml b/rust/cloud-storage/contacts/Cargo.tomlnew file mode 100644index 0000000000..b69b841e56--- /dev/null+++ b/rust/cloud-storage/contacts/Cargo.toml@@ -0,0 +1,50 @@+[package]+edition = "2024"+name = "contacts"+publish = false+version = "0.1.0"++[features]+axum = [+ "dep:axum",+ "dep:axum-extra",+ "dep:macro_auth",+ "dep:macro_middleware",+ "dep:model_user",+ "dep:rate_limit",+ "dep:redis",+ "dep:utoipa",+]+default = ["axum", "inbound", "outbound", "ports"]+inbound = ["axum", "dep:aws-sdk-sqs", "dep:sqs_worker", "ports"]+outbound = ["dep:aws-sdk-sqs", "dep:reqwest", "dep:sqlx", "ports"]+ports = []++[dependencies]+aws-sdk-sqs = { workspace = true, optional = true }+axum = { workspace = true, optional = true }+axum-extra = { workspace = true, optional = true }+reqwest = { workspace = true, optional = true }+macro_auth = { path = "../macro_auth", optional = true }+macro_middleware = { path = "../macro_middleware", default-features = false, features = [+ "auth",+], optional = true }+macro_user_id = { path = "../macro_user_id" }+rootcause = { workspace = true }+model_user = { path = "../model_user", features = ["axum"], optional = true }+rate_limit = { path = "../rate_limit", features = ["axum"], optional = true }+redis = { workspace = true, optional = true }+serde = { workspace = true }+serde_json = { workspace = true }+sqlx = { workspace = true, optional = true }+sqs_worker = { path = "../sqs_worker", optional = true }+tokio = { workspace = true }+tracing = { workspace = true }+utoipa = { workspace = true, optional = true }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+http-body-util = { workspace = true }+macro_auth = { path = "../macro_auth", features = ["testing"] }+rate_limit = { path = "../rate_limit", features = ["axum", "testing"] }+tower = { workspace = true }diff --git a/rust/cloud-storage/contacts/src/domain.rs b/rust/cloud-storage/contacts/src/domain.rsnew file mode 100644index 0000000000..0d41519162--- /dev/null+++ b/rust/cloud-storage/contacts/src/domain.rs@@ -0,0 +1,6 @@+/// Domain models for contact graphs and users.+pub mod models;+/// Port traits defining boundaries between domain and infrastructure.+pub mod ports;+/// Domain service implementing business logic.+pub mod service;diff --git a/rust/cloud-storage/contacts/src/domain/models.rs b/rust/cloud-storage/contacts/src/domain/models.rsnew file mode 100644index 0000000000..0272718026--- /dev/null+++ b/rust/cloud-storage/contacts/src/domain/models.rs@@ -0,0 +1,4 @@+/// Generic graph data structures (vertices and edges).+pub mod graph;+/// SQS message types for the contacts queue.+pub mod messages;diff --git a/rust/cloud-storage/contacts/src/domain/models/graph.rs b/rust/cloud-storage/contacts/src/domain/models/graph.rsnew file mode 100644index 0000000000..55bf081c13--- /dev/null+++ b/rust/cloud-storage/contacts/src/domain/models/graph.rs@@ -0,0 +1,165 @@+use std::collections::{BTreeSet, HashSet};++/// A vertex in a graph, wrapping some data of type T.+/// This type implements referential eq and hashing+#[derive(Debug)]+pub struct Vertex<'a, T> {+ /// The data stored in this vertex.+ data: &'a T,+}++impl<'a, T> Clone for Vertex<'a, T> {+ fn clone(&self) -> Self {+ *self+ }+}++impl<'a, T> Copy for Vertex<'a, T> {}++impl<'a, T> Vertex<'a, T> {+ /// return the pointer address of the &'a T+ fn address(&self) -> usize {+ let ptr: *const T = self.data;+ ptr as usize+ }+}++impl<'a, T> PartialEq for Vertex<'a, T> {+ fn eq(&self, other: &Self) -> bool {+ std::ptr::eq(self.data, other.data)+ }+}++impl<'a, T> Eq for Vertex<'a, T> {}++impl<'a, T> std::hash::Hash for Vertex<'a, T> {+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {+ let ptr_address = self.address();+ ptr_address.hash(state);+ }+}++impl<'a, T> PartialOrd for Vertex<'a, T> {+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {+ Some(self.cmp(other))+ }+}++impl<'a, T> Ord for Vertex<'a, T> {+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {+ self.address().cmp(&other.address())+ }+}++impl<'a, T> Vertex<'a, T> {+ /// Creates a new vertex with the given data.+ pub fn new(x: &'a T) -> Self {+ Vertex { data: x }+ }++ /// Returns a reference to the vertex's data with the original borrow lifetime.+ pub fn data(&self) -> &'a T {+ self.data+ }+}++/// An edge connecting two vertices in a graph.+#[derive(Debug)]+pub struct Edge<'a, T> {+ /// The first vertex of the edge.+ a: Vertex<'a, T>,+ /// The second vertex of the edge.+ b: Vertex<'a, T>,+}++impl<'a, T> Clone for Edge<'a, T> {+ fn clone(&self) -> Self {+ *self+ }+}++impl<'a, T> Copy for Edge<'a, T> {}++impl<'a, T> PartialEq for Edge<'a, T> {+ fn eq(&self, other: &Self) -> bool {+ let a_eq = self.a == other.a || self.a == other.b;+ let b_eq = self.b == other.b || self.b == other.a;+ a_eq && b_eq+ }+}++impl<'a, T> Eq for Edge<'a, T> {}++impl<'a, T> std::hash::Hash for Edge<'a, T> {+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {+ let a_addr = self.a.address();+ let b_addr = self.b.address();+ match a_addr.cmp(&b_addr) {+ std::cmp::Ordering::Less | std::cmp::Ordering::Equal => {+ a_addr.hash(state);+ b_addr.hash(state);+ }+ std::cmp::Ordering::Greater => {+ b_addr.hash(state);+ a_addr.hash(state);+ }+ }+ }+}++/// A graph of vertices and edges backed by borrowed node data.+pub struct UndirectedGraph<'a, T> {+ nodes: BTreeSet<Vertex<'a, T>>,+ edges: HashSet<Edge<'a, T>>,+}++impl<'a, T> Edge<'a, T> {+ /// return a reference to the inner vertex a+ pub fn a(&self) -> &Vertex<'a, T> {+ &self.a+ }+ /// return a reference to the inner vertex b+ pub fn b(&self) -> &Vertex<'a, T> {+ &self.b+ }+}++impl<'a, T> UndirectedGraph<'a, T> {+ /// Creates a new graph from an iterator of vertices.+ pub fn new(nodes: impl IntoIterator<Item = Vertex<'a, T>>) -> Self {+ UndirectedGraph {+ nodes: nodes.into_iter().collect(),+ edges: HashSet::new(),+ }+ }++ /// Returns an iterator over the graph's edges.+ pub fn edges(&self) -> impl Iterator<Item = Edge<'a, T>> {+ self.edges.iter().copied()+ }++ /// Generates all pairwise edges (complete graph) from a set of vertices.+ pub fn complete(self) -> CompleteUndirectedGraph<'a, T> {+ let UndirectedGraph { nodes, .. } = self;++ let edges = nodes+ .iter()+ .flat_map(|i| nodes.range(i..).map(move |j| (i, j)).skip(1))+ .map(|(i, j)| Edge { a: *i, b: *j })+ .collect();+ CompleteUndirectedGraph(UndirectedGraph { nodes, edges })+ }+}++/// A complete undirected graph where every pair of nodes is connected by an edge.+pub struct CompleteUndirectedGraph<'a, T>(UndirectedGraph<'a, T>);++impl<'a, T> CompleteUndirectedGraph<'a, T> {+ /// return a reference to the inner graph+ pub fn inner(&self) -> &UndirectedGraph<'a, T> {+ &self.0+ }+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/contacts/src/domain/models/graph/test.rs b/rust/cloud-storage/contacts/src/domain/models/graph/test.rsnew file mode 100644index 0000000000..42bce50dcb--- /dev/null+++ b/rust/cloud-storage/contacts/src/domain/models/graph/test.rs@@ -0,0 +1,114 @@+use super::*;+use macro_user_id::user_id::MacroUserIdStr;++#[test]+fn test_init() {+ let a_val: u32 = 1234;+ let b_val: u32 = 5678;+ let graph = UndirectedGraph::new([Vertex::new(&a_val), Vertex::new(&b_val)]).complete();+ let edges: Vec<_> = graph.inner().edges().collect();+ assert_eq!(edges.len(), 1);+ let vals = [*edges[0].a().data(), *edges[0].b().data()];+ assert!(vals.contains(&1234));+ assert!(vals.contains(&5678));+}++#[test]+fn test_generate() {+ let vals: [u32; 4] = [1234, 5678, 6666, 7777];+ let graph = UndirectedGraph::new(vals.iter().map(Vertex::new)).complete();+ let edges: Vec<_> = graph.inner().edges().collect();++ assert_eq!(edges.len(), 6);++ let expected: HashSet<(u32, u32)> = [+ (1234, 5678),+ (1234, 6666),+ (1234, 7777),+ (5678, 6666),+ (5678, 7777),+ (6666, 7777),+ ]+ .into_iter()+ .flat_map(|(a, b)| [(a, b), (b, a)])+ .collect();++ for edge in &edges {+ let a = *edge.a().data();+ let b = *edge.b().data();+ assert!(expected.contains(&(a, b)), "Unexpected edge ({a}, {b})",);+ }+}++#[test]+fn test_vertex_same_ref_eq() {+ let val: u32 = 42;+ let v1 = Vertex::new(&val);+ let v2 = Vertex::new(&val);+ assert_eq!(v1, v2);+}++#[test]+fn test_vertex_different_alloc_neq() {+ let a: u32 = 42;+ let b: u32 = 42;+ let v1 = Vertex::new(&a);+ let v2 = Vertex::new(&b);+ assert_ne!(v1, v2);+}++#[test]+fn test_edge_unordered_eq() {+ let a_val: u32 = 1;+ let b_val: u32 = 2;+ let a = Vertex::new(&a_val);+ let b = Vertex::new(&b_val);+ let e1 = Edge { a, b };+ let e2 = Edge { a: b, b: a };+ assert_eq!(e1, e2);+}++#[test]+fn test_edge_neq() {+ let a_val: u32 = 1;+ let b_val: u32 = 2;+ let c_val: u32 = 3;+ let a = Vertex::new(&a_val);+ let b = Vertex::new(&b_val);+ let c = Vertex::new(&c_val);+ let e1 = Edge { a, b };+ let e2 = Edge { a, b: c };+ assert_ne!(e1, e2);+}++#[test]+fn test_edge_dedup_in_hashset() {+ let a_val: u32 = 1;+ let b_val: u32 = 2;+ let a = Vertex::new(&a_val);+ let b = Vertex::new(&b_val);+ let mut set: HashSet<Edge<u32>> = HashSet::new();+ set.insert(Edge { a, b });+ set.insert(Edge { a: b, b: a });+ assert_eq!(set.len(), 1);+}++#[test]+fn test_complete_graph_pairwise_count() {+ let users: Vec<MacroUserIdStr<'static>> = (0..12)+ .map(|i| MacroUserIdStr::try_from(format!("macro|user{i}@test.com")).unwrap())+ .collect();+ let n = users.len();+ let graph = UndirectedGraph::new(users.iter().map(Vertex::new)).complete();+ let edges: Vec<_> = graph.inner().edges().collect();+ assert_eq!(edges.len(), n * (n - 1) / 2);+ assert!(edges.iter().all(|e| e.a() != e.b()));+}++#[test]+fn test_same_pointer_no_self_edge() {+ let id = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();+ let graph = UndirectedGraph::new([Vertex::new(&id), Vertex::new(&id)]).complete();+ let edges: Vec<_> = graph.inner().edges().collect();+ assert!(edges.is_empty());+}diff --git a/rust/cloud-storage/contacts/src/domain/models/messages.rs b/rust/cloud-storage/contacts/src/domain/models/messages.rsnew file mode 100644index 0000000000..4946cbe141--- /dev/null+++ b/rust/cloud-storage/contacts/src/domain/models/messages.rs@@ -0,0 +1,10 @@+use macro_user_id::user_id::MacroUserIdStr;+use serde::{Deserialize, Serialize};+use std::collections::HashSet;++/// A contacts SQS message carrying the list of user IDs to connect.+#[derive(Serialize, Deserialize, Debug)]+pub struct ContactsNodes {+ /// User IDs whose pairwise connections should be upserted.+ pub users: HashSet<MacroUserIdStr<'static>>,+}diff --git a/rust/cloud-storage/contacts/src/domain/ports.rs b/rust/cloud-storage/contacts/src/domain/ports.rsnew file mode 100644index 0000000000..e3c96b272c--- /dev/null+++ b/rust/cloud-storage/contacts/src/domain/ports.rs@@ -0,0 +1,83 @@+use crate::domain::models::messages::ContactsNodes;+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use sqlx::types::Uuid;+use std::collections::HashSet;++/// Port trait for accessing the contacts data store.+pub trait ContactsRepository: Send + Sync + 'static {+ /// Gets the list of contact user IDs for a given user.+ fn get_contacts(+ &self,+ user_id: MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, Report>> + Send;++ /// Creates connection pairs between users within a transaction.+ fn create_connections(+ &self,+ connections: Vec<(MacroUserIdStr<'_>, MacroUserIdStr<'_>)>,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}++/// Port trait for notifying users about contact changes.+pub trait ContactsNotifier: Send + Sync + 'static {+ /// Invalidates cached contacts for the given user IDs.+ fn invalidate_contacts_for_users(+ &self,+ user_ids: Vec<MacroUserIdStr<'_>>,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}++/// Port trait for publishing a contacts message to the ingress queue.+pub trait ContactsIngressQueue: Send + Sync + 'static {+ /// Publish a contacts message to the queue.+ fn publish(&self, message: ContactsNodes) -> impl Future<Output = Result<(), Report>> + Send;+}++/// Port trait for enqueuing contacts messages for async processing.+pub trait ContactsIngress: Send + Sync + 'static {+ /// Enqueues a set of user IDs to have their pairwise connections upserted.+ fn enqueue_contacts(+ &self,+ users: HashSet<MacroUserIdStr<'static>>,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}++/// Trait for contacts service operations+pub trait ContactsService: Send + Sync + 'static {+ /// Queries a user's contacts.+ fn query_contacts(+ &self,+ user_id: MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, rootcause::Report>> + Send;++ /// Adds a contact connection between n users as a complete graph.+ fn add_contact_nodes(+ &self,+ nodes: ContactsNodes,+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;+}++/// Trait for outbox message processing+pub trait ContactsOutboxService: Send + Sync + 'static {+ /// polls the outbox for non-applied messages and attempts to apply them, marking them as done+ fn poll_outbox(&self) -> impl Future<Output = Result<(), rootcause::Report>> + Send;+}++pub(crate) struct ContactsBackfillOutboxMessage {+ pub(crate) id: u64,+ #[expect(dead_code)]+ pub(crate) channel_id: Uuid,+ pub(crate) channel_participants: HashSet<MacroUserIdStr<'static>>,+}++pub(crate) trait ContactsBackfillOutboxRepo: Send + Sync + 'static {+ fn get_unapplied_messages(+ &self,+ ) -> impl Future<Output = Result<Vec<ContactsBackfillOutboxMessage>, rootcause::Report>> + Send;++ fn mark_message_applied(+ &self,+ id: u64,+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;+}diff --git a/rust/cloud-storage/contacts/src/domain/service.rs b/rust/cloud-storage/contacts/src/domain/service.rsnew file mode 100644index 0000000000..da131a91ac--- /dev/null+++ b/rust/cloud-storage/contacts/src/domain/service.rs@@ -0,0 +1,126 @@+use crate::domain::models::graph::{UndirectedGraph, Vertex};+use crate::domain::models::messages::ContactsNodes;+use crate::domain::ports::{+ ContactsBackfillOutboxRepo, ContactsIngress, ContactsIngressQueue, ContactsNotifier,+ ContactsOutboxService, ContactsRepository, ContactsService,+};+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use std::collections::HashSet;+use std::sync::Arc;+use tracing::instrument;++#[cfg(test)]+mod test;++/// Domain service combining a repository and notifier to manage contacts.+pub struct ContactsDomainService<R, N> {+ /// The contacts repository for data persistence.+ pub repository: R,+ /// The notifier for real-time contact invalidation.+ pub notifier: N,+}++impl<R: ContactsRepository, N: ContactsNotifier> ContactsDomainService<R, N> {+ /// Queries a user's contacts from the repository.+ #[tracing::instrument(err, skip(self))]+ async fn query_contacts(+ &self,+ user_id: MacroUserIdStr<'_>,+ ) -> Result<Vec<MacroUserIdStr<'static>>, rootcause::Report> {+ let mut res = self.repository.get_contacts(user_id.copied()).await?;+ // because the database data is a graph there is no edge from Self<->Self+ // we just aritificially insert self as a special case+ res.push(user_id.into_owned());+ Ok(res)+ }++ /// Processes a contacts SQS message by computing all pairwise connections+ /// from the user list and persisting them.+ #[instrument(err, skip(self))]+ pub(crate) async fn process_message(+ &self,+ msg: ContactsNodes,+ ) -> Result<(), rootcause::Report> {+ let connections: Vec<(MacroUserIdStr<'static>, MacroUserIdStr<'static>)> = {+ let graph = UndirectedGraph::new(msg.users.iter().map(Vertex::new)).complete();+ graph+ .inner()+ .edges()+ .map(|e| (e.a().data().clone(), e.b().data().clone()))+ .collect()+ };++ self.repository.create_connections(connections).await?;++ self.notifier+ .invalidate_contacts_for_users(msg.users.into_iter().collect())+ .await?;+ Ok(())+ }+}++impl<R: ContactsRepository, N: ContactsNotifier> ContactsService for ContactsDomainService<R, N> {+ async fn query_contacts(+ &self,+ user_id: MacroUserIdStr<'_>,+ ) -> Result<Vec<MacroUserIdStr<'static>>, rootcause::Report> {+ self.query_contacts(user_id).await+ }++ async fn add_contact_nodes(&self, nodes: ContactsNodes) -> Result<(), rootcause::Report> {+ self.process_message(nodes).await+ }+}++/// Queue-backed implementation of [`ContactsIngress`].+///+/// Serialises the user set into a [`ContactsMessage`] and publishes it through+/// the provided [`ContactsIngressQueue`]. The heavy lifting (computing pairwise+/// connections, persisting them) is done by the contacts service worker that+/// consumes from that queue.+pub struct SqsContactsIngress<Q> {+ /// The queue used to publish contacts messages.+ pub queue: Q,+}++impl<Q: ContactsIngressQueue> ContactsIngress for SqsContactsIngress<Q> {+ async fn enqueue_contacts(+ &self,+ users: HashSet<MacroUserIdStr<'static>>,+ ) -> Result<(), Report> {+ self.queue.publish(ContactsNodes { users }).await+ }+}++/// Domain service that polls the backfill outbox and applies pending entries.+pub struct ContactsOutboxServiceImpl<O, S> {+ /// The outbox repository for fetching and marking applied messages.+ pub outbox_repo: O,+ /// The inner contacts service used to apply each outbox entry.+ pub inner_service: Arc<S>,+}++impl<O, S> ContactsOutboxService for ContactsOutboxServiceImpl<O, S>+where+ O: ContactsBackfillOutboxRepo,+ S: ContactsService,+{+ async fn poll_outbox(&self) -> Result<(), rootcause::Report> {+ let messages = self.outbox_repo.get_unapplied_messages().await?;+ for message in messages {+ let Ok(()) = self+ .inner_service+ .add_contact_nodes(ContactsNodes {+ users: message.channel_participants,+ })+ .await+ else {+ continue;+ };+ let _ = self.outbox_repo.mark_message_applied(message.id).await;+ }+ Ok(())+ }+}diff --git a/rust/cloud-storage/contacts/src/domain/service/test.rs b/rust/cloud-storage/contacts/src/domain/service/test.rsnew file mode 100644index 0000000000..78d80129f3--- /dev/null+++ b/rust/cloud-storage/contacts/src/domain/service/test.rs@@ -0,0 +1,24 @@+use super::*;++#[test]+fn test_deserialize_connections_message() {+ let input_json = include_str!("../../../tests/fixtures/add_connection.json");+ let msg: Option<ContactsNodes> = serde_json::from_str(input_json).ok();+ assert!(msg.is_some());+ assert_eq!(msg.unwrap().users.len(), 3);+}++fn generate_sqs_message() -> aws_sdk_sqs::types::Message {+ let input_json = include_str!("../../../tests/fixtures/add_connection.json");+ aws_sdk_sqs::types::Message::builder()+ .set_body(Some(input_json.to_string()))+ .build()+}++#[test]+fn test_message_from_aws_sqs() {+ let sqs_message = generate_sqs_message();+ let message = crate::inbound::worker::message_from_sqs(&sqs_message);+ assert!(message.is_some(), "Could not parse body from sqs message");+ assert_eq!(message.unwrap().users.len(), 3);+}diff --git a/rust/cloud-storage/contacts/src/inbound.rs b/rust/cloud-storage/contacts/src/inbound.rsnew file mode 100644index 0000000000..60f1c24bb1--- /dev/null+++ b/rust/cloud-storage/contacts/src/inbound.rs@@ -0,0 +1,6 @@+/// HTTP handlers, router, DTOs, and swagger definitions.+#[cfg(feature = "axum")]+pub mod http;+/// SQS message parsing and worker.+#[cfg(feature = "inbound")]+pub mod worker;diff --git a/rust/cloud-storage/contacts/src/inbound/http.rs b/rust/cloud-storage/contacts/src/inbound/http.rsnew file mode 100644index 0000000000..78ed230123--- /dev/null+++ b/rust/cloud-storage/contacts/src/inbound/http.rs@@ -0,0 +1,188 @@+use crate::domain::models::messages::ContactsNodes;+use crate::domain::ports::ContactsService;+use axum::extract::{FromRequestParts, Json, State};+use axum::http::StatusCode;+use axum::response::IntoResponse;+use axum::routing::get;+use axum::{RequestPartsExt, Router};+use axum_extra::extract::Cached;+use macro_user_id::user_id::MacroUserIdStr;+use model_user::axum_extractor::MacroUserExtractor;+use rate_limit::inbound::{RateLimitExtractable, rate_limit_middleware};+use rate_limit::{RateLimitConfig, RateLimitKey, RateLimitService};+use serde::{Deserialize, Serialize};+use std::collections::HashSet;+use std::sync::Arc;+use std::time::Duration;+use tracing::instrument;+use utoipa::{OpenApi, ToSchema};++/// Response body for GET /contacts.+#[derive(Deserialize, Serialize, Debug, ToSchema)]+pub struct GetContactsResponse {+ /// The list of contact user IDs.+ #[schema(value_type = Vec<String>)]+ pub contacts: Vec<MacroUserIdStr<'static>>,+}++/// Request body for POST /contacts.+#[derive(Deserialize, Serialize, Debug, ToSchema)]+pub struct AddContactRequest {+ /// The user ID to add as a contact.+ #[schema(value_type = String)]+ pub user_id: MacroUserIdStr<'static>,+}++/// GET /contacts handler.+#[utoipa::path(get,+ tag = "contacts",+ operation_id = "get_contacts",+ path = "/contacts",+ responses(+ (status = 200, body=GetContactsResponse),+ (status = 401, body=String),+ (status = 404, body=String),+ (status = 500, body=String)))+]+#[instrument(skip(macro_user_id, contacts), fields(user_id = macro_user_id.as_ref()))]+pub async fn handler<S: ContactsService>(+ State(contacts): State<Arc<S>>,+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,+) -> impl IntoResponse {+ match contacts.query_contacts(macro_user_id).await {+ Ok(contacts) if !contacts.is_empty() => {+ (StatusCode::OK, Json(Some(GetContactsResponse { contacts })))+ }+ Ok(_) => (StatusCode::NOT_FOUND, Json(None)),+ Err(_e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(None)),+ }+}++/// POST /contacts handler.+#[utoipa::path(post,+ tag = "contacts",+ operation_id = "add_contact",+ path = "/contacts",+ request_body = AddContactRequest,+ responses(+ (status = 204),+ (status = 401, body=String),+ (status = 500, body=String)))+]+#[instrument(skip(service, macro_user_id), err)]+pub async fn add_contact_handler<S: ContactsService>(+ State(service): State<Arc<S>>,+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,+ Json(body): Json<AddContactRequest>,+) -> Result<StatusCode, StatusCode> {+ service+ .add_contact_nodes(ContactsNodes {+ users: HashSet::from([macro_user_id, body.user_id]),+ })+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to create contact connection");+ StatusCode::INTERNAL_SERVER_ERROR+ })?;+ Ok(StatusCode::NO_CONTENT)+}++/// Rate limit for adding contacts: 50 requests per user per hour.+pub struct PerUserAddContactRateLimit(MacroUserExtractor);++impl<S> RateLimitExtractable<S> for PerUserAddContactRateLimit+where+ S: Send + Sync,+{+ fn config() -> RateLimitConfig {+ RateLimitConfig {+ max_count: 50,+ window: Duration::from_mins(60),+ }+ }++ fn key(&self) -> RateLimitKey {+ RateLimitKey::builder(&"per-user-add-contact")+ .append(&self.0.macro_user_id.as_ref())+ .finish()+ }+}++impl<S> FromRequestParts<S> for PerUserAddContactRateLimit+where+ S: Send + Sync,+{+ type Rejection = <MacroUserExtractor as FromRequestParts<S>>::Rejection;++ async fn from_request_parts(+ parts: &mut axum::http::request::Parts,+ state: &S,+ ) -> Result<Self, Self::Rejection> {+ let Cached(user): Cached<MacroUserExtractor> = parts.extract_with_state(state).await?;+ Ok(Self(user))+ }+}++/// Builds the contacts API router with rate limiting applied to POST.+pub fn contacts_router<R: RateLimitService + Clone, S: ContactsService>(+ rate_limiter: R,+) -> Router<Arc<S>> {+ let post_route = Router::new()+ .route("/contacts", axum::routing::post(add_contact_handler))+ .layer(axum::middleware::from_fn_with_state(+ rate_limiter,+ rate_limit_middleware::<R, PerUserAddContactRateLimit, R>,+ ));++ Router::new()+ .route("/contacts", get(handler))+ .merge(post_route)+}++/// Builds the full API router with JWT auth middleware and rate limiting.+pub fn api_router<S: ContactsService>(app_state: AppState<S>) -> Router {+ contacts_router(app_state.rate_limit_service.clone())+ .layer(axum::middleware::from_fn_with_state(+ app_state.jwt_args.clone(),+ macro_middleware::auth::decode_jwt::handler,+ ))+ .with_state(app_state.contacts_service)+}++/// Application state for the contacts HTTP service.+pub struct AppState<S> {+ /// The port to listen on.+ pub port: usize,+ /// JWT validation arguments.+ pub jwt_args: macro_auth::middleware::decode_jwt::JwtValidationArgs,+ /// The contacts service instance.+ pub contacts_service: Arc<S>,+ /// The rate limiter service.+ pub rate_limit_service:+ rate_limit::RateLimitServiceImpl<rate_limit::RedisRateLimitAdapter<redis::Client>>,+}++/// OpenAPI documentation.+#[derive(OpenApi)]+#[openapi(+ info(+ terms_of_service = "https://macro.com/terms",+ ),+ paths(+ handler,+ add_contact_handler,+ ),+ components(+ schemas(+ GetContactsResponse,+ AddContactRequest,+ ),+ ),+ tags(+ (name = "macro contacts service", description = "Contacts Service")+ )+ )]+pub struct ApiDoc;++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/contacts/src/inbound/http/test.rs b/rust/cloud-storage/contacts/src/inbound/http/test.rsnew file mode 100644index 0000000000..2712f75e55--- /dev/null+++ b/rust/cloud-storage/contacts/src/inbound/http/test.rs@@ -0,0 +1,230 @@+use super::*;+use axum::{Extension, body::Body, http::Request};+use http_body_util::BodyExt;+use model_user::UserContext;+use rate_limit::{+ RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult, RateLimitServiceImpl,+ domain::models::RateLimitOk,+};+use rootcause::Report;+use std::collections::HashSet;+use tower::ServiceExt;++#[derive(Clone, Debug)]+struct MockService;++impl ContactsService for MockService {+ async fn query_contacts(+ &self,+ user_id: MacroUserIdStr<'_>,+ ) -> Result<Vec<MacroUserIdStr<'static>>, rootcause::Report> {+ if user_id.as_ref() == "macro|[email protected]" {+ let contacts = [+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ ]+ .into_iter()+ .map(|s| MacroUserIdStr::try_from(s.to_string()).unwrap())+ .collect();+ return Ok(contacts);+ } else if user_id.as_ref() == "macro|[email protected]" {+ let contacts = [+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ ]+ .into_iter()+ .map(|s| MacroUserIdStr::try_from(s.to_string()).unwrap())+ .collect();+ return Ok(contacts);+ }++ Ok(vec![])+ }++ async fn add_contact_nodes(&self, _nodes: ContactsNodes) -> Result<(), rootcause::Report> {+ Ok(())+ }+}++#[derive(Clone)]+struct MockRateLimitPort {+ should_exceed: bool,+}++impl rate_limit::RateLimitPort for MockRateLimitPort {+ async fn check(+ &self,+ key: RateLimitKey,+ config: RateLimitConfig,+ ) -> Result<RateLimitResult, Report> {+ if self.should_exceed {+ Ok(Err(RateLimitExceeded {+ current_count: config.max_count.saturating_add(1),+ max_count: config.max_count,+ retry_after: config.window,+ }))+ } else {+ Ok(Ok(RateLimitOk::new_testing_value(0, key, config)))+ }+ }++ async fn decrement(&self, _key: &RateLimitKey) -> Result<(), Report> {+ Ok(())+ }+}++fn allowing_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {+ RateLimitServiceImpl {+ repo: MockRateLimitPort {+ should_exceed: false,+ },+ }+}++fn exceeding_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {+ RateLimitServiceImpl {+ repo: MockRateLimitPort {+ should_exceed: true,+ },+ }+}++fn mock_service() -> Arc<MockService> {+ Arc::new(MockService)+}++fn test_user_context(user_id: &str) -> UserContext {+ UserContext {+ user_id: user_id.to_string(),+ permissions: None,+ organization_id: None,+ fusion_user_id: "".to_string(),+ }+}++fn build_test_router(+ rate_limiter: RateLimitServiceImpl<MockRateLimitPort>,+ user_id: &str,+) -> Router {+ contacts_router(rate_limiter)+ .with_state(mock_service())+ .layer(Extension(test_user_context(user_id)))+}++#[tokio::test]+async fn test_get_contact() {+ let user_id = "macro|[email protected]";+ let api = build_test_router(allowing_rate_limiter(), user_id);++ let response = api+ .oneshot(+ Request::builder()+ .uri("/contacts")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let body = response.into_body().collect().await.unwrap().to_bytes();+ let body: GetContactsResponse = serde_json::from_slice(&body).unwrap();++ let contact_list: HashSet<&str> = [+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ ]+ .into_iter()+ .collect();++ assert_eq!(body.contacts.len(), 3, "Not enough contacts");+ for contact in &body.contacts {+ assert!(+ contact_list.contains(contact.as_ref()),+ "Could not find contact: {}",+ contact.as_ref()+ );+ }+}++#[tokio::test]+async fn test_get_contact_not_found() {+ let user_id = "macro|[email protected]";+ let api = build_test_router(allowing_rate_limiter(), user_id);++ let response = api+ .oneshot(+ Request::builder()+ .uri("/contacts")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn test_add_contact() {+ let user_id = "macro|[email protected]";+ let api = build_test_router(allowing_rate_limiter(), user_id);++ let response = api+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/contacts")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::json!({"user_id": "macro|[email protected]"}).to_string(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::NO_CONTENT);+}++#[tokio::test]+async fn test_add_contact_rate_limited() {+ let user_id = "macro|[email protected]";+ let api = build_test_router(exceeding_rate_limiter(), user_id);++ let response = api+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/contacts")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::json!({"user_id": "macro|[email protected]"}).to_string(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);+}++#[tokio::test]+async fn test_get_not_affected_by_rate_limit() {+ let user_id = "macro|[email protected]";+ let api = build_test_router(exceeding_rate_limiter(), user_id);++ let response = api+ .oneshot(+ Request::builder()+ .uri("/contacts")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+}diff --git a/rust/cloud-storage/contacts/src/inbound/worker.rs b/rust/cloud-storage/contacts/src/inbound/worker.rsnew file mode 100644index 0000000000..623a2002f4--- /dev/null+++ b/rust/cloud-storage/contacts/src/inbound/worker.rs@@ -0,0 +1,127 @@+use std::time::Duration;++use crate::domain::models::messages::ContactsNodes;+use crate::domain::ports::{ContactsNotifier, ContactsOutboxService, ContactsRepository};+use crate::domain::service::ContactsDomainService;+use rootcause::report;+use sqs_worker::SQSWorker;+use tracing::instrument;++/// SQS-based contacts worker that polls for messages and delegates processing+/// to the domain service.+pub struct ContactsWorker<R, N> {+ sqs: SQSWorker,+ service: std::sync::Arc<ContactsDomainService<R, N>>,+}++impl<R: ContactsRepository, N: ContactsNotifier> ContactsWorker<R, N> {+ /// Creates a new worker with the given SQS client and domain service.+ pub fn new(sqs: SQSWorker, service: std::sync::Arc<ContactsDomainService<R, N>>) -> Self {+ Self { sqs, service }+ }++ /// Polls SQS indefinitely, processing each message.+ #[instrument(skip(self))]+ pub async fn poll(&self) {+ tracing::info!("initiated notification worker");+ loop {+ tracing::trace!("polling for messages");+ match self.sqs.receive_messages().await {+ Ok(messages) => {+ if messages.is_empty() {+ tracing::trace!("no messages found");+ continue;+ }+ for message in messages {+ if let Err(e) = self.process_message(&message).await {+ tracing::error!(error=?e, "error processing message");+ }+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "error receiving messages");+ }+ }+ }+ }++ #[instrument(skip(self, message), err)]+ async fn process_message(+ &self,+ message: &aws_sdk_sqs::types::Message,+ ) -> Result<(), rootcause::Report> {+ self.parse_message(message).await?;+ self.cleanup_message(message).await?;+ Ok(())+ }++ #[instrument(skip(sqs_message, self), err)]+ async fn parse_message(+ &self,+ sqs_message: &aws_sdk_sqs::types::Message,+ ) -> Result<(), rootcause::Report> {+ match message_from_sqs(sqs_message) {+ Some(message) => self.service.process_message(message).await,+ None => {+ tracing::warn!(+ message_id=?sqs_message.message_id,+ "SQS message body could not be parsed as ContactsMessage"+ );++ Ok(())+ }+ }+ }++ async fn cleanup_message(+ &self,+ message: &aws_sdk_sqs::types::Message,+ ) -> Result<(), rootcause::Report> {+ if let Some(receipt_handle) = message.receipt_handle.as_ref() {+ tracing::trace!(message_id=?message.message_id, message_receipt_handle=?receipt_handle, "deleting message");+ self.sqs+ .delete_message(receipt_handle)+ .await+ .map_err(|e| report!(e.into_boxed_dyn_error()))?;+ }+ Ok(())+ }+}++/// Parses a JSON string into a [`ContactsMessage`].+fn message_from_json(body: &str) -> Option<ContactsNodes> {+ serde_json::from_str(body).ok()+}++/// Extracts and parses the body from an SQS message.+pub(crate) fn message_from_sqs(msg: &aws_sdk_sqs::types::Message) -> Option<ContactsNodes> {+ msg.body.as_ref().and_then(|body| message_from_json(body))+}++/// Worker that periodically polls the contacts backfill outbox.+pub struct OutboxWorker<S> {+ /// The outbox service to poll.+ pub service: S,+}++impl<S> OutboxWorker<S>+where+ S: ContactsOutboxService,+{+ /// Runs the outbox poll loop indefinitely.+ pub async fn run(&self) -> ! {+ loop {+ let fut = self.service.poll_outbox();+ match tokio::time::timeout(Duration::from_secs(15), fut).await {+ Ok(Ok(())) => {}+ Ok(Err(err)) => {+ tracing::error!(error=?err, "Failed to poll contacts outbox")+ }+ Err(_) => {+ tracing::error!("Contacts worker outbox poll failed due to timeout")+ }+ }+ tokio::time::sleep(Duration::from_secs(1)).await;+ }+ }+}diff --git a/rust/cloud-storage/contacts/src/lib.rs b/rust/cloud-storage/contacts/src/lib.rsnew file mode 100644index 0000000000..7f92c198fc--- /dev/null+++ b/rust/cloud-storage/contacts/src/lib.rs@@ -0,0 +1,13 @@+//! Contacts service library.+//!+//! This crate provides a hexagonal architecture-based contacts system+//! for managing user connections and contact graphs.++#![deny(missing_docs)]++/// Domain layer containing core business logic, models, and port definitions.+pub mod domain;+/// Inbound adapters (HTTP handlers, queue worker).+pub mod inbound;+/// Outbound adapters (database, connection gateway).+pub mod outbound;diff --git a/rust/cloud-storage/contacts/src/outbound.rs b/rust/cloud-storage/contacts/src/outbound.rsnew file mode 100644index 0000000000..ca2e35228e--- /dev/null+++ b/rust/cloud-storage/contacts/src/outbound.rs@@ -0,0 +1,9 @@+/// Connection gateway notifier adapter.+#[cfg(feature = "outbound")]+pub mod gateway;+/// SQS-backed contacts ingress queue adapter.+#[cfg(feature = "outbound")]+pub mod ingress;+/// Database-backed contacts repository.+#[cfg(feature = "outbound")]+pub mod repository;diff --git a/rust/cloud-storage/contacts/src/outbound/gateway.rs b/rust/cloud-storage/contacts/src/outbound/gateway.rsnew file mode 100644index 0000000000..d98920a922--- /dev/null+++ b/rust/cloud-storage/contacts/src/outbound/gateway.rs@@ -0,0 +1,63 @@+use crate::domain::ports::ContactsNotifier;+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;++/// Notifier that sends invalidation messages through the connection gateway.+pub struct ConnectionGatewayNotifier {+ url: String,+ client: reqwest::Client,+}++impl ConnectionGatewayNotifier {+ /// Creates a new notifier with the given gateway URL and internal auth key.+ pub fn new(internal_auth_key: String, url: String) -> Result<Self, Report> {+ let mut headers = reqwest::header::HeaderMap::new();+ headers.insert("x-internal-auth-key", internal_auth_key.parse()?);+ let client = reqwest::Client::builder()+ .default_headers(headers)+ .build()?;+ Ok(Self { url, client })+ }++ #[tracing::instrument(skip(self), err)]+ async fn invalidate_contacts(&self, user_id: &str) -> Result<(), Report> {+ self.client+ .post(format!("{}/message/send/user/{}", self.url, user_id))+ .json(&serde_json::json!({"message_type": "contacts_invalidation", "message": {}}))+ .send()+ .await?+ .error_for_status()?;+ Ok(())+ }+}++impl ContactsNotifier for ConnectionGatewayNotifier {+ async fn invalidate_contacts_for_users(+ &self,+ user_ids: Vec<MacroUserIdStr<'_>>,+ ) -> Result<(), Report> {+ for user_id in user_ids {+ self.invalidate_contacts(user_id.as_ref() as &str)+ .await+ .inspect_err(|e| {+ tracing::error!(user_id = %user_id.as_ref(), error = ?e, "Failed to invalidate contacts")+ })+ .ok();+ }+ Ok(())+ }+}++/// Implements [`ContactsNotifier`] for `Option<ConnectionGatewayNotifier>`,+/// acting as a no-op when `None`.+impl ContactsNotifier for Option<ConnectionGatewayNotifier> {+ async fn invalidate_contacts_for_users(+ &self,+ user_ids: Vec<MacroUserIdStr<'_>>,+ ) -> Result<(), Report> {+ if let Some(notifier) = self {+ notifier.invalidate_contacts_for_users(user_ids).await?;+ }+ Ok(())+ }+}diff --git a/rust/cloud-storage/contacts/src/outbound/ingress.rs b/rust/cloud-storage/contacts/src/outbound/ingress.rsnew file mode 100644index 0000000000..c290d0345f--- /dev/null+++ b/rust/cloud-storage/contacts/src/outbound/ingress.rs@@ -0,0 +1,31 @@+use crate::domain::models::messages::ContactsNodes;+use crate::domain::ports::ContactsIngressQueue;+use rootcause::Report;++/// SQS-backed implementation of [`ContactsIngressQueue`].+#[derive(Clone)]+pub struct SqsContactsQueue {+ client: aws_sdk_sqs::Client,+ queue_url: String,+}++impl SqsContactsQueue {+ /// Creates a new queue adapter pointing at the given SQS queue URL.+ pub fn new(client: aws_sdk_sqs::Client, queue_url: String) -> Self {+ Self { client, queue_url }+ }+}++impl ContactsIngressQueue for SqsContactsQueue {+ #[tracing::instrument(skip(self, message), err)]+ async fn publish(&self, message: ContactsNodes) -> Result<(), Report> {+ let body = serde_json::to_string(&message)?;+ self.client+ .send_message()+ .queue_url(&self.queue_url)+ .message_body(body)+ .send()+ .await?;+ Ok(())+ }+}diff --git a/rust/cloud-storage/contacts/src/outbound/repository.rs b/rust/cloud-storage/contacts/src/outbound/repository.rsnew file mode 100644index 0000000000..ba72af69ec--- /dev/null+++ b/rust/cloud-storage/contacts/src/outbound/repository.rs@@ -0,0 +1,133 @@+#[cfg(test)]+mod test;++use crate::domain::ports::{+ ContactsBackfillOutboxMessage, ContactsBackfillOutboxRepo, ContactsRepository,+};+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use sqlx::PgPool;+use sqlx::types::Uuid;++/// Database-backed implementation of [`ContactsRepository`].+pub struct DbContactsRepository {+ /// The PostgreSQL connection pool.+ pub db: PgPool,+}++impl DbContactsRepository {+ /// Creates a new repository with the given connection pool.+ pub fn new(db: PgPool) -> Self {+ Self { db }+ }+}++impl ContactsRepository for DbContactsRepository {+ async fn get_contacts(+ &self,+ user_id: MacroUserIdStr<'_>,+ ) -> Result<Vec<MacroUserIdStr<'static>>, Report> {+ let rows = sqlx::query!(+ "+ SELECT user1 AS contact FROM contacts_connections WHERE user2 = $1+ UNION+ SELECT user2 AS contact FROM contacts_connections WHERE user1 = $1+ ",+ user_id.as_ref()+ )+ .fetch_all(&self.db)+ .await?;++ Ok(rows+ .into_iter()+ .filter_map(|r| r.contact)+ .filter_map(|s| MacroUserIdStr::try_from(s).ok())+ .collect())+ }++ async fn create_connections(+ &self,+ connections: Vec<(MacroUserIdStr<'_>, MacroUserIdStr<'_>)>,+ ) -> Result<(), Report> {+ let (users1, users2): (Vec<_>, Vec<_>) = connections+ .into_iter()+ .filter(|(a, b)| a.as_ref() != b.as_ref())+ .map(|(a, b)| {+ if a.as_ref() <= b.as_ref() {+ (a, b)+ } else {+ (b, a)+ }+ })+ .unzip();++ let u1: Vec<&str> = users1.iter().map(|u| u.as_ref()).collect();+ let u2: Vec<&str> = users2.iter().map(|u| u.as_ref()).collect();++ sqlx::query!(+ "+ INSERT INTO contacts_connections(user1, user2)+ SELECT * FROM unnest($1::text[], $2::text[])+ ON CONFLICT(user1, user2) DO UPDATE SET updated_at = now()+ ",+ &u1 as &[&str],+ &u2 as &[&str]+ )+ .execute(&self.db)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, "couldn't create connections");+ })?;++ Ok(())+ }+}++struct BackfillOutboxRow {+ id: i32,+ comms_channel_id: Uuid,+ user_ids: serde_json::Value,+}++impl ContactsBackfillOutboxRepo for DbContactsRepository {+ async fn get_unapplied_messages(&self) -> Result<Vec<ContactsBackfillOutboxMessage>, Report> {+ let rows = sqlx::query_as!(+ BackfillOutboxRow,+ "SELECT id, comms_channel_id, user_ids+ FROM contacts_backfill_outbox+ WHERE applied_at IS NULL+ ORDER BY id"+ )+ .fetch_all(&self.db)+ .await?;++ rows.into_iter()+ .map(|r| -> Result<ContactsBackfillOutboxMessage, Report> {+ let user_ids: Vec<String> = serde_json::from_value(r.user_ids)?;+ let channel_participants = user_ids+ .into_iter()+ .map(MacroUserIdStr::try_from)+ .collect::<Result<_, _>>()?;+ Ok(ContactsBackfillOutboxMessage {+ id: r.id as u64,+ channel_id: r.comms_channel_id,+ channel_participants,+ })+ })+ .collect()+ }++ #[tracing::instrument(err, skip(self))]+ async fn mark_message_applied(&self, id: u64) -> Result<(), Report> {+ sqlx::query!(+ "UPDATE contacts_backfill_outbox SET applied_at = now() WHERE id = $1",+ id as i64+ )+ .execute(&self.db)+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "couldn't mark backfill outbox message applied"),+ )?;+ Ok(())+ }+}diff --git a/rust/cloud-storage/contacts/src/outbound/repository/fixtures/user_list.sql b/rust/cloud-storage/contacts/src/outbound/repository/fixtures/user_list.sqlnew file mode 100644index 0000000000..400324a9d9--- /dev/null+++ b/rust/cloud-storage/contacts/src/outbound/repository/fixtures/user_list.sql@@ -0,0 +1,4 @@+INSERT INTO contacts_connections(user1, user2) VALUES+ ('macro|[email protected]', 'macro|[email protected]'),+ ('macro|[email protected]', 'macro|[email protected]'),+ ('macro|[email protected]', 'macro|[email protected]');diff --git a/rust/cloud-storage/contacts/src/outbound/repository/test.rs b/rust/cloud-storage/contacts/src/outbound/repository/test.rsnew file mode 100644index 0000000000..b1abcddaa9--- /dev/null+++ b/rust/cloud-storage/contacts/src/outbound/repository/test.rs@@ -0,0 +1,155 @@+use crate::domain::ports::{ContactsBackfillOutboxRepo, ContactsRepository};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;+use sqlx::types::Uuid;++use super::DbContactsRepository;++fn mid(s: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(s.to_owned()).unwrap()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_create_connections_basic(pool: PgPool) -> sqlx::Result<()> {+ let user1 = "macro|[email protected]";+ let user2 = "macro|[email protected]";+ let repo = DbContactsRepository::new(pool.clone());+ repo.create_connections(vec![(mid(user1), mid(user2))])+ .await+ .unwrap();+ let pair = sqlx::query!("SELECT user1, user2 FROM contacts_connections LIMIT 1")+ .fetch_one(&pool)+ .await?;+ assert_eq!(pair.user1, user1);+ assert_eq!(pair.user2, user2);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_create_connections_ordering(pool: PgPool) -> sqlx::Result<()> {+ let user1 = "macro|[email protected]";+ let user2 = "macro|[email protected]";+ let repo = DbContactsRepository::new(pool.clone());+ repo.create_connections(vec![(mid(user2), mid(user1))])+ .await+ .unwrap();+ let pair = sqlx::query!("SELECT user1, user2 FROM contacts_connections LIMIT 1")+ .fetch_one(&pool)+ .await?;+ assert_eq!(pair.user1, user1);+ assert_eq!(pair.user2, user2);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("user_list"))+)]+async fn test_get_contacts(pool: PgPool) -> sqlx::Result<()> {+ let repo = DbContactsRepository::new(pool);+ let contacts = repo.get_contacts(mid("macro|[email protected]")).await.unwrap();+ assert_eq!(contacts.len(), 3);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_create_connections_batch(pool: PgPool) -> sqlx::Result<()> {+ let connections: Vec<(MacroUserIdStr<'static>, MacroUserIdStr<'static>)> = (0..8)+ .map(|i| {+ (+ mid("macro|[email protected]"),+ mid(&format!("macro|user{i}@test.com")),+ )+ })+ .filter(|(a, b)| a.as_ref() != b.as_ref())+ .collect();++ let expected_count = connections.len() as i64;++ let repo = DbContactsRepository::new(pool.clone());+ repo.create_connections(connections).await.unwrap();++ let count = sqlx::query_scalar!("SELECT count(*) FROM contacts_connections")+ .fetch_one(&pool)+ .await?+ .unwrap();+ assert_eq!(count, expected_count);++ let contacts = repo+ .get_contacts(mid("macro|[email protected]"))+ .await+ .unwrap();+ assert_eq!(contacts.len(), expected_count as usize);+ Ok(())+}++async fn insert_channel(pool: &PgPool, id: Uuid) {+ sqlx::query!(+ "INSERT INTO comms_channels (id, channel_type, owner_id) \+ VALUES ($1, 'direct_message', 'macro|[email protected]')",+ id+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_get_unapplied_messages_returns_inserted_rows(pool: PgPool) -> sqlx::Result<()> {+ let channel_id = Uuid::new_v4();+ insert_channel(&pool, channel_id).await;++ // Simulate what the migration backfill inserts+ sqlx::query!(+ "INSERT INTO contacts_backfill_outbox (comms_channel_id, user_ids) \+ VALUES ($1, '[\"macro|[email protected]\", \"macro|[email protected]\"]'::jsonb)",+ channel_id,+ )+ .execute(&pool)+ .await?;++ let repo = DbContactsRepository::new(pool);+ let messages = repo.get_unapplied_messages().await.unwrap();++ assert_eq!(messages.len(), 1);+ assert_eq!(messages[0].channel_id, channel_id);+ assert_eq!(+ messages[0].channel_participants,+ [mid("macro|[email protected]"), mid("macro|[email protected]")]+ .into_iter()+ .collect()+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_get_unapplied_messages_excludes_applied(pool: PgPool) -> sqlx::Result<()> {+ let unapplied_id = Uuid::new_v4();+ let applied_id = Uuid::new_v4();+ insert_channel(&pool, unapplied_id).await;+ insert_channel(&pool, applied_id).await;++ sqlx::query!(+ "INSERT INTO contacts_backfill_outbox (comms_channel_id, user_ids) \+ VALUES ($1, '[\"macro|[email protected]\"]'::jsonb)",+ unapplied_id,+ )+ .execute(&pool)+ .await?;++ sqlx::query!(+ "INSERT INTO contacts_backfill_outbox (comms_channel_id, user_ids, applied_at) \+ VALUES ($1, '[\"macro|[email protected]\"]'::jsonb, now())",+ applied_id,+ )+ .execute(&pool)+ .await?;++ let repo = DbContactsRepository::new(pool);+ let messages = repo.get_unapplied_messages().await.unwrap();++ assert_eq!(messages.len(), 1);+ assert_eq!(messages[0].channel_id, unapplied_id);+ Ok(())+}diff --git a/rust/cloud-storage/contacts/tests/fixtures/add_connection.json b/rust/cloud-storage/contacts/tests/fixtures/add_connection.jsonnew file mode 100644index 0000000000..2635b4dd16--- /dev/null+++ b/rust/cloud-storage/contacts/tests/fixtures/add_connection.json@@ -0,0 +1,3 @@+{+}diff --git a/rust/cloud-storage/contacts_service/tests/fixtures/add_participants.json b/rust/cloud-storage/contacts/tests/fixtures/add_participants.jsonsimilarity index 100%rename from rust/cloud-storage/contacts_service/tests/fixtures/add_participants.jsonrename to rust/cloud-storage/contacts/tests/fixtures/add_participants.jsondiff --git a/rust/cloud-storage/contacts_service/tests/fixtures/connections_message.json b/rust/cloud-storage/contacts/tests/fixtures/connections_message.jsonsimilarity index 100%rename from rust/cloud-storage/contacts_service/tests/fixtures/connections_message.jsonrename to rust/cloud-storage/contacts/tests/fixtures/connections_message.jsondiff --git a/rust/cloud-storage/contacts_service/tests/fixtures/create_group.json b/rust/cloud-storage/contacts/tests/fixtures/create_group.jsonsimilarity index 100%rename from rust/cloud-storage/contacts_service/tests/fixtures/create_group.jsonrename to rust/cloud-storage/contacts/tests/fixtures/create_group.jsondiff --git a/rust/cloud-storage/contacts_db_client/Cargo.toml b/rust/cloud-storage/contacts_db_client/Cargo.tomldeleted file mode 100644index 920c8cad1e..0000000000--- a/rust/cloud-storage/contacts_db_client/Cargo.toml+++ /dev/null@@ -1,14 +0,0 @@-[package]-edition = "2024"-name = "contacts_db_client"-publish = false-version = "0.1.0"--[dependencies]-anyhow = { workspace = true }-serde = { workspace = true }-sqlx = { workspace = true }-tracing = { workspace = true }--[dev-dependencies]-macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/rust/cloud-storage/contacts_db_client/justfile b/rust/cloud-storage/contacts_db_client/justfiledeleted file mode 100644index e7aa0af476..0000000000--- a/rust/cloud-storage/contacts_db_client/justfile+++ /dev/null@@ -1,12 +0,0 @@-import '../database.just'--mod sqlx '../sqlx.just'--prepare_db:- just sqlx::prepare_db {{ DATABASE_URL }}--test $DATABASE_URL=DATABASE_URL:- cargo test--psql $DATABASE_URL=DATABASE_URL:- PGPASSWORD=password psql -h localhost -U user macrodbdiff --git a/rust/cloud-storage/contacts_db_client/src/fixtures/user_list.sql b/rust/cloud-storage/contacts_db_client/src/fixtures/user_list.sqldeleted file mode 100644index b4464918f6..0000000000--- a/rust/cloud-storage/contacts_db_client/src/fixtures/user_list.sql+++ /dev/null@@ -1,25 +0,0 @@-INSERT INTO contacts_connections (user1, user2) VALUES--- user 51's connections-(- '1AF59C26-C5B3-480C-9AD1-B87C2A69E72C',- '51028BDA-67F0-44DF-AA21-5853963524F1'-),-(- '51028BDA-67F0-44DF-AA21-5853963524F1',- '654DF835-BB97-48E0-9B5B-0AD71A608DBD'-),-(- '51028BDA-67F0-44DF-AA21-5853963524F1',- '80C0EFFD-1B9D-4EBA-AD86-BC52C4A63294'-),---- Unrelated connections to 51-(- '80C0EFFD-1B9D-4EBA-AD86-BC52C4A63294',- '99C2C451-B5A2-4F47-9A38-1E7E56E0474B'-),-(- '80C0EFFD-1B9D-4EBA-AD86-BC52C4A63294',- 'CE2759CA-2610-448B-B496-B82AE0B14E41'-);-diff --git a/rust/cloud-storage/contacts_db_client/src/lib.rs b/rust/cloud-storage/contacts_db_client/src/lib.rsdeleted file mode 100644index 0b4e043674..0000000000--- a/rust/cloud-storage/contacts_db_client/src/lib.rs+++ /dev/null@@ -1,227 +0,0 @@-use anyhow::Result;-use serde::{Deserialize, Serialize};-use sqlx::{Pool, Postgres};--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ConnectionRowId {- id: i32,-}--pub async fn create_connections<'a, E: sqlx::Executor<'a, Database = Postgres>>(- transaction: E,- connections: Vec<(String, String)>,-) -> Result<(), sqlx::Error> {- let mut query = "INSERT INTO contacts_connections(user1, user2) VALUES ".to_string();- let mut values: Vec<String> = Vec::new();- let mut parameters: Vec<String> = Vec::new();-- for connection in connections {- let param_number = parameters.len() + 1;- values.push(format!("(${}, ${})", param_number, param_number + 1));-- if connection.0 < connection.1 {- parameters.push(connection.0);- parameters.push(connection.1);- } else {- parameters.push(connection.1);- parameters.push(connection.0);- }- }- query += &values.join(", ");- query += " ON CONFLICT(user1, user2) DO UPDATE SET updated_at = now();";-- let mut query = sqlx::query(&query);-- for param in parameters {- query = query.bind(param);- }-- query.execute(transaction).await?;-- Ok(())-}--/// Retreives a connection from a row id-#[cfg(test)]-async fn get_connection(db: &Pool<Postgres>, id: i32) -> Result<(String, String)> {- let result = sqlx::query!(- "SELECT user1, user2 FROM contacts_connections WHERE id = $1",- id- )- .fetch_one(db)- .await?;-- let user1 = result.user1.to_string();- let user2 = result.user2.to_string();-- Ok((user1, user2))-}--/// Gets a contact list from a user-pub async fn get_contacts(db: &Pool<Postgres>, user: &str) -> Result<Vec<String>> {- let result = sqlx::query!(- "- SELECT user1 AS contact FROM contacts_connections WHERE user2 = $1- UNION- SELECT user2 AS contact from contacts_connections WHERE user1 = $1- ",- &user- )- .fetch_all(db)- .await?;-- let users: Vec<String> = result- .iter()- .map(|row| row.contact.as_ref().unwrap().to_string())- .collect();-- Ok(users)-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::PgPool;- use std::collections::HashSet;-- #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]- async fn test_storage_basic(pool: PgPool) -> sqlx::Result<()> {- let user1 = "05E6766A-7972-4116-8BAD-2038E57D5ADF";- let user2 = "CD7230E3-7718-4692-9C32-7C76BD70C076";- let connections: Vec<(String, String)> = [(user1.to_string(), user2.to_string())].to_vec();- //.into_iter()- //.map(|x| (x.0.to_string(), x.1.to_string()))- //.collect();-- let mut transaction = pool.begin().await?;- create_connections(transaction.as_mut(), connections).await?;- transaction.commit().await?;-- let pair = sqlx::query!("SELECT user1, user2 FROM contacts_connections LIMIT 1")- .fetch_one(&pool)- .await?;-- assert_eq!(&user1, &pair.user1);- assert_eq!(&user2, &pair.user2);-- Ok(())- }-- #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]- async fn test_storage_ordering(pool: PgPool) -> sqlx::Result<()> {- let user1 = "05E6766A-7972-4116-8BAD-2038E57D5ADF".to_string();- let user2 = "CD7230E3-7718-4692-9C32-7C76BD70C076".to_string();-- let connections: Vec<(String, String)> = [(user2.to_string(), user1.to_string())].to_vec();-- // Insert in opposite order- let mut transaction = pool.begin().await?;- create_connections(transaction.as_mut(), connections).await?;- transaction.commit().await?;-- let pair = sqlx::query!("SELECT user1, user2 FROM contacts_connections LIMIT 1")- .fetch_one(&pool)- .await?;-- // Correction- assert_eq!(&user1, &pair.user1);- assert_eq!(&user2, &pair.user2);- Ok(())- }-- #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS", fixtures("user_list"))]- async fn test_get_contacts(pool: PgPool) -> sqlx::Result<()> {- let user = "51028BDA-67F0-44DF-AA21-5853963524F1".to_string();-- let contacts = get_contacts(&pool, &user).await;-- if let Err(e) = &contacts {- dbg!("error: {:?}", e);- }-- assert!(contacts.is_ok());-- let contacts = contacts.unwrap();-- dbg!(&contacts);- assert_eq!(contacts.len(), 3);-- Ok(())- }-- #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]- async fn test_create_connections(pool: PgPool) -> sqlx::Result<()> {- let connections: Vec<(String, String)> = [- (- "C3B1970F-18EE-4DFA-B5FB-E8240E28E51D",- "AE2C090C-E478-4454-A001-3DF458BF1FE4",- ),- (- "AE2C090C-E478-4454-A001-3DF458BF1FE4",- "79A5557B-7827-4E2E-A6AE-F0935CDB762E",- ),- (- "AE2C090C-E478-4454-A001-3DF458BF1FE4",- "D44CAADA-98C0-49EB-AB20-6851B824983A",- ),- (- "AE2C090C-E478-4454-A001-3DF458BF1FE4",- "5AB8C770-F2CB-4C6C-BC08-AE64569E324C",- ),- (- "AE2C090C-E478-4454-A001-3DF458BF1FE4",- "C3F4D826-F8FD-478A-AA66-B5B6BB370CBC",- ),- (- "AE2C090C-E478-4454-A001-3DF458BF1FE4",- "FF038D36-1AEF-461A-8AA8-34001FA1ABAD",- ),- (- "AE2C090C-E478-4454-A001-3DF458BF1FE4",- "9EFFE035-BB12-4FCC-B479-800E1C2551A8",- ),- (- "FF038D36-1AEF-461A-8AA8-34001FA1ABAD",- "9EFFE035-BB12-4FCC-B479-800E1C2551A8",- ),- ]- .into_iter()- .map(|s| (s.0.to_string(), s.1.to_string()))- .collect();-- let mut transaction = pool.begin().await?;- create_connections(transaction.as_mut(), connections).await?;- transaction.commit().await?;-- let result = sqlx::query!("SELECT count(*) as count FROM contacts_connections; ")- .fetch_one(&pool)- .await?;-- let count = result.count.unwrap();- assert_eq!(count, 8);-- let contacts = get_contacts(&pool, "AE2C090C-E478-4454-A001-3DF458BF1FE4").await;- assert!(contacts.is_ok());- let contacts = contacts.unwrap();- assert_eq!(contacts.len(), 7);-- let expectations: HashSet<String> = [- "FF038D36-1AEF-461A-8AA8-34001FA1ABAD",- "C3F4D826-F8FD-478A-AA66-B5B6BB370CBC",- "D44CAADA-98C0-49EB-AB20-6851B824983A",- "5AB8C770-F2CB-4C6C-BC08-AE64569E324C",- "79A5557B-7827-4E2E-A6AE-F0935CDB762E",- "C3B1970F-18EE-4DFA-B5FB-E8240E28E51D",- "9EFFE035-BB12-4FCC-B479-800E1C2551A8",- ]- .into_iter()- .map(String::from)- .collect();-- let reality: HashSet<String> = contacts.into_iter().collect();-- assert_eq!(&expectations, &reality);- Ok(())- }-}diff --git a/rust/cloud-storage/contacts_service/Cargo.toml b/rust/cloud-storage/contacts_service/Cargo.tomlindex 0a8ecbb1e9..aecd4e9bd9 100644--- a/rust/cloud-storage/contacts_service/Cargo.toml+++ b/rust/cloud-storage/contacts_service/Cargo.toml@@ -15,14 +15,10 @@ path = "src/openapi.rs"[dependencies]anyhow = { workspace = true }-async-trait = { workspace = true }aws-sdk-secretsmanager = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true }-axum-extra = { workspace = true }-connection_gateway_client = { path = "../connection_gateway_client" }-contacts_db_client = { path = "../contacts_db_client" }-http-body-util = { workspace = true }+contacts = { path = "../contacts", features = ["axum"] }macro_auth = { path = "../macro_auth" }macro_aws_config = { path = "../macro_aws_config" }macro_cors = { path = "../macro_cors" }@@ -33,7 +29,6 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea] }macro_user_id = { path = "../macro_user_id" }model = { path = "../model" }-model_user = { path = "../model_user", features = ["axum"] }rate_limit = { path = "../rate_limit", features = ["axum"] }redis = { workspace = true }secretsmanager_client = { path = "../secretsmanager_client" }@@ -42,7 +37,6 @@ serde_json = { workspace = true }sqlx = { workspace = true }sqs_worker = { path = "../sqs_worker" }tokio = { workspace = true }-tower = { workspace = true }tracing = { workspace = true }utoipa = { workspace = true }utoipa-swagger-ui = { workspace = true }@@ -51,6 +45,5 @@ utoipa-swagger-ui = { workspace = true }mock = [][dev-dependencies]-macro_auth = { path = "../macro_auth", features = ["testing"] }-rate_limit = { path = "../rate_limit", features = ["axum", "testing"] }-rootcause = { workspace = true }+http-body-util = { workspace = true }+tower = { workspace = true }diff --git a/rust/cloud-storage/contacts_service/examples/generate_message.rs b/rust/cloud-storage/contacts_service/examples/generate_message.rsindex 02e95c3bf1..7b22c5432f 100644--- a/rust/cloud-storage/contacts_service/examples/generate_message.rs+++ b/rust/cloud-storage/contacts_service/examples/generate_message.rs@@ -1,99 +1,74 @@// Small utility to generate a sample connections message to send to the SQS service-use contacts_service::queue::add_user_to_group;-use model::contacts::{AddParticipantsMessageBody, CreateGroupMessageBody, Message};-use std::env;+use contacts::domain::models::messages::ContactsNodes;+use macro_user_id::user_id::MacroUserIdStr;+use std::{collections::HashSet, env};-pub async fn create_group(group: &[String]) -> String {- let body: CreateGroupMessageBody = CreateGroupMessageBody {- group: group.to_vec(),- group_id: None,- };- let msg = Message::CreateGroup(body);- serde_json::to_string(&msg).unwrap()-}--pub async fn add_participants(participants: &[String], group: &[String]) -> String {- let body = AddParticipantsMessageBody {- participants: participants.to_vec(),- group: group.to_vec(),- group_id: None,- };- let msg = Message::AddParticipants(body);- serde_json::to_string(&msg).unwrap()+fn print_contacts_message(users: HashSet<MacroUserIdStr<'static>>) {+ println!(+ "{}",+ serde_json::to_string(&ContactsNodes { users }).unwrap()+ );}async fn genmsg_add_user_to_group() {- let group: Vec<String> = [- "FF038D36-1AEF-461A-8AA8-34001FA1ABAD",- "5AB8C770-F2CB-4C6C-BC08-AE64569E324C",- "D44CAADA-98C0-49EB-AB20-6851B824983A",- "79A5557B-7827-4E2E-A6AE-F0935CDB762E",- "C3F4D826-F8FD-478A-AA66-B5B6BB370CBC",- "C3B1970F-18EE-4DFA-B5FB-E8240E28E51D",- "9EFFE035-BB12-4FCC-B479-800E1C2551A8",+ let mut users: HashSet<MacroUserIdStr<'static>> = [+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",].iter()- .map(|s| s.to_string())+ .map(|s| MacroUserIdStr::try_from(s.to_string()).unwrap()).collect();-- let new_user = "AE2C090C-E478-4454-A001-3DF458BF1FE4";-- let msg = add_user_to_group(&group, new_user).await;- println!("{}", msg);+ users.insert(MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap());+ print_contacts_message(users);}async fn genmsg_add_paul() {- let group: Vec<String> = [- "fake|[email protected]",- "fake|[email protected]",- "fake|[email protected]",- "fake|[email protected]",- "fake|[email protected]",+ let mut users: HashSet<MacroUserIdStr<'static>> = [+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",].iter()- .map(|s| s.to_string())+ .map(|s| MacroUserIdStr::try_from(s.to_string()).unwrap()).collect();-- let new_user = "macro|[email protected]";-- let msg = add_user_to_group(&group, new_user).await;- println!("{}", msg);+ users.insert(MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap());+ print_contacts_message(users);}async fn genmsg_create_group() {- let group: Vec<String> = [- "fake|[email protected]",- "fake|[email protected]",- "fake|[email protected]",- "fake|[email protected]",+ let users: HashSet<MacroUserIdStr<'static>> = [+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]","macro|[email protected]",].iter()- .map(|s| s.to_string())+ .map(|s| MacroUserIdStr::try_from(s.to_string()).unwrap()).collect();-- let msg = create_group(&group).await;- println!("{}", msg);+ print_contacts_message(users);}async fn genmsg_add_participants() {- let group: Vec<String> = [- "fake|[email protected]",- "fake|[email protected]",- "fake|[email protected]",- "fake|[email protected]",+ let users: HashSet<MacroUserIdStr<'static>> = [+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",].iter()- .map(|s| s.to_string())+ .map(|s| MacroUserIdStr::try_from(s.to_string()).unwrap()).collect();-- let participants: Vec<String> = ["macro|[email protected]", "fake|[email protected]"]- .iter()- .map(|s| s.to_string())- .collect();-- let msg = add_participants(&participants, &group).await;- println!("{}", msg);+ print_contacts_message(users);}#[tokio::main]diff --git a/rust/cloud-storage/contacts_service/examples/worker.rs b/rust/cloud-storage/contacts_service/examples/worker.rsindex 3e7096627c..1147ad01a6 100644--- a/rust/cloud-storage/contacts_service/examples/worker.rs+++ b/rust/cloud-storage/contacts_service/examples/worker.rs@@ -1,7 +1,10 @@use anyhow::Context;-use contacts_service::queue::MessageQueue;+use contacts::domain::service::ContactsDomainService;+use contacts::inbound::worker::ContactsWorker;+use contacts::outbound::repository::DbContactsRepository;use macro_entrypoint::MacroEntrypoint;use sqlx::postgres::PgPoolOptions;+use std::sync::Arc;#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> {@@ -27,7 +30,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {.await.context("could not connect to db")?;- let mut worker = MessageQueue::new(sqs, db, None);+ let repository = DbContactsRepository::new(db);+ let notifier: Option<contacts::outbound::gateway::ConnectionGatewayNotifier> = None;+ let service = Arc::new(ContactsDomainService {+ repository,+ notifier,+ });+ let worker = ContactsWorker::new(sqs, service);worker.poll().await;Ok(())}diff --git a/rust/cloud-storage/contacts_service/src/api/context.rs b/rust/cloud-storage/contacts_service/src/api/context.rsdeleted file mode 100644index 1f9f22e72a..0000000000--- a/rust/cloud-storage/contacts_service/src/api/context.rs+++ /dev/null@@ -1,20 +0,0 @@-use crate::{api::Service, config::Config};-use axum::extract::FromRef;-use macro_auth::middleware::decode_jwt::JwtValidationArgs;-use macro_middleware::auth::internal_access::InternalApiSecretKey;-use rate_limit::{RateLimitServiceImpl, RedisRateLimitAdapter};-use secretsmanager_client::LocalOrRemoteSecret;-use sqlx::PgPool;-use std::sync::Arc;--pub type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;--#[derive(Clone, FromRef)]-pub struct AppState {- pub config: Arc<Config>,- pub db: PgPool,- pub jwt_args: JwtValidationArgs,- pub internal_api_secret: LocalOrRemoteSecret<InternalApiSecretKey>,- pub contacts_service: Arc<Service>,- pub rate_limit_service: RateLimiter,-}diff --git a/rust/cloud-storage/contacts_service/src/api/health/mod.rs b/rust/cloud-storage/contacts_service/src/api/health/mod.rsdeleted file mode 100644index bf6d10e81a..0000000000--- a/rust/cloud-storage/contacts_service/src/api/health/mod.rs+++ /dev/null@@ -1,57 +0,0 @@-use axum::{Router, routing::get};--/// Health check-#[utoipa::path(- get,- path = "/health",- responses(- (status = 200, description = "health", body = String),- )- )]-pub async fn health_handler() -> String {- "healthy".to_string()-}--pub fn router() -> Router {- Router::new().route("/health", get(health_handler))-}--#[cfg(test)]-mod tests {- use super::*;- use axum::{- body::Body,- http::{Request, StatusCode},- };- use http_body_util::BodyExt; // for `collect`- use tower::ServiceExt;-- #[tokio::test]- async fn test_health_check() {- let api = router();-- let response = api- .oneshot(- Request::builder()- .uri("/health")- .method("GET")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();-- assert_eq!(response.status(), StatusCode::OK);- let body = String::from_utf8(- response- .into_body()- .collect()- .await- .unwrap()- .to_bytes()- .to_vec(),- )- .unwrap();- assert_eq!(body, "healthy");- }-}diff --git a/rust/cloud-storage/contacts_service/src/api/mod.rs b/rust/cloud-storage/contacts_service/src/api/mod.rsdeleted file mode 100644index 9c2412dcc0..0000000000--- a/rust/cloud-storage/contacts_service/src/api/mod.rs+++ /dev/null@@ -1,441 +0,0 @@-use crate::api::context::AppState;-use anyhow::Context;-use axum::extract::{FromRequestParts, Json, State};-use axum::http::StatusCode;-use axum::response::IntoResponse;-use axum::routing::get;-use axum::{RequestPartsExt, Router};-use axum_extra::extract::Cached;-use macro_user_id::user_id::MacroUserIdStr;-use model_user::axum_extractor::MacroUserExtractor;-use rate_limit::inbound::{RateLimitExtractable, rate_limit_middleware};-use rate_limit::{RateLimitConfig, RateLimitKey, RateLimitService};-use serde::{Deserialize, Serialize};-use sqlx::PgPool;-use std::sync::Arc;-use std::time::Duration;-use tracing::instrument;-use utoipa::{OpenApi, ToSchema};-use utoipa_swagger_ui::SwaggerUi;--pub(crate) mod context;-mod health;-pub(crate) mod swagger;--pub async fn setup_and_serve(state: context::AppState) -> anyhow::Result<()> {- let cors = macro_cors::cors_layer();-- let port = state.config.port;- let app = api_router(state)- .layer(cors.clone())- .merge(health::router().layer(cors))- .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()));-- let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))- .await- .unwrap();-- tracing::info!("contacts service is up and running on port {}", &port);-- axum::serve(listener, app.into_make_service())- .await- .context("error starting service")-}--#[derive(Deserialize, Serialize, Debug, ToSchema)]-pub struct GetContactsResponse {- contacts: Vec<String>,-}--#[derive(Deserialize, Serialize, Debug, ToSchema)]-pub struct AddContactRequest {- #[schema(value_type = String)]- user_id: MacroUserIdStr<'static>,-}--pub trait ContactsService: Send + Sync + 'static {- fn query_contacts(- &self,- user_id: MacroUserIdStr<'_>,- ) -> impl Future<Output = Option<Vec<String>>> + Send;-- fn add_contact(- &self,- caller: MacroUserIdStr<'_>,- recipient: MacroUserIdStr<'_>,- ) -> impl Future<Output = Result<(), anyhow::Error>> + Send;-}--#[cfg(test)]-#[derive(Clone, Debug)]-pub struct MockService;--#[derive(Clone, Debug)]-pub struct Service(pub PgPool);--#[cfg(test)]-impl ContactsService for MockService {- async fn query_contacts(&self, user_id: MacroUserIdStr<'_>) -> Option<Vec<String>> {- if user_id.as_ref() == "macro|[email protected]" {- let contacts = [- "0bcabd1a-1bf5-48d7-b334-5f7e59e8a9ff",- "3a90b186-0288-4819-8e1a-8e10cb685c0c",- "e3cf7c46-60c9-413a-8f27-57c91c3297cf",- ]- .into_iter()- .map(String::from)- .collect();-- return Some(contacts);- } else if user_id.as_ref() == "macro|[email protected]" {- let contacts = [- "d44caada-98c0-49eb-ab20-6851b824983a",- "5ab8c770-f2cb-4c6c-bc08-ae64569e324c",- "79a5557b-7827-4e2e-a6ae-f0935cdb762e",- "c3f4d826-f8fd-478a-aa66-b5b6bb370cbc",- "ff038d36-1aef-461a-8aa8-34001fa1abad",- "c3b1970f-18ee-4dfa-b5fb-e8240e28e51d",- "9effe035-bb12-4fcc-b479-800e1c2551a8",- ]- .into_iter()- .map(String::from)- .collect();-- return Some(contacts);- }-- None- }-- async fn add_contact(- &self,- _caller: MacroUserIdStr<'_>,- _recipient: MacroUserIdStr<'_>,- ) -> Result<(), anyhow::Error> {- Ok(())- }-}--impl ContactsService for Service {- async fn query_contacts(&self, user_id: MacroUserIdStr<'_>) -> Option<Vec<String>> {- let contacts = contacts_db_client::get_contacts(&self.0, user_id.as_ref()).await;- contacts.ok()- }-- async fn add_contact(- &self,- caller: MacroUserIdStr<'_>,- recipient: MacroUserIdStr<'_>,- ) -> Result<(), anyhow::Error> {- contacts_db_client::create_connections(- &self.0,- vec![(caller.as_ref().to_string(), recipient.as_ref().to_string())],- )- .await?;- Ok(())- }-}--#[utoipa::path(get,- tag = "contacts",- operation_id = "get_contacts",- path = "/contacts",- responses(- (status = 200, body=GetContactsResponse),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String)))-]-#[instrument(skip(macro_user_id, contacts), level = "info", fields(user_id = macro_user_id.as_ref()))]-pub async fn handler<S: ContactsService>(- State(contacts): State<Arc<S>>,- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,-) -> impl IntoResponse {- let contacts = contacts.query_contacts(macro_user_id).await;- if contacts.is_none() {- return (StatusCode::NOT_FOUND, Json(None));- }-- let contacts = contacts.unwrap();-- (StatusCode::OK, Json(Some(GetContactsResponse { contacts })))-}--#[utoipa::path(post,- tag = "contacts",- operation_id = "add_contact",- path = "/contacts",- request_body = AddContactRequest,- responses(- (status = 204),- (status = 401, body=String),- (status = 500, body=String)))-]-#[instrument(skip(service, macro_user_id), err)]-pub async fn add_contact_handler<S: ContactsService>(- State(service): State<Arc<S>>,- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,- Json(body): Json<AddContactRequest>,-) -> Result<StatusCode, StatusCode> {- service- .add_contact(macro_user_id, body.user_id)- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to create contact connection");- StatusCode::INTERNAL_SERVER_ERROR- })?;- Ok(StatusCode::NO_CONTENT)-}--/// Rate limit for adding contacts: 50 requests per user per hour.-pub struct PerUserAddContactRateLimit(MacroUserExtractor);--impl<S> RateLimitExtractable<S> for PerUserAddContactRateLimit-where- S: Send + Sync,-{- fn config() -> RateLimitConfig {- RateLimitConfig {- max_count: 50,- window: Duration::from_mins(60),- }- }-- fn key(&self) -> RateLimitKey {- RateLimitKey::builder(&"per-user-add-contact")- .append(&self.0.macro_user_id.as_ref())- .finish()- }-}--impl<S> FromRequestParts<S> for PerUserAddContactRateLimit-where- S: Send + Sync,-{- type Rejection = <MacroUserExtractor as FromRequestParts<S>>::Rejection;-- async fn from_request_parts(- parts: &mut axum::http::request::Parts,- state: &S,- ) -> Result<Self, Self::Rejection> {- let Cached(user): Cached<MacroUserExtractor> = parts.extract_with_state(state).await?;- Ok(Self(user))- }-}--fn api_router(app_state: AppState) -> Router {- contacts_router(app_state.rate_limit_service.clone())- .layer(axum::middleware::from_fn_with_state(- app_state.jwt_args.clone(),- macro_middleware::auth::decode_jwt::handler,- ))- .with_state(app_state.contacts_service)-}--fn contacts_router<R: RateLimitService + Clone, S: ContactsService>(- rate_limiter: R,-) -> Router<Arc<S>> {- let post_route = Router::new()- .route("/contacts", axum::routing::post(add_contact_handler))- .layer(axum::middleware::from_fn_with_state(- rate_limiter,- rate_limit_middleware::<R, PerUserAddContactRateLimit, R>,- ));-- Router::new()- .route("/contacts", get(handler))- .merge(post_route)-}--#[cfg(test)]-mod tests {- use super::*;- use axum::{Extension, body::Body, http::Request};- use http_body_util::BodyExt;- use model_user::UserContext;- use rate_limit::{- RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult, RateLimitServiceImpl,- domain::models::RateLimitOk,- };- use rootcause::Report;- use std::collections::HashSet;- use tower::ServiceExt;-- #[derive(Clone)]- struct MockRateLimitPort {- should_exceed: bool,- }-- impl rate_limit::RateLimitPort for MockRateLimitPort {- async fn check(- &self,- key: RateLimitKey,- config: RateLimitConfig,- ) -> Result<RateLimitResult, Report> {- if self.should_exceed {- Ok(Err(RateLimitExceeded {- current_count: config.max_count.saturating_add(1),- max_count: config.max_count,- retry_after: config.window,- }))- } else {- Ok(Ok(RateLimitOk::new_testing_value(0, key, config)))- }- }-- async fn decrement(&self, _key: &RateLimitKey) -> Result<(), Report> {- Ok(())- }- }-- fn allowing_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {- RateLimitServiceImpl {- repo: MockRateLimitPort {- should_exceed: false,- },- }- }-- fn exceeding_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {- RateLimitServiceImpl {- repo: MockRateLimitPort {- should_exceed: true,- },- }- }-- fn mock_service() -> Arc<MockService> {- Arc::new(MockService)- }-- fn test_user_context(user_id: &str) -> UserContext {- UserContext {- user_id: user_id.to_string(),- permissions: None,- organization_id: None,- fusion_user_id: "".to_string(),- }- }-- fn build_test_router(- rate_limiter: RateLimitServiceImpl<MockRateLimitPort>,- user_id: &str,- ) -> Router {- contacts_router(rate_limiter)- .with_state(mock_service())- .layer(Extension(test_user_context(user_id)))- }-- #[tokio::test]- async fn test_get_contact() {- let user_id = "macro|[email protected]";- let api = build_test_router(allowing_rate_limiter(), user_id);-- let response = api- .oneshot(- Request::builder()- .uri("/contacts")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::OK);- let body = response.into_body().collect().await.unwrap().to_bytes();- let body: GetContactsResponse = serde_json::from_slice(&body).unwrap();-- let contact_list: HashSet<String> = [- "0bcabd1a-1bf5-48d7-b334-5f7e59e8a9ff",- "3a90b186-0288-4819-8e1a-8e10cb685c0c",- "e3cf7c46-60c9-413a-8f27-57c91c3297cf",- ]- .into_iter()- .map(String::from)- .collect();-- assert_eq!(body.contacts.len(), 3, "Not enough contacts");- for contact in &body.contacts {- assert!(- contact_list.contains(contact),- "Could not find contact: {}",- contact- );- }- }-- #[tokio::test]- async fn test_get_contact_not_found() {- let user_id = "macro|[email protected]";- let api = build_test_router(allowing_rate_limiter(), user_id);-- let response = api- .oneshot(- Request::builder()- .uri("/contacts")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::NOT_FOUND);- }-- #[tokio::test]- async fn test_add_contact() {- let user_id = "macro|[email protected]";- let api = build_test_router(allowing_rate_limiter(), user_id);-- let response = api- .oneshot(- Request::builder()- .method("POST")- .uri("/contacts")- .header("content-type", "application/json")- .body(Body::from(- serde_json::json!({"user_id": "macro|[email protected]"}).to_string(),- ))- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::NO_CONTENT);- }-- #[tokio::test]- async fn test_add_contact_rate_limited() {- let user_id = "macro|[email protected]";- let api = build_test_router(exceeding_rate_limiter(), user_id);-- let response = api- .oneshot(- Request::builder()- .method("POST")- .uri("/contacts")- .header("content-type", "application/json")- .body(Body::from(- serde_json::json!({"user_id": "macro|[email protected]"}).to_string(),- ))- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);- }-- #[tokio::test]- async fn test_get_not_affected_by_rate_limit() {- let user_id = "macro|[email protected]";- let api = build_test_router(exceeding_rate_limiter(), user_id);-- let response = api- .oneshot(- Request::builder()- .uri("/contacts")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::OK);- }-}diff --git a/rust/cloud-storage/contacts_service/src/api/swagger.rs b/rust/cloud-storage/contacts_service/src/api/swagger.rsdeleted file mode 100644index 06dd25c9c7..0000000000--- a/rust/cloud-storage/contacts_service/src/api/swagger.rs+++ /dev/null@@ -1,24 +0,0 @@-use utoipa::OpenApi;--use super::{AddContactRequest, GetContactsResponse};--#[derive(OpenApi)]-#[openapi(- info(- terms_of_service = "https://macro.com/terms",- ),- paths(- super::handler,- super::add_contact_handler,- ),- components(- schemas(- GetContactsResponse,- AddContactRequest,- ),- ),- tags(- (name = "macro contacts service", description = "Contacts Service")- )- )]-pub struct ApiDoc;diff --git a/rust/cloud-storage/contacts_service/src/fixtures/user_list.sql b/rust/cloud-storage/contacts_service/src/fixtures/user_list.sqldeleted file mode 100644index c520387815..0000000000--- a/rust/cloud-storage/contacts_service/src/fixtures/user_list.sql+++ /dev/null@@ -1,25 +0,0 @@-insert into connections (user1, user2) values--- user 51's connections-(- '1af59c26-c5b3-480c-9ad1-b87c2a69e72c',- '51028bda-67f0-44df-aa21-5853963524f1'-),-(- '51028bda-67f0-44df-aa21-5853963524f1',- '654df835-bb97-48e0-9b5b-0ad71a608dbd'-),-(- '51028bda-67f0-44df-aa21-5853963524f1',- '80c0effd-1b9d-4eba-ad86-bc52c4a63294'-),---- unrelated connections to 51-(- '80c0effd-1b9d-4eba-ad86-bc52c4a63294',- '99c2c451-b5a2-4f47-9a38-1e7e56e0474b'-),-(- '80c0effd-1b9d-4eba-ad86-bc52c4a63294',- 'ce2759ca-2610-448b-b496-b82ae0b14e41'-);-diff --git a/rust/cloud-storage/contacts_service/src/graph.rs b/rust/cloud-storage/contacts_service/src/graph.rsdeleted file mode 100644index 23981cce3b..0000000000--- a/rust/cloud-storage/contacts_service/src/graph.rs+++ /dev/null@@ -1,140 +0,0 @@-use std::collections::HashSet;--#[allow(dead_code)]-#[derive(Debug, Eq, Hash, PartialEq, Copy, Clone)]-pub struct Vertex<T> {- pub data: T,-}--#[allow(dead_code)]-impl<T> Vertex<T> {- pub fn new(x: T) -> Self {- Vertex { data: x }- }-}--#[allow(dead_code)]-#[derive(Debug)]-pub struct Edge<'a, T> {- pub a: &'a Vertex<T>,- pub b: &'a Vertex<T>,-}--#[allow(dead_code)]-pub fn append<'a, T>(- vertex_set: &'a HashSet<Vertex<T>>,- vertex: &'a Vertex<T>,-) -> Vec<Edge<'a, T>> {- let mut new_edges = vec![];- for vtx in vertex_set {- new_edges.push(Edge { a: vertex, b: vtx });- }-- new_edges-}--#[allow(dead_code)]-pub fn generate<T>(vertex_set: &HashSet<Vertex<T>>) -> Vec<Edge<'_, T>> {- let mut edges = vec![];-- let elements: Vec<&Vertex<T>> = vertex_set.iter().collect();-- for i in 0..elements.len() {- for j in i + 1..elements.len() {- edges.push(Edge {- a: elements[i],- b: elements[j],- });- }- }-- edges-}--#[cfg(test)]-mod tests {- use super::*;- #[test]- // initial edge/vertex setup- fn test_init() {- let a: Vertex<u32> = Vertex::new(1234);- let b: Vertex<u32> = Vertex::new(5678);-- let edge: Edge<u32> = Edge { a: &a, b: &b };-- assert_eq!(edge.a.data, a.data);- assert_eq!(edge.b.data, b.data);- }-- #[test]- // append operation- fn test_append() {- let a: Vertex<u32> = Vertex::new(1234);- let b: Vertex<u32> = Vertex::new(5678);- let c: Vertex<u32> = Vertex::new(1111);- let c_id = c.data;-- let mut vset: HashSet<Vertex<u32>> = HashSet::new();- let mut expected: HashSet<u32> = HashSet::new();- expected.insert(a.data);- expected.insert(b.data);-- vset.insert(a);- vset.insert(b);-- let edges = append(&vset, &c);-- assert_eq!(edges.len(), 2);-- for edge in edges {- assert_eq!(edge.a.data, c_id);- assert!(expected.contains(&edge.b.data));- }- }-- #[test]- // generate operation- fn test_generate() {- let a: Vertex<u32> = Vertex::new(1234);- let b: Vertex<u32> = Vertex::new(5678);- let c: Vertex<u32> = Vertex::new(6666);- let d: Vertex<u32> = Vertex::new(7777);-- let expected_edges = [- [a.data, b.data],- [c.data, a.data],- [c.data, b.data],- [d.data, a.data],- [d.data, b.data],- [d.data, c.data],- ];-- let mut vset: HashSet<Vertex<u32>> = HashSet::new();-- let mut expected_edges_lookup: HashSet<(u32, u32)> = HashSet::new();-- for edge in &expected_edges {- expected_edges_lookup.insert((edge[0], edge[1]));- // Insert phantom edge. Ordering of hashset is unknown- expected_edges_lookup.insert((edge[1], edge[0]));- }-- vset.insert(a);- vset.insert(b);- vset.insert(c);- vset.insert(d);-- let edges = generate(&vset);-- assert_eq!(edges.len(), expected_edges.len());-- for edge in edges {- assert!(- expected_edges_lookup.contains(&(edge.a.data, edge.b.data)),- "Could not find edge ({}, {})",- edge.a.data,- edge.b.data- );- }- }-}diff --git a/rust/cloud-storage/contacts_service/src/health.rs b/rust/cloud-storage/contacts_service/src/health.rsnew file mode 100644index 0000000000..c3f15d2479--- /dev/null+++ b/rust/cloud-storage/contacts_service/src/health.rs@@ -0,0 +1,20 @@+use axum::{Router, routing::get};++/// Health check+#[utoipa::path(+ get,+ path = "/health",+ responses(+ (status = 200, description = "health", body = String),+ )+ )]+pub async fn health_handler() -> String {+ "healthy".to_string()+}++pub fn router() -> Router {+ Router::new().route("/health", get(health_handler))+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/contacts_service/src/health/test.rs b/rust/cloud-storage/contacts_service/src/health/test.rsnew file mode 100644index 0000000000..65195d78f2--- /dev/null+++ b/rust/cloud-storage/contacts_service/src/health/test.rs@@ -0,0 +1,36 @@+use super::*;+use axum::{+ body::Body,+ http::{Request, StatusCode},+};+use http_body_util::BodyExt;+use tower::ServiceExt;++#[tokio::test]+async fn test_health_check() {+ let api = router();++ let response = api+ .oneshot(+ Request::builder()+ .uri("/health")+ .method("GET")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let body = String::from_utf8(+ response+ .into_body()+ .collect()+ .await+ .unwrap()+ .to_bytes()+ .to_vec(),+ )+ .unwrap();+ assert_eq!(body, "healthy");+}diff --git a/rust/cloud-storage/contacts_service/src/lib.rs b/rust/cloud-storage/contacts_service/src/lib.rsdeleted file mode 100644index dd75fa45f0..0000000000--- a/rust/cloud-storage/contacts_service/src/lib.rs+++ /dev/null@@ -1,3 +0,0 @@-pub mod graph;-pub mod queue;-pub mod user;diff --git a/rust/cloud-storage/contacts_service/src/main.rs b/rust/cloud-storage/contacts_service/src/main.rsindex 8ac05d2f6a..20380916af 100644--- a/rust/cloud-storage/contacts_service/src/main.rs+++ b/rust/cloud-storage/contacts_service/src/main.rs@@ -1,28 +1,25 @@#![recursion_limit = "256"]-mod api;mod config;-mod graph;-mod queue;-mod user;+mod health;use std::sync::Arc;use anyhow::Context;use config::{Config, Environment};-use connection_gateway_client::client::ConnectionGatewayClient;-use contacts_service::queue::MessageQueue;-use macro_auth::middleware::decode_jwt::JwtValidationArgs;+use contacts::domain::service::{ContactsDomainService, ContactsOutboxServiceImpl};+use contacts::inbound::http::{ApiDoc, AppState};+use contacts::inbound::worker::{ContactsWorker, OutboxWorker};+use contacts::outbound::gateway::ConnectionGatewayNotifier;+use contacts::outbound::repository::DbContactsRepository;use macro_entrypoint::MacroEntrypoint;use macro_middleware::auth::internal_access::InternalApiSecretKey;use rate_limit::{RateLimitServiceImpl, RedisRateLimitAdapter};use secretsmanager_client::SecretManager;-use sqlx::PgPool;use sqlx::postgres::PgPoolOptions;use sqs_worker::SQSWorker;+use utoipa::OpenApi;+use utoipa_swagger_ui::SwaggerUi;-use crate::api::Service;-use crate::api::context::AppState;--async fn connect_to_database(config: &Config) -> anyhow::Result<PgPool> {+async fn connect_to_database(config: &Config) -> anyhow::Result<sqlx::PgPool> {let (min_connections, max_connections): (u32, u32) = match config.environment {Environment::Production => (5, 30),Environment::Develop => (1, 25),@@ -60,30 +57,51 @@ async fn main() -> anyhow::Result<()> {let config = Config::from_env().context("expected to be able to generate config")?;let db = connect_to_database(&config).await?;- let db_clone = db.clone();let sqs_worker = create_sqs_worker(&config).await;let secretsmanager_client = secretsmanager_client::SecretsManager::new(aws_sdk_secretsmanager::Client::new(¯o_aws_config::get_macro_aws_config().await),);- let internal_api_secret = secretsmanager_client- .get_maybe_secret_value(config.environment, InternalApiSecretKey::new()?)- .await?;+ let notifier = if let Some(url) = config.connection_gateway_url.as_ref() {+ let internal_api_secret = secretsmanager_client+ .get_maybe_secret_value(config.environment, InternalApiSecretKey::new()?)+ .await?;+ Some(+ ConnectionGatewayNotifier::new(internal_api_secret.as_ref().to_string(), url.clone())+ .unwrap(),+ )+ } else {+ None+ };- let connection_gateway_client = config.connection_gateway_url.as_ref().map(|url| {- ConnectionGatewayClient::new(internal_api_secret.as_ref().to_string(), url.clone())+ let repository = DbContactsRepository::new(db.clone());+ let outbox_repo = DbContactsRepository::new(db.clone());+ let service = Arc::new(ContactsDomainService {+ repository,+ notifier,});- let mut worker = MessageQueue::new(sqs_worker, db_clone, connection_gateway_client);-+ let worker = ContactsWorker::new(sqs_worker, service.clone());tokio::spawn(async move {worker.poll().await;});- let jwt_args =- JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)- .await?;+ let outbox_worker = OutboxWorker {+ service: ContactsOutboxServiceImpl {+ outbox_repo,+ inner_service: service.clone(),+ },+ };+ tokio::spawn(async move {+ outbox_worker.run().await;+ });++ let jwt_args = macro_auth::middleware::decode_jwt::JwtValidationArgs::new_with_secret_manager(+ config.environment,+ &secretsmanager_client,+ )+ .await?;let redis_client =redis::Client::open(config.redis_uri.as_str()).context("failed to create redis client")?;@@ -94,14 +112,27 @@ async fn main() -> anyhow::Result<()> {},};- api::setup_and_serve(AppState {- config: Arc::new(config),- db: db.clone(),+ let cors = macro_cors::cors_layer();+ let port = config.port;++ let app = contacts::inbound::http::api_router(AppState {+ port,jwt_args,- internal_api_secret,- contacts_service: Arc::new(Service(db)),+ contacts_service: service,rate_limit_service,})- .await?;+ .layer(cors.clone())+ .merge(health::router().layer(cors))+ .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", ApiDoc::openapi()));++ let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))+ .await+ .unwrap();++ tracing::info!("contacts service is up and running on port {}", &port);++ axum::serve(listener, app.into_make_service())+ .await+ .context("error starting service")?;Ok(())}diff --git a/rust/cloud-storage/contacts_service/src/openapi.rs b/rust/cloud-storage/contacts_service/src/openapi.rsindex e7cbf87023..8fd6bab367 100644--- a/rust/cloud-storage/contacts_service/src/openapi.rs+++ b/rust/cloud-storage/contacts_service/src/openapi.rs@@ -1,16 +1,6 @@-#![allow(unused)]--mod api;-mod config;-mod graph;-mod queue;-mod user;-+use contacts::inbound::http::ApiDoc;use utoipa::OpenApi;fn main() {- println!(- "{}",- api::swagger::ApiDoc::openapi().to_pretty_json().unwrap()- );+ println!("{}", ApiDoc::openapi().to_pretty_json().unwrap());}diff --git a/rust/cloud-storage/contacts_service/src/queue.rs b/rust/cloud-storage/contacts_service/src/queue.rsdeleted file mode 100644index 9440766a90..0000000000--- a/rust/cloud-storage/contacts_service/src/queue.rs+++ /dev/null@@ -1,471 +0,0 @@-use crate::user::{- Connection, Group, UserVertex, create_connections_message, create_user, unpack_connections,- unpack_users,-};-use connection_gateway_client::client::ConnectionGatewayClient;-use contacts_db_client::create_connections;-use model::contacts::{- AddParticipantsMessageBody, ConnectionsMessage, CreateGroupMessageBody, Message,-};-use sqlx::{Pool, Postgres};-use sqs_worker::SQSWorker;-use std::collections::HashSet;-use tracing::instrument;--pub async fn add_participants(body: &AddParticipantsMessageBody) -> Vec<(String, String)> {- // make sure to tack on participants in case they aren't in the group body.- // The underlying HashSet will ensure there are no duplicates- let group = Group::new(&body.group).append_participants(&body.participants);- let mut connections: HashSet<(String, String)> = HashSet::new();- for participant in &body.participants {- let user = UserVertex::generate(participant);- for con in group.append(&user) {- let pair = (con.a.data.id.to_lowercase(), con.b.data.id.to_lowercase());-- // HACK: skip self-connections- if pair.0 != pair.1 {- let pair = if pair.0 > pair.1 {- (pair.1, pair.0)- } else {- pair- };- connections.insert(pair);- }- }- }- connections.into_iter().collect()-}--pub async fn create_group(body: &CreateGroupMessageBody) -> Vec<(String, String)> {- let group = Group::new(&body.group);-- group- .generate()- .into_iter()- .map(|e| (e.a.data.id.to_lowercase(), e.b.data.id.to_lowercase()))- .collect()-}--pub struct MessageQueue {- sqs: SQSWorker,- db: Pool<Postgres>,- connection_gateway_client: Option<ConnectionGatewayClient>,-}--/// Notify all affected users that their contacts have been updated-async fn invalidate_contacts_for_users(- client: &Option<ConnectionGatewayClient>,- connection_pairs: &[(String, String)],-) {- let Some(client) = client else {- return;- };-- let mut user_ids: HashSet<&str> = HashSet::new();- for (user1, user2) in connection_pairs {- user_ids.insert(user1);- user_ids.insert(user2);- }-- for user_id in user_ids {- if let Err(e) = client.invalidate_contacts(user_id).await {- tracing::error!(user_id = %user_id, error = ?e, "Failed to invalidate contacts");- }- }-}--async fn connections_message_handler(conmsg: &ConnectionsMessage, queue: &MessageQueue) {- let users = unpack_users(conmsg).await;- let connections = unpack_connections(conmsg, &users).await;- let db = &queue.db;-- tracing::info!("Writing connections to DB");- let mut transaction = db.begin().await.unwrap();- let connection_pairs: Vec<(String, String)> = connections- .into_iter()- .map(|e| (e.a.data.id.to_string(), e.b.data.id.to_string()))- .collect();- let _ = create_connections(transaction.as_mut(), connection_pairs.clone())- .await- .inspect_err(|e| {- tracing::error!("couldn't create connections: {:?}", e);- });- let _ = transaction.commit().await.inspect_err(|e| {- tracing::error!("transaction error: {:?}", e);- });-- invalidate_contacts_for_users(&queue.connection_gateway_client, &connection_pairs).await;-}--#[instrument(level = "info", skip(queue))]-async fn add_participants_handler(body: &AddParticipantsMessageBody, queue: &MessageQueue) {- tracing::info!("adding participants");- let db = &queue.db;- let connection_pairs = add_participants(body).await;- let mut transaction = db.begin().await.unwrap();- let _ = create_connections(transaction.as_mut(), connection_pairs.clone())- .await- .inspect_err(|e| {- tracing::error!("couldn't create connections: {:?}", e);- });- let _ = transaction.commit().await.inspect_err(|e| {- tracing::error!("transaction error: {:?}", e);- });-- // Notify affected users- invalidate_contacts_for_users(&queue.connection_gateway_client, &connection_pairs).await;-}--#[instrument(level = "info", skip(queue))]-async fn create_group_handler(body: &CreateGroupMessageBody, queue: &MessageQueue) {- tracing::info!("creating group");- let db = &queue.db;- let connection_pairs = create_group(body).await;- let mut transaction = db.begin().await.unwrap();- let _ = create_connections(transaction.as_mut(), connection_pairs.clone())- .await- .inspect_err(|e| {- tracing::error!("couldn't create connections: {:?}", e);- });- let _ = transaction.commit().await.inspect_err(|e| {- tracing::error!("transaction error: {:?}", e);- });-- // Notify affected users- invalidate_contacts_for_users(&queue.connection_gateway_client, &connection_pairs).await;-}--#[cfg(test)]-fn connections_message_from_message(msg: Message) -> Option<ConnectionsMessage> {- match msg {- Message::AddConnection(con) => Some(con),- _ => None,- }-}--fn message_from_json(body: &str) -> Option<Message> {- serde_json::from_str(body).ok()-}--async fn message_from_sqs(msg: &aws_sdk_sqs::types::Message) -> Option<Message> {- if let Some(body) = msg.body.as_ref() {- message_from_json(body)- } else {- None- }-}--pub async fn process(msg: &Message, queue: &MessageQueue) -> anyhow::Result<()> {- match msg {- Message::AddConnection(con) => connections_message_handler(con, queue).await,- Message::AddParticipants(body) => add_participants_handler(body, queue).await,- Message::CreateGroup(body) => create_group_handler(body, queue).await,- };- Ok(())-}--#[allow(dead_code)]-impl MessageQueue {- pub fn new(- sqs: SQSWorker,- db: Pool<Postgres>,- connection_gateway_client: Option<ConnectionGatewayClient>,- ) -> MessageQueue {- MessageQueue {- sqs,- db,- connection_gateway_client,- }- }-- #[instrument(level = "info", skip(self))]- pub async fn poll(&mut self) {- let sqs = &self.sqs;- tracing::info!("initiated notification worker");- loop {- tracing::trace!("polling for messages");- match sqs.receive_messages().await {- Ok(messages) => {- if messages.is_empty() {- tracing::trace!("no messages found");- continue;- }- for message in messages {- match self.process_message(&message).await {- Ok(_) => (),- Err(e) => {- tracing::error!(error=?e, "error processing message");- }- };- }- }- Err(e) => {- tracing::error!(error=?e, "error receiving messages");- }- }- }- }-- #[instrument(level = "info", skip(self, message))]- pub async fn process_message(- &self,- message: &aws_sdk_sqs::types::Message,- ) -> anyhow::Result<()> {- self.parse_message(message).await?;- self.cleanup_message(message).await?;- Ok(())- }-- #[allow(dead_code)]- #[instrument(level = "info", skip(sqs_message, self))]- pub async fn parse_message(- &self,- sqs_message: &aws_sdk_sqs::types::Message,- ) -> anyhow::Result<()> {- let message = message_from_sqs(sqs_message).await;- if let Some(message) = message {- let _ = process(&message, self).await;- } else {- tracing::info!("Message could not be processed properly");- }- Ok(())- }-- async fn cleanup_message(&self, message: &aws_sdk_sqs::types::Message) -> anyhow::Result<()> {- let sqs = &self.sqs;- if let Some(receipt_handle) = message.receipt_handle.as_ref() {- tracing::trace!(message_id=?message.message_id, message_receipt_handle=?receipt_handle, "deleting message");- sqs.delete_message(receipt_handle).await?;- }- Ok(())- }-}--#[allow(dead_code)]-pub async fn add_user_to_group(group: &[String], user: &str) -> String {- // Convert string list to group- let mut group = Group::new(group);- // Convert user string to user vertex- let user: UserVertex = UserVertex::new(create_user(user));- // Apply append operation- let con: Vec<Connection> = if group.participants.contains(&user) {- vec![]- } else {- // HACK: insert user before calling append, then remove self-referenced edge- group.participants.insert(user.clone());- group- .append(&user)- .into_iter()- .filter(|e| e.a.data.id != e.b.data.id)- .collect()- };- // Convert results to message- let body = create_connections_message(&group, &con);- let msg = Message::AddConnection(body);- // Serialize message- serde_json::to_string(&msg).unwrap()-}--#[cfg(test)]-mod tests {- use super::*;- use std::collections::HashSet;-- #[test]- fn test_deserialize_connections_message() {- let input_json = include_str!("../tests/fixtures/add_connection.json");-- let message: Message = message_from_json(input_json).unwrap();- let conn_msg = connections_message_from_message(message);- assert!(conn_msg.is_some());- }-- fn generate_sqs_message() -> aws_sdk_sqs::types::Message {- let input_json = include_str!("../tests/fixtures/add_connection.json");- aws_sdk_sqs::types::Message::builder()- .set_body(Some(input_json.to_string()))- .build()- }-- #[tokio::test]- async fn test_message_from_aws_sqs() {- let sqs_message = generate_sqs_message();- let message = message_from_sqs(&sqs_message).await;-- assert!(message.is_some(), "Could not parse body from sqs message");-- let conn_msg = connections_message_from_message(message.unwrap());- assert!(conn_msg.is_some());- }-- #[tokio::test]- async fn test_add_user_to_group() {- let group: Vec<String> = [- "ff038d36-1aef-461a-8aa8-34001fa1abad",- "5ab8c770-f2cb-4c6c-bc08-ae64569e324c",- "d44caada-98c0-49eb-ab20-6851b824983a",- "79a5557b-7827-4e2e-a6ae-f0935cdb762e",- "c3f4d826-f8fd-478a-aa66-b5b6bb370cbc",- "c3b1970f-18ee-4dfa-b5fb-e8240e28e51d",- "9effe035-bb12-4fcc-b479-800e1c2551a8",- ]- .iter()- .map(|s| s.to_string())- .collect();- let new_user = "ae2c090c-e478-4454-a001-3df458bf1fe4";-- let msg = add_user_to_group(&group, new_user).await;-- let msg: Message = serde_json::from_str(&msg).expect("could not parse JSON");-- let body = match msg {- Message::AddConnection(body) => Some(body),- _ => None,- };-- assert!(body.is_some());-- let body = body.unwrap();-- assert_eq!(body.connections.len(), group.len());- }-- #[tokio::test]- async fn test_user_already_in_group() {- let group: Vec<String> = [- "ff038d36-1aef-461a-8aa8-34001fa1abad",- "5ab8c770-f2cb-4c6c-bc08-ae64569e324c",- "d44caada-98c0-49eb-ab20-6851b824983a",- "79a5557b-7827-4e2e-a6ae-f0935cdb762e",- "c3f4d826-f8fd-478a-aa66-b5b6bb370cbc",- "c3b1970f-18ee-4dfa-b5fb-e8240e28e51d",- "9effe035-bb12-4fcc-b479-800e1c2551a8",- "ae2c090c-e478-4454-a001-3df458bf1fe4",- ]- .iter()- .map(|s| s.to_string())- .collect();- let new_user = "ae2c090c-e478-4454-a001-3df458bf1fe4";-- let msg = add_user_to_group(&group, new_user).await;-- let msg: Message = serde_json::from_str(&msg).expect("could not parse JSON");-- let body = match msg {- Message::AddConnection(body) => Some(body),- _ => None,- };-- assert!(body.is_some());-- let body = body.unwrap();-- assert_eq!(body.connections.len(), 0);- }-- #[tokio::test]- async fn test_add_participants_message_body() {- // The full group: it's assumed the participants are in here already- // And that this will always be a correct message- let group = ["paul", "john", "ringo", "george"];- // We've just add ringo and george to the group- let participants = ["ringo", "george"];-- // one participant to group of 4 (including self): 3 new connections- // two new participants: 3 new connections, plus 2- // (make sure to account for redundant connection)- let expected_nconnections = 5;-- let body = AddParticipantsMessageBody {- group: group.into_iter().map(String::from).collect(),- participants: participants.into_iter().map(String::from).collect(),- group_id: None,- };-- let connections = add_participants(&body).await;-- assert_eq!(connections.len(), expected_nconnections);- }-- #[tokio::test]- async fn test_create_group_message_body() {- let group = ["paul", "john", "ringo", "george"];- let n = group.len();-- let expected_nconnections = n * (n - 1) / 2;-- let body = CreateGroupMessageBody {- group: group.into_iter().map(String::from).collect(),- group_id: None,- };-- let connections = create_group(&body).await;-- assert_eq!(connections.len(), expected_nconnections);- }-- #[tokio::test]- async fn test_add_participants_lowercase() {- // full group, including new participants- let full_group = [- "macro|[email protected]",- "macro|[email protected]",- "macro|[email protected]",- "macro|[email protected]",- ];- // We've just add ringo and george to the group, but they case is different- let new_participants = ["macro|[email protected]", "macro|[email protected]"];-- let body = AddParticipantsMessageBody {- group: full_group.into_iter().map(String::from).collect(),- participants: new_participants.into_iter().map(String::from).collect(),- group_id: None,- };-- // one participant to group of 4 (including self): 3 new connections- // two new participants: 3 new connections, plus 2- // (make sure to account for redundant connection)- let expected_nconnections = 5;-- let connections = add_participants(&body).await;- assert_eq!(connections.len(), expected_nconnections);- }- #[tokio::test]- async fn test_create_group_lowercase() {- let group = [- "macro|[email protected]",- "macro|[email protected]",- "macro|[email protected]",- "macro|[email protected]",- ];-- let body = CreateGroupMessageBody {- group: group.into_iter().map(String::from).collect(),- group_id: None,- };-- let connections = create_group(&body).await;-- let expected: HashSet<String> = [- "macro|[email protected]",- "macro|[email protected]",- "macro|[email protected]",- "macro|[email protected]",- ]- .to_vec()- .into_iter()- .map(|s| s.to_string())- .collect();-- let mut reality: HashSet<String> = HashSet::new();-- for con in connections {- reality.insert(con.0);- reality.insert(con.1);- }-- let reality: HashSet<String> = reality.into_iter().collect();-- assert_eq!(expected, reality);- }-}diff --git a/rust/cloud-storage/contacts_service/src/user.rs b/rust/cloud-storage/contacts_service/src/user.rsdeleted file mode 100644index 668bfba72b..0000000000--- a/rust/cloud-storage/contacts_service/src/user.rs+++ /dev/null@@ -1,256 +0,0 @@-use crate::graph;-use crate::graph::{Edge, Vertex};-use model::contacts::ConnectionsMessage;-use model::document::ID;-use std::collections::{HashMap, HashSet};--pub type User = ID;--pub fn create_user(id: &str) -> User {- User { id: id.to_string() }-}--#[allow(dead_code)]-#[derive(Default, Debug)]-pub struct Group {- pub participants: HashSet<Vertex<User>>,-}--pub type Connection<'a> = Edge<'a, User>;-pub type UserVertex = Vertex<User>;--impl Group {- pub fn append<'a, 'b>(&'a self, user: &'b Vertex<User>) -> Vec<Connection<'b>>- where- 'a: 'b,- {- graph::append(&self.participants, user)- }-- #[allow(dead_code)]- pub fn generate(&self) -> Vec<Connection<'_>> {- graph::generate(&self.participants)- }-- pub fn new(group: &[String]) -> Self {- Self::default().append_participants(group)- }-- pub fn append_participants(mut self, group: &[String]) -> Group {- for user in group {- self.participants.insert(Vertex::new(create_user(user)));- }- self- }-}--pub fn create_connections_message(group: &Group, connections: &[Connection]) -> ConnectionsMessage {- let mut users = vec![];- let mut user_to_index: HashMap<String, usize> = HashMap::new();-- for user in &group.participants {- let id = user.data.id.clone();- let pos = users.len();- users.push(id);- user_to_index.insert(users[pos].clone(), pos);- }-- let mut connection_references = vec![];-- for con in connections {- let user_a = &con.a.data.id;- let user_b = &con.b.data.id;-- // TODO: error handling- let user_a_index = if let Some(idx) = user_to_index.get(user_a) {- idx- } else {- panic!("Could not find user '{}'", user_a);- };- let user_b_index = user_to_index.get(user_b).unwrap();- connection_references.push((*user_a_index, *user_b_index));- }-- ConnectionsMessage {- users,- connections: connection_references,- }-}--pub async fn unpack_users(msg: &ConnectionsMessage) -> Vec<Vertex<User>> {- let mut vertex_list = vec![];-- for user in &msg.users {- let vtx = Vertex::new(User {- id: user.to_string(),- });- vertex_list.push(vtx);- }-- vertex_list-}--pub async fn unpack_connections<'a, 'b>(- msg: &'a ConnectionsMessage,- users: &'b [Vertex<User>],-) -> Vec<Connection<'b>>-where- 'a: 'b,-{- let mut connections = vec![];-- for con in &msg.connections {- connections.push(Connection {- a: &users[con.0],- b: &users[con.1],- })- }-- connections-}--#[cfg(test)]-async fn unpack<'a, 'b>(- msg: &'a ConnectionsMessage,- users: &'b Vec<UserVertex>,-) -> (Group, Vec<Connection<'b>>)-where- 'a: 'b,-{- let mut group = Group::default();- for user in users {- group.participants.insert(user.clone());- }-- let connections = unpack_connections(msg, users).await;-- (group, connections)-}--#[allow(dead_code)]-impl UserVertex {- pub fn generate(name: &str) -> Self {- Vertex::new(create_user(name))- }-}--#[cfg(test)]-mod tests {- use super::*;-- fn generate_test_users() -> Vec<Vertex<User>> {- let ulist: Vec<Vertex<User>> = [- ("oceanus", "ff038d36-1aef-461a-8aa8-34001fa1abad"),- ("tethys", "5ab8c770-f2cb-4c6c-bc08-ae64569e324c"),- ("hyperion", "d44caada-98c0-49eb-ab20-6851b824983a"),- ("theia", "79a5557b-7827-4e2e-a6ae-f0935cdb762e"),- ("coeus", "c3f4d826-f8fd-478a-aa66-b5b6bb370cbc"),- ("phoebe", "c3b1970f-18ee-4dfa-b5fb-e8240e28e51d"),- ("cornus", "9effe035-bb12-4fcc-b479-800e1c2551a8"),- ("rhea", "ae2c090c-e478-4454-a001-3df458bf1fe4"),- ("mnemosyne", "b4e6267e-83c4-427d-88f4-40483f4b97e6"),- ("themis", "f5263664-b82f-41f5-bd4c-65e445f43e54"),- ("crius", "083a6148-26c6-4a59-9106-dbfb82579edc"),- ("iapetus", "6be3aef7-0701-4f0c-be6e-750f23ae953c"),- ]- .iter()- .map(|(_, uuid)| {- Vertex::new(User {- id: uuid.to_string(),- })- })- .collect();-- ulist- }-- #[test]- fn test_group() {- let mut g = Group::default();- let users = generate_test_users();- let bob = Vertex::new(User {- id: "52D09596-7F05-4956-B64C-977AB9E334F9".to_string(),- });-- let nusers = users.len();- // Populate group with some users- for user in users {- g.participants.insert(user);- }-- // append a new user- let new_connections = g.append(&bob);-- assert_eq!(new_connections.len(), nusers);- }-- #[test]- // sanity test for group.generate(), which wraps graph::generate()- fn test_group_generate() {- let mut g = Group::default();- let users = generate_test_users();-- let nusers = users.len();- let nconnections = nusers * (nusers - 1) / 2;-- // Populate group with some users- for user in users {- g.participants.insert(user);- }-- let connections = g.generate();-- assert_eq!(connections.len(), nconnections);- }-- #[test]- // sanity test for creating ConnectionsMessage- fn test_connections_message() {- let mut g = Group::default();- let users = generate_test_users();-- let nusers = users.len();- let nconnections = nusers * (nusers - 1) / 2;-- // Populate group with some users- for user in users {- g.participants.insert(user);- }- let connections = g.generate();- let msg = create_connections_message(&g, &connections);-- assert_eq!(msg.users.len(), nusers);- assert_eq!(msg.connections.len(), nconnections);- }- #[tokio::test]- // make sure ConnectionsMessage can unpack itself into- // a Group and connetions- async fn test_connections_message_unpack() {- let mut g = Group::default();- let users = generate_test_users();-- let nusers = users.len();- let nconnections = nusers * (nusers - 1) / 2;-- // Populate group with some users- for user in users {- g.participants.insert(user);- }- let connections = g.generate();- let msg = create_connections_message(&g, &connections);-- let new_users = unpack_users(&msg).await;- let (new_group, new_connections) = unpack(&msg, &new_users).await;-- // Make sure all particiapnts are accounted for- for user in &g.participants {- assert!(- new_group.participants.contains(user),- "Could not find user {}",- user.data.id- );- }-- assert_eq!(new_connections.len(), nconnections);- }-}diff --git a/rust/cloud-storage/contacts_service/tests/fixtures/add_connection.json b/rust/cloud-storage/contacts_service/tests/fixtures/add_connection.jsondeleted file mode 100644index 64f5c820e7..0000000000--- a/rust/cloud-storage/contacts_service/tests/fixtures/add_connection.json+++ /dev/null@@ -1,7 +0,0 @@-{- "type": "add_connection",- "body": {- "users": ["zeus", "apollo", "athena"],- "connections": [[0, 1], [1, 2], [2, 0]]- }-}diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 7b95bd942f..f0ee5363a8 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -43,6 +43,7 @@ cloudfront_sign = { workspace = true }comms = { path = "../comms", features = ["outbound"] }comms_db_client = { path = "../comms_db_client" }comms_service = { path = "../comms_service" }+contacts = { path = "../contacts" }connection = { path = "../connection", default-features = false, features = ["outbound",] }@@ -119,7 +120,6 @@ serde_json = { workspace = true }soup = { path = "../soup", features = ["axum", "inbound", "outbound"] }sqlx = { workspace = true }sqs_client = { path = "../sqs_client", default-features = false, features = [- "contacts","document","search",] }diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 4f1a12a38e..57f5fdb90b 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -1,3 +1,6 @@+use contacts::domain::service::SqsContactsIngress;+use contacts::outbound::ingress::SqsContactsQueue;+use crate::{config::Config, service::s3::S3};use axum::extract::FromRef;use cal::{@@ -229,6 +232,7 @@ pub(crate) struct ApiContext {pub dynamo_db: aws_sdk_dynamodb::Client,pub soup_router_state: DssSoupState,pub sqs_client: Arc<sqs_client::SQS>,+ pub contacts_ingress: Arc<SqsContactsIngress<SqsContactsQueue>>,pub notification_ingress_service: Arc<NotificationIngressType>,pub conn_gateway_client: Arc<ConnectionGatewayClient>,pub sync_service_client: Arc<SyncServiceClient>,@@ -297,6 +301,7 @@ impl From<&ApiContext> for CommsHandlerState {connection_gateway_client: ctx.conn_gateway_client.clone(),notification_ingress_service: ctx.notification_ingress_service.clone(),sqs_client: ctx.sqs_client.clone(),+ contacts_ingress: ctx.contacts_ingress.clone(),permissions_token_secret: ctx.permissions_token_secret.clone(),frecency_storage: ctx.frecency_storage.clone(),comms_state: ctx.comms_state.clone(),diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 4e14c790be..4b07ba9ceb 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -161,10 +161,16 @@ async fn main() -> anyhow::Result<()> {tracing::trace!("initialized s3 client");let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))- .contacts_queue(&config.vars.contacts_queue).search_event_queue(&config.vars.search_event_queue).document_delete_queue(&config.vars.document_delete_queue);+ let contacts_ingress = Arc::new(contacts::domain::service::SqsContactsIngress {+ queue: contacts::outbound::ingress::SqsContactsQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ config.vars.contacts_queue.as_ref().to_string(),+ ),+ });+tracing::trace!("initialized sqs client");// Redis handles it own connection pool internally. Each time we use redis@@ -478,6 +484,7 @@ async fn main() -> anyhow::Result<()> {);let api_context = ApiContext {+ contacts_ingress,soup_router_state: SoupRouterState::new(SoupImpl::new(PgSoupRepo::new(readonly_pool::ReadOnlyPool(readonly_db.clone())),diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex 4f27ed6a18..e27ccaa113 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -107,6 +107,7 @@ notification = { path = "../notification" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }mime_guess = "2.0.5"+contacts = { path = "../contacts" }model = { path = "../model" }model-entity = { path = "../model-entity" }model_file_type = { path = "../model_file_type" }@@ -133,7 +134,6 @@ sha2 = { workspace = true }sqlx = { workspace = true }sqlx-core = { workspace = true }sqs_client = { path = "../sqs_client", default-features = false, features = [- "contacts","email","gmail","search",diff --git a/rust/cloud-storage/email_service/src/bin/backfill_contacts/backfill_contacts.rs b/rust/cloud-storage/email_service/src/bin/backfill_contacts/backfill_contacts.rsindex e4871747d8..1be834c10b 100644--- a/rust/cloud-storage/email_service/src/bin/backfill_contacts/backfill_contacts.rs+++ b/rust/cloud-storage/email_service/src/bin/backfill_contacts/backfill_contacts.rs@@ -26,8 +26,12 @@ async fn main() -> anyhow::Result<()> {let aws_config = macro_aws_config::get_macro_aws_config().await;- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))- .contacts_queue(&config.contacts_queue);+ let contacts_ingress = contacts::domain::service::SqsContactsIngress {+ queue: contacts::outbound::ingress::SqsContactsQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ config.contacts_queue.clone(),+ ),+ };println!("Processing {} macro IDs: {:?}", macro_ids.len(), macro_ids);@@ -39,7 +43,7 @@ async fn main() -> anyhow::Result<()> {macro_ids.len());- match process::process_macro_id(&db_pool, &sqs_client, macro_id).await {+ match process::process_macro_id(&db_pool, &contacts_ingress, macro_id).await {Ok(()) => {println!("Completed processing for {}.", macro_id);}diff --git a/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs b/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rsindex 12c4641951..051c1d0f46 100644--- a/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs+++ b/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs@@ -1,10 +1,12 @@-use model::contacts::ConnectionsMessage;-use sqs_client::SQS;+use contacts::domain::ports::ContactsIngress;+use contacts::domain::service::SqsContactsIngress;+use contacts::outbound::ingress::SqsContactsQueue;+use macro_user_id::user_id::MacroUserIdStr;/// Process contacts for a single macro IDpub async fn process_macro_id(db_pool: &sqlx::PgPool,- sqs_client: &SQS,+ contacts_ingress: &SqsContactsIngress<SqsContactsQueue>,macro_id: &str,) -> anyhow::Result<()> {let link = email_db_client::links::get::fetch_link_by_macro_id(db_pool, macro_id)@@ -23,20 +25,19 @@ pub async fn process_macro_id(return Ok(());}- let mut users = vec![link.macro_id.to_string()];- users.extend(- contact_emails- .iter()- .map(|email| format!("macro|{}", email)),- );-- let connections = (1..users.len()).map(|i| (0, i)).collect::<Vec<_>>();-- let connections_message = ConnectionsMessage { users, connections };+ let users: std::collections::HashSet<MacroUserIdStr<'static>> =+ std::iter::once(Ok(link.macro_id.clone()))+ .chain(+ contact_emails+ .iter()+ .map(|email| MacroUserIdStr::try_from_email(email)),+ )+ .collect::<Result<_, _>>()?;- sqs_client- .enqueue_contacts_add_connection(connections_message)- .await?;+ contacts_ingress+ .enqueue_contacts(users)+ .await+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;Ok(())}diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rsindex 1a42fdd740..0e07adeb93 100644--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs@@ -84,9 +84,15 @@ async fn main() -> anyhow::Result<()> {.email_scheduled_queue(&config.email_scheduled_queue).sfs_uploader_queue(&config.sfs_uploader_queue).sfs_delete_queue(&config.sfs_delete_queue)- .contacts_queue(&config.contacts_queue).email_link_manager_queue(&config.link_manager_queue);+ let contacts_ingress = Arc::new(contacts::domain::service::SqsContactsIngress {+ queue: contacts::outbound::ingress::SqsContactsQueue::new(+ aws_sdk_sqs::Client::new(&gmail_queue_aws_config),+ config.contacts_queue.clone(),+ ),+ });+let link_manager_worker = sqs_worker::SQSWorker::new(aws_sdk_sqs::Client::new(&gmail_queue_aws_config),config.link_manager_queue.clone(),@@ -233,6 +239,7 @@ async fn main() -> anyhow::Result<()> {for worker in inbox_sync_workers {let db_inbox_sync = db.clone();let sqs_client_inbox_sync = sqs_client.clone();+ let contacts_ingress_inbox_sync = contacts_ingress.clone();let gmail_client_inbox_sync = gmail_client.clone();let auth_service_client_inbox_sync = auth_service_client.clone();let redis_client_inbox_sync = redis_client.clone();@@ -246,6 +253,7 @@ async fn main() -> anyhow::Result<()> {db_inbox_sync,worker,sqs_client_inbox_sync,+ contacts_ingress_inbox_sync,gmail_client_inbox_sync,auth_service_client_inbox_sync,redis_client_inbox_sync,@@ -269,6 +277,7 @@ async fn main() -> anyhow::Result<()> {for worker in inbox_sync_retry_workers {let db_inbox_sync = db.clone();let sqs_client_inbox_sync = sqs_client.clone();+ let contacts_ingress_inbox_sync = contacts_ingress.clone();let gmail_client_inbox_sync = gmail_client.clone();let auth_service_client_inbox_sync = auth_service_client.clone();let redis_client_inbox_sync = redis_client.clone();@@ -282,6 +291,7 @@ async fn main() -> anyhow::Result<()> {db_inbox_sync,worker,sqs_client_inbox_sync,+ contacts_ingress_inbox_sync,gmail_client_inbox_sync,auth_service_client_inbox_sync,redis_client_inbox_sync,@@ -355,6 +365,7 @@ async fn main() -> anyhow::Result<()> {for worker in backfill_workers {let db_backfill = db_backfill.clone();let sqs_client_backfill = sqs_client.clone();+ let contacts_ingress_backfill = contacts_ingress.clone();let gmail_client_backfill = gmail_client.clone();let auth_service_client_backfill = auth_service_client.clone();let redis_client_backfill = redis_client.clone();@@ -368,6 +379,7 @@ async fn main() -> anyhow::Result<()> {db_backfill,worker,sqs_client_backfill,+ contacts_ingress_backfill,gmail_client_backfill,auth_service_client_backfill,redis_client_backfill,diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rsindex f7102ce883..ad2f45e1a0 100644--- a/rust/cloud-storage/email_service/src/main.rs+++ b/rust/cloud-storage/email_service/src/main.rs@@ -76,7 +76,6 @@ async fn main() -> anyhow::Result<()> {.email_backfill_queue(&config.backfill_queue).email_scheduled_queue(&config.email_scheduled_queue).sfs_uploader_queue(&config.sfs_uploader_queue)- .contacts_queue(&config.contacts_queue).email_link_manager_queue(&config.link_manager_queue);let auth_service_client = authentication_service_client::AuthServiceClient::new(diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rsindex 1de5fb9517..de764d0739 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs@@ -1,5 +1,8 @@+use std::collections::HashSet;+use crate::pubsub::context::PubSubContext;-use model::contacts::ConnectionsMessage;+use contacts::domain::ports::ContactsIngress;+use macro_user_id::user_id::MacroUserIdStr;use models_email::db::address::EmailRecipientType;use models_email::service::attachment::{AttachmentUploadArgs, AttachmentUploadDestination, AttachmentUploadMetadata,@@ -157,24 +160,27 @@ async fn handle_contacts_sync(ctx: &PubSubContext, link: &Link) -> Result<(), Prlink.macro_id);- let mut users = vec![link.macro_id.to_string()];- users.extend(- email_addresses- .iter()- .map(|email| format!("macro|{}", email)),- );-- let connections = (1..users.len()).map(|i| (0, i)).collect::<Vec<_>>();-- let connections_message = ConnectionsMessage { users, connections };+ let users: HashSet<MacroUserIdStr<'static>> = std::iter::once(Ok(link.macro_id.clone()))+ .chain(+ email_addresses+ .iter()+ .map(|email| MacroUserIdStr::try_from_email(email)),+ )+ .collect::<Result<_, _>>()+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: anyhow::anyhow!(e).context("invalid user email for contacts"),+ })+ })?;- ctx.sqs_client- .enqueue_contacts_add_connection(connections_message)+ ctx.contacts_ingress+ .enqueue_contacts(users).await.map_err(|e| {ProcessingError::NonRetryable(DetailedError {reason: FailureReason::SqsEnqueueFailed,- source: e.context(format!(+ source: anyhow::anyhow!("{e:?}").context(format!("Failed to enqueue contacts message for {}",email_addresses.join(", "))),diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rsindex 6ea189ebd5..80a54c5bd7 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs@@ -3,6 +3,8 @@ use crate::pubsub::context::{NotificationIngressType, PubSubContext};use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;+use contacts::domain::service::SqsContactsIngress;+use contacts::outbound::ingress::SqsContactsQueue;use document_storage_service_client::DocumentStorageServiceClient;use futures::StreamExt;use static_file_service_client::StaticFileServiceClient;@@ -15,6 +17,7 @@ pub async fn run_worker(db: sqlx::Pool<sqlx::Postgres>,worker: sqs_worker::SQSWorker,sqs_client: sqs_client::SQS,+ contacts_ingress: Arc<SqsContactsIngress<SqsContactsQueue>>,gmail_client: gmail_client::GmailClient,auth_service_client: AuthServiceClient,redis_client: RedisClient,@@ -29,6 +32,7 @@ pub async fn run_worker(db,sqs_worker: worker.clone(),sqs_client,+ contacts_ingress,gmail_client,auth_service_client,redis_client,diff --git a/rust/cloud-storage/email_service/src/pubsub/context.rs b/rust/cloud-storage/email_service/src/pubsub/context.rsindex 0d490a5004..4781655705 100644--- a/rust/cloud-storage/email_service/src/pubsub/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/context.rs@@ -1,6 +1,8 @@use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;+use contacts::domain::service::SqsContactsIngress;+use contacts::outbound::ingress::SqsContactsQueue;use document_storage_service_client::DocumentStorageServiceClient;use gmail_client::GmailClient;use notification::domain::service::SqsNotificationIngress;@@ -18,6 +20,7 @@ pub struct PubSubContext {pub db: PgPool,pub sqs_worker: sqs_worker::SQSWorker,pub sqs_client: sqs_client::SQS,+ pub contacts_ingress: Arc<SqsContactsIngress<SqsContactsQueue>>,pub gmail_client: GmailClient,pub auth_service_client: AuthServiceClient,pub redis_client: RedisClient,diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rsindex 576830813d..f00ba06c12 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs@@ -1,3 +1,5 @@+use contacts::domain::ports::ContactsIngress;+use crate::convert::{map_message_resource_to_service, map_thread_resources_to_service};use crate::pubsub::context::PubSubContext;use crate::pubsub::inbox_sync::operations::shared::notify_search;@@ -9,7 +11,6 @@ use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment}use email_db_client::threads;use email_utils::dedupe_emails;use macro_user_id::user_id::MacroUserIdStr;-use model::contacts::ConnectionsMessage;use model_entity::EntityType;use model_notifications::NewEmailMetadata;use models_email::db::address::EmailRecipientType;@@ -337,24 +338,28 @@ async fn handle_contacts_sync(return Ok(());}- // Build users list: current user at index 0, connection targets after- let mut users = vec![link.macro_id.to_string()];- users.extend(- connection_emails- .iter()- .map(|email| format!("macro|{email}")),- );-- // Create connections from current user (index 0) to each other user- let connections = (1..users.len()).map(|i| (0, i)).collect();+ let users: std::collections::HashSet<MacroUserIdStr<'static>> =+ std::iter::once(Ok(link.macro_id.clone()))+ .chain(+ connection_emails+ .iter()+ .map(|email| MacroUserIdStr::try_from_email(email)),+ )+ .collect::<Result<_, _>>()+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: anyhow::anyhow!(e).context("invalid user email for contacts"),+ })+ })?;- ctx.sqs_client- .enqueue_contacts_add_connection(ConnectionsMessage { users, connections })+ ctx.contacts_ingress+ .enqueue_contacts(users).await.map_err(|e| {ProcessingError::NonRetryable(DetailedError {reason: FailureReason::SqsEnqueueFailed,- source: e.context(format!(+ source: anyhow::anyhow!("{e:?}").context(format!("Failed to enqueue contacts message for {}",link.macro_id)),diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rsindex 69dc58ce1e..894a9fd46f 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rs@@ -3,6 +3,8 @@ use crate::pubsub::inbox_sync::process;use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;+use contacts::domain::service::SqsContactsIngress;+use contacts::outbound::ingress::SqsContactsQueue;use document_storage_service_client::DocumentStorageServiceClient;use futures::StreamExt;use static_file_service_client::StaticFileServiceClient;@@ -15,6 +17,7 @@ pub async fn run_worker(db: sqlx::Pool<sqlx::Postgres>,worker: sqs_worker::SQSWorker,sqs_client: sqs_client::SQS,+ contacts_ingress: Arc<SqsContactsIngress<SqsContactsQueue>>,gmail_client: gmail_client::GmailClient,auth_service_client: AuthServiceClient,redis_client: RedisClient,@@ -30,6 +33,7 @@ pub async fn run_worker(db,sqs_worker: worker.clone(),sqs_client,+ contacts_ingress,gmail_client,auth_service_client,redis_client,diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 913e3cc111..c9ab5aa114 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -52,7 +52,11 @@ build_lambdas:# Copies over necessary .env files for sqlx testssetup_test_envs:- echo "DATABASE_URL={{ DATABASE_URL }}" >> ./contacts_db_client/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./contacts/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./delete_chat_handler/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./integration_tests/test_pdf_modification_data_deserialize/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./email_sfs_delete_handler/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./scheduled_action/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./notification_db_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./notification/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./properties_db_client/.envdiff --git a/rust/cloud-storage/macro_db_client/migrations/20260429120000_contacts_no_self_connection.sql b/rust/cloud-storage/macro_db_client/migrations/20260429120000_contacts_no_self_connection.sqlnew file mode 100644index 0000000000..f92b7dd051--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260429120000_contacts_no_self_connection.sql@@ -0,0 +1,5 @@+DELETE FROM contacts_connections WHERE user1 = user2;++ALTER TABLE contacts_connections+ DROP CONSTRAINT contacts_connections_check,+ ADD CONSTRAINT contacts_connections_user1_user2_check CHECK (user1 < user2 COLLATE "C");diff --git a/rust/cloud-storage/macro_db_client/migrations/20260429140000_contacts_backfill_outbox.sql b/rust/cloud-storage/macro_db_client/migrations/20260429140000_contacts_backfill_outbox.sqlnew file mode 100644index 0000000000..0cad78cf4f--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260429140000_contacts_backfill_outbox.sql@@ -0,0 +1,42 @@+CREATE TABLE contacts_backfill_outbox (+ id SERIAL PRIMARY KEY,+ comms_channel_id uuid NOT NULL REFERENCES comms_channels(id),+ user_ids jsonb NOT NULL,+ applied_at timestamptz,+ created_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX idx_contacts_backfill_outbox_applied_at ON contacts_backfill_outbox(applied_at);++DO $$+DECLARE+ batch_size INT := 100;+ last_id TEXT := '00000000-0000-0000-0000-000000000000';+ batch_count INT;+BEGIN+ LOOP+ WITH batch AS (+ SELECT c.id+ FROM comms_channels c+ WHERE c.id::text > last_id+ ORDER BY c.id::text+ LIMIT batch_size+ ),+ inserted AS (+ INSERT INTO contacts_backfill_outbox (comms_channel_id, user_ids)+ SELECT+ b.id,+ jsonb_agg(p.user_id)+ FROM batch b+ JOIN comms_channel_participants p ON p.channel_id = b.id+ GROUP BY b.id+ RETURNING comms_channel_id+ )+ SELECT COUNT(*), MAX(b.id::text)+ INTO batch_count, last_id+ FROM batch b;++ EXIT WHEN batch_count < batch_size;+ PERFORM pg_sleep(0.5);+ END LOOP;+END $$;diff --git a/rust/cloud-storage/model/src/contacts/mod.rs b/rust/cloud-storage/model/src/contacts/mod.rsdeleted file mode 100644index 66e90369df..0000000000--- a/rust/cloud-storage/model/src/contacts/mod.rs+++ /dev/null@@ -1,31 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Debug)]-pub struct ConnectionsMessage {- pub users: Vec<String>,- pub connections: Vec<(usize, usize)>,-}--#[derive(Serialize, Deserialize, Debug)]-pub struct AddParticipantsMessageBody {- pub participants: Vec<String>,- pub group: Vec<String>,- pub group_id: Option<String>,-}--#[derive(Serialize, Deserialize, Debug)]-pub struct CreateGroupMessageBody {- pub group: Vec<String>,- pub group_id: Option<String>,-}--#[derive(Serialize, Deserialize, Debug)]-#[serde(tag = "type", content = "body")]-pub enum Message {- #[serde(rename = "add_connection")]- AddConnection(ConnectionsMessage),- #[serde(rename = "add_participants")]- AddParticipants(AddParticipantsMessageBody),- #[serde(rename = "create_group")]- CreateGroup(CreateGroupMessageBody),-}diff --git a/rust/cloud-storage/model/src/lib.rs b/rust/cloud-storage/model/src/lib.rsindex 1faa7dc76b..d9cbd36627 100644--- a/rust/cloud-storage/model/src/lib.rs+++ b/rust/cloud-storage/model/src/lib.rs@@ -5,7 +5,6 @@ pub mod authentication;pub mod chat;pub mod citations;pub mod comms;-pub mod contacts;pub mod convert;pub mod document;pub mod document_storage_service_internal;diff --git a/rust/cloud-storage/sqs_client/Cargo.toml b/rust/cloud-storage/sqs_client/Cargo.tomlindex 716578361e..5ca6cd96bc 100644--- a/rust/cloud-storage/sqs_client/Cargo.toml+++ b/rust/cloud-storage/sqs_client/Cargo.toml@@ -6,11 +6,9 @@ version = "0.1.0"[features]chat = []-contacts = ["model"]convert = ["model"]default = ["chat",- "contacts","convert","document","document_text_extractor",@@ -45,6 +43,5 @@ serde_json = { workspace = true }strum = { workspace = true, features = ["derive"] }tracing = { workspace = true }uuid = { workspace = true, optional = true }-macro_user_id = { path = "../macro_user_id", optional = true }models_opensearch = { path = "../models_opensearch", optional = true }futures = { workspace = true, optional = true }diff --git a/rust/cloud-storage/sqs_client/src/contacts.rs b/rust/cloud-storage/sqs_client/src/contacts.rsdeleted file mode 100644index 80c8fde4e6..0000000000--- a/rust/cloud-storage/sqs_client/src/contacts.rs+++ /dev/null@@ -1,129 +0,0 @@-use crate::SQS;-use model::contacts::{- AddParticipantsMessageBody, ConnectionsMessage, CreateGroupMessageBody, Message,-};--impl SQS {- pub fn contacts_queue(mut self, contacts_queue: &str) -> Self {- self.contacts_queue = Some(contacts_queue.to_string());- self- }-- #[tracing::instrument(skip(self))]- pub async fn enqueue_contacts_add_participants(- &self,- new_participants: Vec<String>,- channel_participants: Vec<String>,- channel_id: &str,- ) -> anyhow::Result<()> {- if let Some(contacts_queue) = &self.contacts_queue {- return enqueue_contacts_add_participants(- &self.inner,- contacts_queue,- new_participants,- channel_participants,- channel_id,- )- .await;- }- Err(anyhow::anyhow!("contacts_queue is not configured"))- }-- #[tracing::instrument(skip(self))]- pub async fn enqueue_contacts_create_channel(- &self,- participants: Vec<String>,- channel_id: &str,- ) -> anyhow::Result<()> {- if let Some(contacts_queue) = &self.contacts_queue {- return enqueue_contacts_create_channel(- &self.inner,- contacts_queue,- participants,- channel_id,- )- .await;- }-- Err(anyhow::anyhow!("contacts_queue is not configured"))- }-- #[tracing::instrument(skip(self))]- pub async fn enqueue_contacts_add_connection(- &self,- connections_message: ConnectionsMessage,- ) -> anyhow::Result<()> {- if let Some(contacts_queue) = &self.contacts_queue {- return enqueue_contacts_add_connection(- &self.inner,- contacts_queue,- connections_message,- )- .await;- }- Err(anyhow::anyhow!("contacts_queue is not configured"))- }-}--#[tracing::instrument(skip(sqs_client, participants))]-pub async fn enqueue_contacts_create_channel(- sqs_client: &aws_sdk_sqs::Client,- queue_url: &str,- participants: Vec<String>,- channel_id: &str,-) -> anyhow::Result<()> {- let body = CreateGroupMessageBody {- group: participants,- group_id: Some(channel_id.to_string()),- };- let message = Message::CreateGroup(body);- let message_str = serde_json::to_string(&message)?;- sqs_client- .send_message()- .queue_url(queue_url)- .message_body(message_str)- .send()- .await?;- Ok(())-}--#[tracing::instrument(skip(sqs_client, new_participants, channel_participants))]-pub async fn enqueue_contacts_add_participants(- sqs_client: &aws_sdk_sqs::Client,- queue_url: &str,- new_participants: Vec<String>,- channel_participants: Vec<String>,- channel_id: &str,-) -> anyhow::Result<()> {- let body = AddParticipantsMessageBody {- group: channel_participants,- participants: new_participants,- group_id: Some(channel_id.to_string()),- };- let message = Message::AddParticipants(body);- let message_str = serde_json::to_string(&message)?;- sqs_client- .send_message()- .queue_url(queue_url)- .message_body(message_str)- .send()- .await?;- Ok(())-}--#[tracing::instrument(skip(sqs_client, queue_url))]-pub async fn enqueue_contacts_add_connection(- sqs_client: &aws_sdk_sqs::Client,- queue_url: &str,- connections_message: ConnectionsMessage,-) -> anyhow::Result<()> {- let message = Message::AddConnection(connections_message);- let message_str = serde_json::to_string(&message)?;- sqs_client- .send_message()- .queue_url(queue_url)- .message_body(message_str)- .send()- .await?;- Ok(())-}diff --git a/rust/cloud-storage/sqs_client/src/lib.rs b/rust/cloud-storage/sqs_client/src/lib.rsindex 304ba1805a..e2fc8a342c 100644--- a/rust/cloud-storage/sqs_client/src/lib.rs+++ b/rust/cloud-storage/sqs_client/src/lib.rs@@ -3,9 +3,6 @@ mod message_attribute;#[cfg(feature = "chat")]pub mod chat;-#[cfg(feature = "contacts")]-pub mod contacts;-#[cfg(feature = "convert")]pub mod convert;@@ -63,8 +60,6 @@ pub struct SQS {chat_delete_queue: Option<String>,#[cfg(feature = "document_text_extractor")]document_text_extractor_queue: Option<String>,- #[cfg(feature = "contacts")]- contacts_queue: Option<String>,#[cfg(feature = "upload_extractor")]upload_extractor_queue: Option<String>,#[cfg(feature = "convert")]@@ -103,8 +98,6 @@ impl SQS {chat_delete_queue: None,#[cfg(feature = "document_text_extractor")]document_text_extractor_queue: None,- #[cfg(feature = "contacts")]- contacts_queue: None,#[cfg(feature = "upload_extractor")]upload_extractor_queue: None,#[cfg(feature = "convert")]