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): Apollo.io company enrichment behind a flag (#3666)
Evan Hutnik7cbd4f26c79c
diff --git a/.env-local.enc b/.env-local.encindex 8f0e8636b2..dca30f545c 100644--- a/.env-local.enc+++ b/.env-local.enc@@ -1,4 +1,5 @@ANTHROPIC_API_KEY=ENC[AES256_GCM,data:FWiyy0fQujeHueZgjza65J/ysbJn/MdgO7ViPQsOmyvgQ4Vxg31PWQOtaVsumDTIMBTwqJgV7quHw/UyNoBsyuT0VjsFGbst7Noid19jU+C1SxuTRkRPjoWWU5CdsfIbO6IE6jep22RiNENryfQ=,iv:5o04Rs6pDYMK1tgABtVf88fEMKfVneOgqb7XCyj72Gc=,tag:CMQFMra1np9IW6oHDqDeHw==,type:str]+APOLLO_API_KEY=ENC[AES256_GCM,data:7uXJ7Jam5dRbcA==,iv:mDA4fnXh0/FX/Imu/6KQpHsvhYu8U5FfBjGausagWhg=,tag:JkW59Lq0MS2VjQKItl4VmQ==,type:str]APPLE_BUNDLE_ID=ENC[AES256_GCM,data:Er+vj5c5kr0pKG9FP1fRAdFkNh8=,iv:K5qF4pdHVlhsV+9oYTLMBjH29tSIKh6HLtsrNs3mhpU=,tag:ZXbUCNSuZ7eSga/KbI7KKw==,type:str]ATTACHMENT_BUCKET=ENC[AES256_GCM,data:wxJ2a31CpoKfhybQkD0kgJFzuzXtLhoPmQ==,iv:5lLkCkFdAyU5QoUMoOlH7cGPxsktOeCJwl42gIhSyFs=,tag:RLGD048ajeRvO9UL9Jisfw==,type:str]AUTHENTICATION_SERVICE_INTERNAL_API_SECRET_KEY=ENC[AES256_GCM,data:vsMb/ks9TQ==,iv:UBfSPDDu+1kaXIruQleGqD9KETykb+BeGn0EeT4g4hA=,tag:LhoN2TUtYug52lD6BaiRVg==,type:str]@@ -145,7 +146,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480sops_kms__list_1__map_aws_profile=sops_kms__list_1__map_created_at=2026-03-03T19:32:07Zsops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wFUqf7u/HEfCUGv7j69Mb6YAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMpcJQR1XeIAFFE7ebAgEQgDvYRYIWelwN8TuwA+6fZVaB34yKo9EQ5xPLr/3BU+ro1Mn2eBPCg3q8ie2LuE/3voim1X35P/cdtDqTZg==-sops_lastmodified=2026-05-29T20:47:44Z-sops_mac=ENC[AES256_GCM,data:D7VSo7W9M4UOn1lmoO+jPl3kGHuKAOlpbbfCLPiVLmFzzvplRw8Wq4eY8qkx9q83Nt49SZkfBas3lsdNAqWKDTKjvPKsIWv8gcBMdnxCnu0A4EV3s6R0v/sZuVU/IaozaNS0Lg624kmeDS8ytCVATxZyQ+EkEOQGZKXWYygVEJg=,iv:ZGyonEY+Jc6Sz3vIWExkKQB697RCNu9Zv8ou5yIDmBQ=,tag:k1qLY83Y/mV4wzEi2J1XJA==,type:str]+sops_lastmodified=2026-05-29T22:49:06Z+sops_mac=ENC[AES256_GCM,data:Z9sFo/yho9fkOZizDS1A5rFPZD+vjESmUkHzB/1fkpOj52MMO7jpOu/sOpl2GGBETehvVBIgwyDl7svOJ3/crc0SjGdNqM3KbvvN+4M6GcJqOQLrtgI/79rM10tj3II0WR0SONizAl1KaFNbf36Oby+GMjNjCigjG4BItDLhT6c=,iv:8BV0/0WELgki57QnZJigX2wXzN706ZVLp03WQ5TfTjo=,tag:1t7b9hC393apNbHUG0lsWg==,type:str]sops_unencrypted_suffix=_unencryptedsops_version=3.12.2diff --git a/.env-localdev.enc b/.env-localdev.encindex 8e308febb6..8cf1b7ca92 100644--- a/.env-localdev.enc+++ b/.env-localdev.enc@@ -1,4 +1,5 @@ANTHROPIC_API_KEY=ENC[AES256_GCM,data:VYcI7QM6IC7rKIiHKOCnLEJYsUE1CF7rihThMrwV1J9RlC42yZHNw2HbCmzinoUA+sHX08fNRNBSik4RlI/H8DAWmvibXj7id2D1rqsu7BnFooC8g3Hw4z7ck0qUAhZdHPtBM/5j4vLcYF42nkE=,iv:Nnz6RwkI0yFO+Lm11emZcG1183CGX8mkppHfmpQtsoo=,tag:uxQY2GlN8P7XnWVvJ6Xgkg==,type:str]+APOLLO_API_KEY=ENC[AES256_GCM,data:gp/KzUAd8IEEFKyf8zsw7ogCiCObngZgZCu7p3PD,iv:0BB37hNTOg/cqsVK5DlZ7UW+MuVT3TEWrGJmvNGcZPQ=,tag:jBaVxRp1Nrba9JR4W0Tc8g==,type:str]APPLE_BUNDLE_ID=ENC[AES256_GCM,data:LBMu/kSe02LuOg7g5rBeQyypWEY=,iv:G+ut3Pp6WppCvf5sKxVviDpd5MVkPkmz09vVO8bepHY=,tag:Khu3dCBTKH2a38NVIfks3Q==,type:str]ATTACHMENT_BUCKET=ENC[AES256_GCM,data:Q2nRR8QhQatbdjurfjztEdn8rskpWOJOwiI+9A0=,iv:ts1TShEePc5wlU/gqM9Bh46nYQk64/giaVRrpjAyEo8=,tag:ge1wP4sLeJk6LOxPtslVdQ==,type:str]AUDIENCE=ENC[AES256_GCM,data:+/9oVoZ5GJnuGUlyyda0SmU67CjaWOZdNfv0O/0tKYBbcTuWt8Q=,iv:qWc1qVvvv6WbcVn9iQx9a7WvuZW+mLJlJOmv8/lDznE=,tag:VnC+Q+y8Ixrc2ySNYCCc9g==,type:str]@@ -150,7 +151,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480sops_kms__list_1__map_aws_profile=sops_kms__list_1__map_created_at=2026-03-03T19:32:17Zsops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wHtcTS4UVhM79Eansn1/OmrAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMRrFwSp99ZM2mPtJzAgEQgDvsIaiNifNz0/18C9OH77AG/LQLpmDiXiJYV46yLDv9vdyPL3PaLMvkAqgL3Xb2F4RcZOIUxkTS3u92xQ==-sops_lastmodified=2026-05-25T18:56:54Z-sops_mac=ENC[AES256_GCM,data:/FUVn8citGc9qR3GcQZu/6xQSavYsiEl9pSayJmNfXy9ZhUjRv15tCJPJt/DqYF3xW93gWL6ldgAKh2xD5IRtJ3XrWv1NUt+PdziZUZg8JEVUcDkg0DURY3MTAr5z/rm7FhVJZ70diZH1xtqk9xjCvjMNHp941h8BqH1iT5t0Ho=,iv:1aiZY8VM8Egc+IGFDQZloSGi/9rCf7Upvvaup0MPUyc=,tag:RlO+gicM8sZ9bXarGR0cew==,type:str]+sops_lastmodified=2026-05-29T21:44:38Z+sops_mac=ENC[AES256_GCM,data:nlYdxJaSaARFAJUPcjw7VEOEDH38hvcjLp+hT/9bU8epQ40XWzM86u7uaBsVVEMNKI5aBheUMi81zVpkH5qvu9iTjrb+LMaGf4mutLwefhbiOw9L26CWYy0hxLk8LmOcmTEMJ2fOjMIWkE0yIl5xmyWGtOQA7EJyAveQfKw0n/M=,iv:2ONBMErpjEPqR7wgOqabUIL07qUdJ5+Lg1ACTpUvMYw=,tag:dDpjHzr783fYW0OhSxj8qQ==,type:str]sops_unencrypted_suffix=_unencryptedsops_version=3.12.2diff --git a/infra/stacks/email-service/Pulumi.dev.yaml b/infra/stacks/email-service/Pulumi.dev.yamlindex bd7768fc21..91c73463be 100644--- a/infra/stacks/email-service/Pulumi.dev.yaml+++ b/infra/stacks/email-service/Pulumi.dev.yaml@@ -9,6 +9,8 @@ config:email-service:internal_auth_key: document-storage-service-auth-key-devemail-service:cf_private_key: email-attachments-private-key-devemail-service:notifications_enabled: true+ email-service:use_apollo_crm_enrichment: true+ email-service:apollo_api_key_secret_name: apollo-io-api-key-masteremail-service:sent_undo_delay_secs: 5email-service:redis_rate_limit_reqs: 14000email-service:redis_rate_limit_reqs_backfill: 13000diff --git a/infra/stacks/email-service/Pulumi.prod.yaml b/infra/stacks/email-service/Pulumi.prod.yamlindex cd39394b9d..c8646e84b3 100644--- a/infra/stacks/email-service/Pulumi.prod.yaml+++ b/infra/stacks/email-service/Pulumi.prod.yaml@@ -9,6 +9,8 @@ config:email-service:internal_auth_key: document-storage-service-auth-key-prodemail-service:cf_private_key: email-attachments-private-key-prodemail-service:notifications_enabled: true+ email-service:use_apollo_crm_enrichment: false+ email-service:apollo_api_key_secret_name: apollo-io-api-key-masteremail-service:sent_undo_delay_secs: 5email-service:redis_rate_limit_reqs: 14000email-service:redis_rate_limit_reqs_backfill: 13000diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.tsindex 34053a859b..ddd8eed201 100644--- a/infra/stacks/email-service/index.ts+++ b/infra/stacks/email-service/index.ts@@ -44,6 +44,8 @@ const AUDIENCE = aws.secretsmanager.apply((secret) => secret.secretString);const ISSUER = config.require(`fusionauth_issuer`);const NOTIFICATIONS_ENABLED = config.require(`notifications_enabled`);+const USE_APOLLO_CRM_ENRICHMENT = config.require(`use_apollo_crm_enrichment`);+const APOLLO_API_KEY_SECRET_NAME = config.require(`apollo_api_key_secret_name`);const SENT_UNDO_DELAY_SECS = config.require(`sent_undo_delay_secs`);const REDIS_RATE_LIMIT_REQS = config.require(`redis_rate_limit_reqs`);const REDIS_RATE_LIMIT_REQS_BACKFILL = config.require(@@ -163,6 +165,10 @@ const macroDbUrlArn: pulumi.Output<string> = aws.secretsmanager.getSecretVersionOutput({ secretId: MACRO_DB_URL_SECRET_NAME }).apply((secret) => secret.arn);+const apolloApiKeySecretArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: APOLLO_API_KEY_SECRET_NAME })+ .apply((secret) => secret.arn);+const inbox_sync_queue = new Queue('email-service-gmail-webhook', {tags,maxReceiveCount: 3,@@ -273,6 +279,7 @@ const secretKeyArns = [macroDbUrlArn,MACRO_API_TOKENS.macroApiTokenPublicKeyArn,cloudfrontSecretKey.arn,+ apolloApiKeySecretArn,];const queueArns = [@@ -475,6 +482,14 @@ const containerEnvVars = [name: 'NOTIFICATIONS_ENABLED',value: pulumi.interpolate`${NOTIFICATIONS_ENABLED}`,},+ {+ name: 'USE_APOLLO_CRM_ENRICHMENT',+ value: pulumi.interpolate`${USE_APOLLO_CRM_ENRICHMENT}`,+ },+ {+ name: 'APOLLO_API_KEY',+ value: pulumi.interpolate`${APOLLO_API_KEY_SECRET_NAME}`,+ },{name: 'SEARCH_EVENT_QUEUE',value: pulumi.interpolate`${searchEventQueueName}`,diff --git a/rust/cloud-storage/.sqlx/query-acb38333fa7958869cc39acafee4f7d08731aa1543d9d2d6f6d105be9e7a0530.json b/rust/cloud-storage/.sqlx/query-acb38333fa7958869cc39acafee4f7d08731aa1543d9d2d6f6d105be9e7a0530.jsonnew file mode 100644index 0000000000..fa3d8b95c4--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-acb38333fa7958869cc39acafee4f7d08731aa1543d9d2d6f6d105be9e7a0530.json@@ -0,0 +1,190 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n name, description, icon_url,\n apollo_organization_id, website_url, linkedin_url, twitter_url,\n facebook_url, industry, keywords, technologies,\n estimated_num_employees, annual_revenue, annual_revenue_printed,\n total_funding, total_funding_printed, latest_funding_stage,\n latest_funding_round_date, founded_year, publicly_traded_symbol,\n publicly_traded_exchange, phone, raw_address, street_address,\n city, state, postal_code, country, raw\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"+ },+ {+ "ordinal": 3,+ "name": "apollo_organization_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "website_url",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "linkedin_url",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "twitter_url",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "facebook_url",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "industry",+ "type_info": "Text"+ },+ {+ "ordinal": 9,+ "name": "keywords",+ "type_info": "TextArray"+ },+ {+ "ordinal": 10,+ "name": "technologies",+ "type_info": "TextArray"+ },+ {+ "ordinal": 11,+ "name": "estimated_num_employees",+ "type_info": "Int4"+ },+ {+ "ordinal": 12,+ "name": "annual_revenue",+ "type_info": "Int8"+ },+ {+ "ordinal": 13,+ "name": "annual_revenue_printed",+ "type_info": "Text"+ },+ {+ "ordinal": 14,+ "name": "total_funding",+ "type_info": "Int8"+ },+ {+ "ordinal": 15,+ "name": "total_funding_printed",+ "type_info": "Text"+ },+ {+ "ordinal": 16,+ "name": "latest_funding_stage",+ "type_info": "Text"+ },+ {+ "ordinal": 17,+ "name": "latest_funding_round_date",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 18,+ "name": "founded_year",+ "type_info": "Int4"+ },+ {+ "ordinal": 19,+ "name": "publicly_traded_symbol",+ "type_info": "Text"+ },+ {+ "ordinal": 20,+ "name": "publicly_traded_exchange",+ "type_info": "Text"+ },+ {+ "ordinal": 21,+ "name": "phone",+ "type_info": "Text"+ },+ {+ "ordinal": 22,+ "name": "raw_address",+ "type_info": "Text"+ },+ {+ "ordinal": 23,+ "name": "street_address",+ "type_info": "Text"+ },+ {+ "ordinal": 24,+ "name": "city",+ "type_info": "Text"+ },+ {+ "ordinal": 25,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 26,+ "name": "postal_code",+ "type_info": "Text"+ },+ {+ "ordinal": 27,+ "name": "country",+ "type_info": "Text"+ },+ {+ "ordinal": 28,+ "name": "raw",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true+ ]+ },+ "hash": "acb38333fa7958869cc39acafee4f7d08731aa1543d9d2d6f6d105be9e7a0530"+}diff --git a/rust/cloud-storage/.sqlx/query-b82668085a22fb075f49e9618cf9ca870181917da54f25119cdd605affa1aa7d.json b/rust/cloud-storage/.sqlx/query-b82668085a22fb075f49e9618cf9ca870181917da54f25119cdd605affa1aa7d.jsondeleted file mode 100644index 7bb8312322..0000000000--- a/rust/cloud-storage/.sqlx/query-b82668085a22fb075f49e9618cf9ca870181917da54f25119cdd605affa1aa7d.json+++ /dev/null@@ -1,17 +0,0 @@-{- "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-dc937df67edeb079120e4c2f457748e9bbaf4f9856a1b4e1e0675e50de4175d3.json b/rust/cloud-storage/.sqlx/query-dc937df67edeb079120e4c2f457748e9bbaf4f9856a1b4e1e0675e50de4175d3.jsondeleted file mode 100644index 9d66c14a44..0000000000--- a/rust/cloud-storage/.sqlx/query-dc937df67edeb079120e4c2f457748e9bbaf4f9856a1b4e1e0675e50de4175d3.json+++ /dev/null@@ -1,34 +0,0 @@-{- "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-fa0410f4a8b799f01b4a582582d0baafac16a1058e7017d63813abf87b340e4a.json b/rust/cloud-storage/.sqlx/query-fa0410f4a8b799f01b4a582582d0baafac16a1058e7017d63813abf87b340e4a.jsonnew file mode 100644index 0000000000..1913a02577--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-fa0410f4a8b799f01b4a582582d0baafac16a1058e7017d63813abf87b340e4a.json@@ -0,0 +1,43 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO crm_domain_directory (\n domain, name, description, icon_url,\n apollo_organization_id, website_url, linkedin_url, twitter_url,\n facebook_url, industry, keywords, technologies,\n estimated_num_employees, annual_revenue, annual_revenue_printed,\n total_funding, total_funding_printed, latest_funding_stage,\n latest_funding_round_date, founded_year, publicly_traded_symbol,\n publicly_traded_exchange, phone, raw_address, street_address,\n city, state, postal_code, country, raw, enriched_at\n )\n VALUES (\n $1, $2, $3, $4,\n $5, $6, $7, $8,\n $9, $10, $11, $12,\n $13, $14, $15,\n $16, $17, $18,\n $19, $20, $21,\n $22, $23, $24, $25,\n $26, $27, $28, $29, $30, now()\n )\n ON CONFLICT (LOWER(domain)) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "TextArray",+ "TextArray",+ "Int4",+ "Int8",+ "Text",+ "Int8",+ "Text",+ "Text",+ "Timestamptz",+ "Int4",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "fa0410f4a8b799f01b4a582582d0baafac16a1058e7017d63813abf87b340e4a"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 75d45e47ba..9f25e7c8d1 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2665,6 +2665,7 @@ dependencies = ["macro_db_migrator","macro_uuid","model-error-response",+ "reqwest 0.13.3","serde","serde_json","sqlx",diff --git a/rust/cloud-storage/crm/Cargo.toml b/rust/cloud-storage/crm/Cargo.tomlindex 0664deeda4..935c0d31fd 100644--- a/rust/cloud-storage/crm/Cargo.toml+++ b/rust/cloud-storage/crm/Cargo.toml@@ -16,7 +16,7 @@ axum = []default = ["inbound", "outbound", "ports"]inbound = ["axum", "ports"]-outbound = ["dep:sqlx", "dep:unfurl", "ports"]+outbound = ["dep:reqwest", "dep:sqlx", "dep:unfurl", "ports"]ports = [][dependencies]@@ -37,6 +37,7 @@ model-error-response = { path = "../model-error-response", optional = true }utoipa = { workspace = true, optional = true }# Outbound dependencies+reqwest = { workspace = true, optional = true }sqlx = { workspace = true, optional = true }unfurl = { path = "../unfurl", features = ["ports"], optional = true }diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rsindex 88bc1fcf56..889c3117c9 100644--- a/rust/cloud-storage/crm/src/domain/model.rs+++ b/rust/cloud-storage/crm/src/domain/model.rs@@ -1,6 +1,7 @@//! Domain models for CRM companies and their related records.use chrono::{DateTime, Utc};+use serde_json::Value;/// A [`CrmCompany`] bundled with display metadata resolved from/// `crm_domain_directory` against the primary (earliest-created) domain.@@ -44,24 +45,76 @@ 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`.+/// Cached metadata about a company keyed on its email domain. Resolved+/// by [`CompanyMetadataResolver`] (the Apollo.io organization-enrichment+/// adapter) 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)]+/// Every scalar is `Option` and every list defaults empty: the resolver+/// may succeed with little data or fail entirely, and both collapse to an+/// all-empty row so the directory doubles as a negative cache.+///+/// [`CompanyMetadataResolver`]: crate::domain::company_metadata_resolver::CompanyMetadataResolver+#[derive(Debug, Clone, Default, PartialEq)]pub struct DomainMetadata {- /// Display name of the company (typically the page `<title>` /- /// `og:title`).+ /// Company display name (Apollo `name`).pub name: Option<String>,- /// Short description of the company (typically `og:description`).+ /// Short company description (Apollo `short_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`).+ /// Logo / icon URL (Apollo `logo_url`).pub icon_url: Option<String>,+ /// Apollo's organization id, for re-enrichment / linking.+ pub apollo_organization_id: Option<String>,+ /// Canonical company website (Apollo `website_url`).+ pub website_url: Option<String>,+ /// LinkedIn company URL.+ pub linkedin_url: Option<String>,+ /// Twitter / X URL.+ pub twitter_url: Option<String>,+ /// Facebook URL.+ pub facebook_url: Option<String>,+ /// Primary industry (Apollo `industry`).+ pub industry: Option<String>,+ /// Free-text keywords / tags (Apollo `keywords`).+ pub keywords: Vec<String>,+ /// Detected technologies (Apollo `technology_names`).+ pub technologies: Vec<String>,+ /// Estimated headcount.+ pub estimated_num_employees: Option<i32>,+ /// Estimated annual revenue, in dollars.+ pub annual_revenue: Option<i64>,+ /// Human-readable annual revenue (e.g. "100M").+ pub annual_revenue_printed: Option<String>,+ /// Total funding raised, in dollars.+ pub total_funding: Option<i64>,+ /// Human-readable total funding (e.g. "251.2M").+ pub total_funding_printed: Option<String>,+ /// Latest funding stage (e.g. "Series D").+ pub latest_funding_stage: Option<String>,+ /// Date of the latest funding round.+ pub latest_funding_round_date: Option<DateTime<Utc>>,+ /// Year the company was founded.+ pub founded_year: Option<i32>,+ /// Ticker symbol if publicly traded.+ pub publicly_traded_symbol: Option<String>,+ /// Exchange if publicly traded.+ pub publicly_traded_exchange: Option<String>,+ /// Company phone number.+ pub phone: Option<String>,+ /// Full formatted HQ address.+ pub raw_address: Option<String>,+ /// HQ street address.+ pub street_address: Option<String>,+ /// HQ city.+ pub city: Option<String>,+ /// HQ state / region.+ pub state: Option<String>,+ /// HQ postal code.+ pub postal_code: Option<String>,+ /// HQ country.+ pub country: Option<String>,+ /// Full Apollo `organization` payload (minus our workspace `account`),+ /// kept so fields we don't model yet aren't lost.+ pub raw: Option<Value>,}/// A domain (e.g. "acme.com") associated with a [`CrmCompany`]. A companydiff --git a/rust/cloud-storage/crm/src/outbound.rs b/rust/cloud-storage/crm/src/outbound.rsindex d0212f34a8..e327feed04 100644--- a/rust/cloud-storage/crm/src/outbound.rs+++ b/rust/cloud-storage/crm/src/outbound.rs@@ -1,3 +1,5 @@+/// Apollo.io-backed implementation of the company metadata resolver+pub mod apollo_resolver;/// Postgres implementation of the companies repositorypub mod companies_repo;/// Resolver stub for binaries that don't populate the CRMdiff --git a/rust/cloud-storage/crm/src/outbound/apollo_resolver.rs b/rust/cloud-storage/crm/src/outbound/apollo_resolver.rsnew file mode 100644index 0000000000..7bf0da6e1f--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/apollo_resolver.rs@@ -0,0 +1,199 @@+//! [`CompanyMetadataResolver`] adapter backed by the Apollo.io+//! organization-enrichment API.+//!+//! Calls `GET https://api.apollo.io/api/v1/organizations/enrich?domain={domain}`+//! with an `x-api-key` header and maps the returned `organization` object+//! onto [`DomainMetadata`]. The full payload — minus our own Apollo+//! workspace `account` record — is preserved in [`DomainMetadata::raw`].+//!+//! Best-effort: any failure (network error, non-2xx status, malformed+//! body, missing `organization`) is logged and surfaced as+//! [`DomainMetadata::default`] so the caller can persist a negative-cache+//! row and avoid re-resolving the domain.++#[cfg(test)]+mod test;++use std::time::Duration;++use chrono::{DateTime, Utc};+use serde_json::Value;++use crate::domain::{company_metadata_resolver::CompanyMetadataResolver, model::DomainMetadata};++/// Default Apollo API base URL.+const DEFAULT_BASE_URL: &str = "https://api.apollo.io";++/// Request timeout for Apollo calls — a stalled connection must not block+/// the populate worker indefinitely.+const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);++/// Build the reqwest client with the request timeout applied.+fn build_client() -> reqwest::Client {+ reqwest::Client::builder()+ .timeout(REQUEST_TIMEOUT)+ .build()+ .expect("apollo reqwest client should build")+}++/// Adapter that resolves [`DomainMetadata`] via Apollo.io organization+/// enrichment. Cheap to [`Clone`] — the inner [`reqwest::Client`] is+/// reference-counted.+#[derive(Clone)]+pub struct ApolloCompanyMetadataResolver {+ client: reqwest::Client,+ api_key: String,+ base_url: String,+}++impl ApolloCompanyMetadataResolver {+ /// Build a resolver with the given Apollo API key and a fresh HTTP client.+ pub fn new(api_key: String) -> Self {+ Self {+ client: build_client(),+ api_key,+ base_url: DEFAULT_BASE_URL.to_string(),+ }+ }++ /// Build a resolver pointed at a custom base URL (used in tests).+ pub fn with_base_url(api_key: String, base_url: String) -> Self {+ Self {+ client: build_client(),+ api_key,+ base_url,+ }+ }+}++impl CompanyMetadataResolver for ApolloCompanyMetadataResolver {+ #[tracing::instrument(skip(self))]+ async fn resolve(&self, domain: &str) -> DomainMetadata {+ // No key configured (e.g. local without APOLLO_API_KEY): skip the+ // call entirely rather than burning a 401 and caching an empty row.+ if self.api_key.is_empty() {+ tracing::debug!(domain, "apollo enrich: no api key configured; skipping");+ return DomainMetadata::default();+ }++ let url = format!("{}/api/v1/organizations/enrich", self.base_url);+ let response = self+ .client+ .get(&url)+ .query(&[("domain", domain)])+ .header("x-api-key", self.api_key.as_str())+ .header(reqwest::header::ACCEPT, "application/json")+ .send()+ .await;++ let body = match response {+ Ok(resp) if resp.status().is_success() => match resp.json::<Value>().await {+ Ok(body) => body,+ Err(e) => {+ tracing::warn!(error=?e, domain, "apollo enrich: failed to parse body");+ return DomainMetadata::default();+ }+ },+ Ok(resp) => {+ tracing::warn!(status = %resp.status(), domain, "apollo enrich: non-success status");+ return DomainMetadata::default();+ }+ Err(e) => {+ tracing::warn!(error=?e, domain, "apollo enrich: request failed");+ return DomainMetadata::default();+ }+ };++ let Some(organization) = body.get("organization") else {+ tracing::warn!(domain, "apollo enrich: response had no organization");+ return DomainMetadata::default();+ };++ map_organization(organization)+ }+}++/// Map an Apollo `organization` JSON object onto [`DomainMetadata`].+/// Tolerant of missing / mistyped fields — anything unreadable stays+/// `None` / empty. The `account` and `account_id` keys (our own Apollo+/// workspace record, not company data) are stripped from `raw`.+fn map_organization(org: &Value) -> DomainMetadata {+ let mut raw = org.clone();+ if let Some(obj) = raw.as_object_mut() {+ obj.remove("account");+ obj.remove("account_id");+ }++ DomainMetadata {+ name: str_field(org, "name"),+ description: str_field(org, "short_description"),+ icon_url: str_field(org, "logo_url"),+ apollo_organization_id: str_field(org, "id"),+ website_url: str_field(org, "website_url"),+ linkedin_url: str_field(org, "linkedin_url"),+ twitter_url: str_field(org, "twitter_url"),+ facebook_url: str_field(org, "facebook_url"),+ industry: str_field(org, "industry"),+ keywords: str_array(org, "keywords"),+ technologies: str_array(org, "technology_names"),+ estimated_num_employees: i32_field(org, "estimated_num_employees"),+ annual_revenue: i64_field(org, "annual_revenue"),+ annual_revenue_printed: str_field(org, "annual_revenue_printed"),+ total_funding: i64_field(org, "total_funding"),+ total_funding_printed: str_field(org, "total_funding_printed"),+ latest_funding_stage: str_field(org, "latest_funding_stage"),+ latest_funding_round_date: date_field(org, "latest_funding_round_date"),+ founded_year: i32_field(org, "founded_year"),+ publicly_traded_symbol: str_field(org, "publicly_traded_symbol"),+ publicly_traded_exchange: str_field(org, "publicly_traded_exchange"),+ phone: str_field(org, "phone"),+ raw_address: str_field(org, "raw_address"),+ street_address: str_field(org, "street_address"),+ city: str_field(org, "city"),+ state: str_field(org, "state"),+ postal_code: str_field(org, "postal_code"),+ country: str_field(org, "country"),+ raw: Some(raw),+ }+}++/// Read a string field; `None` when absent, null, non-string, or+/// blank after trimming.+fn str_field(org: &Value, key: &str) -> Option<String> {+ let s = org.get(key)?.as_str()?.trim();+ (!s.is_empty()).then(|| s.to_string())+}++/// Read an integer field as `i64`. Floats and strings yield `None`.+fn i64_field(org: &Value, key: &str) -> Option<i64> {+ org.get(key)?.as_i64()+}++/// Read an integer field as `i32`, dropping out-of-range values.+fn i32_field(org: &Value, key: &str) -> Option<i32> {+ i32::try_from(org.get(key)?.as_i64()?).ok()+}++/// Read an array-of-strings field, skipping non-string / blank elements.+fn str_array(org: &Value, key: &str) -> Vec<String> {+ org.get(key)+ .and_then(Value::as_array)+ .map(|items| {+ items+ .iter()+ .filter_map(Value::as_str)+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(String::from)+ .collect()+ })+ .unwrap_or_default()+}++/// Read an RFC 3339 timestamp field; `None` when absent or unparseable.+fn date_field(org: &Value, key: &str) -> Option<DateTime<Utc>> {+ let s = org.get(key)?.as_str()?;+ DateTime::parse_from_rfc3339(s)+ .ok()+ .map(|dt| dt.with_timezone(&Utc))+}diff --git a/rust/cloud-storage/crm/src/outbound/apollo_resolver/test.rs b/rust/cloud-storage/crm/src/outbound/apollo_resolver/test.rsnew file mode 100644index 0000000000..03eb0fefa2--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/apollo_resolver/test.rs@@ -0,0 +1,136 @@+use super::*;+use crate::domain::company_metadata_resolver::CompanyMetadataResolver;+use serde_json::json;++/// The documented Apollo sample payload maps onto every field, and the+/// `account` / `account_id` keys are stripped from `raw`.+#[test]+fn maps_full_apollo_organization() {+ let org = json!({+ "id": "5e66b6381e05b4008c8331b8",+ "name": "Apollo.io",+ "website_url": "http://www.apollo.io",+ "linkedin_url": "http://www.linkedin.com/company/apolloio",+ "twitter_url": "https://twitter.com/meetapollo/",+ "facebook_url": "https://www.facebook.com/MeetApollo",+ "logo_url": "https://example.com/logo.png",+ "founded_year": 2015,+ "industry": "information technology & services",+ "keywords": ["sales engagement", "lead generation"],+ "technology_names": ["AI", "Android"],+ "estimated_num_employees": 1600,+ "annual_revenue": 100000000_i64,+ "annual_revenue_printed": "100M",+ "total_funding": 251200000_i64,+ "total_funding_printed": "251.2M",+ "latest_funding_stage": "Series D",+ "latest_funding_round_date": "2023-08-01T00:00:00.000+00:00",+ "short_description": "Apollo.io combines a buyer database.",+ "raw_address": "415 Mission St, Floor 37, San Francisco, California 94105, US",+ "street_address": "415 Mission St",+ "city": "San Francisco",+ "state": "California",+ "postal_code": "94105-2301",+ "country": "United States",+ "account_id": "63f53afe4ceeca00016bdd37",+ "account": { "id": "63f53afe4ceeca00016bdd37", "team_id": "ours" }+ });++ let md = map_organization(&org);++ assert_eq!(md.name.as_deref(), Some("Apollo.io"));+ assert_eq!(+ md.description.as_deref(),+ Some("Apollo.io combines a buyer database.")+ );+ assert_eq!(md.icon_url.as_deref(), Some("https://example.com/logo.png"));+ assert_eq!(+ md.apollo_organization_id.as_deref(),+ Some("5e66b6381e05b4008c8331b8")+ );+ assert_eq!(md.website_url.as_deref(), Some("http://www.apollo.io"));+ assert_eq!(+ md.linkedin_url.as_deref(),+ Some("http://www.linkedin.com/company/apolloio")+ );+ assert_eq!(+ md.industry.as_deref(),+ Some("information technology & services")+ );+ assert_eq!(md.keywords, vec!["sales engagement", "lead generation"]);+ assert_eq!(md.technologies, vec!["AI", "Android"]);+ assert_eq!(md.estimated_num_employees, Some(1600));+ assert_eq!(md.annual_revenue, Some(100_000_000));+ assert_eq!(md.annual_revenue_printed.as_deref(), Some("100M"));+ assert_eq!(md.total_funding, Some(251_200_000));+ assert_eq!(md.latest_funding_stage.as_deref(), Some("Series D"));+ assert_eq!(md.founded_year, Some(2015));+ assert_eq!(md.city.as_deref(), Some("San Francisco"));+ assert_eq!(md.country.as_deref(), Some("United States"));+ assert!(md.latest_funding_round_date.is_some());++ let raw = md.raw.expect("raw present");+ assert!(raw.get("account").is_none(), "account stripped from raw");+ assert!(+ raw.get("account_id").is_none(),+ "account_id stripped from raw"+ );+ assert_eq!(raw.get("name").and_then(Value::as_str), Some("Apollo.io"));+}++/// A sparse / empty organization collapses to an all-empty metadata+/// (negative-cache row), with `raw` still present.+#[test]+fn missing_fields_collapse_to_empty() {+ let md = map_organization(&json!({}));++ assert_eq!(md.name, None);+ assert_eq!(md.annual_revenue, None);+ assert_eq!(md.latest_funding_round_date, None);+ assert!(md.keywords.is_empty());+ assert!(md.technologies.is_empty());+ assert!(md.raw.is_some());+}++/// Mistyped fields are tolerated: a string revenue / blank name don't+/// blow up the whole mapping.+#[test]+fn tolerates_mistyped_and_blank_fields() {+ let org = json!({+ "name": " ",+ "annual_revenue": "not a number",+ "estimated_num_employees": 42,+ "keywords": ["ok", "", 123, " spaced "],+ });++ let md = map_organization(&org);++ assert_eq!(md.name, None, "blank name -> None");+ assert_eq!(md.annual_revenue, None, "string revenue -> None");+ assert_eq!(md.estimated_num_employees, Some(42));+ assert_eq!(+ md.keywords,+ vec!["ok", "spaced"],+ "blank / non-string elements dropped"+ );+}++/// Live smoke test against the real Apollo API. Ignored by default — it+/// makes a network call and consumes an Apollo credit. Run with:+/// APOLLO_API_KEY=<key> cargo test -p crm apollo_live -- --ignored --nocapture+/// Optionally set APOLLO_TEST_DOMAIN (defaults to "macro.com").+#[tokio::test]+#[ignore = "hits the live Apollo API; requires APOLLO_API_KEY"]+async fn apollo_live_enrich() {+ let api_key = std::env::var("APOLLO_API_KEY").expect("set APOLLO_API_KEY to run this test");+ let domain = std::env::var("APOLLO_TEST_DOMAIN").unwrap_or_else(|_| "macro.com".to_string());++ let resolver = ApolloCompanyMetadataResolver::new(api_key);+ let md = resolver.resolve(&domain).await;++ println!("DomainMetadata for {domain}:\n{md:#?}");+ assert!(+ md.name.is_some() || md.raw.is_some(),+ "expected Apollo data for {domain}; got empty — check API key, credits, or domain",+ );+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rsindex 4e572cbc75..31cc67d6a2 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs@@ -619,7 +619,15 @@ impl CompaniesRepository for CompaniesRepositoryImpl {let normalized_domain = domain.to_ascii_lowercase();let row = sqlx::query!(r#"- SELECT name, description, icon_url+ SELECT+ name, description, icon_url,+ apollo_organization_id, website_url, linkedin_url, twitter_url,+ facebook_url, industry, keywords, technologies,+ estimated_num_employees, annual_revenue, annual_revenue_printed,+ total_funding, total_funding_printed, latest_funding_stage,+ latest_funding_round_date, founded_year, publicly_traded_symbol,+ publicly_traded_exchange, phone, raw_address, street_address,+ city, state, postal_code, country, rawFROM crm_domain_directoryWHERE LOWER(domain) = $1LIMIT 1@@ -634,6 +642,32 @@ impl CompaniesRepository for CompaniesRepositoryImpl {name: r.name,description: r.description,icon_url: r.icon_url,+ apollo_organization_id: r.apollo_organization_id,+ website_url: r.website_url,+ linkedin_url: r.linkedin_url,+ twitter_url: r.twitter_url,+ facebook_url: r.facebook_url,+ industry: r.industry,+ keywords: r.keywords.unwrap_or_default(),+ technologies: r.technologies.unwrap_or_default(),+ estimated_num_employees: r.estimated_num_employees,+ annual_revenue: r.annual_revenue,+ annual_revenue_printed: r.annual_revenue_printed,+ total_funding: r.total_funding,+ total_funding_printed: r.total_funding_printed,+ latest_funding_stage: r.latest_funding_stage,+ latest_funding_round_date: r.latest_funding_round_date,+ founded_year: r.founded_year,+ publicly_traded_symbol: r.publicly_traded_symbol,+ publicly_traded_exchange: r.publicly_traded_exchange,+ phone: r.phone,+ raw_address: r.raw_address,+ street_address: r.street_address,+ city: r.city,+ state: r.state,+ postal_code: r.postal_code,+ country: r.country,+ raw: r.raw,}))}@@ -644,18 +678,62 @@ impl CompaniesRepository for CompaniesRepositoryImpl {metadata: &DomainMetadata,) -> Result<(), CrmError> {let normalized_domain = domain.to_ascii_lowercase();- // First-write-wins. Negative cache entries (all-NULL) are- // preserved to suppress future resolver calls.+ // First-write-wins. All-empty rows are negative-cache entries that+ // suppress future resolver calls; `enriched_at` stamps resolve time.sqlx::query!(r#"- INSERT INTO crm_domain_directory (domain, name, description, icon_url)- VALUES ($1, $2, $3, $4)+ INSERT INTO crm_domain_directory (+ domain, name, description, icon_url,+ apollo_organization_id, website_url, linkedin_url, twitter_url,+ facebook_url, industry, keywords, technologies,+ estimated_num_employees, annual_revenue, annual_revenue_printed,+ total_funding, total_funding_printed, latest_funding_stage,+ latest_funding_round_date, founded_year, publicly_traded_symbol,+ publicly_traded_exchange, phone, raw_address, street_address,+ city, state, postal_code, country, raw, enriched_at+ )+ VALUES (+ $1, $2, $3, $4,+ $5, $6, $7, $8,+ $9, $10, $11, $12,+ $13, $14, $15,+ $16, $17, $18,+ $19, $20, $21,+ $22, $23, $24, $25,+ $26, $27, $28, $29, $30, now()+ )ON CONFLICT (LOWER(domain)) DO NOTHING"#,normalized_domain,metadata.name,metadata.description,metadata.icon_url,+ metadata.apollo_organization_id,+ metadata.website_url,+ metadata.linkedin_url,+ metadata.twitter_url,+ metadata.facebook_url,+ metadata.industry,+ &metadata.keywords,+ &metadata.technologies,+ metadata.estimated_num_employees,+ metadata.annual_revenue,+ metadata.annual_revenue_printed,+ metadata.total_funding,+ metadata.total_funding_printed,+ metadata.latest_funding_stage,+ metadata.latest_funding_round_date,+ metadata.founded_year,+ metadata.publicly_traded_symbol,+ metadata.publicly_traded_exchange,+ metadata.phone,+ metadata.raw_address,+ metadata.street_address,+ metadata.city,+ metadata.state,+ metadata.postal_code,+ metadata.country,+ metadata.raw,).execute(&self.pool).awaitdiff --git a/rust/cloud-storage/crm/src/outbound/unfurl_resolver.rs b/rust/cloud-storage/crm/src/outbound/unfurl_resolver.rsindex 8b8b624f5b..937dbaa6c4 100644--- a/rust/cloud-storage/crm/src/outbound/unfurl_resolver.rs+++ b/rust/cloud-storage/crm/src/outbound/unfurl_resolver.rs@@ -77,6 +77,7 @@ wherename,description: response.description,icon_url: response.favicon_url,+ ..Default::default()}}Err(e) => {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 7b8423698f..3dc73ebe11 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@@ -2,6 +2,7 @@use anyhow::Context;use document_storage_service_client::DocumentStorageServiceClient;use email_service::config::{Config, EmailServiceCloudfrontSignerPrivateKey};+use email_service::pubsub::CrmMetadataResolver;use macro_entrypoint::MacroEntrypoint;use macro_env::Environment;use macro_middleware::auth::internal_access::InternalApiSecretKey;@@ -235,18 +236,50 @@ 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);+ // The CRM crate's company-metadata resolver is consulted by+ // `crm_service.populate_contact` only on `crm_domain_directory` misses.+ // `USE_APOLLO_CRM_ENRICHMENT` selects Apollo.io vs. the unfurl-backed+ // resolver; we also fall back to unfurl when the Apollo key can't be+ // loaded. The resolver is cheap to clone.+ let build_unfurl = || -> anyhow::Result<CrmMetadataResolver> {+ // Wrap the SSRF-safe reqwest fetcher in an `UnfurlServiceImpl`,+ // then the `UnfurlCompanyMetadataResolver`.+ let unfurl_service = Arc::new(unfurl::domain::service::UnfurlServiceImpl::new(+ unfurl::outbound::ReqwestUnfurlFetcher::new()+ .context("failed to build ReqwestUnfurlFetcher")?,+ ));+ Ok(CrmMetadataResolver::Unfurl(+ crm::outbound::unfurl_resolver::UnfurlCompanyMetadataResolver::new(unfurl_service),+ ))+ };++ let metadata_resolver = if config.use_apollo_crm_enrichment {+ // Apollo key: `config.apollo_api_key` is the key itself locally, or+ // the name of the Secrets Manager secret holding it in deployed envs+ // (resolved here).+ let apollo_api_key = match config.environment {+ Environment::Local => config.apollo_api_key.clone(),+ _ => secretsmanager_client+ .get_secret_value(config.apollo_api_key.clone())+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to load apollo api key secret"))+ .map(|k| k.to_string())+ .unwrap_or_default(),+ };+ // No usable key (missing/unreadable secret, or unset locally): fall+ // back to unfurl rather than running Apollo with an empty key, which+ // would no-op and pollute the directory with negative-cache rows.+ if apollo_api_key.is_empty() {+ tracing::warn!("apollo api key unavailable; falling back to unfurl CRM enrichment");+ build_unfurl()?+ } else {+ CrmMetadataResolver::Apollo(+ crm::outbound::apollo_resolver::ApolloCompanyMetadataResolver::new(apollo_api_key),+ )+ }+ } else {+ build_unfurl()?+ };let crm_service = crm::domain::service::CrmServiceImpl::new(crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),diff --git a/rust/cloud-storage/email_service/src/config.rs b/rust/cloud-storage/email_service/src/config.rsindex 3f34d1bfbe..8b9e95e776 100644--- a/rust/cloud-storage/email_service/src/config.rs+++ b/rust/cloud-storage/email_service/src/config.rs@@ -65,6 +65,15 @@ pub struct Config {/// Notification-service functionalitypub notifications_enabled: bool,+ /// Use Apollo.io for CRM company enrichment. When `false`, fall back+ /// to the unfurl-based resolver.+ pub use_apollo_crm_enrichment: bool,++ /// Apollo.io API key for CRM enrichment. Locally this is the key+ /// itself; in deployed envs it's the name of the Secrets Manager+ /// secret holding it (resolved at startup). Empty disables enrichment.+ pub apollo_api_key: String,+/// The queue max messages per pollpub queue_max_messages: i32,@@ -216,6 +225,13 @@ impl Config {.parse::<bool>().context("NOTIFICATIONS_ENABLED must be a boolean value")?;+ let use_apollo_crm_enrichment: bool = std::env::var("USE_APOLLO_CRM_ENRICHMENT")+ .unwrap_or("false".to_string())+ .parse::<bool>()+ .context("USE_APOLLO_CRM_ENRICHMENT must be a boolean value")?;++ let apollo_api_key = std::env::var("APOLLO_API_KEY").unwrap_or_default();+let queue_max_messages: i32 = std::env::var("QUEUE_MAX_MESSAGES").unwrap_or("10".to_string()).parse::<i32>()@@ -349,6 +365,8 @@ impl Config {attachment_bucket,sent_undo_delay_secs,notifications_enabled,+ use_apollo_crm_enrichment,+ apollo_api_key,queue_max_messages,queue_wait_time_seconds,backfill_queue_workers,diff --git a/rust/cloud-storage/email_service/src/pubsub/context.rs b/rust/cloud-storage/email_service/src/pubsub/context.rsindex b4f6a7fb0d..9562b5605c 100644--- a/rust/cloud-storage/email_service/src/pubsub/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/context.rs@@ -3,7 +3,10 @@ use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;use contacts::domain::service::SqsContactsIngress;use contacts::outbound::ingress::SqsContactsQueue;+use crm::domain::company_metadata_resolver::CompanyMetadataResolver;+use crm::domain::model::DomainMetadata;use crm::domain::service::CrmServiceImpl;+use crm::outbound::apollo_resolver::ApolloCompanyMetadataResolver;use crm::outbound::companies_repo::CompaniesRepositoryImpl;use crm::outbound::unfurl_resolver::UnfurlCompanyMetadataResolver;use document_storage_service_client::DocumentStorageServiceClient;@@ -18,16 +21,38 @@ use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImp/// The concrete notification ingress service type.pub type NotificationIngressType = SqsNotificationIngress<SqsQueue>;+/// The unfurl-backed resolver used when Apollo enrichment is disabled.+type UnfurlResolver = UnfurlCompanyMetadataResolver<+ unfurl::domain::service::UnfurlServiceImpl<unfurl::outbound::ReqwestUnfurlFetcher>,+>;++/// CRM company-metadata resolver, chosen at startup from the+/// `USE_APOLLO_CRM_ENRICHMENT` flag: Apollo.io when enabled, the+/// unfurl-backed resolver otherwise. A single concrete type so it slots+/// into [`CrmServiceType`] — `CompanyMetadataResolver` is RPITIT and thus+/// not dyn-compatible, so we dispatch via an enum rather than `dyn`.+#[derive(Clone)]+pub enum CrmMetadataResolver {+ /// Apollo.io organization enrichment.+ Apollo(ApolloCompanyMetadataResolver),+ /// Unfurl-backed homepage metadata.+ Unfurl(UnfurlResolver),+}++impl CompanyMetadataResolver for CrmMetadataResolver {+ async fn resolve(&self, domain: &str) -> DomainMetadata {+ match self {+ CrmMetadataResolver::Apollo(r) => r.resolve(domain).await,+ CrmMetadataResolver::Unfurl(r) => r.resolve(domain).await,+ }+ }+}+/// 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+/// flag-selected [`CrmMetadataResolver`]. 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>,- >,->;+pub type CrmServiceType = CrmServiceImpl<CompaniesRepositoryImpl, CrmMetadataResolver>;#[derive(Clone)]pub struct PubSubContext {diff --git a/rust/cloud-storage/email_service/src/pubsub/mod.rs b/rust/cloud-storage/email_service/src/pubsub/mod.rsindex 7bb16e02f4..0d1fb58e16 100644--- a/rust/cloud-storage/email_service/src/pubsub/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/mod.rs@@ -1,5 +1,8 @@pub mod backfill;pub(crate) mod context;+/// The flag-selected CRM metadata resolver, re-exported for the+/// pubsub_workers binary to construct.+pub use context::CrmMetadataResolver;pub mod gmail_ops;pub mod inbox_sync;pub mod link_manager;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260529164720_crm_domain_directory_apollo_fields.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260529164720_crm_domain_directory_apollo_fields.down.sqlnew file mode 100644index 0000000000..b3b9717926--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260529164720_crm_domain_directory_apollo_fields.down.sql@@ -0,0 +1,28 @@+ALTER TABLE crm_domain_directory+ DROP COLUMN IF EXISTS apollo_organization_id,+ DROP COLUMN IF EXISTS website_url,+ DROP COLUMN IF EXISTS linkedin_url,+ DROP COLUMN IF EXISTS twitter_url,+ DROP COLUMN IF EXISTS facebook_url,+ DROP COLUMN IF EXISTS industry,+ DROP COLUMN IF EXISTS keywords,+ DROP COLUMN IF EXISTS technologies,+ DROP COLUMN IF EXISTS estimated_num_employees,+ DROP COLUMN IF EXISTS annual_revenue,+ DROP COLUMN IF EXISTS annual_revenue_printed,+ DROP COLUMN IF EXISTS total_funding,+ DROP COLUMN IF EXISTS total_funding_printed,+ DROP COLUMN IF EXISTS latest_funding_stage,+ DROP COLUMN IF EXISTS latest_funding_round_date,+ DROP COLUMN IF EXISTS founded_year,+ DROP COLUMN IF EXISTS publicly_traded_symbol,+ DROP COLUMN IF EXISTS publicly_traded_exchange,+ DROP COLUMN IF EXISTS phone,+ DROP COLUMN IF EXISTS raw_address,+ DROP COLUMN IF EXISTS street_address,+ DROP COLUMN IF EXISTS city,+ DROP COLUMN IF EXISTS state,+ DROP COLUMN IF EXISTS postal_code,+ DROP COLUMN IF EXISTS country,+ DROP COLUMN IF EXISTS raw,+ DROP COLUMN IF EXISTS enriched_at;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260529164720_crm_domain_directory_apollo_fields.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260529164720_crm_domain_directory_apollo_fields.up.sqlnew file mode 100644index 0000000000..d0a4fe1553--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260529164720_crm_domain_directory_apollo_fields.up.sql@@ -0,0 +1,31 @@+-- Expand crm_domain_directory with Apollo.io organization-enrichment data.+-- High-signal fields are promoted to typed columns; the full Apollo+-- `organization` payload (minus our own workspace `account`) is kept in `raw`.+ALTER TABLE crm_domain_directory+ ADD COLUMN IF NOT EXISTS apollo_organization_id TEXT,+ ADD COLUMN IF NOT EXISTS website_url TEXT,+ ADD COLUMN IF NOT EXISTS linkedin_url TEXT,+ ADD COLUMN IF NOT EXISTS twitter_url TEXT,+ ADD COLUMN IF NOT EXISTS facebook_url TEXT,+ ADD COLUMN IF NOT EXISTS industry TEXT,+ ADD COLUMN IF NOT EXISTS keywords TEXT[],+ ADD COLUMN IF NOT EXISTS technologies TEXT[],+ ADD COLUMN IF NOT EXISTS estimated_num_employees INTEGER,+ ADD COLUMN IF NOT EXISTS annual_revenue BIGINT,+ ADD COLUMN IF NOT EXISTS annual_revenue_printed TEXT,+ ADD COLUMN IF NOT EXISTS total_funding BIGINT,+ ADD COLUMN IF NOT EXISTS total_funding_printed TEXT,+ ADD COLUMN IF NOT EXISTS latest_funding_stage TEXT,+ ADD COLUMN IF NOT EXISTS latest_funding_round_date TIMESTAMPTZ,+ ADD COLUMN IF NOT EXISTS founded_year INTEGER,+ ADD COLUMN IF NOT EXISTS publicly_traded_symbol TEXT,+ ADD COLUMN IF NOT EXISTS publicly_traded_exchange TEXT,+ ADD COLUMN IF NOT EXISTS phone TEXT,+ ADD COLUMN IF NOT EXISTS raw_address TEXT,+ ADD COLUMN IF NOT EXISTS street_address TEXT,+ ADD COLUMN IF NOT EXISTS city TEXT,+ ADD COLUMN IF NOT EXISTS state TEXT,+ ADD COLUMN IF NOT EXISTS postal_code TEXT,+ ADD COLUMN IF NOT EXISTS country TEXT,+ ADD COLUMN IF NOT EXISTS raw JSONB,+ ADD COLUMN IF NOT EXISTS enriched_at TIMESTAMPTZ;