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
feat(crm): wire populate/depopulate into inbox-sync, team-removal, and link-delete paths (#3408)
Evan Hutnikc0b0c3f5e792
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.tsindex c134f65adf..34053a859b 100644--- a/infra/stacks/email-service/index.ts+++ b/infra/stacks/email-service/index.ts@@ -377,7 +377,7 @@ emailAttachmentBucket.attachCloudfrontPolicy({const containerEnvVars = [{name: 'RUST_LOG',- value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${stack === 'prod' ? 'debug' : 'debug'},entity_access=${stack === 'prod' ? 'debug' : 'debug'},pubsub_workers=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info`,+ value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${stack === 'prod' ? 'debug' : 'debug'},entity_access=${stack === 'prod' ? 'debug' : 'debug'},pubsub_workers=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info,crm=${stack === 'prod' ? 'info' : 'debug'},teams=${stack === 'prod' ? 'info' : 'debug'}`,},{name: 'ENVIRONMENT',diff --git a/rust/cloud-storage/.sqlx/query-1b10aa25f5e73a6f33bb2e4cc000644ee2329d7917c9d6692e52b803eaad1e81.json b/rust/cloud-storage/.sqlx/query-1b10aa25f5e73a6f33bb2e4cc000644ee2329d7917c9d6692e52b803eaad1e81.jsonnew file mode 100644index 0000000000..6e368ae2f5--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-1b10aa25f5e73a6f33bb2e4cc000644ee2329d7917c9d6692e52b803eaad1e81.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m\n JOIN email_message_recipients r ON r.message_id = m.id\n JOIN email_contacts c ON c.id = r.contact_id\n WHERE m.link_id = $1\n AND m.is_sent = true\n AND LOWER(c.email_address) = $2\n LIMIT 1\n ) AS \"exists!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "1b10aa25f5e73a6f33bb2e4cc000644ee2329d7917c9d6692e52b803eaad1e81"+}diff --git a/rust/cloud-storage/.sqlx/query-1d935a7fdb8ef926a5b7613fcb7ecc9949bb5adff895d426acbcdbef50a87e96.json b/rust/cloud-storage/.sqlx/query-1d935a7fdb8ef926a5b7613fcb7ecc9949bb5adff895d426acbcdbef50a87e96.jsonnew file mode 100644index 0000000000..8b039290a8--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-1d935a7fdb8ef926a5b7613fcb7ecc9949bb5adff895d426acbcdbef50a87e96.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM crm_contacts WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "1d935a7fdb8ef926a5b7613fcb7ecc9949bb5adff895d426acbcdbef50a87e96"+}diff --git a/rust/cloud-storage/.sqlx/query-2b0bd67ac9cce9b0698818204cf404ae3e408b20117fa9e3664d19b0a9ef8f8d.json b/rust/cloud-storage/.sqlx/query-2b0bd67ac9cce9b0698818204cf404ae3e408b20117fa9e3664d19b0a9ef8f8d.jsonnew file mode 100644index 0000000000..cd65d53f6b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-2b0bd67ac9cce9b0698818204cf404ae3e408b20117fa9e3664d19b0a9ef8f8d.json@@ -0,0 +1,47 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.id, c.team_id, dd.name, c.email_sync, c.created_at\n FROM crm_companies c\n JOIN crm_domains d ON d.company_id = c.id\n LEFT JOIN crm_domain_directory dd ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE c.team_id = $1\n AND LOWER(d.domain) = $2\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "email_sync",+ "type_info": "Bool"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "2b0bd67ac9cce9b0698818204cf404ae3e408b20117fa9e3664d19b0a9ef8f8d"+}diff --git a/rust/cloud-storage/.sqlx/query-3115f8be3dd48c06ee8fc8262edc5ba54935753a9e5eebdd49ba0ba86f371e34.json b/rust/cloud-storage/.sqlx/query-3115f8be3dd48c06ee8fc8262edc5ba54935753a9e5eebdd49ba0ba86f371e34.jsonnew file mode 100644index 0000000000..2fb8652d13--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-3115f8be3dd48c06ee8fc8262edc5ba54935753a9e5eebdd49ba0ba86f371e34.json@@ -0,0 +1,41 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.id, c.team_id, c.email_sync, c.created_at\n FROM crm_companies c\n JOIN crm_domains d ON d.company_id = c.id\n WHERE c.team_id = $1\n AND LOWER(d.domain) = $2\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "email_sync",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "created_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false+ ]+ },+ "hash": "3115f8be3dd48c06ee8fc8262edc5ba54935753a9e5eebdd49ba0ba86f371e34"+}diff --git a/rust/cloud-storage/.sqlx/query-5a21a770cc376a29715d9becc8a69193889b701c49f3bbef18e69f340b041eba.json b/rust/cloud-storage/.sqlx/query-5a21a770cc376a29715d9becc8a69193889b701c49f3bbef18e69f340b041eba.jsonnew file mode 100644index 0000000000..827fdca86e--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-5a21a770cc376a29715d9becc8a69193889b701c49f3bbef18e69f340b041eba.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO crm_companies (team_id)\n VALUES ($1)\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "5a21a770cc376a29715d9becc8a69193889b701c49f3bbef18e69f340b041eba"+}diff --git a/rust/cloud-storage/.sqlx/query-5cc14a0cfb5a12ade0a35b3492e2a67bc3653e98e5fc5769d0189583e63a2bc8.json b/rust/cloud-storage/.sqlx/query-5cc14a0cfb5a12ade0a35b3492e2a67bc3653e98e5fc5769d0189583e63a2bc8.jsonnew file mode 100644index 0000000000..335e18cc3c--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-5cc14a0cfb5a12ade0a35b3492e2a67bc3653e98e5fc5769d0189583e63a2bc8.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT name\n FROM email_contacts\n WHERE LOWER(email_address) = LOWER($1)\n AND link_id = $2\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "name",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "5cc14a0cfb5a12ade0a35b3492e2a67bc3653e98e5fc5769d0189583e63a2bc8"+}diff --git a/rust/cloud-storage/.sqlx/query-654e58c390f6a8935cd310d596202b9b2036019140bb0da9d2f033cdba2289f3.json b/rust/cloud-storage/.sqlx/query-654e58c390f6a8935cd310d596202b9b2036019140bb0da9d2f033cdba2289f3.jsonnew file mode 100644index 0000000000..4b5337dcfa--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-654e58c390f6a8935cd310d596202b9b2036019140bb0da9d2f033cdba2289f3.json@@ -0,0 +1,36 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n ct.id AS contact_id,\n co.id AS company_id,\n co.email_sync AS \"email_sync!\"\n FROM crm_contacts ct\n JOIN crm_companies co ON co.id = ct.company_id\n JOIN crm_domains d ON d.company_id = co.id\n WHERE co.team_id = $1\n AND LOWER(ct.email) = $2\n AND LOWER(d.domain) = $3\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "contact_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "company_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "email_sync!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "654e58c390f6a8935cd310d596202b9b2036019140bb0da9d2f033cdba2289f3"+}diff --git a/rust/cloud-storage/.sqlx/query-65d1dc0e96a4a41d52387f43fe08cea15b4124517eeed1d24ab006dd33e409e1.json b/rust/cloud-storage/.sqlx/query-65d1dc0e96a4a41d52387f43fe08cea15b4124517eeed1d24ab006dd33e409e1.jsonnew file mode 100644index 0000000000..0ce7460420--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-65d1dc0e96a4a41d52387f43fe08cea15b4124517eeed1d24ab006dd33e409e1.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM crm_contact_sources cs\n USING crm_contacts ct, crm_companies co\n WHERE cs.contact_id = ct.id\n AND ct.company_id = co.id\n AND co.team_id = $1\n AND cs.link_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "65d1dc0e96a4a41d52387f43fe08cea15b4124517eeed1d24ab006dd33e409e1"+}diff --git a/rust/cloud-storage/.sqlx/query-6c77980a2f5bad42f7b99481c3cbaeabb6e10d11cd1f2926d3c27cb62a8025c5.json b/rust/cloud-storage/.sqlx/query-6c77980a2f5bad42f7b99481c3cbaeabb6e10d11cd1f2926d3c27cb62a8025c5.jsonnew file mode 100644index 0000000000..cc6f8a9dc3--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6c77980a2f5bad42f7b99481c3cbaeabb6e10d11cd1f2926d3c27cb62a8025c5.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO crm_contacts (company_id, email, name)\n VALUES ($1, $2, $3)\n ON CONFLICT (company_id, email) DO UPDATE\n SET name = COALESCE(crm_contacts.name, EXCLUDED.name)\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "6c77980a2f5bad42f7b99481c3cbaeabb6e10d11cd1f2926d3c27cb62a8025c5"+}diff --git a/rust/cloud-storage/.sqlx/query-6ea476e8245e7216dab1393cd8f0da3d51a68f4e1240540fe06c72fc75ff8006.json b/rust/cloud-storage/.sqlx/query-6ea476e8245e7216dab1393cd8f0da3d51a68f4e1240540fe06c72fc75ff8006.jsonnew file mode 100644index 0000000000..0136a4dd0c--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6ea476e8245e7216dab1393cd8f0da3d51a68f4e1240540fe06c72fc75ff8006.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE crm_companies\n SET name = $1\n WHERE id = $2 AND name IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "6ea476e8245e7216dab1393cd8f0da3d51a68f4e1240540fe06c72fc75ff8006"+}diff --git a/rust/cloud-storage/.sqlx/query-85c2f0bf2436f55cacf260a16b215803b469829ffe73f13210dc6899a5f352d1.json b/rust/cloud-storage/.sqlx/query-85c2f0bf2436f55cacf260a16b215803b469829ffe73f13210dc6899a5f352d1.jsonnew file mode 100644index 0000000000..bdd58aa2c3--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-85c2f0bf2436f55cacf260a16b215803b469829ffe73f13210dc6899a5f352d1.json@@ -0,0 +1,30 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT ct.id AS contact_id, co.id AS company_id\n FROM crm_contacts ct\n JOIN crm_companies co ON co.id = ct.company_id\n JOIN crm_domains d ON d.company_id = co.id\n WHERE co.team_id = $1\n AND LOWER(ct.email) = $2\n AND LOWER(d.domain) = $3\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "contact_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "company_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "85c2f0bf2436f55cacf260a16b215803b469829ffe73f13210dc6899a5f352d1"+}diff --git a/rust/cloud-storage/.sqlx/query-8b108dfc93000693ed7304ba54279a1381c53b51d012ea135fcaae0f013bdf76.json b/rust/cloud-storage/.sqlx/query-8b108dfc93000693ed7304ba54279a1381c53b51d012ea135fcaae0f013bdf76.jsonnew file mode 100644index 0000000000..5229808bab--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-8b108dfc93000693ed7304ba54279a1381c53b51d012ea135fcaae0f013bdf76.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO crm_companies (team_id, name)\n VALUES ($1, $2)\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "8b108dfc93000693ed7304ba54279a1381c53b51d012ea135fcaae0f013bdf76"+}diff --git a/rust/cloud-storage/.sqlx/query-8b7c148e88c11c3a2ba484c8ada918bf6497d8ec2339d9173904a7532b2b0052.json b/rust/cloud-storage/.sqlx/query-8b7c148e88c11c3a2ba484c8ada918bf6497d8ec2339d9173904a7532b2b0052.jsonnew file mode 100644index 0000000000..46fe53d17b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-8b7c148e88c11c3a2ba484c8ada918bf6497d8ec2339d9173904a7532b2b0052.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM crm_companies co\n WHERE co.team_id = $1\n AND co.email_sync = TRUE\n AND NOT EXISTS (\n SELECT 1 FROM crm_contacts WHERE company_id = co.id\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "8b7c148e88c11c3a2ba484c8ada918bf6497d8ec2339d9173904a7532b2b0052"+}diff --git a/rust/cloud-storage/.sqlx/query-a306e4c1385aab43d5fa2510f0fbdb20d4e37ebf037dceeb2673f6a3d64738de.json b/rust/cloud-storage/.sqlx/query-a306e4c1385aab43d5fa2510f0fbdb20d4e37ebf037dceeb2673f6a3d64738de.jsonnew file mode 100644index 0000000000..608cbb9acf--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-a306e4c1385aab43d5fa2510f0fbdb20d4e37ebf037dceeb2673f6a3d64738de.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM crm_contact_sources\n WHERE contact_id = $1 AND link_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "a306e4c1385aab43d5fa2510f0fbdb20d4e37ebf037dceeb2673f6a3d64738de"+}diff --git a/rust/cloud-storage/.sqlx/query-b82668085a22fb075f49e9618cf9ca870181917da54f25119cdd605affa1aa7d.json b/rust/cloud-storage/.sqlx/query-b82668085a22fb075f49e9618cf9ca870181917da54f25119cdd605affa1aa7d.jsonnew file mode 100644index 0000000000..7bb8312322--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-b82668085a22fb075f49e9618cf9ca870181917da54f25119cdd605affa1aa7d.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO crm_domain_directory (domain, name, description, icon_url)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (LOWER(domain)) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "b82668085a22fb075f49e9618cf9ca870181917da54f25119cdd605affa1aa7d"+}diff --git a/rust/cloud-storage/.sqlx/query-b9bacf772f93b494f7664caa2f90aa0a816f897a0f4f9bdcc2bbeded8e4409cd.json b/rust/cloud-storage/.sqlx/query-b9bacf772f93b494f7664caa2f90aa0a816f897a0f4f9bdcc2bbeded8e4409cd.jsonnew file mode 100644index 0000000000..f9d7b175f2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-b9bacf772f93b494f7664caa2f90aa0a816f897a0f4f9bdcc2bbeded8e4409cd.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT DISTINCT\n LOWER(c.email_address) AS \"email!\",\n c.name AS \"name\"\n FROM email_messages m\n JOIN email_message_recipients r ON r.message_id = m.id\n JOIN email_contacts c ON c.id = r.contact_id\n WHERE m.link_id = $1\n AND m.is_sent = true\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "email!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null,+ true+ ]+ },+ "hash": "b9bacf772f93b494f7664caa2f90aa0a816f897a0f4f9bdcc2bbeded8e4409cd"+}diff --git a/rust/cloud-storage/.sqlx/query-bab2c7e9807103ec8ece1edcdc8e357dc50be7a4d634f45990b772eb0824a35d.json b/rust/cloud-storage/.sqlx/query-bab2c7e9807103ec8ece1edcdc8e357dc50be7a4d634f45990b772eb0824a35d.jsonnew file mode 100644index 0000000000..73f58e81b1--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-bab2c7e9807103ec8ece1edcdc8e357dc50be7a4d634f45990b772eb0824a35d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM crm_contacts ct\n USING crm_companies co\n WHERE ct.company_id = co.id\n AND co.team_id = $1\n AND NOT EXISTS (\n SELECT 1 FROM crm_contact_sources WHERE contact_id = ct.id\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "bab2c7e9807103ec8ece1edcdc8e357dc50be7a4d634f45990b772eb0824a35d"+}diff --git a/rust/cloud-storage/.sqlx/query-dc937df67edeb079120e4c2f457748e9bbaf4f9856a1b4e1e0675e50de4175d3.json b/rust/cloud-storage/.sqlx/query-dc937df67edeb079120e4c2f457748e9bbaf4f9856a1b4e1e0675e50de4175d3.jsonnew file mode 100644index 0000000000..9d66c14a44--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-dc937df67edeb079120e4c2f457748e9bbaf4f9856a1b4e1e0675e50de4175d3.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT name, description, icon_url\n FROM crm_domain_directory\n WHERE LOWER(domain) = $1\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "icon_url",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true,+ true,+ true+ ]+ },+ "hash": "dc937df67edeb079120e4c2f457748e9bbaf4f9856a1b4e1e0675e50de4175d3"+}diff --git a/rust/cloud-storage/.sqlx/query-e7906bd42de06eff9291279715d9f6f1a860c05be610f8b620fe2426d59b2e62.json b/rust/cloud-storage/.sqlx/query-e7906bd42de06eff9291279715d9f6f1a860c05be610f8b620fe2426d59b2e62.jsonnew file mode 100644index 0000000000..2f6ba5b042--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-e7906bd42de06eff9291279715d9f6f1a860c05be610f8b620fe2426d59b2e62.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS(\n SELECT 1 FROM crm_contact_sources WHERE contact_id = $1 LIMIT 1\n ) AS \"exists!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "e7906bd42de06eff9291279715d9f6f1a860c05be610f8b620fe2426d59b2e62"+}diff --git a/rust/cloud-storage/.sqlx/query-f419ff9b35e559aedd0c8623986307a3d445a6a5643262d3efda804e3d04ccc6.json b/rust/cloud-storage/.sqlx/query-f419ff9b35e559aedd0c8623986307a3d445a6a5643262d3efda804e3d04ccc6.jsonnew file mode 100644index 0000000000..23b9253715--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-f419ff9b35e559aedd0c8623986307a3d445a6a5643262d3efda804e3d04ccc6.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS(\n SELECT 1 FROM crm_contacts WHERE company_id = $1 LIMIT 1\n ) AS \"exists!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "f419ff9b35e559aedd0c8623986307a3d445a6a5643262d3efda804e3d04ccc6"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 3576f9ae9d..19ee32db62 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2646,6 +2646,7 @@ dependencies = ["thiserror 2.0.17","tokio","tracing",+ "unfurl","uuid",]@@ -3976,6 +3977,7 @@ dependencies = ["tower 0.5.2","tower-http","tracing",+ "unfurl","url","urlencoding","utoipa",diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rsindex b754f79f40..ad31a7aed8 100644--- a/rust/cloud-storage/ai_tools/src/build_context.rs+++ b/rust/cloud-storage/ai_tools/src/build_context.rs@@ -150,6 +150,7 @@ pub async fn build_tool_service_context_from_env(let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);let email_service = EmailServiceImpl::new(EmailPgRepo::new(pool.clone()),diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex ce6fb066a9..bf8fabfd45 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -31,8 +31,15 @@ pub type ToolFrecencyService = frecency::domain::services::FrecencyQueryServiceI>;/// Type alias for the CRM service implementation used by tools.-pub type ToolCrmService =- crm::domain::service::CrmServiceImpl<crm::outbound::companies_repo::CompaniesRepositoryImpl>;+///+/// Tools only read CRM rows (e.g. `get_company_by_domain`); the populate+/// path runs in the email-service pubsub worker. The no-op resolver+/// keeps reqwest/scraper out of the tool binary at the cost of a silent+/// negative cache if populate is ever invoked here.+pub type ToolCrmService = crm::domain::service::CrmServiceImpl<+ crm::outbound::companies_repo::CompaniesRepositoryImpl,+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,+>;/// Type alias for the email service implementationpub type ToolEmailService = EmailServiceImpl<diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex 752561a393..07dedbc1f0 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -39,7 +39,7 @@ pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<teams::outbound::team_channels_repo::TeamChannelsRepositoryImpl,UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,NotificationIngressType,- teams::outbound::populate_crm_enqueuer::SqsPopulateCrmEnqueuer,+ teams::outbound::crm_enqueuer::SqsCrmEnqueuer,>;type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex 5b3416a36a..e7f676221a 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -268,8 +268,7 @@ async fn main() -> anyhow::Result<()> {let notification_ingress_service = Arc::new(notification_ingress_service);- let populate_crm_enqueuer =- teams::outbound::populate_crm_enqueuer::SqsPopulateCrmEnqueuer::new(sqs_client.clone());+ let crm_enqueuer = teams::outbound::crm_enqueuer::SqsCrmEnqueuer::new(sqs_client.clone());let teams_service_impl = TeamServiceImpl::new(teams_repo_impl,@@ -277,7 +276,7 @@ async fn main() -> anyhow::Result<()> {team_channels_repo_impl,user_roles_and_permissions_service.clone(),notification_ingress_service.clone(),- populate_crm_enqueuer,+ crm_enqueuer,);let github_link_service_impl = GithubLinkServiceImpl::new(diff --git a/rust/cloud-storage/crm/Cargo.toml b/rust/cloud-storage/crm/Cargo.tomlindex 2f1b93c79e..ea10cc17f9 100644--- a/rust/cloud-storage/crm/Cargo.toml+++ b/rust/cloud-storage/crm/Cargo.toml@@ -6,7 +6,7 @@ version = "0.1.0"[features]default = ["outbound", "ports"]-outbound = ["dep:sqlx", "ports"]+outbound = ["dep:sqlx", "dep:unfurl", "ports"]ports = [][dependencies]@@ -19,6 +19,7 @@ uuid = { workspace = true }# Outbound dependenciessqlx = { workspace = true, optional = true }+unfurl = { path = "../unfurl", features = ["ports"], optional = true }[dev-dependencies]macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/rust/cloud-storage/crm/src/domain.rs b/rust/cloud-storage/crm/src/domain.rsindex 797d9aba6c..39ba44445f 100644--- a/rust/cloud-storage/crm/src/domain.rs+++ b/rust/cloud-storage/crm/src/domain.rs@@ -1,9 +1,17 @@/// Domain models for CRM recordspub mod model;+/// Static list of generic/personal email-provider domains to exclude+/// from CRM populate+#[cfg(feature = "ports")]+pub(crate) mod generic_email_domains;+/// Persistence port for CRM companies#[cfg(feature = "ports")]pub mod companies_repo;+/// Outbound port for resolving company metadata from a domain+#[cfg(feature = "ports")]+pub mod company_metadata_resolver;/// The CRM service trait and implementation#[cfg(feature = "ports")]pub mod service;diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rsindex 14677a58fd..73f584d2d2 100644--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs@@ -1,6 +1,6 @@//! Port for persistence operations on CRM companies.-use crate::domain::model::{CrmCompany, CrmError};+use crate::domain::model::{CrmCompany, CrmError, DomainMetadata};/// The CompaniesRepository defines persistence operations for CRM/// companies and their associated domains.@@ -25,21 +25,131 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {/// this domain out (the killswitch): no rows are written and the/// method returns `Ok(())` so the caller can ack the job./// - If a row exists with `email_sync = true` it is reused.- /// - Otherwise a new `crm_companies` row (name = `"TODO"`) and a- /// matching `crm_domains` row are inserted.- /// 2. Upsert `crm_contacts (company_id, email)` with- /// `ON CONFLICT DO NOTHING`.+ /// - Otherwise a new `crm_companies` row and a matching+ /// `crm_domains` row are inserted. The company name itself+ /// lives in `crm_domain_directory` keyed by `domain`, not on+ /// `crm_companies` — see [`lookup_domain_metadata`] /+ /// [`upsert_domain_metadata`].+ /// 2. Upsert `crm_contacts (company_id, email, name)` with+ /// `ON CONFLICT DO UPDATE SET name = COALESCE(crm_contacts.name, EXCLUDED.name)`+ /// so the first non-NULL name wins and later populates can't+ /// overwrite it./// 3. Upsert `crm_contact_sources (contact_id, link_id)` with/// `ON CONFLICT DO NOTHING`.////// `domain` and `email` are both normalized to lowercase before storage- /// and comparison.+ /// and comparison. `name` is the display name observed for `email` on+ /// this user's link (sourced from `email_contacts.name` by the+ /// caller); pass `None` when no display name is available.+ ///+ /// The caller is expected to have ensured a `crm_domain_directory`+ /// entry exists for `domain` (via [`upsert_domain_metadata`]) before+ /// invoking — this method writes no metadata of its own.+ ///+ /// [`lookup_domain_metadata`]: CompaniesRepository::lookup_domain_metadata+ /// [`upsert_domain_metadata`]: CompaniesRepository::upsert_domain_metadatafn populate_contact(&self,team_id: &uuid::Uuid,link_id: &uuid::Uuid,domain: &str,email: &str,+ name: Option<&str>,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Read the cached [`DomainMetadata`] for `domain` from+ /// `crm_domain_directory`, if any. `domain` is matched+ /// case-insensitively. Returns `Ok(None)` when no row exists for+ /// the domain — the caller is expected to resolve via+ /// [`crate::domain::company_metadata_resolver::CompanyMetadataResolver`]+ /// and then [`upsert_domain_metadata`] before retrying.+ ///+ /// `Some(DomainMetadata { name: None, ... })` is distinct from+ /// `None`: it means the domain has been looked up before and the+ /// resolver returned nothing useful — the negative-cache entry+ /// suppresses further resolver calls.+ ///+ /// [`upsert_domain_metadata`]: CompaniesRepository::upsert_domain_metadata+ fn lookup_domain_metadata(+ &self,+ domain: &str,+ ) -> impl Future<Output = Result<Option<DomainMetadata>, CrmError>> + Send;++ /// Insert `metadata` for `domain` into `crm_domain_directory` with+ /// `ON CONFLICT (LOWER(domain)) DO NOTHING`. The directory is a+ /// global, first-write-wins cache: a row for `domain` (whether+ /// populated or all-NULL) is preserved as-is for the lifetime of+ /// the table. `domain` is lower-cased before storage.+ ///+ /// Idempotent under concurrent calls — racing producers can both+ /// resolve the same domain and both call this method; the second+ /// is a no-op.+ fn upsert_domain_metadata(+ &self,+ domain: &str,+ metadata: &DomainMetadata,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Reverses [`populate_contact`] for one `(link_id, email)`: drops the+ /// matching `crm_contact_sources` row, then `crm_contacts` if no other+ /// source rows remain for that contact, then `crm_companies` (cascading+ /// to `crm_domains`) if no other contact rows remain for that company+ /// **and** the company has `email_sync = true`. Companies with+ /// `email_sync = false` (the killswitch opt-out) are kept so the+ /// team's configuration survives teardown — a future populate will+ /// re-discover the row and short-circuit on the same flag.+ ///+ /// Source and contact rows are derived data and are always cleaned+ /// up regardless of the killswitch.+ ///+ /// The whole cascade runs in a single transaction that begins by+ /// acquiring the same advisory lock [`populate_contact`] takes (key+ /// `"{team_id}:{lower(domain)}"`) **before** observing any state, so+ /// a concurrent in-flight populate for the same `(team_id, domain)`+ /// can't slip an uncommitted insert past the existence check.+ ///+ /// No-op (returns `Ok(())`) when the contact / company / domain is+ /// not found for `(team_id, domain, email)`. `domain` and `email` are+ /// matched case-insensitively.+ fn depopulate_contact(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,+ domain: &str,+ email: &str,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Bulk counterpart to [`depopulate_contact`]: removes everything+ /// the link contributed to a single team's CRM rows. In one+ /// transaction:+ /// 1. Delete every `crm_contact_sources` row whose `link_id`+ /// matches AND whose contact lives under `team_id`.+ /// 2. Delete every `crm_contacts` row in `team_id` that has no+ /// remaining `crm_contact_sources` (orphaned by step 1 or by+ /// any earlier cleanup race).+ /// 3. Delete every `crm_companies` row in `team_id` that has no+ /// remaining `crm_contacts` AND `email_sync = true`. Companies+ /// with `email_sync = false` are preserved so the team's+ /// killswitch configuration survives teardown. `crm_domains`+ /// falls out via FK cascade.+ ///+ /// Scoping every query to `team_id` keeps the blast radius bounded+ /// — sources the link contributed to a *different* team (from a+ /// prior membership) are untouched — and lets the orphan cleanup+ /// run as a single SQL pass per layer instead of snapshotting+ /// candidate ids into memory first.+ ///+ /// Does NOT take per-`(team, domain)` advisory locks. A link can+ /// span many domains within a team, and a concurrent populate on+ /// the same team won't see the user as a member once the team+ /// membership change has propagated, so the race window is benign.+ ///+ /// Used by the `DepopulateCrmForUser` backfill step (fired when a+ /// user is removed from a team).+ fn depopulate_link_in_team(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,) -> impl Future<Output = Result<(), CrmError>> + Send;/// Returns the team id that `macro_id` belongs to. When the user is ondiff --git a/rust/cloud-storage/crm/src/domain/company_metadata_resolver.rs b/rust/cloud-storage/crm/src/domain/company_metadata_resolver.rsnew file mode 100644index 0000000000..e75f6937bc--- /dev/null+++ b/rust/cloud-storage/crm/src/domain/company_metadata_resolver.rs@@ -0,0 +1,26 @@+//! Outbound port for resolving [`DomainMetadata`] (display name,+//! description, icon URL) from a contact's email domain.+//!+//! The default adapter (`crm::outbound::unfurl_resolver`) fetches+//! `https://{domain}` via the unfurl service and maps its+//! [`unfurl::domain::models::GetUnfurlResponse`] onto [`DomainMetadata`].+//! Keeping the port abstract here lets the crm domain stay free of HTTP+//! / scraping concerns and lets the resolver be swapped for a different+//! provider (e.g. Clearbit) or mocked in tests without touching the+//! crm core.++use crate::domain::model::DomainMetadata;++/// Resolves company metadata for a single email domain.+///+/// Implementations are expected to be best-effort: a missing page,+/// network timeout, or malformed metadata should be surfaced as a+/// [`DomainMetadata`] with all-NULL fields rather than an error, since+/// the caller writes the result into `crm_domain_directory` as a+/// negative cache so the domain isn't re-resolved on the next populate.+pub trait CompanyMetadataResolver: Clone + Send + Sync + 'static {+ /// Resolve metadata for the given lower-cased `domain`. Returns+ /// [`DomainMetadata::default`] (all fields `None`) on any failure;+ /// implementations are expected to log internally.+ fn resolve(&self, domain: &str) -> impl Future<Output = DomainMetadata> + Send;+}diff --git a/rust/cloud-storage/crm/src/domain/generic_email_domains.rs b/rust/cloud-storage/crm/src/domain/generic_email_domains.rsnew file mode 100644index 0000000000..6ed5fb4843--- /dev/null+++ b/rust/cloud-storage/crm/src/domain/generic_email_domains.rs@@ -0,0 +1,374 @@+//! Static list of "generic" / personal-mail-provider domains that+//! should not be promoted into the CRM.+//!+//! CRM rows represent *companies* — when a user sends mail to+//! `[email protected]`, they're emailing a personal account, not a+//! business at gmail.com. Populating `gmail.com` as a company would (a)+//! pollute the team's CRM with a single mega-row that aggregates+//! every Gmail-using contact, and (b) burn an unfurl roundtrip+//! resolving the `gmail.com` homepage for no benefit.+//!+//! This is intentionally distinct from+//! [`email_utils::is_generic_email`], which checks the *local-part* of+//! an address for role-account patterns (`noreply@`, `support@`, etc.).+//! Both filters compose: a contact at `[email protected]` is dropped by+//! the role filter; a contact at `[email protected]` is dropped by this+//! domain filter. Together they keep CRM populate focused on real+//! company-to-company correspondence.+//!+//! Entries are kept in three categories so downstream consumers+//! (scoring, retention, alerting) can later distinguish a contact at a+//! big consumer provider from one at a disposable inbox or an alias+//! forwarder. The check ([`is_generic_email_domain`]) unions all+//! three plus a small set of suffix rules for RFC-reserved TLDs.++#[cfg(test)]+mod test;++/// Returns `true` when `domain` is a known personal / free email+/// provider, a disposable-mail service, a privacy-relay / alias+/// forwarder, or a reserved-namespace TLD. Matching is case-insensitive+/// and tolerates surrounding whitespace and a leading `www.` prefix.+pub(crate) fn is_generic_email_domain(domain: &str) -> bool {+ let normalized = normalize_domain(domain);+ if normalized.is_empty() {+ return false;+ }+ if matches_reserved_tld(&normalized) {+ return true;+ }+ contains_ci(CONSUMER_EMAIL_DOMAINS, &normalized)+ || contains_ci(DISPOSABLE_EMAIL_DOMAINS, &normalized)+ || contains_ci(ALIAS_FORWARDER_DOMAINS, &normalized)+}++/// Trim surrounding whitespace, lowercase, and strip a leading `www.`+/// label. We don't attempt IDN/punycode normalization here — the+/// curated lists are all ASCII, and IDN-form variants of consumer+/// providers (e.g. localized brand names) are rare enough to skip.+fn normalize_domain(domain: &str) -> String {+ let lower = domain.trim().to_ascii_lowercase();+ lower+ .strip_prefix("www.")+ .map(String::from)+ .unwrap_or(lower)+}++/// Catches names under RFC 2606 / RFC 6762 / RFC 8375 reserved+/// namespaces (`.test`, `.example`, `.invalid`, `.localhost`, `.local`,+/// `.internal`) plus the bare reserved labels. None of these belong in+/// any CRM under any circumstances — they're never valid public+/// company domains.+fn matches_reserved_tld(domain: &str) -> bool {+ matches!(domain, "localhost" | "invalid" | "localdomain")+ || domain.ends_with(".localhost")+ || domain.ends_with(".local")+ || domain.ends_with(".internal")+ || domain.ends_with(".invalid")+ || domain.ends_with(".test")+ || domain.ends_with(".example")+}++fn contains_ci(haystack: &[&str], needle: &str) -> bool {+ haystack+ .iter()+ .any(|known| known.eq_ignore_ascii_case(needle))+}++/// Mainstream consumer / free-mail providers and ISP-hosted mailboxes.+/// Anything on this list is overwhelmingly used for personal accounts;+/// a custom-domain company would not show up here.+const CONSUMER_EMAIL_DOMAINS: &[&str] = &[+ // ---- Google ----+ "gmail.com",+ "googlemail.com",+ // ---- Microsoft (Outlook / Hotmail / Live / MSN / Passport) ----+ "outlook.com",+ "outlook.co.uk",+ "outlook.fr",+ "outlook.de",+ "outlook.es",+ "outlook.it",+ "outlook.com.au",+ "outlook.com.br",+ "outlook.in",+ "outlook.jp",+ "outlook.kr",+ "outlook.cl",+ "outlook.dk",+ "outlook.ie",+ "outlook.my",+ "outlook.ph",+ "outlook.pt",+ "outlook.sa",+ "outlook.sg",+ "hotmail.com",+ "hotmail.co.uk",+ "hotmail.fr",+ "hotmail.de",+ "hotmail.it",+ "hotmail.es",+ "hotmail.com.br",+ "hotmail.com.ar",+ "hotmail.com.mx",+ "hotmail.com.au",+ "hotmail.be",+ "hotmail.nl",+ "hotmail.ca",+ "hotmail.no",+ "hotmail.se",+ "live.com",+ "live.co.uk",+ "live.fr",+ "live.de",+ "live.it",+ "live.com.au",+ "live.ca",+ "live.nl",+ "live.se",+ "live.no",+ "live.dk",+ "live.fi",+ "live.com.mx",+ "msn.com",+ "passport.com",+ // ---- Yahoo ----+ "yahoo.com",+ "ymail.com",+ "rocketmail.com",+ "yahoo.co.uk",+ "yahoo.fr",+ "yahoo.de",+ "yahoo.it",+ "yahoo.es",+ "yahoo.com.br",+ "yahoo.com.mx",+ "yahoo.com.ar",+ "yahoo.co.in",+ "yahoo.co.jp",+ "yahoo.com.au",+ "yahoo.ca",+ "yahoo.com.sg",+ "yahoo.com.hk",+ "yahoo.com.tw",+ "yahoo.com.ph",+ "yahoo.com.vn",+ "yahoo.com.my",+ "yahoo.no",+ "yahoo.se",+ "yahoo.dk",+ "yahoo.nl",+ "yahoo.gr",+ "yahoo.pt",+ // ---- Apple ----+ "icloud.com",+ "me.com",+ "mac.com",+ // ---- AOL / Verizon (legacy) ----+ "aol.com",+ "aim.com",+ "att.net",+ "bellsouth.net",+ "sbcglobal.net",+ "ameritech.net",+ "verizon.net",+ // ---- Privacy-focused providers ----+ "protonmail.com",+ "proton.me",+ "pm.me",+ "tutanota.com",+ "tutanota.de",+ "tutamail.com",+ "tuta.io",+ "tuta.com",+ "fastmail.com",+ "fastmail.fm",+ "hey.com",+ "hushmail.com",+ "posteo.de",+ "mailbox.org",+ "runbox.com",+ "countermail.com",+ "startmail.com",+ "skiff.com",+ // ---- Germany / DACH ----+ "gmx.com",+ "gmx.de",+ "gmx.net",+ "gmx.at",+ "gmx.ch",+ "gmx.fr",+ "gmx.es",+ "gmx.us",+ "web.de",+ "t-online.de",+ "freenet.de",+ // ---- Russia / CIS ----+ "yandex.com",+ "yandex.ru",+ "ya.ru",+ "mail.ru",+ "list.ru",+ "inbox.ru",+ "bk.ru",+ "rambler.ru",+ "ukr.net",+ // ---- China ----+ "qq.com",+ "163.com",+ "126.com",+ "sina.com",+ "sina.cn",+ "sohu.com",+ "139.com",+ "aliyun.com",+ "foxmail.com",+ "21cn.com",+ // ---- Korea ----+ "naver.com",+ "daum.net",+ "hanmail.net",+ "nate.com",+ // ---- Japan (carrier mailboxes are personal in practice) ----+ "ezweb.ne.jp",+ "docomo.ne.jp",+ "softbank.ne.jp",+ "au.com",+ // ---- Taiwan ----+ "pchome.com.tw",+ // ---- Southeast Asia ----+ "singnet.com.sg",+ // ---- India ----+ "rediffmail.com",+ "indiatimes.com",+ // ---- Brazil ----+ "uol.com.br",+ "bol.com.br",+ "ig.com.br",+ "terra.com.br",+ // ---- ISPs / telcos (US) ----+ "comcast.net",+ "xfinity.com",+ "cox.net",+ "charter.net",+ "spectrum.net",+ "earthlink.net",+ "optonline.net",+ // ---- ISPs / telcos (UK) ----+ "btinternet.com",+ "virginmedia.com",+ // ---- ISPs / telcos (France) ----+ "orange.fr",+ "wanadoo.fr",+ "free.fr",+ "laposte.net",+ // ---- ISPs / telcos (Italy) ----+ "libero.it",+ "alice.it",+ "virgilio.it",+ // ---- ISPs / telcos (Spain) ----+ "telefonica.net",+ // ---- ISPs / telcos (Poland) ----+ "onet.pl",+ "wp.pl",+ "o2.pl",+ "interia.pl",+ // ---- ISPs / telcos (Czech) ----+ "seznam.cz",+ "centrum.cz",+ // ---- Generic / other free providers ----+ "mail.com",+ "email.com",+ "zohomail.com", // intentionally NOT zoho.com — that's the company itself+ "gawab.com",+ "inbox.com",+ "lavabit.com",+ "lycos.com",+ "usa.com",+ "consultant.com",+ "engineer.com",+ "cheerful.com",+ "dr.com",+ "myself.com",+ "linuxmail.org",+ "iname.com",+];++/// Disposable / temporary inbox services. Used by signups that want to+/// avoid commitment — never associated with a real business.+const DISPOSABLE_EMAIL_DOMAINS: &[&str] = &[+ "mailinator.com",+ "mailinator.net",+ "mailinator.org",+ "mailinator2.com",+ "guerrillamail.com",+ "guerrillamail.net",+ "guerrillamail.org",+ "guerrillamailblock.com",+ "sharklasers.com",+ "grr.la",+ "10minutemail.com",+ "tempmail.com",+ "temp-mail.org",+ "temp-mail.io",+ "tempmail.org",+ "tmpmail.org",+ "throwaway.email",+ "trashmail.com",+ "trashmail.de",+ "trashmail.ws",+ "yopmail.com",+ "mvrht.net",+ "maildrop.cc",+ "getairmail.com",+ "dispostable.com",+ "fakeinbox.com",+ "mintemail.com",+ "spambox.us",+ "spamgourmet.com",+ "spam4.me",+ "33mail.com",+ "anonbox.net",+ "mailnesia.com",+ "pokemail.net",+ "bccto.me",+ "chacuo.net",+ "moakt.com",+ "dropmail.me",+ "emailondeck.com",+ "burnermail.io",+ "tempinbox.com",+ "mytemp.email",+ "jetable.org",+ "mailcatch.com",+ "mail-temporaire.fr",+ "wegwerfemail.de",+ "wegwerfmail.de",+ "temporarymail.com",+ "fakemail.net",+ "mailnull.com",+ "tempail.com",+];++/// Privacy-relay / alias-forwarding services. These look like one+/// "company" by domain but actually mask many unrelated personal+/// accounts, so they're useless for CRM grouping. Often missed by+/// off-the-shelf blocklists.+const ALIAS_FORWARDER_DOMAINS: &[&str] = &[+ // Apple Hide-My-Email+ "privaterelay.appleid.com",+ // DuckDuckGo Email Protection+ "duck.com",+ "duckduckgo.com",+ // Mozilla Relay+ "mozmail.com",+ "relay.firefox.com",+ // SimpleLogin (Proton)+ "simplelogin.com",+ "simplelogin.co",+ // AnonAddy / addy.io+ "anonaddy.com",+ "addy.io",+ // Other independents+ "firemail.de",+];diff --git a/rust/cloud-storage/crm/src/domain/generic_email_domains/test.rs b/rust/cloud-storage/crm/src/domain/generic_email_domains/test.rsnew file mode 100644index 0000000000..939ceb9a88--- /dev/null+++ b/rust/cloud-storage/crm/src/domain/generic_email_domains/test.rs@@ -0,0 +1,165 @@+use super::is_generic_email_domain;++#[test]+fn matches_common_consumer_providers() {+ for domain in [+ "gmail.com",+ "yahoo.com",+ "hotmail.com",+ "outlook.com",+ "icloud.com",+ "aol.com",+ "protonmail.com",+ "yandex.ru",+ "qq.com",+ "msn.com",+ "passport.com",+ ] {+ assert!(+ is_generic_email_domain(domain),+ "expected {domain} to be flagged as a consumer provider"+ );+ }+}++#[test]+fn matches_isp_carryover_domains() {+ for domain in [+ "verizon.net",+ "att.net",+ "sbcglobal.net",+ "comcast.net",+ "earthlink.net",+ "btinternet.com",+ "orange.fr",+ "libero.it",+ "wp.pl",+ "seznam.cz",+ ] {+ assert!(+ is_generic_email_domain(domain),+ "expected {domain} to be flagged as an ISP mailbox"+ );+ }+}++#[test]+fn matches_disposable_inbox_services() {+ for domain in [+ "mailinator.com",+ "10minutemail.com",+ "guerrillamail.com",+ "yopmail.com",+ "burnermail.io",+ "trashmail.com",+ "temp-mail.org",+ "dropmail.me",+ ] {+ assert!(+ is_generic_email_domain(domain),+ "expected {domain} to be flagged as disposable"+ );+ }+}++#[test]+fn matches_alias_forwarders() {+ for domain in [+ "privaterelay.appleid.com",+ "duck.com",+ "duckduckgo.com",+ "mozmail.com",+ "relay.firefox.com",+ "simplelogin.com",+ "anonaddy.com",+ "addy.io",+ ] {+ assert!(+ is_generic_email_domain(domain),+ "expected {domain} to be flagged as an alias forwarder"+ );+ }+}++#[test]+fn matches_reserved_tlds() {+ for domain in [+ "user.local",+ "host.internal",+ "acme.invalid",+ "site.test",+ "site.example",+ "service.localhost",+ ] {+ assert!(+ is_generic_email_domain(domain),+ "expected {domain} to be flagged as reserved TLD"+ );+ }+ for bare in ["localhost", "invalid", "localdomain"] {+ assert!(+ is_generic_email_domain(bare),+ "expected bare reserved label {bare} to be flagged"+ );+ }+}++#[test]+fn match_is_case_insensitive() {+ assert!(is_generic_email_domain("Gmail.com"));+ assert!(is_generic_email_domain("GMAIL.COM"));+ assert!(is_generic_email_domain("Outlook.Co.Uk"));+ assert!(is_generic_email_domain("PrivateRelay.appleid.COM"));+}++#[test]+fn surrounding_whitespace_is_ignored() {+ assert!(is_generic_email_domain(" gmail.com "));+ assert!(is_generic_email_domain("\tyahoo.com\n"));+}++#[test]+fn www_prefix_is_stripped() {+ assert!(is_generic_email_domain("www.gmail.com"));+ assert!(is_generic_email_domain("WWW.outlook.com"));+ // `www.` only strips at the start — a `www.` in the middle of the+ // domain (vanishingly unlikely in practice, but defensive) stays put.+ assert!(!is_generic_email_domain("foo.www.gmail.com"));+}++#[test]+fn zohomail_is_flagged_but_zoho_is_not() {+ // Zoho the company runs `zoho.com`; their free personal mail+ // service lives at `zohomail.com`. Mixing them up would block real+ // CRM entries for Zoho.+ assert!(is_generic_email_domain("zohomail.com"));+ assert!(!is_generic_email_domain("zoho.com"));+}++#[test]+fn legitimate_company_domains_pass_through() {+ for domain in [+ "anthropic.com",+ "macro.com",+ "acme.io",+ "stripe.com",+ "zoho.com",+ // Subdomains of generic providers aren't on the list — they+ // belong to whoever runs the subdomain, not the parent+ // provider. The lookup is exact-match by design.+ "mail.gmail.com",+ "support.outlook.com",+ ] {+ assert!(+ !is_generic_email_domain(domain),+ "expected {domain} to NOT be flagged"+ );+ }+}++#[test]+fn empty_and_garbage_inputs_are_safe() {+ assert!(!is_generic_email_domain(""));+ assert!(!is_generic_email_domain(" "));+ assert!(!is_generic_email_domain("not-an-email"));+}diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rsindex 1e4dd614a9..08264ccb4f 100644--- a/rust/cloud-storage/crm/src/domain/model.rs+++ b/rust/cloud-storage/crm/src/domain/model.rs@@ -5,14 +5,16 @@ use chrono::{DateTime, Utc};/// A known external company tracked by a team (CRM-style record). A company/// aggregates one or more email domains and individual contacts that are/// considered to belong to the same external party.+///+/// Company display metadata (name, description, icon) lives in+/// `crm_domain_directory` keyed by domain, not on `crm_companies` —+/// look it up via [`DomainMetadata`] when needed.#[derive(Debug, Clone, serde::Serialize)]pub struct CrmCompany {/// The id of the companypub id: uuid::Uuid,/// The id of the team that owns this company recordpub team_id: uuid::Uuid,- /// The display name of the company- pub name: String,/// Whether email sync is enabled for this companypub email_sync: bool,/// When the company was created@@ -21,6 +23,26 @@ pub struct CrmCompany {pub domains: Vec<CrmDomain>,}+/// Cached metadata about a company keyed on its email domain. Populated+/// lazily by [`crate::domain::company_metadata_resolver::CompanyMetadataResolver`] (typically+/// an unfurl of `https://{domain}`) and stored in `crm_domain_directory`.+///+/// Every field is `Option` because the resolver may succeed with the+/// page returning no useful metadata, or fail entirely — both cases+/// are represented as a row with all-NULL fields so the cache is a+/// negative cache as well as a positive one.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct DomainMetadata {+ /// Display name of the company (typically the page `<title>` /+ /// `og:title`).+ pub name: Option<String>,+ /// Short description of the company (typically `og:description`).+ pub description: Option<String>,+ /// URL of a logo / icon for the company (favicon resolved from the+ /// page's `<link rel="icon">`, falling back to `/favicon.ico`).+ pub icon_url: Option<String>,+}+/// A domain (e.g. "acme.com") associated with a [`CrmCompany`]. A company/// may have many domains.#[derive(Debug, Clone, serde::Serialize)]diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rsindex 18df3c72fc..0d97eb8060 100644--- a/rust/cloud-storage/crm/src/domain/service.rs+++ b/rust/cloud-storage/crm/src/domain/service.rs@@ -2,6 +2,8 @@use crate::domain::{companies_repo::CompaniesRepository,+ company_metadata_resolver::CompanyMetadataResolver,+ generic_email_domains::is_generic_email_domain,model::{CrmCompany, CrmError},};@@ -23,11 +25,68 @@ pub trait CrmService: Clone + Send + Sync + 'static {/// `crm_contact_sources` in a single transaction. If the team has/// opted the contact's domain out (`crm_companies.email_sync = false`)/// the call is a no-op.+ ///+ /// `name` is the display name observed for `email` on this user's+ /// link — typically `email_contacts.name`, which the caller looks up+ /// before invoking. The first non-NULL name wins for the+ /// `crm_contacts` row; later populates from other team members can't+ /// overwrite it. Pass `None` when no display name is available.+ ///+ /// Before the populate transaction, this method ensures+ /// `crm_domain_directory` has an entry for the email's domain — if+ /// not, it invokes the+ /// [`crate::domain::company_metadata_resolver::CompanyMetadataResolver`]+ /// and inserts the result (which may be all-NULL on resolver+ /// failure — that's the negative cache). The directory write is its+ /// own transaction so the populate tx never holds locks across an+ /// HTTP fetch.fn populate_contact(&self,team_id: &uuid::Uuid,link_id: &uuid::Uuid,email: &str,+ name: Option<&str>,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Reverses [`populate_contact`] for one `(link_id, email)`. Drops the+ /// `crm_contact_sources` row, then cascades up to `crm_contacts` and+ /// `crm_companies` (with `crm_domains` cascading via FK) when no+ /// sibling rows remain — except that companies with `email_sync =+ /// false` are preserved so the team's opt-out configuration survives+ /// teardown. See+ /// [`crate::domain::companies_repo::CompaniesRepository::depopulate_contact`].+ ///+ /// Treats malformed emails (missing `@`, empty local-part, empty or+ /// multi-`@` domain) as a no-op rather than an error so that retries+ /// don't pile up on poisoned messages. This is stricter than+ /// [`populate_contact`], which errors on malformed input — depopulate+ /// is a teardown step and we'd rather drop a bad payload than churn+ /// it through the retry path. The caller is expected to gate this+ /// call on a prior check that the link has no other sent messages to+ /// `email`.+ fn depopulate_contact(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,+ email: &str,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Bulk teardown for one user's email link within one team: drops+ /// the team's `crm_contact_sources` rows owned by `link_id`, then+ /// cascades to `crm_contacts` and `crm_companies` for the rows+ /// orphaned as a result. Companies with `email_sync = false` are+ /// preserved. See+ /// [`crate::domain::companies_repo::CompaniesRepository::depopulate_link_in_team`].+ ///+ /// Used by the `DepopulateCrmForUser` backfill step. Unlike+ /// [`depopulate_contact`], this bypasses any per-message gate — the+ /// trigger here is "user is no longer on this team", which makes+ /// the presence of the user's sent messages in `email_messages`+ /// irrelevant.+ fn depopulate_link_in_team(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,) -> impl Future<Output = Result<(), CrmError>> + Send;/// Returns the team id `macro_id` belongs to, or `None` when the user@@ -40,42 +99,53 @@ pub trait CrmService: Clone + Send + Sync + 'static {) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;}-/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`].+/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`]+/// and a [`CompanyMetadataResolver`].#[derive(Debug)]-pub struct CrmServiceImpl<CR>+pub struct CrmServiceImpl<CR, R>whereCR: CompaniesRepository,+ R: CompanyMetadataResolver,{/// The underlying companies repositorycompanies_repository: CR,+ /// Resolver consulted only when `crm_domain_directory` has no entry+ /// for a given domain. The resolver itself is best-effort — its+ /// failures collapse to a negative-cache row in the directory.+ metadata_resolver: R,}-impl<CR> Clone for CrmServiceImpl<CR>+impl<CR, R> Clone for CrmServiceImpl<CR, R>whereCR: CompaniesRepository,+ R: CompanyMetadataResolver,{fn clone(&self) -> Self {Self {companies_repository: self.companies_repository.clone(),+ metadata_resolver: self.metadata_resolver.clone(),}}}-impl<CR> CrmServiceImpl<CR>+impl<CR, R> CrmServiceImpl<CR, R>whereCR: CompaniesRepository,+ R: CompanyMetadataResolver,{/// Creates a new CrmServiceImpl- pub fn new(companies_repository: CR) -> Self {+ pub fn new(companies_repository: CR, metadata_resolver: R) -> Self {Self {companies_repository,+ metadata_resolver,}}}-impl<CR> CrmService for CrmServiceImpl<CR>+impl<CR, R> CrmService for CrmServiceImpl<CR, R>whereCR: CompaniesRepository,+ R: CompanyMetadataResolver,{#[tracing::instrument(skip(self), err)]async fn get_company_by_domain(@@ -94,6 +164,7 @@ whereteam_id: &uuid::Uuid,link_id: &uuid::Uuid,email: &str,+ name: Option<&str>,) -> Result<(), CrmError> {let email = email.trim();let Some((local_part, domain)) = email.split_once('@') else {@@ -111,8 +182,76 @@ where"email {email} has an empty domain")));}++ // Skip personal / free-mail-provider domains (gmail, yahoo,+ // hotmail, …). CRM rows are meant to represent companies+ if is_generic_email_domain(domain) {+ tracing::debug!(+ domain,+ "Skipping CRM populate for generic email provider domain"+ );+ return Ok(());+ }++ // Ensure `crm_domain_directory` has an entry for this domain+ // before the populate tx — the populate tx no longer carries any+ // name metadata of its own, and we don't want to hold its+ // advisory lock across an HTTP fetch. The directory upsert is+ // its own transaction, idempotent under concurrent populates+ // for the same domain (first-write-wins via the unique index+ // on `LOWER(domain)`).+ if self+ .companies_repository+ .lookup_domain_metadata(domain)+ .await?+ .is_none()+ {+ let metadata = self.metadata_resolver.resolve(domain).await;+ self.companies_repository+ .upsert_domain_metadata(domain, &metadata)+ .await?;+ }++ self.companies_repository+ .populate_contact(team_id, link_id, domain, email, name)+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn depopulate_contact(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,+ email: &str,+ ) -> Result<(), CrmError> {+ let email = email.trim();+ let Some((local_part, domain)) = email.split_once('@') else {+ tracing::debug!(+ email,+ "depopulate_contact: skipping malformed email (no '@')"+ );+ return Ok(());+ };+ if local_part.is_empty() || domain.is_empty() || domain.contains('@') {+ tracing::debug!(+ email,+ "depopulate_contact: skipping malformed email (empty part or multiple '@')"+ );+ return Ok(());+ }+ self.companies_repository+ .depopulate_contact(team_id, link_id, domain, email)+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn depopulate_link_in_team(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,+ ) -> Result<(), CrmError> {self.companies_repository- .populate_contact(team_id, link_id, domain, email)+ .depopulate_link_in_team(team_id, link_id).await}diff --git a/rust/cloud-storage/crm/src/outbound.rs b/rust/cloud-storage/crm/src/outbound.rsindex c1e03765d7..d0212f34a8 100644--- a/rust/cloud-storage/crm/src/outbound.rs+++ b/rust/cloud-storage/crm/src/outbound.rs@@ -1,2 +1,6 @@/// Postgres implementation of the companies repositorypub mod companies_repo;+/// Resolver stub for binaries that don't populate the CRM+pub mod no_op_resolver;+/// Unfurl-backed implementation of the company metadata resolver+pub mod unfurl_resolver;diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rsindex b371136817..b8b2a4d9c0 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs@@ -1,11 +1,8 @@//! Implementation of [`CompaniesRepository`] backed by MacroDB.-#[cfg(test)]-mod test;-use crate::domain::{companies_repo::CompaniesRepository,- model::{CrmCompany, CrmDomain, CrmError},+ model::{CrmCompany, CrmDomain, CrmError, DomainMetadata},};use sqlx::PgPool;@@ -34,7 +31,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {let company = sqlx::query!(r#"- SELECT c.id, c.team_id, c.name, c.email_sync, c.created_at+ SELECT c.id, c.team_id, c.email_sync, c.created_atFROM crm_companies cJOIN crm_domains d ON d.company_id = c.idWHERE c.team_id = $1@@ -76,7 +73,6 @@ impl CompaniesRepository for CompaniesRepositoryImpl {Ok(Some(CrmCompany {id: company.id,team_id: company.team_id,- name: company.name,email_sync: company.email_sync,created_at: company.created_at,domains,@@ -90,6 +86,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {link_id: &uuid::Uuid,domain: &str,email: &str,+ name: Option<&str>,) -> Result<(), CrmError> {let normalized_domain = domain.to_ascii_lowercase();let normalized_email = email.to_ascii_lowercase();@@ -149,8 +146,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {None => {let new_company = sqlx::query!(r#"- INSERT INTO crm_companies (team_id, name)- VALUES ($1, 'TODO')+ INSERT INTO crm_companies (team_id)+ VALUES ($1)RETURNING id"#,team_id,@@ -210,19 +207,25 @@ impl CompaniesRepository for CompaniesRepositoryImpl {}};- // Upsert the contact. `ON CONFLICT DO UPDATE SET email = EXCLUDED.email`- // is a no-op write that exists only to force RETURNING to fire on the- // conflict path, so we get the existing row's id without a second- // round trip.+ // Upsert the contact. `name` is supplied by the caller (the+ // backfill consumer looks it up in email_contacts before invoking+ // populate). On conflict, COALESCE preserves the existing+ // crm_contacts.name when it's non-NULL, so the first non-empty+ // name wins and a subsequent populate from a different team+ // member can't overwrite it. If the existing name is NULL+ // (previous populate ran before email_contacts had a name), the+ // conflict path still gets a chance to fill it.let contact_id = sqlx::query_scalar!(r#"- INSERT INTO crm_contacts (company_id, email)- VALUES ($1, $2)- ON CONFLICT (company_id, email) DO UPDATE SET email = EXCLUDED.email+ INSERT INTO crm_contacts (company_id, email, name)+ VALUES ($1, $2, $3)+ ON CONFLICT (company_id, email) DO UPDATE+ SET name = COALESCE(crm_contacts.name, EXCLUDED.name)RETURNING id"#,company_id,normalized_email,+ name,).fetch_one(&mut *tx).await@@ -248,6 +251,289 @@ impl CompaniesRepository for CompaniesRepositoryImpl {Ok(())}+ #[tracing::instrument(skip(self), err)]+ async fn depopulate_contact(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,+ domain: &str,+ email: &str,+ ) -> Result<(), CrmError> {+ let normalized_domain = domain.to_ascii_lowercase();+ let normalized_email = email.to_ascii_lowercase();++ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ // Take the lock BEFORE looking at any state. A concurrent+ // populate_contact for the same (team, domain) might have a tx+ // open that has inserted rows but hasn't committed yet — without+ // the lock our SELECT below would miss those rows, return+ // Ok(()) here, and the in-flight populate would then commit and+ // leave the team with CRM data for a since-deleted sent message.+ // Holding the lock for the rest of this tx forces populate to+ // either commit first (we then see + tear down its rows) or+ // wait until we're done (its row will be inserted after, and+ // a future depopulate will catch it).+ sqlx::query!(+ r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,+ format!("{team_id}:{normalized_domain}"),+ )+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ // Resolve (contact_id, company_id, email_sync) for this+ // (team, domain, email). Returning None here means there is+ // nothing to tear down: commit the empty tx and ack.+ let Some(row) = sqlx::query!(+ r#"+ SELECT+ ct.id AS contact_id,+ co.id AS company_id,+ co.email_sync AS "email_sync!"+ FROM crm_contacts ct+ JOIN crm_companies co ON co.id = ct.company_id+ JOIN crm_domains d ON d.company_id = co.id+ WHERE co.team_id = $1+ AND LOWER(ct.email) = $2+ AND LOWER(d.domain) = $3+ LIMIT 1+ "#,+ team_id,+ normalized_email,+ normalized_domain,+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?+ else {+ tx.commit()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ return Ok(());+ };++ // 1. Drop the per-link source row.+ sqlx::query!(+ r#"+ DELETE FROM crm_contact_sources+ WHERE contact_id = $1 AND link_id = $2+ "#,+ row.contact_id,+ link_id,+ )+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ // 2. Keep the contact iff any other link in the team still+ // references it.+ let other_sources = sqlx::query_scalar!(+ r#"+ SELECT EXISTS(+ SELECT 1 FROM crm_contact_sources WHERE contact_id = $1 LIMIT 1+ ) AS "exists!"+ "#,+ row.contact_id,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ if other_sources {+ tx.commit()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ return Ok(());+ }++ sqlx::query!(r#"DELETE FROM crm_contacts WHERE id = $1"#, row.contact_id,)+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ // 3. Keep the company when other contacts in the team still+ // belong to it, OR when the team has opted the domain out.+ // The killswitch (`email_sync = false`) is stored on+ // crm_companies and is configuration, not derived data;+ // dropping the company would silently erase the opt-out and+ // a future populate would recreate the row with the default+ // `email_sync = true`.+ if !row.email_sync {+ tx.commit()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ return Ok(());+ }++ let other_contacts = sqlx::query_scalar!(+ r#"+ SELECT EXISTS(+ SELECT 1 FROM crm_contacts WHERE company_id = $1 LIMIT 1+ ) AS "exists!"+ "#,+ row.company_id,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ if other_contacts {+ tx.commit()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ return Ok(());+ }++ // crm_domains FK is ON DELETE CASCADE — deleting the company+ // takes its domain rows with it.+ sqlx::query!(r#"DELETE FROM crm_companies WHERE id = $1"#, row.company_id,)+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ tx.commit()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ Ok(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn depopulate_link_in_team(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,+ ) -> Result<(), CrmError> {+ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ // 1. Drop the link's source rows scoped to this team.+ sqlx::query!(+ r#"+ DELETE FROM crm_contact_sources cs+ USING crm_contacts ct, crm_companies co+ WHERE cs.contact_id = ct.id+ AND ct.company_id = co.id+ AND co.team_id = $1+ AND cs.link_id = $2+ "#,+ team_id,+ link_id,+ )+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ // 2. Drop every contact in this team that no longer has any+ // source.+ sqlx::query!(+ r#"+ DELETE FROM crm_contacts ct+ USING crm_companies co+ WHERE ct.company_id = co.id+ AND co.team_id = $1+ AND NOT EXISTS (+ SELECT 1 FROM crm_contact_sources WHERE contact_id = ct.id+ )+ "#,+ team_id,+ )+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ // 3. Drop every company in this team that no longer has any+ // contact AND is not killswitched. Companies with+ // `email_sync = false` are preserved so the team's+ // configuration survives teardown — a future populate will+ // re-find the row and short-circuit on the same flag.+ // `crm_domains` falls out via FK cascade.+ sqlx::query!(+ r#"+ DELETE FROM crm_companies co+ WHERE co.team_id = $1+ AND co.email_sync = TRUE+ AND NOT EXISTS (+ SELECT 1 FROM crm_contacts WHERE company_id = co.id+ )+ "#,+ team_id,+ )+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ tx.commit()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ Ok(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn lookup_domain_metadata(+ &self,+ domain: &str,+ ) -> Result<Option<DomainMetadata>, CrmError> {+ let normalized_domain = domain.to_ascii_lowercase();+ let row = sqlx::query!(+ r#"+ SELECT name, description, icon_url+ FROM crm_domain_directory+ WHERE LOWER(domain) = $1+ LIMIT 1+ "#,+ normalized_domain,+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ Ok(row.map(|r| DomainMetadata {+ name: r.name,+ description: r.description,+ icon_url: r.icon_url,+ }))+ }++ #[tracing::instrument(skip(self, metadata), err)]+ async fn upsert_domain_metadata(+ &self,+ domain: &str,+ metadata: &DomainMetadata,+ ) -> Result<(), CrmError> {+ let normalized_domain = domain.to_ascii_lowercase();+ // First-write-wins: the unique index is on `LOWER(domain)`, so+ // a concurrent populate of the same domain hits the conflict+ // path and we leave the existing row untouched (treat-as-forever+ // cache). Negative cache entries (all-NULL fields) are inserted+ // verbatim so subsequent populates suppress the resolver call.+ sqlx::query!(+ r#"+ INSERT INTO crm_domain_directory (domain, name, description, icon_url)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (LOWER(domain)) DO NOTHING+ "#,+ normalized_domain,+ metadata.name,+ metadata.description,+ metadata.icon_url,+ )+ .execute(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ Ok(())+ }+#[tracing::instrument(skip(self), err)]async fn get_team_id_for_user(&self, macro_id: &str) -> Result<Option<uuid::Uuid>, CrmError> {sqlx::query_scalar!(diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rsindex 0628c3a53e..615ffdbb62 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs@@ -36,29 +36,27 @@ async fn seed_team(pool: &PgPool, team_id: Uuid, owner_id: &str) -> sqlx::Resultasync fn insert_company(pool: &PgPool,team_id: Uuid,- name: &str,email_sync: bool,domains: &[&str],) -> sqlx::Result<Uuid> {let company_id = Uuid::now_v7();- sqlx::query(- r#"INSERT INTO crm_companies (id, team_id, name, email_sync) VALUES ($1, $2, $3, $4)"#,- )- .bind(company_id)- .bind(team_id)- .bind(name)- .bind(email_sync)- .execute(pool)- .await?;+ sqlx::query(r#"INSERT INTO crm_companies (id, team_id, email_sync) VALUES ($1, $2, $3)"#)+ .bind(company_id)+ .bind(team_id)+ .bind(email_sync)+ .execute(pool)+ .await?;for domain in domains {- sqlx::query(r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#)- .bind(company_id)- .bind(team_id)- .bind(*domain)- .execute(pool)- .await?;+ sqlx::query(+ r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#,+ )+ .bind(company_id)+ .bind(team_id)+ .bind(*domain)+ .execute(pool)+ .await?;}Ok(company_id)@@ -80,7 +78,7 @@ async fn returns_none_when_no_company_for_domain(pool: PgPool) -> anyhow::Resultasync fn returns_company_with_all_domains_when_match(pool: PgPool) -> anyhow::Result<()> {let team_id = Uuid::now_v7();seed_team(&pool, team_id, "macro|[email protected]").await?;- let company_id = insert_company(&pool, team_id, "Acme", true, &["acme.com", "acme.io"]).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com", "acme.io"]).await?;let repo = CompaniesRepositoryImpl::new(pool);let company = repo@@ -90,7 +88,6 @@ async fn returns_company_with_all_domains_when_match(pool: PgPool) -> anyhow::Reassert_eq!(company.id, company_id);assert_eq!(company.team_id, team_id);- assert_eq!(company.name, "Acme");assert!(company.email_sync);let mut domains: Vec<_> = company.domains.iter().map(|d| d.domain.as_str()).collect();@@ -103,7 +100,7 @@ async fn returns_company_with_all_domains_when_match(pool: PgPool) -> anyhow::Reasync fn domain_lookup_is_case_insensitive(pool: PgPool) -> anyhow::Result<()> {let team_id = Uuid::now_v7();seed_team(&pool, team_id, "macro|[email protected]").await?;- insert_company(&pool, team_id, "Acme", true, &["acme.com"]).await?;+ insert_company(&pool, team_id, true, &["acme.com"]).await?;let repo = CompaniesRepositoryImpl::new(pool);@@ -126,7 +123,7 @@ async fn does_not_return_companies_from_other_teams(pool: PgPool) -> anyhow::Reslet team_b = Uuid::now_v7();seed_team(&pool, team_a, "macro|[email protected]").await?;seed_team(&pool, team_b, "macro|[email protected]").await?;- insert_company(&pool, team_a, "Acme A", true, &["acme.com"]).await?;+ insert_company(&pool, team_a, true, &["acme.com"]).await?;let repo = CompaniesRepositoryImpl::new(pool);let result = repo.get_company_by_domain(&team_b, "acme.com").await?;@@ -139,7 +136,7 @@ async fn does_not_return_companies_from_other_teams(pool: PgPool) -> anyhow::Resasync fn returns_company_when_email_sync_is_false(pool: PgPool) -> anyhow::Result<()> {let team_id = Uuid::now_v7();seed_team(&pool, team_id, "macro|[email protected]").await?;- insert_company(&pool, team_id, "Acme", false, &["acme.com"]).await?;+ insert_company(&pool, team_id, false, &["acme.com"]).await?;let repo = CompaniesRepositoryImpl::new(pool);let company = repodiff --git a/rust/cloud-storage/crm/src/outbound/no_op_resolver.rs b/rust/cloud-storage/crm/src/outbound/no_op_resolver.rsnew file mode 100644index 0000000000..33acb706a6--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/no_op_resolver.rs@@ -0,0 +1,34 @@+//! [`CompanyMetadataResolver`] adapter that always returns+//! [`DomainMetadata::default`].+//!+//! Used by binaries that need to construct a [`CrmService`] but never+//! call [`populate_contact`] — typically HTTP API servers that only+//! read existing CRM rows via [`get_company_by_domain`]. Wiring in a+//! real unfurl-backed resolver in those binaries would force them to+//! carry the reqwest + scraper deps for code paths they never hit.+//!+//! If a binary using this resolver ever *does* call `populate_contact`,+//! the resulting `crm_domain_directory` entries will all have NULL+//! `name`/`description`/`icon_url` fields — i.e. the directory's+//! negative cache fires for every domain. That's a silent loss of+//! company metadata, not a crash, so callers should prefer wiring in+//! the real [`UnfurlCompanyMetadataResolver`] when they participate in+//! the populate path.+//!+//! [`CrmService`]: crate::domain::service::CrmService+//! [`populate_contact`]: crate::domain::service::CrmService::populate_contact+//! [`get_company_by_domain`]: crate::domain::service::CrmService::get_company_by_domain+//! [`UnfurlCompanyMetadataResolver`]: crate::outbound::unfurl_resolver::UnfurlCompanyMetadataResolver++use crate::domain::{company_metadata_resolver::CompanyMetadataResolver, model::DomainMetadata};++/// A [`CompanyMetadataResolver`] that always resolves to+/// [`DomainMetadata::default`] (all fields `None`).+#[derive(Debug, Default, Clone, Copy)]+pub struct NoOpCompanyMetadataResolver;++impl CompanyMetadataResolver for NoOpCompanyMetadataResolver {+ async fn resolve(&self, _domain: &str) -> DomainMetadata {+ DomainMetadata::default()+ }+}diff --git a/rust/cloud-storage/crm/src/outbound/unfurl_resolver.rs b/rust/cloud-storage/crm/src/outbound/unfurl_resolver.rsnew file mode 100644index 0000000000..8b8b624f5b--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/unfurl_resolver.rs@@ -0,0 +1,92 @@+//! [`CompanyMetadataResolver`] adapter that fetches metadata via the+//! [`unfurl`] crate.+//!+//! Resolves `https://{domain}` through an [`UnfurlService`] and maps the+//! response onto a [`DomainMetadata`]:+//!+//! | unfurl field | DomainMetadata field |+//! |------------------------|----------------------|+//! | `title` | `name` |+//! | `description` | `description` |+//! | `favicon_url` | `icon_url` |+//!+//! `title` is dropped when it equals the input URL itself —+//! [`unfurl::domain::models::GetUnfurlResponse::get_title`] falls back+//! to the URL when no usable meta-tag exists, and persisting that as a+//! company name would be worse than persisting `None`.+//!+//! Failures (network errors, SSRF-blocked redirects, parse errors,+//! non-HTML responses) are logged and surfaced as+//! [`DomainMetadata::default`] so the caller can persist a+//! negative-cache entry and never re-resolve the domain.++use std::sync::Arc;++use crate::domain::{company_metadata_resolver::CompanyMetadataResolver, model::DomainMetadata};+use unfurl::domain::ports::UnfurlService;++/// Adapter that resolves [`DomainMetadata`] by unfurling+/// `https://{domain}`. Holds the underlying [`UnfurlService`] behind an+/// [`Arc`] so the resolver itself is cheap to [`Clone`].+pub struct UnfurlCompanyMetadataResolver<U> {+ unfurl_service: Arc<U>,+}++// Manual Clone impl — `#[derive(Clone)]` would require `U: Clone` even+// though we only hold `Arc<U>`. The Arc clone is always cheap regardless+// of whether the inner type is Clone.+impl<U> Clone for UnfurlCompanyMetadataResolver<U> {+ fn clone(&self) -> Self {+ Self {+ unfurl_service: Arc::clone(&self.unfurl_service),+ }+ }+}++impl<U> UnfurlCompanyMetadataResolver<U>+where+ U: UnfurlService,+{+ /// Build a resolver around an existing unfurl service.+ pub fn new(unfurl_service: Arc<U>) -> Self {+ Self { unfurl_service }+ }+}++impl<U> CompanyMetadataResolver for UnfurlCompanyMetadataResolver<U>+where+ U: UnfurlService,+{+ #[tracing::instrument(skip(self))]+ async fn resolve(&self, domain: &str) -> DomainMetadata {+ let url = format!("https://{domain}");+ match self.unfurl_service.unfurl(&url).await {+ Ok(response) => {+ // `get_title` returns the URL string itself when no+ // usable title was found — drop that case. Trim+ // surrounding whitespace so accidental padding (or a+ // whitespace-only title) collapses to `None` rather+ // than getting persisted as the company name.+ let title = response.title.trim();+ let name = if title.is_empty() || title == url {+ None+ } else {+ Some(title.to_string())+ };+ DomainMetadata {+ name,+ description: response.description,+ icon_url: response.favicon_url,+ }+ }+ Err(e) => {+ tracing::warn!(+ error=?e,+ domain,+ "unfurl failed; returning empty DomainMetadata for negative cache"+ );+ DomainMetadata::default()+ }+ }+ }+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex e84d7367df..0b50865af6 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -161,6 +161,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arlet frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);let email_service = EmailServiceImpl::new(EmailPgRepo::new(pool.clone()),diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 669758db35..8254c56484 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -205,6 +205,7 @@ async fn main() -> anyhow::Result<()> {let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);let email_service = EmailServiceImpl::new(EmailPgRepo::new(db.clone()),diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 582870beee..9fbc02c406 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -76,7 +76,10 @@ type DssEmailService = EmailServiceImpl<EmailPgRepo,FrecencyQueryServiceImpl<FrecencyPgStorage>,email::domain::ports::NoOpEnqueuer,- crm::domain::service::CrmServiceImpl<crm::outbound::companies_repo::CompaniesRepositoryImpl>,+ crm::domain::service::CrmServiceImpl<+ crm::outbound::companies_repo::CompaniesRepositoryImpl,+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,+ >,>;type DssSoupState = SoupRouterState<diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex c14f55beb6..08921ea63e 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -247,8 +247,11 @@ async fn main() -> anyhow::Result<()> {let frecency_storage = FrecencyPgStorage::new(db.clone());let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ // DSS only reads CRM rows — no-op resolver keeps reqwest/scraper+ // out of this binary.let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);let email_service = EmailServiceImpl::new(EmailPgRepo::new(db.clone()),diff --git a/rust/cloud-storage/email/examples/ai_tools_cli.rs b/rust/cloud-storage/email/examples/ai_tools_cli.rsindex a47300fb06..6e0994cbf4 100644--- a/rust/cloud-storage/email/examples/ai_tools_cli.rs+++ b/rust/cloud-storage/email/examples/ai_tools_cli.rs@@ -80,6 +80,7 @@ async fn main() {let email_repo = EmailPgRepo::new(pool.clone());let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);let email_service = EmailServiceImpl::new(email_repo,diff --git a/rust/cloud-storage/email_db_client/src/contacts/get.rs b/rust/cloud-storage/email_db_client/src/contacts/get.rsindex 817a5e0620..e0ddaceed4 100644--- a/rust/cloud-storage/email_db_client/src/contacts/get.rs+++ b/rust/cloud-storage/email_db_client/src/contacts/get.rs@@ -79,17 +79,24 @@ struct RecipientQueryResult {/// given `link_id`. Walks To/Cc/Bcc indiscriminately — the caller is/// responsible for any filtering (e.g. dropping the user's own address).///+/// Returns `(lowercased_email, name)` pairs — `email_contacts` is unique+/// per `(link_id, email_address)`, so each address appears at most once+/// in the result with the single display name stored on its row. `name`+/// is `None` when no display name was recorded.+////// Used by the `PopulateCrmForUser` backfill step to enumerate the/// contacts a user has previously emailed so they can be seeded into/// their team's CRM tables.#[tracing::instrument(skip(pool), err)]-pub async fn fetch_sent_message_recipient_emails_by_link(+pub async fn fetch_sent_message_recipient_contacts_by_link(pool: &PgPool,link_id: Uuid,-) -> anyhow::Result<Vec<String>> {- sqlx::query_scalar!(+) -> anyhow::Result<Vec<(String, Option<String>)>> {+ let rows = sqlx::query!(r#"- SELECT DISTINCT LOWER(c.email_address) AS "email!"+ SELECT DISTINCT+ LOWER(c.email_address) AS "email!",+ c.name AS "name"FROM email_messages mJOIN email_message_recipients r ON r.message_id = m.idJOIN email_contacts c ON c.id = r.contact_id@@ -99,6 +106,39 @@ pub async fn fetch_sent_message_recipient_emails_by_link(link_id,).fetch_all(pool)+ .await?;++ Ok(rows.into_iter().map(|r| (r.email, r.name)).collect())+}++/// Returns true iff `link_id` still has at least one sent message whose+/// recipients (to/cc/bcc) include `email`. Used by the depopulate-CRM-+/// contact backfill step as the pre-check: if any sent message remains,+/// the CRM source row must stay. `email` is matched case-insensitively.+#[tracing::instrument(skip(pool), err)]+pub async fn link_has_sent_message_to(+ pool: &PgPool,+ link_id: Uuid,+ email: &str,+) -> anyhow::Result<bool> {+ let normalized = email.to_ascii_lowercase();+ sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM email_messages m+ JOIN email_message_recipients r ON r.message_id = m.id+ JOIN email_contacts c ON c.id = r.contact_id+ WHERE m.link_id = $1+ AND m.is_sent = true+ AND LOWER(c.email_address) = $2+ LIMIT 1+ ) AS "exists!"+ "#,+ link_id,+ normalized,+ )+ .fetch_one(pool).await.map_err(Into::into)}diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex 05afbc1604..e93b4b5539 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -79,6 +79,7 @@ chrono = { workspace = true }cloudfront_sign = { workspace = true }connection_gateway_client = { path = "../connection_gateway_client" }crm = { path = "../crm" }+unfurl = { path = "../unfurl", features = ["outbound"] }document_storage_service_client = { path = "../document_storage_service_client" }doppleganger = { workspace = true }ego-tree = { workspace = true }diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rsindex cf77d6de86..02a496ee6a 100644--- a/rust/cloud-storage/email_service/src/api/context.rs+++ b/rust/cloud-storage/email_service/src/api/context.rs@@ -25,7 +25,10 @@ pub(crate) type EmailSvc = EmailServiceImpl<EmailPgRepo,FrecencyQueryServiceImpl<FrecencyPgStorage>,sqs_client::SQS,- crm::domain::service::CrmServiceImpl<crm::outbound::companies_repo::CompaniesRepositoryImpl>,+ crm::domain::service::CrmServiceImpl<+ crm::outbound::companies_repo::CompaniesRepositoryImpl,+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,+ >,>;#[derive(Clone, FromRef)]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 151b61e6ec..7b8423698f 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@@ -235,8 +235,22 @@ async fn main() -> anyhow::Result<()> {PgSystemPropertiesRepository::new(db.clone()),));+ // Shared unfurl service drives the CRM crate's company metadata+ // resolver — wraps the SSRF-safe reqwest fetcher in an+ // `UnfurlServiceImpl`, then in an `UnfurlCompanyMetadataResolver`+ // adapter. Resolver is cheap to clone (`Arc` internally) and is+ // consulted by `crm_service.populate_contact` only on+ // `crm_domain_directory` misses.+ let unfurl_service = Arc::new(unfurl::domain::service::UnfurlServiceImpl::new(+ unfurl::outbound::ReqwestUnfurlFetcher::new()+ .context("failed to build ReqwestUnfurlFetcher")?,+ ));+ let metadata_resolver =+ crm::outbound::unfurl_resolver::UnfurlCompanyMetadataResolver::new(unfurl_service);+let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ metadata_resolver.clone(),);// Backfill workers run against a dedicated pool to keep their writes@@ -244,6 +258,7 @@ async fn main() -> anyhow::Result<()> {// flow, so route them through `db_backfill` too.let crm_service_backfill = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db_backfill.clone()),+ metadata_resolver,);// process user inbox updates from gmail inbox_sync queue, triggered by update pubsub messages from Google@@ -420,6 +435,7 @@ async fn main() -> anyhow::Result<()> {let auth_service_client_link_manager = auth_service_client.clone();let redis_client_link_manager = redis_client.clone();let sqs_client_link_manager = sqs_client.clone();+ let crm_service_link_manager = crm_service.clone();// daily link_manager operations for user contacts and inbox subscriptionstokio::spawn(async move {email_service::pubsub::link_manager::worker::run_worker(@@ -429,6 +445,7 @@ async fn main() -> anyhow::Result<()> {auth_service_client_link_manager,redis_client_link_manager,sqs_client_link_manager,+ crm_service_link_manager,).await;});diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rsindex 95320485e6..fbed8fe0c4 100644--- a/rust/cloud-storage/email_service/src/main.rs+++ b/rust/cloud-storage/email_service/src/main.rs@@ -129,8 +129,12 @@ async fn main() -> anyhow::Result<()> {let sqs_client = Arc::new(sqs_client);let gmail_client = Arc::new(gmail_client);+ // HTTP API only reads CRM rows — populate runs in the pubsub+ // worker. The no-op resolver makes the unused branch explicit and+ // keeps reqwest/scraper out of this binary.let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);let email_service = EmailRouterState::new(EmailServiceImpl::new(EmailPgRepo::new(db.clone()),diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rsindex a8103b543a..72e1e60d9c 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs@@ -1,8 +1,9 @@use crate::convert::map_message_resource_to_service;use crate::pubsub::backfill::increment_counters;-use crate::pubsub::backfill::populate_crm_contact::enqueue_populate_crm_contacts;use crate::pubsub::context::PubSubContext;-use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};+use crate::pubsub::util::{+ CheckGmailRateLimitArgs, check_gmail_rate_limit, enqueue_populate_crm_contacts,+};use crate::util::process_pre_insert::process_message_pre_insert;use anyhow::Context;use models_email::email::service::backfill::{BackfillMessagePayload, JobScopedPayload};@@ -83,17 +84,19 @@ pub async fn backfill_message(// For messages sent BY the user, fan out a PopulateCrmContact job per// recipient so the CRM tables learn about the contacts the team has been// emailing. ON CONFLICT DO NOTHING on the consumer side keeps duplicate- // enqueues (e.g. retried backfill_message attempts) harmless.+ // enqueues (e.g. retried backfill_message attempts) harmless. The+ // display name from the gmail header is threaded through so the+ // consumer doesn't have to re-query email_contacts.if message.is_sent {let self_email = link.email_address.0.as_ref().to_ascii_lowercase();- let recipient_emails: Vec<String> = message+ let recipients: Vec<(String, Option<String>)> = message.to.iter().chain(&message.cc).chain(&message.bcc)- .map(|c| c.email.clone())+ .map(|c| (c.email.clone(), c.name.clone())).collect();- enqueue_populate_crm_contacts(ctx, link.id, &self_email, recipient_emails).await?;+ enqueue_populate_crm_contacts(ctx, link.id, &self_email, recipients).await?;}// Handle all success-related operationsdiff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_contact.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_contact.rsnew file mode 100644index 0000000000..e3aeaa6477--- /dev/null+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_contact.rs@@ -0,0 +1,80 @@+use crate::pubsub::context::PubSubContext;+use crm::domain::service::CrmService;+use models_email::email::service::backfill::DepopulateCrmContactPayload;+use models_email::email::service::link;+use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};++/// Removes a contact from the CRM tables for one `(link, contact_email)`+/// when a sent message is deleted.+///+/// Fanned out one-per-recipient from `delete_message` in the inbox-sync+/// worker. The cascade is: drop the per-link `crm_contact_sources` row,+/// then `crm_contacts` if no other sources remain, then `crm_companies`+/// (with `crm_domains` falling out via FK cascade) if no other contacts+/// remain. See+/// [`crm::domain::companies_repo::CompaniesRepository::depopulate_contact`].+///+/// Pre-check: before invoking the CRM cascade we verify via+/// [`email_db_client::contacts::get::link_has_sent_message_to`] that this+/// link no longer has any sent message to `contact_email`. If a sibling+/// sent message still exists, we ack the job without touching CRM —+/// duplicate enqueues from retries or out-of-order processing land here.+///+/// The check runs outside the CRM crate's advisory lock, so a brand-new+/// sent message landing in the microseconds between the check and the+/// cascade could see a transient deleted state; the populate path on+/// that new message re-creates the rows on its next run.+#[tracing::instrument(skip(ctx), err, fields(contact_email = %p.contact_email, link_id = %link.id))]+pub async fn depopulate_crm_contact(+ ctx: &PubSubContext,+ link: &link::Link,+ p: &DepopulateCrmContactPayload,+) -> Result<(), ProcessingError> {+ let macro_user_id = link.macro_id.to_string();++ let team_id = ctx+ .crm_service+ .get_team_id_for_user(¯o_user_id)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: anyhow::Error::from(e).context("Failed to look up team for link.macro_id"),+ })+ })?;++ let Some(team_id) = team_id else {+ tracing::debug!("User has no team; skipping CRM depopulation");+ return Ok(());+ };++ let still_has_sent = email_db_client::contacts::get::link_has_sent_message_to(+ &ctx.db,+ link.id,+ &p.contact_email,+ )+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to check remaining sent messages for contact"),+ })+ })?;++ if still_has_sent {+ tracing::debug!("Link still has other sent messages to contact; skipping depopulation");+ return Ok(());+ }++ ctx.crm_service+ .depopulate_contact(&team_id, &link.id, &p.contact_email)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: anyhow::Error::from(e).context("Failed to depopulate CRM contact"),+ })+ })?;++ Ok(())+}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_for_user.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_for_user.rsnew file mode 100644index 0000000000..a5715c6644--- /dev/null+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_for_user.rs@@ -0,0 +1,53 @@+use crate::pubsub::context::PubSubContext;+use crm::domain::service::CrmService;+use models_email::email::service::backfill::DepopulateCrmForUserPayload;+use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};++/// Removes every CRM source row owned by the user's email link within+/// `payload.team_id`, plus the team's contact / company rows orphaned+/// as a result (preserving companies with `email_sync = false`).+///+/// Triggered when a user is removed from a team. Counterpart to+/// [`populate_crm_for_user`]. Unlike the per-message+/// `DepopulateCrmContact` step, this bypasses the per-recipient+/// `link_has_sent_message_to` pre-check: the user's sent messages still+/// exist after team removal, but the team no longer cares about the+/// contacts on them — so we tear down based on link ownership inside+/// the team, not message presence.+///+/// No-ops (acks the message) when the user has no email link.+/// Team-deletion does NOT go through this path; the+/// `crm_companies.team_id` FK cascade handles it in macrodb.+#[tracing::instrument(skip(ctx), err, fields(macro_id = %payload.macro_id, team_id = %payload.team_id))]+pub async fn depopulate_crm_for_user(+ ctx: &PubSubContext,+ payload: &DepopulateCrmForUserPayload,+) -> Result<(), ProcessingError> {+ let macro_id_str = payload.macro_id.0.as_ref();++ let link = email_db_client::links::get::fetch_link_by_macro_id(&ctx.db, macro_id_str)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to fetch link by macro_id"),+ })+ })?;++ let Some(link) = link else {+ tracing::debug!("User has no email link; skipping CRM teardown");+ return Ok(());+ };++ ctx.crm_service+ .depopulate_link_in_team(&payload.team_id, &link.id)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: anyhow::Error::from(e).context("Failed to depopulate CRM for link in team"),+ })+ })?;++ Ok(())+}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rsindex ebea97a2f5..7ffff301ba 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs@@ -38,7 +38,9 @@ pub async fn handle_non_retryable_error(}BackfillOperation::BackfillAttachment(_) => {}BackfillOperation::PopulateCrmContact(_) => {}+ BackfillOperation::DepopulateCrmContact(_) => {}BackfillOperation::PopulateCrmForUser(_) => {}+ BackfillOperation::DepopulateCrmForUser(_) => {}}cleanup_message(&ctx.sqs_worker, message).await?;@@ -111,12 +113,24 @@ pub async fn handle_retryable_error("Retryable error populating CRM contact")}+ BackfillOperation::DepopulateCrmContact(scope) => {+ tracing::debug!(+ contact_email = %scope.payload.contact_email,+ "Retryable error depopulating CRM contact"+ )+ }BackfillOperation::PopulateCrmForUser(payload) => {tracing::debug!(macro_id = %payload.macro_id,"Retryable error populating CRM for user")}+ BackfillOperation::DepopulateCrmForUser(payload) => {+ tracing::debug!(+ macro_id = %payload.macro_id,+ "Retryable error depopulating CRM for user"+ )+ }}Ok(())}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rsindex 547419aa08..2023708253 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs@@ -1,6 +1,8 @@mod backfill_attachment;mod backfill_message;mod backfill_thread;+mod depopulate_crm_contact;+mod depopulate_crm_for_user;mod error_handlers;mod increment_counters;mod init;diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_contact.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_contact.rsindex ff69267bfa..b8ff9fa18b 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_contact.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_contact.rs@@ -1,12 +1,8 @@use crate::pubsub::context::PubSubContext;use crm::domain::service::CrmService;-use models_email::email::service::backfill::{- BackfillOperation, BackfillPubsubMessage, LinkScopedPayload, PopulateCrmContactPayload,-};+use models_email::email::service::backfill::PopulateCrmContactPayload;use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};-use std::collections::HashSet;-use uuid::Uuid;/// Idempotently records a contact the user has emailed into the CRM tables.///@@ -16,6 +12,11 @@ use uuid::Uuid;/// `crm_contact_sources` atomically. A killswitch row/// (`crm_companies.email_sync = false` for the contact's domain) is also a/// no-op — see [`crm::domain::companies_repo::CompaniesRepository::populate_contact`].+///+/// Company metadata (name, description, icon) is resolved and cached+/// inside `crm_service.populate_contact` via the+/// `crm_domain_directory` lookup → resolver → upsert path, so the+/// consumer here doesn't need to know how that's done.#[tracing::instrument(skip(ctx), err, fields(contact_email = %p.contact_email, link_id = %link.id))]pub async fn populate_crm_contact(ctx: &PubSubContext,@@ -41,7 +42,12 @@ pub async fn populate_crm_contact(};ctx.crm_service- .populate_contact(&team_id, &link.id, &p.contact_email)+ .populate_contact(+ &team_id,+ &link.id,+ &p.contact_email,+ p.contact_name.as_deref(),+ ).await.map_err(|e| {ProcessingError::Retryable(DetailedError {@@ -52,56 +58,3 @@ pub async fn populate_crm_contact(Ok(())}--/// Producer-side fan-out helper: normalizes and enqueues one-/// `PopulateCrmContact` message per distinct, non-self contact email.-///-/// Used by both the per-message path (`backfill_message`, called every-/// time a sent message is backfilled) and the historical path-/// (`populate_crm_for_user`, called once when a user is added to a team-/// to seed contacts from their existing sent mail). Centralising the-/// validation and dedup here means the two paths can't drift in subtle-/// ways — e.g. one normalising case-sensitively while the other doesn't.-///-/// Normalization on each input:-/// - `trim()` + `to_ascii_lowercase()`-/// - drops anything without `@` (defensive against malformed addresses)-/// - drops the caller's own address (`self_email`, expected pre-lowercased)-/// - dedupes within this invocation-pub async fn enqueue_populate_crm_contacts(- ctx: &PubSubContext,- link_id: Uuid,- self_email: &str,- contact_emails: impl IntoIterator<Item = String>,-) -> Result<(), ProcessingError> {- let mut seen: HashSet<String> = HashSet::new();-- for raw in contact_emails {- let contact_email = raw.trim().to_ascii_lowercase();- if !contact_email.contains('@') || contact_email == self_email {- continue;- }- if !seen.insert(contact_email.clone()) {- continue;- }-- let ps_message = BackfillPubsubMessage {- backfill_operation: BackfillOperation::PopulateCrmContact(LinkScopedPayload {- link_id,- payload: PopulateCrmContactPayload { contact_email },- }),- };-- ctx.sqs_client- .enqueue_email_backfill_message(ps_message)- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::SqsEnqueueFailed,- source: e.context("Failed to enqueue PopulateCrmContact message"),- })- })?;- }-- Ok(())-}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_for_user.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_for_user.rsindex 0ffb455ebe..80fbd5041e 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_for_user.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_for_user.rs@@ -1,5 +1,5 @@-use crate::pubsub::backfill::populate_crm_contact::enqueue_populate_crm_contacts;use crate::pubsub::context::PubSubContext;+use crate::pubsub::util::enqueue_populate_crm_contacts;use crm::domain::service::CrmService;use models_email::email::service::backfill::PopulateCrmForUserPayload;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};@@ -53,20 +53,22 @@ pub async fn populate_crm_for_user(let self_email = link.email_address.0.as_ref().to_ascii_lowercase();- // Pull every distinct recipient address from sent messages on this link.- // Mirrors what backfill_message would have produced if the per-message- // fan-out had been running when these messages were first backfilled.- let recipient_emails =- email_db_client::contacts::get::fetch_sent_message_recipient_emails_by_link(- &ctx.db, link.id,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to fetch sent-message recipients"),- })- })?;+ // Pull every distinct recipient (email + display name) from sent+ // messages on this link. Mirrors what backfill_message would have+ // produced if the per-message fan-out had been running when these+ // messages were first backfilled — including the name from+ // email_contacts so the consumer can set crm_contacts.name without+ // its own round-trip.+ let recipients = email_db_client::contacts::get::fetch_sent_message_recipient_contacts_by_link(+ &ctx.db, link.id,+ )+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to fetch sent-message recipients"),+ })+ })?;- enqueue_populate_crm_contacts(ctx, link.id, &self_email, recipient_emails).await+ enqueue_populate_crm_contacts(ctx, link.id, &self_email, recipients).await}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rsindex 13c48fd098..a3b7fe449a 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs@@ -1,6 +1,7 @@use crate::pubsub::backfill::{- backfill_attachment, backfill_message, backfill_thread, error_handlers, init, list_threads,- populate_crm_contact, populate_crm_for_user, update_metadata,+ backfill_attachment, backfill_message, backfill_thread, depopulate_crm_contact,+ depopulate_crm_for_user, error_handlers, init, list_threads, populate_crm_contact,+ populate_crm_for_user, update_metadata,};use crate::pubsub::context::PubSubContext;use crate::util::gmail::auth::fetch_token_or_delete_on_revocation;@@ -133,9 +134,16 @@ async fn inner_process_message(let link = fetch_link(ctx, scope.link_id).await?;populate_crm_contact::populate_crm_contact(ctx, &link, &scope.payload).await}+ BackfillOperation::DepopulateCrmContact(scope) => {+ let link = fetch_link(ctx, scope.link_id).await?;+ depopulate_crm_contact::depopulate_crm_contact(ctx, &link, &scope.payload).await+ }BackfillOperation::PopulateCrmForUser(payload) => {populate_crm_for_user::populate_crm_for_user(ctx, payload).await}+ BackfillOperation::DepopulateCrmForUser(payload) => {+ depopulate_crm_for_user::depopulate_crm_for_user(ctx, payload).await+ }}}diff --git a/rust/cloud-storage/email_service/src/pubsub/context.rs b/rust/cloud-storage/email_service/src/pubsub/context.rsindex 3f2a5bdcea..b4f6a7fb0d 100644--- a/rust/cloud-storage/email_service/src/pubsub/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/context.rs@@ -5,6 +5,7 @@ use contacts::domain::service::SqsContactsIngress;use contacts::outbound::ingress::SqsContactsQueue;use crm::domain::service::CrmServiceImpl;use crm::outbound::companies_repo::CompaniesRepositoryImpl;+use crm::outbound::unfurl_resolver::UnfurlCompanyMetadataResolver;use document_storage_service_client::DocumentStorageServiceClient;use gmail_client::GmailClient;use notification::domain::service::SqsNotificationIngress;@@ -17,8 +18,16 @@ use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImp/// The concrete notification ingress service type.pub type NotificationIngressType = SqsNotificationIngress<SqsQueue>;-/// The concrete CRM service type, backed by Postgres.-pub type CrmServiceType = CrmServiceImpl<CompaniesRepositoryImpl>;+/// The concrete CRM service type, backed by Postgres and the+/// unfurl-driven metadata resolver. The resolver is consulted only on+/// `crm_domain_directory` misses, so it isn't surfaced separately on+/// [`PubSubContext`].+pub type CrmServiceType = CrmServiceImpl<+ CompaniesRepositoryImpl,+ UnfurlCompanyMetadataResolver<+ unfurl::domain::service::UnfurlServiceImpl<unfurl::outbound::ReqwestUnfurlFetcher>,+ >,+>;#[derive(Clone)]pub struct PubSubContext {diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/delete_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/delete_message.rsindex e5d5f9c36d..f35c0f865b 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/delete_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/delete_message.rs@@ -1,5 +1,7 @@use crate::pubsub::context::PubSubContext;-use crate::pubsub::util::{cg_refresh_email, complete_transaction_with_processing_error};+use crate::pubsub::util::{+ cg_refresh_email, complete_transaction_with_processing_error, enqueue_depopulate_crm_contacts,+};use models_email::email::service::link;use models_email::gmail::inbox_sync::DeleteMessagePayload;use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};@@ -35,6 +37,46 @@ pub async fn delete_message(}};+ // For sent messages, snapshot the recipients before deletion so we can+ // tear down the CRM source rows we created in `populate_crm_contact` /+ // `upsert_message`. Received messages don't contribute to CRM, so the+ // snapshot is skipped for them. Generic addresses are dropped here for+ // parity with the producer side.+ let recipient_emails: Vec<String> = if message.is_sent {+ let recipients =+ email_db_client::contacts::get::fetch_db_recipients(&ctx.db, message.db_id)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e+ .context("Failed to fetch recipients for deleted message".to_string()),+ })+ })?;+ // No producer-side filtering — the crm crate decides what's+ // depopulatable. Filtering here would create drift with the+ // populate side, which is also unfiltered at the producer.+ recipients+ .into_iter()+ .filter_map(|(contact, _)| contact.email_address)+ .collect()+ } else {+ Vec::new()+ };++ // Enqueue CRM teardown BEFORE the delete commits, so a transient+ // enqueue failure here doesn't strand the depopulate job after the+ // message row is already gone (SQS retry would then short-circuit+ // at the `None` arm above and never re-enqueue). If enqueue+ // succeeds but the delete below fails, the depopulate consumer's+ // `link_has_sent_message_to` pre-check sees the message still in+ // place and acks without touching CRM — so the ordering is safe in+ // both directions.+ if !recipient_emails.is_empty() {+ let self_email = link.email_address.0.as_ref().to_ascii_lowercase();+ enqueue_depopulate_crm_contacts(ctx, link.id, &self_email, recipient_emails).await?;+ }+let mut tx = ctx.db.begin().await.map_err(|e| {ProcessingError::Retryable(DetailedError {reason: FailureReason::DatabaseQueryFailed,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 803defe490..16902fd91b 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@@ -4,6 +4,7 @@ use crate::pubsub::inbox_sync::operations::shared::notify_search;use crate::pubsub::inbox_sync::process;use crate::pubsub::inbox_sync::process::check_gmail_rate_limit_inbox_sync;use crate::pubsub::util::cg_refresh_email;+use crate::pubsub::util::enqueue_populate_crm_contacts;use crate::util::process_pre_insert::{process_message_pre_insert, process_threads_pre_insert};use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};use contacts::domain::ports::ContactsIngress;@@ -95,16 +96,37 @@ pub async fn upsert_message(// deduped list of all non-generic emails the message was sent tolet recipient_emails = dedupe_emails(message- .cc+ .to.iter()+ .chain(&message.cc)+ .chain(&message.bcc).map(|c| c.email.clone())- .chain(message.to.iter().map(|t| t.email.clone())).collect(),).into_iter().filter(|e| !email_utils::is_generic_email(e)).collect::<Vec<_>>();+ // Snapshot `(email, name)` pairs for the CRM populate fan-out below.+ // We capture it here (before `message` is moved into+ // `process_and_insert_message`) so the consumer can write+ // `crm_contacts.name` without a separate email_contacts lookup.+ // No producer-side filtering — the crm crate is the single source+ // of truth for "what belongs in the CRM" (generic-provider domains,+ // killswitched companies, etc.) and applying the same rules here+ // would just drift over time.+ let crm_recipients: Vec<(String, Option<String>)> = if is_sent {+ message+ .to+ .iter()+ .chain(&message.cc)+ .chain(&message.bcc)+ .map(|c| (c.email.clone(), c.name.clone()))+ .collect()+ } else {+ Vec::new()+ };+// determine if message's thread already exists in the databaselet thread_provider_to_db_map = threads::get::get_threads_by_link_id_and_provider_ids(&ctx.db,@@ -194,6 +216,15 @@ pub async fn upsert_message().await?;+ // For messages sent BY the user, fan out a PopulateCrmContact job per+ // recipient so the CRM tables learn about the contacts the team has+ // been emailing. Mirrors the backfill path in backfill_message.rs;+ // `crm_recipients` was snapshotted above before `message` was moved.+ if is_sent {+ let self_email = link.email_address.0.as_ref().to_ascii_lowercase();+ enqueue_populate_crm_contacts(ctx, link.id, &self_email, crm_recipients).await?;+ }+notify_search(ctx, link, message_db_id, is_spam_or_trash).await?;// trigger FE inbox refreshdiff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/context.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/context.rsindex 0c013778d9..82ab36c99d 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/context.rs@@ -1,3 +1,4 @@+use crate::pubsub::context::CrmServiceType;use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use gmail_client::GmailClient;@@ -12,4 +13,5 @@ pub struct LinkManagerContext {pub auth_service_client: AuthServiceClient,pub redis_client: RedisClient,pub sqs_client: SQS,+ pub crm_service: CrmServiceType,}diff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rsindex a41b96d200..5d31e48fe2 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs@@ -4,6 +4,7 @@ use crate::util::gmail::auth::{};use crate::util::sync_contacts::sync_contacts;use anyhow::{Context, anyhow};+use crm::domain::service::CrmService;use models_email::email::service::pubsub::{DeletionReason, LinkManagerMessage};use models_email::service::cache::TokenCacheKey;use models_email::service::link::{Link, UserProvider};@@ -221,6 +222,31 @@ async fn handle_delete(}).ok();+ // Tear down CRM rows this link contributed to the user's team before+ // the big cascading link delete fires. Best-effort: a failure here+ // would only leave orphan `crm_contacts`/`crm_companies` rows behind+ // (the `crm_contact_sources` FK to `email_links` cascades on the+ // upcoming `delete_link_by_id`, so the link-scoped source rows go+ // away regardless), so we log and continue rather than bailing.+ let macro_id_str = link.macro_id.to_string();+ match ctx.crm_service.get_team_id_for_user(¯o_id_str).await {+ Ok(Some(team_id)) => {+ if let Err(e) = ctx+ .crm_service+ .depopulate_link_in_team(&team_id, &link.id)+ .await+ {+ tracing::error!(error=?e, team_id=%team_id, link_id=%link.id, "Failed to depopulate CRM rows before link delete; orphan crm_contacts/crm_companies may remain");+ }+ }+ Ok(None) => {+ tracing::debug!("User has no team; skipping CRM teardown before link delete");+ }+ Err(e) => {+ tracing::error!(error=?e, link_id=%link.id, "Failed to look up team for CRM teardown before link delete");+ }+ }+// finally, delete all the user's link as well as all of their email data in a big cascading deleteemail_db_client::links::delete::delete_link_by_id(&ctx.db, link.id).awaitdiff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/worker.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/worker.rsindex d4d5e3454c..c8b69edc41 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/worker.rs@@ -1,3 +1,4 @@+use crate::pubsub::context::CrmServiceType;use crate::pubsub::link_manager::context::LinkManagerContext;use crate::pubsub::link_manager::process;use crate::util::redis::RedisClient;@@ -14,6 +15,7 @@ pub async fn run_worker(auth_service_client: AuthServiceClient,redis_client: RedisClient,sqs_client: SQS,+ crm_service: CrmServiceType,) {let ctx = LinkManagerContext {db,@@ -22,6 +24,7 @@ pub async fn run_worker(auth_service_client,redis_client,sqs_client,+ crm_service,};loop {let worker_result = tokio::spawn({diff --git a/rust/cloud-storage/email_service/src/pubsub/util.rs b/rust/cloud-storage/email_service/src/pubsub/util.rsindex 0d96425e90..19113403d7 100644--- a/rust/cloud-storage/email_service/src/pubsub/util.rs+++ b/rust/cloud-storage/email_service/src/pubsub/util.rs@@ -1,9 +1,15 @@+use crate::pubsub::context::PubSubContext;use crate::util::redis::RedisClient;use crate::util::redis::rate_limit::RateLimitArgs;use connection_gateway_client::client::ConnectionGatewayClient;/// shared utils across different pubsub workers+use models_email::email::service::backfill::{+ BackfillOperation, BackfillPubsubMessage, DepopulateCrmContactPayload, LinkScopedPayload,+ PopulateCrmContactPayload,+};use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use models_email::gmail::operations::GmailApiOperation;+use std::collections::HashSet;use uuid::Uuid;/// Arguments for checking Gmail API rate limits@@ -88,3 +94,126 @@ pub async fn cg_refresh_email(client: &ConnectionGatewayClient, macro_id: &str,.inspect_err(|e| tracing::error!(macro_id = %macro_id, "Failed to refresh email: {e}"));}}++/// Shared filter/dedup pass for the CRM populate + depopulate enqueue+/// helpers. Returns each input email, lowercased and trimmed, with+/// malformed addresses and the caller's own address dropped, and+/// duplicates collapsed.+///+/// Validation is stricter than a bare `contains('@')` check:+/// - must contain exactly one `@`+/// - local-part and domain must both be non-empty+///+/// Matches the validation in [`crm::domain::service::CrmService::populate_contact`]+/// so malformed inputs never reach the consumer side.+fn normalized_non_self_contact_emails(+ self_email: &str,+ contact_emails: impl IntoIterator<Item = String>,+) -> Vec<String> {+ let mut seen: HashSet<String> = HashSet::new();+ contact_emails+ .into_iter()+ .filter_map(|raw| {+ let email = raw.trim().to_ascii_lowercase();+ let (local, domain) = email.split_once('@')?;+ if local.is_empty() || domain.is_empty() || domain.contains('@') {+ return None;+ }+ if email == self_email || !seen.insert(email.clone()) {+ return None;+ }+ Some(email)+ })+ .collect()+}++/// Producer-side fan-out helper: normalizes and enqueues one+/// `PopulateCrmContact` message per distinct, non-self contact.+///+/// Takes `(email, name)` pairs so the consumer can write+/// `crm_contacts.name` without a follow-up round-trip to `email_contacts`.+/// `name` comes from the gmail message's recipient header on the+/// per-message paths (`backfill_message`, `upsert_message`) and from+/// `email_contacts.name` on the historical path (`populate_crm_for_user`).+///+/// Email validation rules and dedup match+/// [`normalized_non_self_contact_emails`]; dedup is by email only, so the+/// first name seen for a given address in this batch wins.+pub async fn enqueue_populate_crm_contacts(+ ctx: &PubSubContext,+ link_id: Uuid,+ self_email: &str,+ contacts: impl IntoIterator<Item = (String, Option<String>)>,+) -> Result<(), ProcessingError> {+ let mut seen: HashSet<String> = HashSet::new();+ for (raw_email, contact_name) in contacts {+ let contact_email = raw_email.trim().to_ascii_lowercase();+ let Some((local, domain)) = contact_email.split_once('@') else {+ continue;+ };+ if local.is_empty() || domain.is_empty() || domain.contains('@') {+ continue;+ }+ if contact_email == self_email || !seen.insert(contact_email.clone()) {+ continue;+ }++ let ps_message = BackfillPubsubMessage {+ backfill_operation: BackfillOperation::PopulateCrmContact(LinkScopedPayload {+ link_id,+ payload: PopulateCrmContactPayload {+ contact_email,+ contact_name,+ },+ }),+ };++ ctx.sqs_client+ .enqueue_email_backfill_message(ps_message)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: e.context("Failed to enqueue PopulateCrmContact message"),+ })+ })?;+ }++ Ok(())+}++/// Producer-side fan-out helper for tearing CRM contacts down when a sent+/// message is deleted. Mirrors [`enqueue_populate_crm_contacts`] and uses+/// the same [`normalized_non_self_contact_emails`] filter.+///+/// Used by `delete_message` in the inbox-sync worker. The consumer+/// (`depopulate_crm_contact`) re-checks whether the link still has any+/// sent message to the contact before deleting, so duplicate enqueues+/// from retries are harmless.+pub async fn enqueue_depopulate_crm_contacts(+ ctx: &PubSubContext,+ link_id: Uuid,+ self_email: &str,+ contact_emails: impl IntoIterator<Item = String>,+) -> Result<(), ProcessingError> {+ for contact_email in normalized_non_self_contact_emails(self_email, contact_emails) {+ let ps_message = BackfillPubsubMessage {+ backfill_operation: BackfillOperation::DepopulateCrmContact(LinkScopedPayload {+ link_id,+ payload: DepopulateCrmContactPayload { contact_email },+ }),+ };++ ctx.sqs_client+ .enqueue_email_backfill_message(ps_message)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: e.context("Failed to enqueue DepopulateCrmContact message"),+ })+ })?;+ }++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260520150000_crm_contacts_name.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260520150000_crm_contacts_name.down.sqlnew file mode 100644index 0000000000..35a0464131--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260520150000_crm_contacts_name.down.sql@@ -0,0 +1,2 @@+ALTER TABLE crm_contacts+ DROP COLUMN IF EXISTS name;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260520150000_crm_contacts_name.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260520150000_crm_contacts_name.up.sqlnew file mode 100644index 0000000000..b9ec6302e3--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260520150000_crm_contacts_name.up.sql@@ -0,0 +1,2 @@+ALTER TABLE crm_contacts+ ADD COLUMN IF NOT EXISTS name TEXT;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260521120000_crm_domain_directory.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260521120000_crm_domain_directory.down.sqlnew file mode 100644index 0000000000..fb3df82632--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260521120000_crm_domain_directory.down.sql@@ -0,0 +1,15 @@+ALTER TABLE crm_companies ADD COLUMN IF NOT EXISTS name TEXT;++UPDATE crm_companies c+SET name = dd.name+FROM crm_domains d+JOIN crm_domain_directory dd ON LOWER(dd.domain) = LOWER(d.domain)+WHERE d.company_id = c.id+ AND dd.name IS NOT NULL+ AND c.name IS NULL;++UPDATE crm_companies SET name = 'TODO' WHERE name IS NULL;++ALTER TABLE crm_companies ALTER COLUMN name SET NOT NULL;++DROP TABLE IF EXISTS crm_domain_directory;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260521120000_crm_domain_directory.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260521120000_crm_domain_directory.up.sqlnew file mode 100644index 0000000000..bf8d4e2019--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260521120000_crm_domain_directory.up.sql@@ -0,0 +1,14 @@+CREATE TABLE IF NOT EXISTS crm_domain_directory+(+ id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),+ domain TEXT NOT NULL,+ name TEXT,+ description TEXT,+ icon_url TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE UNIQUE INDEX IF NOT EXISTS crm_domain_directory_domain_key+ ON crm_domain_directory (LOWER(domain));++ALTER TABLE crm_companies DROP COLUMN IF EXISTS name;diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rsindex e19ed74677..650cf711f4 100644--- a/rust/cloud-storage/mcp_service/src/context.rs+++ b/rust/cloud-storage/mcp_service/src/context.rs@@ -162,6 +162,7 @@ async fn build_tool_context(let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);let email_service = EmailServiceImpl::new(EmailPgRepo::new(db.clone()),diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rsindex 26e115bac1..2032827558 100644--- a/rust/cloud-storage/memory/src/context.rs+++ b/rust/cloud-storage/memory/src/context.rs@@ -70,6 +70,7 @@ pub async fn build_tool_service_context(let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);let email_service = EmailServiceImpl::new(EmailPgRepo::new(pool.clone()),diff --git a/rust/cloud-storage/models_email/src/email/service/backfill.rs b/rust/cloud-storage/models_email/src/email/service/backfill.rsindex 94946798cc..491e33c0bb 100644--- a/rust/cloud-storage/models_email/src/email/service/backfill.rs+++ b/rust/cloud-storage/models_email/src/email/service/backfill.rs@@ -80,11 +80,24 @@ pub enum BackfillOperation {// sent by the user. No-op if the user has no team or the contact's domain// has been opted out by the team (crm_companies.email_sync = false).PopulateCrmContact(LinkScopedPayload<PopulateCrmContactPayload>),+ // Walks the CRM cascade in reverse for one (link, contact_email): drops+ // the matching crm_contact_sources row, then crm_contacts when no other+ // sources remain, then crm_companies when no other contacts remain.+ // Fanned out one-per-recipient from delete_message when a sent message+ // is deleted. Ignores the company-level email_sync killswitch so that+ // deletions stay reflected in the CRM tables even on opted-out domains.+ DepopulateCrmContact(LinkScopedPayload<DepopulateCrmContactPayload>),// Fans out PopulateCrmContact messages for every contact a user has// previously emailed. Resolves the user's link + team itself (bails if// either is missing). Triggered when a user gets added to a team so// their historical sent-mail recipients seed the team's CRM tables.PopulateCrmForUser(PopulateCrmForUserPayload),+ // Tears down every CRM source row owned by the user's email link,+ // plus the contact/company rows that become orphaned as a result+ // (preserving companies with `email_sync = false`). Triggered when a+ // user is removed from a team. Team deletion is handled separately+ // via the `crm_companies.team_id` FK cascade in macrodb.+ DepopulateCrmForUser(DepopulateCrmForUserPayload),}impl BackfillOperation {@@ -99,7 +112,9 @@ impl BackfillOperation {BackfillOperation::UpdateThreadMetadata(s) => Some(s.link_id),BackfillOperation::BackfillAttachment(s) => Some(s.link_id),BackfillOperation::PopulateCrmContact(s) => Some(s.link_id),+ BackfillOperation::DepopulateCrmContact(s) => Some(s.link_id),BackfillOperation::PopulateCrmForUser(_) => None,+ BackfillOperation::DepopulateCrmForUser(_) => None,}}@@ -113,9 +128,10 @@ impl BackfillOperation {BackfillOperation::BackfillMessage(s) => Some(s.job_id),BackfillOperation::UpdateThreadMetadata(s) => Some(s.job_id),BackfillOperation::BackfillAttachment(s) => Some(s.job_id),- BackfillOperation::PopulateCrmContact(_) | BackfillOperation::PopulateCrmForUser(_) => {- None- }+ BackfillOperation::PopulateCrmContact(_)+ | BackfillOperation::DepopulateCrmContact(_)+ | BackfillOperation::PopulateCrmForUser(_)+ | BackfillOperation::DepopulateCrmForUser(_) => None,}}}@@ -256,9 +272,33 @@ pub struct BackfillAttachmentPayload {#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]pub struct PopulateCrmContactPayload {pub contact_email: String,+ /// Display name observed for `contact_email` at producer time — the+ /// caller copies it from the gmail message's recipient header+ /// (`backfill_message`, `upsert_message`) or from `email_contacts.name`+ /// (`populate_crm_for_user`). Threading it through the payload lets+ /// the consumer skip its own `email_contacts` round-trip. `None` when+ /// no display name was associated with the address.+ #[serde(default)]+ pub contact_name: Option<String>,+}++#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]+pub struct DepopulateCrmContactPayload {+ pub contact_email: String,}#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]pub struct PopulateCrmForUserPayload {pub macro_id: MacroUserIdStr<'static>,}++#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]+pub struct DepopulateCrmForUserPayload {+ pub macro_id: MacroUserIdStr<'static>,+ /// Team the user was just removed from. Passed explicitly because+ /// the consumer cannot recover this via `get_team_id_for_user` —+ /// by the time it runs the user has already been removed from+ /// `team_user`, so the lookup would either be empty or return a+ /// different team if the user is on multiple.+ pub team_id: Uuid,+}diff --git a/rust/cloud-storage/soup/examples/ai_tools_cli.rs b/rust/cloud-storage/soup/examples/ai_tools_cli.rsindex dc818911e6..6028cb7c6a 100644--- a/rust/cloud-storage/soup/examples/ai_tools_cli.rs+++ b/rust/cloud-storage/soup/examples/ai_tools_cli.rs@@ -53,6 +53,7 @@ async fn main() {let email_repo = EmailPgRepo::new(pool.clone());let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,);let email_service = EmailServiceImpl::new(email_repo,diff --git a/rust/cloud-storage/teams/src/domain.rs b/rust/cloud-storage/teams/src/domain.rsindex d3585a73a3..8cea096395 100644--- a/rust/cloud-storage/teams/src/domain.rs+++ b/rust/cloud-storage/teams/src/domain.rs@@ -1,5 +1,5 @@+pub mod crm_enqueuer;pub mod customer_repo;pub mod model;-pub mod populate_crm_enqueuer;pub mod team_repo;pub mod team_service;diff --git a/rust/cloud-storage/teams/src/domain/crm_enqueuer.rs b/rust/cloud-storage/teams/src/domain/crm_enqueuer.rsnew file mode 100644index 0000000000..9df749ac8e--- /dev/null+++ b/rust/cloud-storage/teams/src/domain/crm_enqueuer.rs@@ -0,0 +1,74 @@+//! Outbound port for triggering CRM-fanout backfills from the teams+//! service.+//!+//! The teams service uses this to ask the email service to seed+//! (`enqueue_populate_crm_for_user`) or tear down+//! (`enqueue_depopulate_crm_for_user`) its+//! `crm_companies`/`crm_domains`/`crm_contacts`/`crm_contact_sources`+//! tables for a single user. The teams service does not know — and+//! does not need to know — that the email service consumes these via a+//! pubsub queue; the port keeps the contract to domain types only. See+//! the matching SQS adapter in `crate::outbound::crm_enqueuer`.+//!+//! Modeled on [`email::domain::ports::EmailMessageEnqueuer`].++use macro_user_id::user_id::MacroUserIdStr;++/// Asks the email service to seed or tear down the CRM tables for one+/// user. Implementations are expected to be best-effort and+/// fire-and-forget — callers (e.g. `join_team`, `remove_user_from_team`)+/// log and swallow failures rather than rolling back the team membership+/// change.+pub trait CrmEnqueuer: Clone + Send + Sync + 'static {+ /// Error type for enqueue operations.+ type Err: std::fmt::Display + std::fmt::Debug + Send;++ /// Enqueue a request to populate the CRM tables for `macro_id`. The+ /// user is expected to already be a member of a team at the time this+ /// fires — the email-service consumer re-checks team membership and+ /// per-domain killswitches, so a race with `remove_user_from_team` is+ /// safe.+ fn enqueue_populate_crm_for_user(+ &self,+ macro_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Enqueue a request to tear down `team_id`'s CRM rows sourced from+ /// `macro_id`'s email link. Counterpart to+ /// [`Self::enqueue_populate_crm_for_user`]; called from+ /// `remove_user_from_team`. The user is expected to no longer be a+ /// member of `team_id` at the time the consumer runs — `team_id` is+ /// passed explicitly because the consumer can't recover it via a+ /// fresh lookup after the removal has committed. Team deletion is+ /// handled separately by the `crm_companies.team_id` FK cascade in+ /// macrodb, so this is not invoked from `delete_team`.+ fn enqueue_depopulate_crm_for_user(+ &self,+ team_id: &uuid::Uuid,+ macro_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+}++/// No-op enqueuer for callers that don't need the CRM fan-out side+/// effect (e.g. unit tests, callers that don't have SQS wired up).+#[derive(Clone, Debug)]+pub struct NoOpCrmEnqueuer;++impl CrmEnqueuer for NoOpCrmEnqueuer {+ type Err = std::convert::Infallible;++ async fn enqueue_populate_crm_for_user(+ &self,+ _macro_id: &MacroUserIdStr<'_>,+ ) -> Result<(), Self::Err> {+ Ok(())+ }++ async fn enqueue_depopulate_crm_for_user(+ &self,+ _team_id: &uuid::Uuid,+ _macro_id: &MacroUserIdStr<'_>,+ ) -> Result<(), Self::Err> {+ Ok(())+ }+}diff --git a/rust/cloud-storage/teams/src/domain/populate_crm_enqueuer.rs b/rust/cloud-storage/teams/src/domain/populate_crm_enqueuer.rsdeleted file mode 100644index 61d285ecd5..0000000000--- a/rust/cloud-storage/teams/src/domain/populate_crm_enqueuer.rs+++ /dev/null@@ -1,47 +0,0 @@-//! Outbound port for triggering a "populate CRM for user" backfill from the-//! teams service.-//!-//! The teams service uses this to ask the email service to seed its-//! `crm_contacts`/`crm_contact_sources` tables with the contacts a user has-//! previously emailed, at the moment that user joins a team. The teams-//! service does not know — and does not need to know — that the email-//! service consumes this via a pubsub queue; the port keeps the contract-//! to domain types only. See `sqs_client::teams` for the SQS adapter.-//!-//! Modeled on [`email::domain::ports::EmailMessageEnqueuer`].--use macro_user_id::user_id::MacroUserIdStr;--/// Asks the email service to seed the CRM tables with the user's historical-/// sent-mail contacts. Implementations are expected to be best-effort and-/// fire-and-forget — callers (e.g. `join_team`) log and swallow failures-/// rather than rolling back the team membership.-pub trait PopulateCrmEnqueuer: Clone + Send + Sync + 'static {- /// Error type for enqueue operations.- type Err: std::fmt::Display + std::fmt::Debug + Send;-- /// Enqueue a request to populate the CRM tables for `macro_id`. The user- /// is expected to already be a member of a team at the time this fires —- /// the email-service consumer re-checks team membership and per-domain- /// killswitches, so a race with `remove_user_from_team` is safe.- fn enqueue_populate_crm_for_user(- &self,- macro_id: &MacroUserIdStr<'_>,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;-}--/// No-op enqueuer for callers that don't need the CRM seeding side effect-/// (e.g. unit tests, callers that don't have SQS wired up).-#[derive(Clone, Debug)]-pub struct NoOpPopulateCrmEnqueuer;--impl PopulateCrmEnqueuer for NoOpPopulateCrmEnqueuer {- type Err = std::convert::Infallible;-- async fn enqueue_populate_crm_for_user(- &self,- _macro_id: &MacroUserIdStr<'_>,- ) -> Result<(), Self::Err> {- Ok(())- }-}diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rsindex 8adc076a04..49a3ce254b 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -22,6 +22,7 @@ use model_notifications::InviteToTeamMetadata;use notification::domain::{models::SendNotificationRequestBuilder, service::NotificationIngress};use crate::domain::{+ crm_enqueuer::CrmEnqueuer,customer_repo::CustomerRepository,model::{CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,@@ -30,20 +31,19 @@ use crate::domain::{TeamCheckoutError, TeamCheckoutSessionRequest, TeamError, TeamInvite, TeamInviteDetails,TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,},- populate_crm_enqueuer::PopulateCrmEnqueuer,team_repo::{TeamChannelsRepository, TeamMembersService, TeamRepository, TeamService},};/// Implementation of the TeamService using a TeamRepository#[derive(Debug)]-pub struct TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>+pub struct TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,- PCE: PopulateCrmEnqueuer,+ CE: CrmEnqueuer,{/// The underlying team repositoryteam_repository: TR,@@ -55,19 +55,20 @@ whereuser_roles_and_permissions_service: URPS,/// The notification ingress servicenotification_ingress: Arc<NI>,- /// Outbound enqueuer for the "populate CRM for user" backfill that- /// runs after a successful `join_team`. See [`PopulateCrmEnqueuer`].- populate_crm_enqueuer: PCE,+ /// Outbound enqueuer for the populate / depopulate CRM backfills+ /// fired from `create_team` / `join_team` / `remove_user_from_team`.+ /// See [`CrmEnqueuer`].+ crm_enqueuer: CE,}-impl<TR, CR, TCR, URPS, NI, PCE> Clone for TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>+impl<TR, CR, TCR, URPS, NI, CE> Clone for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,- PCE: PopulateCrmEnqueuer,+ CE: CrmEnqueuer,{fn clone(&self) -> Self {Self {@@ -76,19 +77,19 @@ whereteam_channels_repository: self.team_channels_repository.clone(),user_roles_and_permissions_service: self.user_roles_and_permissions_service.clone(),notification_ingress: self.notification_ingress.clone(),- populate_crm_enqueuer: self.populate_crm_enqueuer.clone(),+ crm_enqueuer: self.crm_enqueuer.clone(),}}}-impl<TR, CR, TCR, URPS, NI, PCE> TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>+impl<TR, CR, TCR, URPS, NI, CE> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,- PCE: PopulateCrmEnqueuer,+ CE: CrmEnqueuer,{/// Creates a new TeamServicepub fn new(@@ -97,7 +98,7 @@ whereteam_channels_repository: TCR,user_roles_and_permissions_service: URPS,notification_ingress: Arc<NI>,- populate_crm_enqueuer: PCE,+ crm_enqueuer: CE,) -> Self {Self {team_repository,@@ -105,19 +106,19 @@ whereteam_channels_repository,user_roles_and_permissions_service,notification_ingress,- populate_crm_enqueuer,+ crm_enqueuer,}}}-impl<TR, CR, TCR, URPS, NI, PCE> TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>+impl<TR, CR, TCR, URPS, NI, CE> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,- PCE: PopulateCrmEnqueuer,+ CE: CrmEnqueuer,{/// Gets the teams subscription id/// If the team doesn't have a subscription yet, it will convert the owners personal subscription into a team subscription@@ -222,14 +223,14 @@ impl GetTeamSubscriptionError {}}-impl<TR, CR, TCR, URPS, NI, PCE> TeamMembersService for TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>+impl<TR, CR, TCR, URPS, NI, CE> TeamMembersService for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,- PCE: PopulateCrmEnqueuer,+ CE: CrmEnqueuer,{#[tracing::instrument(skip(self), err)]async fn list_team_members(@@ -246,14 +247,14 @@ where}}-impl<TR, CR, TCR, URPS, NI, PCE> TeamService for TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>+impl<TR, CR, TCR, URPS, NI, CE> TeamService for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,- PCE: PopulateCrmEnqueuer,+ CE: CrmEnqueuer,{#[tracing::instrument(skip(self), err)]async fn create_team(@@ -269,7 +270,7 @@ where// so a missed enqueue can be retried (or covered by per-message CRM// fan-out) without leaving the system in an inconsistent state.if let Err(e) = self- .populate_crm_enqueuer+ .crm_enqueuer.enqueue_populate_crm_for_user(user_id).await{@@ -389,6 +390,27 @@ where.await.map_err(RemoveUserFromTeamError::RemoveRolesFromUserError)?;+ // Best-effort: ask the email service to tear down CRM rows+ // sourced from this user's email link. Log and swallow failures+ // — the removal is already committed and the email-service+ // handler is idempotent, so a missed enqueue can be retried+ // without leaving the system in an inconsistent state. Team+ // deletion is handled separately via the+ // `crm_companies.team_id` FK cascade and does NOT route through+ // this enqueuer.+ if let Err(e) = self+ .crm_enqueuer+ .enqueue_depopulate_crm_for_user(&team_id, user_id)+ .await+ {+ tracing::error!(+ error = ?e,+ team_id = %team_id,+ macro_id = %user_id,+ "Failed to enqueue DepopulateCrmForUser after remove_user_from_team; CRM rows owned by the removed user's link will be left in place until manual cleanup"+ );+ }+Ok(())}@@ -512,7 +534,7 @@ where// so a missed enqueue can be retried (or covered by per-message CRM// fan-out) without leaving the system in an inconsistent state.if let Err(e) = self- .populate_crm_enqueuer+ .crm_enqueuer.enqueue_populate_crm_for_user(user_id).await{diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rsindex 6703e21527..dc05c5494c 100644--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs@@ -20,7 +20,7 @@ use roles_and_permissions::domain::{port::UserRolesAndPermissionsService,};-use crate::domain::populate_crm_enqueuer::NoOpPopulateCrmEnqueuer;+use crate::domain::crm_enqueuer::NoOpCrmEnqueuer;fn test_team_receipt<T: RequiredPermission>(team_id: uuid::Uuid,@@ -580,7 +580,7 @@ fn build_service(MockTeamChannelsRepository,MockUserRolesAndPermissionsService,notification_ingress.clone(),- NoOpPopulateCrmEnqueuer,+ NoOpCrmEnqueuer,);(service, notification_ingress)}@@ -739,7 +739,7 @@ fn build_service_with_team(MockTeamChannelsRepository,MockUserRolesAndPermissionsService,notification_ingress,- NoOpPopulateCrmEnqueuer,+ NoOpCrmEnqueuer,);(service, role_calls, name_calls)}diff --git a/rust/cloud-storage/teams/src/outbound.rs b/rust/cloud-storage/teams/src/outbound.rsindex 2455af2b40..5a7f07bd86 100644--- a/rust/cloud-storage/teams/src/outbound.rs+++ b/rust/cloud-storage/teams/src/outbound.rs@@ -1,4 +1,4 @@+pub mod crm_enqueuer;pub mod customer_repo;-pub mod populate_crm_enqueuer;pub mod team_channels_repo;pub mod team_repo;diff --git a/rust/cloud-storage/teams/src/outbound/crm_enqueuer.rs b/rust/cloud-storage/teams/src/outbound/crm_enqueuer.rsnew file mode 100644index 0000000000..4f506af643--- /dev/null+++ b/rust/cloud-storage/teams/src/outbound/crm_enqueuer.rs@@ -0,0 +1,76 @@+//! SQS-backed adapter for the+//! [`crate::domain::crm_enqueuer::CrmEnqueuer`] port.+//!+//! Publishes `BackfillOperation::PopulateCrmForUser` /+//! `BackfillOperation::DepopulateCrmForUser` messages onto the email+//! backfill queue (the same queue `email_service` consumes from for its+//! backfill worker). This is the only file in the teams crate that+//! depends on `models_email` — the port itself speaks in domain types+//! only, so consumers that don't need SQS enqueueing (tests, callers+//! using a no-op) never pull `models_email` in.++use crate::domain::crm_enqueuer::CrmEnqueuer;+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use models_email::email::service::backfill::{+ BackfillOperation, BackfillPubsubMessage, DepopulateCrmForUserPayload,+ PopulateCrmForUserPayload,+};++/// SQS adapter for [`CrmEnqueuer`]. Wraps a `sqs_client::SQS` that must+/// have been built with `.email_backfill_queue(...)` set.+#[derive(Clone, Debug)]+pub struct SqsCrmEnqueuer {+ /// The underlying SQS client. Expected to have `email_backfill_queue`+ /// configured.+ sqs: sqs_client::SQS,+}++impl SqsCrmEnqueuer {+ /// Creates a new SqsCrmEnqueuer over the given SQS client.+ pub fn new(sqs: sqs_client::SQS) -> Self {+ Self { sqs }+ }+}++impl CrmEnqueuer for SqsCrmEnqueuer {+ type Err = anyhow::Error;++ #[tracing::instrument(skip(self), err)]+ async fn enqueue_populate_crm_for_user(+ &self,+ macro_id: &MacroUserIdStr<'_>,+ ) -> Result<(), Self::Err> {+ // The payload owns the macro_id with a 'static lifetime — clone+ // into an owned `MacroUserIdStr<'static>` so it can be serialized+ // and shipped through SQS.+ let macro_id_owned: MacroUserIdStr<'static> = macro_id.clone().into_owned();++ let message = BackfillPubsubMessage {+ backfill_operation: BackfillOperation::PopulateCrmForUser(PopulateCrmForUserPayload {+ macro_id: macro_id_owned,+ }),+ };++ self.sqs.enqueue_email_backfill_message(message).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn enqueue_depopulate_crm_for_user(+ &self,+ team_id: &uuid::Uuid,+ macro_id: &MacroUserIdStr<'_>,+ ) -> Result<(), Self::Err> {+ let macro_id_owned: MacroUserIdStr<'static> = macro_id.clone().into_owned();++ let message = BackfillPubsubMessage {+ backfill_operation: BackfillOperation::DepopulateCrmForUser(+ DepopulateCrmForUserPayload {+ macro_id: macro_id_owned,+ team_id: *team_id,+ },+ ),+ };++ self.sqs.enqueue_email_backfill_message(message).await+ }+}diff --git a/rust/cloud-storage/teams/src/outbound/populate_crm_enqueuer.rs b/rust/cloud-storage/teams/src/outbound/populate_crm_enqueuer.rsdeleted file mode 100644index ce3011ae5c..0000000000--- a/rust/cloud-storage/teams/src/outbound/populate_crm_enqueuer.rs+++ /dev/null@@ -1,54 +0,0 @@-//! SQS-backed adapter for the-//! [`crate::domain::populate_crm_enqueuer::PopulateCrmEnqueuer`] port.-//!-//! Publishes a `BackfillOperation::PopulateCrmForUser` message onto the-//! email backfill queue (the same queue `email_service` consumes from for-//! its backfill worker). This is the only file in the teams crate that-//! depends on `models_email` — the port itself speaks in domain types-//! only, so consumers that don't need SQS enqueueing (tests, callers using-//! a no-op) never pull `models_email` in.--use crate::domain::populate_crm_enqueuer::PopulateCrmEnqueuer;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use models_email::email::service::backfill::{- BackfillOperation, BackfillPubsubMessage, PopulateCrmForUserPayload,-};--/// SQS adapter for [`PopulateCrmEnqueuer`]. Wraps a `sqs_client::SQS` that-/// must have been built with `.email_backfill_queue(...)` set.-#[derive(Clone, Debug)]-pub struct SqsPopulateCrmEnqueuer {- /// The underlying SQS client. Expected to have `email_backfill_queue`- /// configured.- sqs: sqs_client::SQS,-}--impl SqsPopulateCrmEnqueuer {- /// Creates a new SqsPopulateCrmEnqueuer over the given SQS client.- pub fn new(sqs: sqs_client::SQS) -> Self {- Self { sqs }- }-}--impl PopulateCrmEnqueuer for SqsPopulateCrmEnqueuer {- type Err = anyhow::Error;-- #[tracing::instrument(skip(self), err)]- async fn enqueue_populate_crm_for_user(- &self,- macro_id: &MacroUserIdStr<'_>,- ) -> Result<(), Self::Err> {- // The payload owns the macro_id with a 'static lifetime — clone- // into an owned `MacroUserIdStr<'static>` so it can be serialized- // and shipped through SQS.- let macro_id_owned: MacroUserIdStr<'static> = macro_id.clone().into_owned();-- let message = BackfillPubsubMessage {- backfill_operation: BackfillOperation::PopulateCrmForUser(PopulateCrmForUserPayload {- macro_id: macro_id_owned,- }),- };-- self.sqs.enqueue_email_backfill_message(message).await- }-}