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): populate CRM tables from sent-mail history (#3377)
Evan Hutnikdfc51cfa268f
diff --git a/infra/packages/shared/src/backfill_queue.ts b/infra/packages/shared/src/backfill_queue.tsnew file mode 100644index 0000000000..cd2e9e22a4--- /dev/null+++ b/infra/packages/shared/src/backfill_queue.ts@@ -0,0 +1,30 @@+import * as pulumi from '@pulumi/pulumi';+import { stack } from '../../shared';++/**+ * Returns the SQS queue the email service's backfill worker consumes from.+ * Used by other services (e.g. authentication-service) that need to enqueue+ * backfill operations — currently the `PopulateCrmForUser` job that the+ * teams hex crate publishes after a successful `join_team`.+ */+export function getBackfillQueue(): {+ backfillQueueName: pulumi.Output<string>;+ backfillQueueArn: pulumi.Output<string>;+} {+ const emailServiceStack = new pulumi.StackReference('backfill-queue-stack', {+ name: `macro-inc/email-service/${stack}`,+ });++ const backfillQueueArn: pulumi.Output<string> = emailServiceStack+ .getOutput('backfillQueueArn')+ .apply((arn) => arn as string);++ const backfillQueueName: pulumi.Output<string> = emailServiceStack+ .getOutput('backfillQueueName')+ .apply((name) => name as string);++ return {+ backfillQueueName,+ backfillQueueArn,+ };+}diff --git a/infra/packages/shared/src/index.ts b/infra/packages/shared/src/index.tsindex 2364a1bc05..47cf7dd88a 100644--- a/infra/packages/shared/src/index.ts+++ b/infra/packages/shared/src/index.ts@@ -43,6 +43,7 @@ export { getMacroApiToken } from './macro_api_token';export { getMacroNotify } from './macro_notify';export { getSearchEventQueue } from './search_event_queue';export { getLinkManagerQueue } from './link_manager_queue';+export { getBackfillQueue } from './backfill_queue';export {getAiToolsInfra,getAiToolsServiceRoleArns,diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.tsindex 27526445ed..30d673bd13 100644--- a/infra/stacks/authentication-service/index.ts+++ b/infra/stacks/authentication-service/index.ts@@ -2,6 +2,7 @@ import * as aws from '@pulumi/aws';import * as pulumi from '@pulumi/pulumi';import {config,+ getBackfillQueue,getLinkManagerQueue,getMacroApiToken,getMacroNotify,@@ -202,6 +203,8 @@ const { searchEventQueueName, searchEventQueueArn } = getSearchEventQueue();const { linkManagerQueueName, linkManagerQueueArn } = getLinkManagerQueue();+const { backfillQueueName, backfillQueueArn } = getBackfillQueue();+const service = new AuthenticationService('authentication-service', {secretKeyArns,clusterName: fusionAuthClusterName,@@ -219,6 +222,7 @@ const service = new AuthenticationService('authentication-service', {notificationIngressQueueArn,searchEventQueueArn,linkManagerQueueArn,+ backfillQueueArn,],containerEnvVars: [{ name: 'ENVIRONMENT', value: stack },@@ -303,6 +307,10 @@ const service = new AuthenticationService('authentication-service', {name: 'LINK_MANAGER_QUEUE',value: pulumi.interpolate`${linkManagerQueueName}`,},+ {+ name: 'EMAIL_BACKFILL_QUEUE',+ value: pulumi.interpolate`${backfillQueueName}`,+ },{name: 'MACRO_API_TOKEN_ISSUER',value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,diff --git a/rust/cloud-storage/.sqlx/query-1250ece710fe7b331de87620f60fde712254a69e033e4135dc64d2a14acd8071.json b/rust/cloud-storage/.sqlx/query-1250ece710fe7b331de87620f60fde712254a69e033e4135dc64d2a14acd8071.jsonnew file mode 100644index 0000000000..71e31cfdb5--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-1250ece710fe7b331de87620f60fde712254a69e033e4135dc64d2a14acd8071.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO crm_companies (team_id, name)\n VALUES ($1, 'TODO')\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "1250ece710fe7b331de87620f60fde712254a69e033e4135dc64d2a14acd8071"+}diff --git a/rust/cloud-storage/.sqlx/query-361c3d6e5a9549af7dd9042a088005f8da9e6128de27e65a9bb69e780615bf4c.json b/rust/cloud-storage/.sqlx/query-361c3d6e5a9549af7dd9042a088005f8da9e6128de27e65a9bb69e780615bf4c.jsonnew file mode 100644index 0000000000..48c07f8426--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-361c3d6e5a9549af7dd9042a088005f8da9e6128de27e65a9bb69e780615bf4c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO crm_domains (company_id, team_id, domain)\n VALUES ($1, $2, $3)\n ON CONFLICT (team_id, LOWER(domain)) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "361c3d6e5a9549af7dd9042a088005f8da9e6128de27e65a9bb69e780615bf4c"+}diff --git a/rust/cloud-storage/.sqlx/query-4948508d8a7862e5986502d9373c0b1a97e277c5c50d9f14dd86c121164b486b.json b/rust/cloud-storage/.sqlx/query-4948508d8a7862e5986502d9373c0b1a97e277c5c50d9f14dd86c121164b486b.jsonnew file mode 100644index 0000000000..afedbb4e78--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-4948508d8a7862e5986502d9373c0b1a97e277c5c50d9f14dd86c121164b486b.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO crm_contact_sources (contact_id, link_id)\n VALUES ($1, $2)\n ON CONFLICT (contact_id, link_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "4948508d8a7862e5986502d9373c0b1a97e277c5c50d9f14dd86c121164b486b"+}diff --git a/rust/cloud-storage/.sqlx/query-745780ca3e0e26284050ac92cd3c90f9a796ec770c53cbee32660ed867c138a4.json b/rust/cloud-storage/.sqlx/query-745780ca3e0e26284050ac92cd3c90f9a796ec770c53cbee32660ed867c138a4.jsonnew file mode 100644index 0000000000..12c74e21a2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-745780ca3e0e26284050ac92cd3c90f9a796ec770c53cbee32660ed867c138a4.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.id\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"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "745780ca3e0e26284050ac92cd3c90f9a796ec770c53cbee32660ed867c138a4"+}diff --git a/rust/cloud-storage/.sqlx/query-751f836dc8f78c330387456dd68a8803972c7b3e2b6a2b95c27f15068bed2ca5.json b/rust/cloud-storage/.sqlx/query-751f836dc8f78c330387456dd68a8803972c7b3e2b6a2b95c27f15068bed2ca5.jsonnew file mode 100644index 0000000000..a784094d72--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-751f836dc8f78c330387456dd68a8803972c7b3e2b6a2b95c27f15068bed2ca5.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "pg_advisory_xact_lock",+ "type_info": "Void"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "751f836dc8f78c330387456dd68a8803972c7b3e2b6a2b95c27f15068bed2ca5"+}diff --git a/rust/cloud-storage/.sqlx/query-c4896935fe37524d12c5745fdbf087d0d6bd11642a303dfc2213eaf8d6eb8e4e.json b/rust/cloud-storage/.sqlx/query-c4896935fe37524d12c5745fdbf087d0d6bd11642a303dfc2213eaf8d6eb8e4e.jsonnew file mode 100644index 0000000000..adcd04d499--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c4896935fe37524d12c5745fdbf087d0d6bd11642a303dfc2213eaf8d6eb8e4e.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.id, c.email_sync\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": "email_sync",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "c4896935fe37524d12c5745fdbf087d0d6bd11642a303dfc2213eaf8d6eb8e4e"+}diff --git a/rust/cloud-storage/.sqlx/query-c55a8270d85d85cd73e1468cfed63223fe781efb943d080e79998dff5500cfbb.json b/rust/cloud-storage/.sqlx/query-c55a8270d85d85cd73e1468cfed63223fe781efb943d080e79998dff5500cfbb.jsonnew file mode 100644index 0000000000..17d7e7e14f--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c55a8270d85d85cd73e1468cfed63223fe781efb943d080e79998dff5500cfbb.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT DISTINCT LOWER(c.email_address) AS \"email!\"\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"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "c55a8270d85d85cd73e1468cfed63223fe781efb943d080e79998dff5500cfbb"+}diff --git a/rust/cloud-storage/.sqlx/query-e28bfb9ffa642d99401e17cbbe174df5312e5fae38f374945f807ce68d0314a8.json b/rust/cloud-storage/.sqlx/query-e28bfb9ffa642d99401e17cbbe174df5312e5fae38f374945f807ce68d0314a8.jsonnew file mode 100644index 0000000000..20764699a6--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-e28bfb9ffa642d99401e17cbbe174df5312e5fae38f374945f807ce68d0314a8.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT team_id\n FROM team_user\n WHERE user_id = $1\n ORDER BY team_role DESC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e28bfb9ffa642d99401e17cbbe174df5312e5fae38f374945f807ce68d0314a8"+}diff --git a/rust/cloud-storage/.sqlx/query-e617879c8a87f29fd7aefc87549f8e2867a9c395519fa6ecda6232daa31069bf.json b/rust/cloud-storage/.sqlx/query-e617879c8a87f29fd7aefc87549f8e2867a9c395519fa6ecda6232daa31069bf.jsonnew file mode 100644index 0000000000..4401ca872c--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-e617879c8a87f29fd7aefc87549f8e2867a9c395519fa6ecda6232daa31069bf.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO crm_contacts (company_id, email)\n VALUES ($1, $2)\n ON CONFLICT (company_id, email) DO UPDATE SET email = EXCLUDED.email\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e617879c8a87f29fd7aefc87549f8e2867a9c395519fa6ecda6232daa31069bf"+}diff --git a/rust/cloud-storage/.sqlx/query-ff54b7462bad2c7811807786e3b57f3b77a2108138b267fd97144edad023be1c.json b/rust/cloud-storage/.sqlx/query-ff54b7462bad2c7811807786e3b57f3b77a2108138b267fd97144edad023be1c.jsonnew file mode 100644index 0000000000..688074a36f--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-ff54b7462bad2c7811807786e3b57f3b77a2108138b267fd97144edad023be1c.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM crm_companies WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "ff54b7462bad2c7811807786e3b57f3b77a2108138b267fd97144edad023be1c"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex badd1adb46..3576f9ae9d 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -11228,6 +11228,7 @@ dependencies = ["model-error-response","model_notifications","model_user",+ "models_email","non_empty","notification","roles_and_permissions",@@ -11236,6 +11237,7 @@ dependencies = ["serde","serde_json","sqlx",+ "sqs_client","thiserror 2.0.17","tokio","tracing",diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex 9b8578aded..752561a393 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -39,6 +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,>;type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rsindex a617e90692..eb8b579258 100644--- a/rust/cloud-storage/authentication_service/src/config.rs+++ b/rust/cloud-storage/authentication_service/src/config.rs@@ -63,6 +63,11 @@ pub struct Config {/// The email link manager queuepub link_manager_queue: String,+ /// The email backfill queue. Used by `join_team` to enqueue a+ /// `PopulateCrmForUser` message that seeds CRM tables with the new+ /// member's historical sent-mail contacts.+ pub email_backfill_queue: String,+/// The github client idpub github_client_id: String,/// The github client secret@@ -188,6 +193,9 @@ impl Config {let link_manager_queue =std::env::var("LINK_MANAGER_QUEUE").context("LINK_MANAGER_QUEUE must be provided")?;+ let email_backfill_queue = std::env::var("EMAIL_BACKFILL_QUEUE")+ .context("EMAIL_BACKFILL_QUEUE must be provided")?;+let github_client_id =std::env::var("GITHUB_CLIENT_ID").context("GITHUB_CLIENT_ID must be provided")?;let github_client_secret = std::env::var("GITHUB_CLIENT_SECRET")@@ -231,6 +239,7 @@ impl Config {notification_queue,search_event_queue,link_manager_queue,+ email_backfill_queue,environment,github_client_id,github_client_secret,diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex 2119d51d2d..5b3416a36a 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -191,7 +191,8 @@ async fn main() -> anyhow::Result<()> {¯o_aws_config::get_macro_aws_config().await,)).search_event_queue(&config.search_event_queue)- .email_link_manager_queue(&config.link_manager_queue);+ .email_link_manager_queue(&config.link_manager_queue)+ .email_backfill_queue(&config.email_backfill_queue);tracing::trace!("initialized sqs client");// Initialize analytics client with configured providers@@ -267,12 +268,16 @@ 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 teams_service_impl = TeamServiceImpl::new(teams_repo_impl,customer_repo_impl,team_channels_repo_impl,user_roles_and_permissions_service.clone(),notification_ingress_service.clone(),+ populate_crm_enqueuer,);let github_link_service_impl = GithubLinkServiceImpl::new(diff --git a/rust/cloud-storage/crm/justfile b/rust/cloud-storage/crm/justfilenew file mode 100644index 0000000000..fad4a0c048--- /dev/null+++ b/rust/cloud-storage/crm/justfile@@ -0,0 +1,6 @@+import '../database.just'++mod sqlx '../sqlx.just'++prepare_db:+ just sqlx::prepare_db {{ DATABASE_URL }}diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rsindex b751f50351..14677a58fd 100644--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs@@ -14,4 +14,41 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {team_id: &uuid::Uuid,domain: &str,) -> impl Future<Output = Result<Option<CrmCompany>, CrmError>> + Send;++ /// Idempotently records that `email` (which lives on `domain`) was seen+ /// from the mailbox identified by `link_id`, for the team `team_id`.+ /// Performs the company/domain/contact/contact_source upserts in a single+ /// transaction:+ ///+ /// 1. Look up the company for `(team_id, domain)`.+ /// - If a row exists with `email_sync = false` the team has opted+ /// 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`.+ /// 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.+ fn populate_contact(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,+ domain: &str,+ email: &str,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Returns the team id that `macro_id` belongs to. When the user is on+ /// multiple teams the highest-privileged role wins (Postgres orders the+ /// `team_role` enum as `member < admin < owner`), matching the+ /// behavior of `entity_access::ports::get_user_team`. Returns+ /// `Ok(None)` when the user has no team membership.+ fn get_team_id_for_user(+ &self,+ macro_id: &str,+ ) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;}diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rsindex 6682c27bec..18df3c72fc 100644--- a/rust/cloud-storage/crm/src/domain/service.rs+++ b/rust/cloud-storage/crm/src/domain/service.rs@@ -16,6 +16,28 @@ pub trait CrmService: Clone + Send + Sync + 'static {team_id: &uuid::Uuid,domain: &str,) -> impl Future<Output = Result<Option<CrmCompany>, CrmError>> + Send;++ /// Idempotently records that `email` was seen from the mailbox+ /// identified by `link_id`, for the team `team_id`. Upserts+ /// `crm_companies` (+ `crm_domains`), `crm_contacts`, and+ /// `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.+ fn populate_contact(+ &self,+ team_id: &uuid::Uuid,+ link_id: &uuid::Uuid,+ email: &str,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Returns the team id `macro_id` belongs to, or `None` when the user+ /// has no team membership. See+ /// [`crate::domain::companies_repo::CompaniesRepository::get_team_id_for_user`]+ /// for tie-breaking when the user is on multiple teams.+ fn get_team_id_for_user(+ &self,+ macro_id: &str,+ ) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;}/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`].@@ -65,4 +87,39 @@ where.get_company_by_domain(team_id, domain).await}++ #[tracing::instrument(skip(self), err)]+ async fn populate_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 {+ return Err(CrmError::StorageLayerError(anyhow::anyhow!(+ "email {email} has no '@' separator"+ )));+ };+ if local_part.is_empty() {+ return Err(CrmError::StorageLayerError(anyhow::anyhow!(+ "email {email} has an empty local part"+ )));+ }+ if domain.is_empty() {+ return Err(CrmError::StorageLayerError(anyhow::anyhow!(+ "email {email} has an empty domain"+ )));+ }+ self.companies_repository+ .populate_contact(team_id, link_id, domain, email)+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_team_id_for_user(&self, macro_id: &str) -> Result<Option<uuid::Uuid>, CrmError> {+ self.companies_repository+ .get_team_id_for_user(macro_id)+ .await+ }}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rsindex 51cfa60704..b371136817 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs@@ -82,4 +82,186 @@ impl CompaniesRepository for CompaniesRepositoryImpl {domains,}))}++ #[tracing::instrument(skip(self), err)]+ async fn populate_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()))?;++ // Serialize on (team_id, lower(domain)) for the duration of this+ // transaction. Without this lock two concurrent populate_contact+ // calls can both observe "no existing company" and both insert one,+ // leaving the team with duplicate crm_companies rows. The+ // UNIQUE(team_id, LOWER(domain)) on crm_domains catches the race at+ // the second insert, but only after the first transaction has+ // already created an orphan company. The advisory lock prevents+ // that orphan from ever existing. Lock scope is the (team, domain)+ // key only — different teams/different domains run in parallel.+ 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()))?;++ // Look up the company for this (team, domain). The killswitch lives+ // here: a pre-existing row with email_sync=false means the team has+ // opted this domain out and we must not write anything.+ let existing = sqlx::query!(+ r#"+ SELECT c.id, c.email_sync+ FROM crm_companies c+ JOIN crm_domains d ON d.company_id = c.id+ WHERE c.team_id = $1+ AND LOWER(d.domain) = $2+ LIMIT 1+ "#,+ team_id,+ normalized_domain,+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ let company_id = match existing {+ Some(row) if !row.email_sync => {+ // Killswitch: team has opted this domain out. Commit the+ // (empty) transaction and return so the caller acks.+ tx.commit()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ return Ok(());+ }+ Some(row) => row.id,+ None => {+ let new_company = sqlx::query!(+ r#"+ INSERT INTO crm_companies (team_id, name)+ VALUES ($1, 'TODO')+ RETURNING id+ "#,+ team_id,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ // The advisory lock guarantees no concurrent insert for the+ // same (team_id, lower(domain)). The UNIQUE index on+ // crm_domains backs that promise up — `ON CONFLICT DO+ // NOTHING` is defensive. If it does fire (e.g. an old row+ // predating the advisory lock somehow exists), the+ // crm_companies row we just inserted would be orphaned with+ // no domain pointing at it. Detect via rows_affected, look+ // up the real company id, and delete the orphan.+ let domain_insert = sqlx::query!(+ r#"+ INSERT INTO crm_domains (company_id, team_id, domain)+ VALUES ($1, $2, $3)+ ON CONFLICT (team_id, LOWER(domain)) DO NOTHING+ "#,+ new_company.id,+ team_id,+ normalized_domain,+ )+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ if domain_insert.rows_affected() == 0 {+ let existing_company_id = sqlx::query_scalar!(+ r#"+ SELECT c.id+ FROM crm_companies c+ JOIN crm_domains d ON d.company_id = c.id+ WHERE c.team_id = $1+ AND LOWER(d.domain) = $2+ LIMIT 1+ "#,+ team_id,+ normalized_domain,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ sqlx::query!(r#"DELETE FROM crm_companies WHERE id = $1"#, new_company.id,)+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ existing_company_id+ } else {+ new_company.id+ }+ }+ };++ // 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.+ 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+ RETURNING id+ "#,+ company_id,+ normalized_email,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ sqlx::query!(+ r#"+ INSERT INTO crm_contact_sources (contact_id, link_id)+ VALUES ($1, $2)+ ON CONFLICT (contact_id, link_id) DO NOTHING+ "#,+ contact_id,+ link_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 get_team_id_for_user(&self, macro_id: &str) -> Result<Option<uuid::Uuid>, CrmError> {+ sqlx::query_scalar!(+ r#"+ SELECT team_id+ FROM team_user+ WHERE user_id = $1+ ORDER BY team_role DESC+ LIMIT 1+ "#,+ macro_id,+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))+ }}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rsindex cd1045f94f..0628c3a53e 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs@@ -53,8 +53,9 @@ async fn insert_company(.await?;for domain in domains {- sqlx::query(r#"INSERT INTO crm_domains (company_id, domain) VALUES ($1, $2)"#)+ 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?;diff --git a/rust/cloud-storage/email_db_client/src/contacts/get.rs b/rust/cloud-storage/email_db_client/src/contacts/get.rsindex 423f7b45c9..817a5e0620 100644--- a/rust/cloud-storage/email_db_client/src/contacts/get.rs+++ b/rust/cloud-storage/email_db_client/src/contacts/get.rs@@ -74,6 +74,35 @@ struct RecipientQueryResult {recipient_type: db::address::EmailRecipientType,}+/// Returns the deduped, lowercased set of recipient email addresses that+/// appear on any sent message (`email_messages.is_sent = true`) on the+/// given `link_id`. Walks To/Cc/Bcc indiscriminately — the caller is+/// responsible for any filtering (e.g. dropping the user's own address).+///+/// 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(+ pool: &PgPool,+ link_id: Uuid,+) -> anyhow::Result<Vec<String>> {+ sqlx::query_scalar!(+ r#"+ SELECT DISTINCT LOWER(c.email_address) AS "email!"+ 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+ "#,+ link_id,+ )+ .fetch_all(pool)+ .await+ .map_err(Into::into)+}+/// fetch recipients (to, cc, bcc) from db#[tracing::instrument(skip(pool), err)]pub async fn fetch_db_recipients(diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rsindex 676a89df1c..077e244d9a 100644--- a/rust/cloud-storage/email_service/src/api/email/init.rs+++ b/rust/cloud-storage/email_service/src/api/email/init.rs@@ -15,7 +15,7 @@ use model::response::ErrorResponse;use model::user::UserContext;use model::user::axum_extractor::MacroUserExtractor;use models_email::email::service::backfill::{- BackfillJobStatus, BackfillOperation, BackfillPubsubMessage,+ BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, InitPayload, JobScopedPayload,};use models_email::service::link;use models_email::service::link::Link;@@ -157,9 +157,11 @@ pub async fn handler(.context("Failed to create backfill job")?;let ps_message = BackfillPubsubMessage {- link_id: link.id,- job_id: backfill_job.id,- backfill_operation: BackfillOperation::Init,+ backfill_operation: BackfillOperation::Init(JobScopedPayload {+ link_id: link.id,+ job_id: backfill_job.id,+ payload: InitPayload {},+ }),};if let Err(e) = ctxdiff --git a/rust/cloud-storage/email_service/src/api/internal/gmail/create.rs b/rust/cloud-storage/email_service/src/api/internal/gmail/create.rsindex 1ad5992f98..895ef63207 100644--- a/rust/cloud-storage/email_service/src/api/internal/gmail/create.rs+++ b/rust/cloud-storage/email_service/src/api/internal/gmail/create.rs@@ -6,7 +6,7 @@ use axum::{};use model::response::ErrorResponse;use models_email::email::service::backfill::{- BackfillJobStatus, BackfillOperation, BackfillPubsubMessage,+ BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, InitPayload, JobScopedPayload,};use sqlx::types::Uuid;use utoipa::ToSchema;@@ -94,9 +94,11 @@ pub async fn handler(});let ps_message = BackfillPubsubMessage {- link_id: link.id,- job_id: backfill_job.id,- backfill_operation: BackfillOperation::Init,+ backfill_operation: BackfillOperation::Init(JobScopedPayload {+ link_id: link.id,+ job_id: backfill_job.id,+ payload: InitPayload {},+ }),};ctx.sqs_client.enqueue_email_backfill_message(ps_message)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 0e07adeb93..151b61e6ec 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,6 +235,17 @@ async fn main() -> anyhow::Result<()> {PgSystemPropertiesRepository::new(db.clone()),));+ let crm_service = crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),+ );++ // Backfill workers run against a dedicated pool to keep their writes+ // off the primary worker pool. CRM writes are part of the backfill+ // 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()),+ );+// process user inbox updates from gmail inbox_sync queue, triggered by update pubsub messages from Googlefor worker in inbox_sync_workers {let db_inbox_sync = db.clone();@@ -248,6 +259,7 @@ async fn main() -> anyhow::Result<()> {let connection_gateway_client_inbox_sync = connection_gateway_client.clone();let dss_client_inbox_sync = dss_client.clone();let system_properties_service_inbox_sync = system_properties_service.clone();+ let crm_service_inbox_sync = crm_service.clone();tokio::spawn(async move {email_service::pubsub::inbox_sync::worker::run_worker(db_inbox_sync,@@ -262,6 +274,7 @@ async fn main() -> anyhow::Result<()> {connection_gateway_client_inbox_sync,dss_client_inbox_sync,system_properties_service_inbox_sync,+ crm_service_inbox_sync,config.notifications_enabled,false,)@@ -286,6 +299,7 @@ async fn main() -> anyhow::Result<()> {let connection_gateway_client_inbox_sync = connection_gateway_client.clone();let dss_client_inbox_sync = dss_client.clone();let system_properties_service_inbox_sync = system_properties_service.clone();+ let crm_service_inbox_sync = crm_service.clone();tokio::spawn(async move {email_service::pubsub::inbox_sync::worker::run_worker(db_inbox_sync,@@ -300,6 +314,7 @@ async fn main() -> anyhow::Result<()> {connection_gateway_client_inbox_sync,dss_client_inbox_sync,system_properties_service_inbox_sync,+ crm_service_inbox_sync,config.notifications_enabled,true,)@@ -374,6 +389,7 @@ async fn main() -> anyhow::Result<()> {let connection_gateway_client_backfill = connection_gateway_client.clone();let dss_client_backfill = dss_client.clone();let system_properties_service_backfill = system_properties_service.clone();+ let crm_service_backfill = crm_service_backfill.clone();tokio::spawn(async move {email_service::pubsub::backfill::worker::run_worker(db_backfill,@@ -388,6 +404,7 @@ async fn main() -> anyhow::Result<()> {connection_gateway_client_backfill,dss_client_backfill,system_properties_service_backfill,+ crm_service_backfill,config.notifications_enabled,).await;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 1a5d386761..a8103b543a 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,13 +1,15 @@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::util::process_pre_insert::process_message_pre_insert;use anyhow::Context;-use models_email::email::service::backfill::{BackfillMessagePayload, BackfillPubsubMessage};+use models_email::email::service::backfill::{BackfillMessagePayload, JobScopedPayload};use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use models_email::gmail::operations::GmailApiOperation;+/// This step is invoked by BackfillThread once for each message in the thread./// Creates a message object in the database. If the message is the last message in/// the thread to be processed, it sends an UpdateThreadMetadata message for the thread.@@ -15,10 +17,10 @@ use models_email::gmail::operations::GmailApiOperation;pub async fn backfill_message(ctx: &PubSubContext,access_token: &str,- data: &BackfillPubsubMessage,+ scope: &JobScopedPayload<BackfillMessagePayload>,link: &link::Link,- p: &BackfillMessagePayload,) -> Result<(), ProcessingError> {+ let p = &scope.payload;check_gmail_rate_limit(CheckGmailRateLimitArgs {redis_client: &ctx.redis_client,link_id: link.id,@@ -78,6 +80,22 @@ 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.+ if message.is_sent {+ let self_email = link.email_address.0.as_ref().to_ascii_lowercase();+ let recipient_emails: Vec<String> = message+ .to+ .iter()+ .chain(&message.cc)+ .chain(&message.bcc)+ .map(|c| c.email.clone())+ .collect();+ enqueue_populate_crm_contacts(ctx, link.id, &self_email, recipient_emails).await?;+ }+// Handle all success-related operations- increment_counters::incr_completed_messages(ctx, link, data.job_id, p).await+ increment_counters::incr_completed_messages(ctx, link, scope.job_id, p).await}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rsindex 6dcba137cd..19a4c060e3 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs@@ -3,6 +3,7 @@ use crate::pubsub::context::PubSubContext;use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};use models_email::email::service::backfill::{BackfillMessagePayload, BackfillOperation, BackfillPubsubMessage, BackfillThreadPayload,+ JobScopedPayload,};use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};@@ -16,10 +17,10 @@ use std::collections::HashSet;pub async fn backfill_thread(ctx: &PubSubContext,access_token: &str,- data: &BackfillPubsubMessage,+ scope: &JobScopedPayload<BackfillThreadPayload>,link: &link::Link,- p: &BackfillThreadPayload,) -> Result<(), ProcessingError> {+ let p = &scope.payload;let thread_provider_id = p.thread_provider_id.clone();let existing_threads = email_db_client::threads::get::get_threads_by_link_id_and_provider_ids(@@ -40,7 +41,7 @@ pub async fn backfill_thread(// if the thread already exists, skip backfilling and update redis countersif !existing_threads.is_empty() {- incr_completed_threads(ctx, link, data.job_id).await?;+ incr_completed_threads(ctx, link, scope.job_id).await?;return Ok(());}@@ -71,7 +72,7 @@ pub async fn backfill_thread(};ctx.redis_client- .init_backfill_thread_progress(data.job_id, &thread_provider_id, message_ids.len() as i32)+ .init_backfill_thread_progress(scope.job_id, &thread_provider_id, message_ids.len() as i32).await.map_err(|e| {ProcessingError::Retryable(DetailedError {@@ -109,9 +110,11 @@ pub async fn backfill_thread(};let ps_message = BackfillPubsubMessage {- link_id: link.id,- job_id: data.job_id,- backfill_operation: BackfillOperation::BackfillMessage(new_payload),+ backfill_operation: BackfillOperation::BackfillMessage(JobScopedPayload {+ link_id: link.id,+ job_id: scope.job_id,+ payload: new_payload,+ }),};ctx.sqs_clientdiff --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 6ae1d86b8c..ebea97a2f5 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@@ -4,6 +4,7 @@ use crate::pubsub::backfill::increment_counters::{use crate::pubsub::context::PubSubContext;use models_email::email::service::backfill::{BackfillJobStatus, BackfillMessagePayload, BackfillOperation, BackfillPubsubMessage,+ JobScopedPayload,};use models_email::email::service::pubsub::DetailedError;use sqs_worker::cleanup_message;@@ -24,38 +25,46 @@ pub async fn handle_non_retryable_error();match &data.backfill_operation {- BackfillOperation::Init | BackfillOperation::ListThreads(_) => {- // update backfill job status to failed- if let Err(db_err) = email_db_client::backfill::job::update::update_backfill_job_status(- &ctx.db,- data.job_id,- BackfillJobStatus::Failed,- )- .await- {- tracing::error!(- error = %db_err,- "Failed to update backfill job status to Failed"- );- }+ BackfillOperation::Init(scope) => mark_job_failed(ctx, scope.job_id).await,+ BackfillOperation::ListThreads(scope) => mark_job_failed(ctx, scope.job_id).await,+ BackfillOperation::BackfillThread(scope) => {+ handle_thread_failure(ctx, scope.link_id, scope.job_id).await;}- BackfillOperation::BackfillThread(_) | BackfillOperation::UpdateThreadMetadata(_) => {- handle_thread_failure(ctx, data.link_id, data.job_id).await;+ BackfillOperation::UpdateThreadMetadata(scope) => {+ handle_thread_failure(ctx, scope.link_id, scope.job_id).await;}- BackfillOperation::BackfillMessage(p) => {- handle_message_failure(ctx, data, p).await;+ BackfillOperation::BackfillMessage(scope) => {+ handle_message_failure(ctx, scope).await;}BackfillOperation::BackfillAttachment(_) => {}+ BackfillOperation::PopulateCrmContact(_) => {}+ BackfillOperation::PopulateCrmForUser(_) => {}}cleanup_message(&ctx.sqs_worker, message).await?;Ok(())}+async fn mark_job_failed(ctx: &PubSubContext, job_id: Uuid) {+ if let Err(db_err) = email_db_client::backfill::job::update::update_backfill_job_status(+ &ctx.db,+ job_id,+ BackfillJobStatus::Failed,+ )+ .await+ {+ tracing::error!(+ error = %db_err,+ job_id = %job_id,+ "Failed to update backfill job status to Failed"+ );+ }+}+/// Handles retryable errors by updating status to InProgress and adding the error message#[tracing::instrument(skip(data, _e),- fields(link_id = %data.link_id, error = tracing::field::Empty)+ fields(link_id = ?data.backfill_operation.link_id(), error = tracing::field::Empty))]pub async fn handle_retryable_error(data: &BackfillPubsubMessage,@@ -65,37 +74,49 @@ pub async fn handle_retryable_error(tracing::Span::current().record("error", &error_chain);match &data.backfill_operation {- BackfillOperation::Init => {+ BackfillOperation::Init(_) => {tracing::debug!("Retryable error in Init")}BackfillOperation::ListThreads(_) => {tracing::debug!("Retryable error listing threads")}- BackfillOperation::BackfillThread(p) => {+ BackfillOperation::BackfillThread(scope) => {tracing::debug!(- thread_id = %p.thread_provider_id,+ thread_id = %scope.payload.thread_provider_id,"Retryable error backfilling thread");}- BackfillOperation::BackfillMessage(p) => {+ BackfillOperation::BackfillMessage(scope) => {tracing::debug!(- thread_id = %p.thread_provider_id,- message_id = %p.message_provider_id,+ thread_id = %scope.payload.thread_provider_id,+ message_id = %scope.payload.message_provider_id,"Retryable error backfilling message");}- BackfillOperation::UpdateThreadMetadata(p) => {+ BackfillOperation::UpdateThreadMetadata(scope) => {tracing::debug!(- thread_id = %p.thread_provider_id,+ thread_id = %scope.payload.thread_provider_id,"Retryable error updating thread metadata");}- BackfillOperation::BackfillAttachment(p) => {+ BackfillOperation::BackfillAttachment(scope) => {tracing::debug!(- attachment_db_id = %p.metadata.attachment_metadata.attachment_db_id,+ attachment_db_id = %scope.payload.metadata.attachment_metadata.attachment_db_id,"Retryable error backfilling attachment")}+ BackfillOperation::PopulateCrmContact(scope) => {+ tracing::debug!(+ contact_email = %scope.payload.contact_email,+ "Retryable error populating CRM contact"+ )+ }+ BackfillOperation::PopulateCrmForUser(payload) => {+ tracing::debug!(+ macro_id = %payload.macro_id,+ "Retryable error populating CRM for user"+ )+ }}Ok(())}@@ -105,18 +126,26 @@ async fn handle_thread_failure(ctx: &PubSubContext, link_id: Uuid, job_id: Uuid)let link = match email_db_client::links::get::fetch_link_by_id(&ctx.db, link_id).await {Ok(Some(link)) => link,Ok(None) => {+ // Link is gone — `incr_completed_threads` can't run without+ // it, so this thread will never complete on its own. Mark the+ // parent job failed instead of silently dropping the message+ // (the SQS message gets cleaned up after this returns, so a+ // silent return strands the job in InProgress forever).tracing::error!(link_id = link_id.to_string(),job_id = job_id.to_string(),- "Link not found"+ "Link not found in handle_thread_failure; marking backfill job failed");+ mark_job_failed(ctx, job_id).await;return;}Err(db_err) => {tracing::error!(error = %db_err,- "Failed to fetch link"+ job_id = job_id.to_string(),+ "Failed to fetch link in handle_thread_failure; marking backfill job failed");+ mark_job_failed(ctx, job_id).await;return;}};@@ -133,32 +162,38 @@ async fn handle_thread_failure(ctx: &PubSubContext, link_id: Uuid, job_id: Uuid)#[tracing::instrument(skip(ctx))]pub async fn handle_message_failure(ctx: &PubSubContext,- data: &BackfillPubsubMessage,- p: &BackfillMessagePayload,+ scope: &JobScopedPayload<BackfillMessagePayload>,) {- let link = match email_db_client::links::get::fetch_link_by_id(&ctx.db, data.link_id).await {+ let link = match email_db_client::links::get::fetch_link_by_id(&ctx.db, scope.link_id).await {Ok(Some(link)) => link,Ok(None) => {+ // Same defense as handle_thread_failure — without a link we+ // can't increment counters, and a silent return leaves the+ // parent job in InProgress forever after the SQS message is+ // cleaned up.tracing::error!(- link_id = data.link_id.to_string(),- job_id = data.job_id.to_string(),- "Link not found"+ link_id = scope.link_id.to_string(),+ job_id = scope.job_id.to_string(),+ "Link not found in handle_message_failure; marking backfill job failed");+ mark_job_failed(ctx, scope.job_id).await;return;}Err(db_err) => {tracing::error!(error = %db_err,- "Failed to fetch link"+ job_id = scope.job_id.to_string(),+ "Failed to fetch link in handle_message_failure; marking backfill job failed");+ mark_job_failed(ctx, scope.job_id).await;return;}};- if let Err(err) = incr_completed_messages(ctx, &link, data.job_id, p).await {+ if let Err(err) = incr_completed_messages(ctx, &link, scope.job_id, &scope.payload).await {tracing::error!(error = %err,- job_id = data.job_id.to_string(),+ job_id = scope.job_id.to_string(),"Failed to check if thread is completed in handle message failure");}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rsindex de764d0739..6d7d18987d 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs@@ -9,7 +9,7 @@ use models_email::service::attachment::{};use models_email::service::backfill::{BackfillAttachmentPayload, BackfillJobStatus, BackfillMessagePayload, BackfillOperation,- BackfillPubsubMessage, UpdateMetadataPayload,+ BackfillPubsubMessage, JobScopedPayload, UpdateMetadataPayload,};use models_email::service::link::Link;use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};@@ -210,9 +210,11 @@ async fn handle_thread_completed(};let ps_message = BackfillPubsubMessage {- link_id: link.id,- job_id,- backfill_operation: BackfillOperation::UpdateThreadMetadata(new_payload),+ backfill_operation: BackfillOperation::UpdateThreadMetadata(JobScopedPayload {+ link_id: link.id,+ job_id,+ payload: new_payload,+ }),};ctx.sqs_client@@ -291,9 +293,11 @@ async fn send_attachment_backfill_messages(};let ps_message = BackfillPubsubMessage {- link_id,- job_id,- backfill_operation: BackfillOperation::BackfillAttachment(new_payload),+ backfill_operation: BackfillOperation::BackfillAttachment(JobScopedPayload {+ link_id,+ job_id,+ payload: new_payload,+ }),};ctx.sqs_clientdiff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/init.rsindex 69e268e260..d1756e35d1 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs@@ -3,7 +3,7 @@ use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};use crate::util::process_pre_insert::sync_labels::sync_labels;use crate::util::sync_contacts::sync_contacts;use models_email::email::service::backfill::{- BackfillJobStatus, BackfillOperation, BackfillPubsubMessage,+ BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, InitPayload, JobScopedPayload,};use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use models_email::email::service::thread::ListThreadsPayload;@@ -17,7 +17,7 @@ use std::cmp::min;pub async fn init_backfill(ctx: &PubSubContext,access_token: &str,- data: &BackfillPubsubMessage,+ scope: &JobScopedPayload<InitPayload>,link: &link::Link,backfill_job: &backfill::BackfillJob,) -> Result<(), ProcessingError> {@@ -80,7 +80,7 @@ pub async fn init_backfill(email_db_client::backfill::job::update::update_job_total_threads(&ctx.db,- data.job_id,+ scope.job_id,total_threads,).await@@ -92,7 +92,7 @@ pub async fn init_backfill(})?;ctx.redis_client- .init_backfill_job_progress(data.job_id, total_threads)+ .init_backfill_job_progress(scope.job_id, total_threads).await.map_err(|e| {ProcessingError::Retryable(DetailedError {@@ -102,10 +102,12 @@ pub async fn init_backfill(})?;let thread_sqs_msg = BackfillPubsubMessage {- link_id: data.link_id,- job_id: data.job_id,- backfill_operation: BackfillOperation::ListThreads(ListThreadsPayload {- next_page_token: None, // a value of None tells the process to start from the beginning+ backfill_operation: BackfillOperation::ListThreads(JobScopedPayload {+ link_id: scope.link_id,+ job_id: scope.job_id,+ payload: ListThreadsPayload {+ next_page_token: None, // a value of None tells the process to start from the beginning+ },}),};@@ -121,7 +123,7 @@ pub async fn init_backfill(email_db_client::backfill::job::update::update_backfill_job_status(&ctx.db,- data.job_id,+ scope.job_id,BackfillJobStatus::InProgress,).awaitdiff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rsindex d84a0eb47d..db9aa4671d 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rs@@ -1,7 +1,7 @@use crate::pubsub::context::PubSubContext;use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};use models_email::email::service::backfill::{- BackfillJob, BackfillOperation, BackfillPubsubMessage, BackfillThreadPayload,+ BackfillJob, BackfillOperation, BackfillPubsubMessage, BackfillThreadPayload, JobScopedPayload,};use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};@@ -20,11 +20,11 @@ const BACKFILL_THREAD_BATCH_SIZE: u32 = 500;pub async fn list_threads(ctx: &PubSubContext,access_token: &str,- data: &BackfillPubsubMessage,+ scope: &JobScopedPayload<ListThreadsPayload>,link: &link::Link,- p: &ListThreadsPayload,job: &BackfillJob,) -> Result<(), ProcessingError> {+ let p = &scope.payload;let total_threads = job.total_threads;let threads_retrieved_count = job.threads_retrieved_count;@@ -67,7 +67,7 @@ pub async fn list_threads(// add the threads we just discovered to the job counteremail_db_client::backfill::job::update::update_job_threads_retrieved_count(&ctx.db,- data.job_id,+ scope.job_id,thread_list.threads.len() as i32,).await@@ -81,10 +81,12 @@ pub async fn list_threads(// send a pubsub message for each discovered threadfor thread in thread_list.threads {let thread_sqs_msg = BackfillPubsubMessage {- link_id: data.link_id,- job_id: data.job_id,- backfill_operation: BackfillOperation::BackfillThread(BackfillThreadPayload {- thread_provider_id: thread.provider_id.clone(),+ backfill_operation: BackfillOperation::BackfillThread(JobScopedPayload {+ link_id: scope.link_id,+ job_id: scope.job_id,+ payload: BackfillThreadPayload {+ thread_provider_id: thread.provider_id.clone(),+ },}),};@@ -102,10 +104,10 @@ pub async fn list_threads(// if we have more threads to fetch, send another pubsub messageif next_page_token.is_some() {let list_thread_msg = BackfillPubsubMessage {- link_id: data.link_id,- job_id: data.job_id,- backfill_operation: BackfillOperation::ListThreads(ListThreadsPayload {- next_page_token,+ backfill_operation: BackfillOperation::ListThreads(JobScopedPayload {+ link_id: scope.link_id,+ job_id: scope.job_id,+ payload: ListThreadsPayload { next_page_token },}),};diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rsindex 4762bcc49b..547419aa08 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs@@ -5,6 +5,8 @@ mod error_handlers;mod increment_counters;mod init;mod list_threads;+mod populate_crm_contact;+mod populate_crm_for_user;mod process;mod update_metadata;pub mod worker;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.rsnew file mode 100644index 0000000000..ff69267bfa--- /dev/null+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_contact.rs@@ -0,0 +1,107 @@+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::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.+///+/// Fanned out one-per-recipient from `backfill_message` when the message was+/// sent by the user. Resolves the user's team (no-op if the user has no+/// team), then upserts `crm_companies`/`crm_domains`/`crm_contacts`/+/// `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`].+#[tracing::instrument(skip(ctx), err, fields(contact_email = %p.contact_email, link_id = %link.id))]+pub async fn populate_crm_contact(+ ctx: &PubSubContext,+ link: &link::Link,+ p: &PopulateCrmContactPayload,+) -> 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 population");+ return Ok(());+ };++ ctx.crm_service+ .populate_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 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.rsnew file mode 100644index 0000000000..0ffb455ebe--- /dev/null+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_for_user.rs@@ -0,0 +1,72 @@+use crate::pubsub::backfill::populate_crm_contact::enqueue_populate_crm_contacts;+use crate::pubsub::context::PubSubContext;+use crm::domain::service::CrmService;+use models_email::email::service::backfill::PopulateCrmForUserPayload;+use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};++/// Seeds the team's CRM tables with every contact the user has sent email+/// to in the past. Triggered when a user is added to a team — the user only+/// has their macro_id at this point, so this handler resolves the link and+/// team itself, then fans out one `PopulateCrmContact` job per distinct+/// recipient of a sent message on that link.+///+/// No-ops (acks the message) when the user has no email link or no team+/// membership. The downstream `PopulateCrmContact` consumer is idempotent+/// and re-checks the team membership + per-domain killswitch, so racing+/// removals between fan-out and consumption are safe.+#[tracing::instrument(skip(ctx), err, fields(macro_id = %payload.macro_id))]+pub async fn populate_crm_for_user(+ ctx: &PubSubContext,+ payload: &PopulateCrmForUserPayload,+) -> 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 fan-out");+ return Ok(());+ };++ let team_id = ctx+ .crm_service+ .get_team_id_for_user(macro_id_str)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: anyhow::Error::from(e).context("Failed to look up team for macro_id"),+ })+ })?;++ if team_id.is_none() {+ tracing::debug!("User has no team; skipping CRM fan-out");+ return Ok(());+ }++ 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"),+ })+ })?;++ enqueue_populate_crm_contacts(ctx, link.id, &self_email, recipient_emails).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 a1cd729d61..13c48fd098 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs@@ -1,15 +1,17 @@use crate::pubsub::backfill::{backfill_attachment, backfill_message, backfill_thread, error_handlers, init, list_threads,- update_metadata,+ 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;use anyhow::Context;use models_email::email::service::backfill::{- BackfillJobStatus, BackfillOperation, BackfillPubsubMessage,+ BackfillJob, BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, JobScopedPayload,};+use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use sqs_worker::cleanup_message;+use uuid::Uuid;// Process a single message from the backfill queuepub async fn process_message(@@ -54,7 +56,120 @@ async fn inner_process_message(ctx: &PubSubContext,data: &BackfillPubsubMessage,) -> Result<(), ProcessingError> {- let backfill_job = email_db_client::backfill::job::get::get_backfill_job(&ctx.db, data.job_id)+ match &data.backfill_operation {+ BackfillOperation::Init(scope) => {+ let Some(JobContext {+ link,+ backfill_job,+ access_token,+ }) = fetch_job_context(ctx, scope).await?+ else {+ return Ok(());+ };+ init::init_backfill(ctx, &access_token, scope, &link, &backfill_job).await+ }+ BackfillOperation::ListThreads(scope) => {+ let Some(JobContext {+ link,+ backfill_job,+ access_token,+ }) = fetch_job_context(ctx, scope).await?+ else {+ return Ok(());+ };+ list_threads::list_threads(ctx, &access_token, scope, &link, &backfill_job).await+ }+ BackfillOperation::BackfillThread(scope) => {+ let Some(JobContext {+ link, access_token, ..+ }) = fetch_job_context(ctx, scope).await?+ else {+ return Ok(());+ };+ backfill_thread::backfill_thread(ctx, &access_token, scope, &link).await+ }+ BackfillOperation::BackfillMessage(scope) => {+ let Some(JobContext {+ link, access_token, ..+ }) = fetch_job_context(ctx, scope).await?+ else {+ // BackfillMessage owns per-thread progress in addition to+ // the job-level progress that fetch_job_context already+ // cleared on cancellation. Drop it so a re-run of the+ // cancelled job doesn't see stale thread counters.+ let _ = ctx+ .redis_client+ .delete_backfill_thread_progress(+ scope.job_id,+ &scope.payload.thread_provider_id,+ )+ .await;+ return Ok(());+ };+ backfill_message::backfill_message(ctx, &access_token, scope, &link).await+ }+ BackfillOperation::UpdateThreadMetadata(scope) => {+ // UpdateThreadMetadata is a DB-only step; skip the Gmail token+ // fetch so a revoked token can't fail this handler with+ // AccessTokenFetchFailed.+ let Some(JobContextNoToken { link, .. }) =+ fetch_job_context_no_token(ctx, scope).await?+ else {+ return Ok(());+ };+ update_metadata::update_thread_metadata(ctx, scope, &link).await+ }+ BackfillOperation::BackfillAttachment(scope) => {+ let Some(JobContext {+ link, access_token, ..+ }) = fetch_job_context(ctx, scope).await?+ else {+ return Ok(());+ };+ backfill_attachment::backfill_attachment(ctx, &access_token, &link, &scope.payload)+ .await+ }+ BackfillOperation::PopulateCrmContact(scope) => {+ let link = fetch_link(ctx, scope.link_id).await?;+ populate_crm_contact::populate_crm_contact(ctx, &link, &scope.payload).await+ }+ BackfillOperation::PopulateCrmForUser(payload) => {+ populate_crm_for_user::populate_crm_for_user(ctx, payload).await+ }+ }+}++/// The pre-fetched context every job-scoped handler used to receive from+/// the top-level dispatcher: the link the operation targets, the backfill+/// job it belongs to, and a fresh Gmail access token for the link. Used by+/// handlers that talk to Gmail.+struct JobContext {+ link: link::Link,+ backfill_job: BackfillJob,+ access_token: String,+}++/// Same as [`JobContext`] but without a Gmail access token. Used by+/// handlers that only talk to the database (e.g. UpdateThreadMetadata) so+/// they don't fail with `AccessTokenFetchFailed` when a user's token is+/// revoked or temporarily unavailable.+struct JobContextNoToken {+ link: link::Link,+ backfill_job: BackfillJob,+}++/// Shared prefetch for DB-only job-scoped handlers: loads the backfill+/// job, short-circuits on cancellation (also cleaning up the job-level+/// redis progress key), and loads the link. Returns `Ok(None)` when the+/// parent backfill job has been cancelled — the caller should ack the+/// message without running the handler. Variant-specific cancellation+/// cleanup (e.g. per-thread progress keys) belongs at the call site, not+/// here.+async fn fetch_job_context_no_token<P>(+ ctx: &PubSubContext,+ scope: &JobScopedPayload<P>,+) -> Result<Option<JobContextNoToken>, ProcessingError> {+ let backfill_job = email_db_client::backfill::job::get::get_backfill_job(&ctx.db, scope.job_id).await.map_err(|e| {ProcessingError::Retryable(DetailedError {@@ -70,26 +185,29 @@ async fn inner_process_message(})?;if backfill_job.status == BackfillJobStatus::Cancelled {- let _ = handle_cancel_backfill_job(ctx, data).await;- return Ok(());+ let _ = ctx+ .redis_client+ .delete_backfill_job_progress(scope.job_id)+ .await;+ return Ok(None);}- let link = match email_db_client::links::get::fetch_link_by_id(&ctx.db, data.link_id).await {- Ok(Some(link)) => link,- Ok(None) => {- let err_msg = format!("Link not found for link_id: {}", data.link_id);- tracing::error!("{}", err_msg);- return Err(ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::LinkNotFound,- source: anyhow::anyhow!(err_msg),- }));- }- Err(e) => {- return Err(ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e,- }));- }+ let link = fetch_link(ctx, scope.link_id).await?;++ Ok(Some(JobContextNoToken { link, backfill_job }))+}++/// As [`fetch_job_context_no_token`], plus a fresh Gmail access token for+/// the link. For handlers that need to talk to Gmail (Init, ListThreads,+/// BackfillThread, BackfillMessage, BackfillAttachment).+async fn fetch_job_context<P>(+ ctx: &PubSubContext,+ scope: &JobScopedPayload<P>,+) -> Result<Option<JobContext>, ProcessingError> {+ let Some(JobContextNoToken { link, backfill_job }) =+ fetch_job_context_no_token(ctx, scope).await?+ else {+ return Ok(None);};let access_token = fetch_token_or_delete_on_revocation(@@ -106,28 +224,31 @@ async fn inner_process_message(})})?;- match &data.backfill_operation {- BackfillOperation::Init => {- init::init_backfill(ctx, &access_token, data, &link, &backfill_job).await?- }- BackfillOperation::ListThreads(p) => {- list_threads::list_threads(ctx, &access_token, data, &link, p, &backfill_job).await?- }- BackfillOperation::BackfillThread(p) => {- backfill_thread::backfill_thread(ctx, &access_token, data, &link, p).await?- }- BackfillOperation::BackfillMessage(p) => {- backfill_message::backfill_message(ctx, &access_token, data, &link, p).await?- }- BackfillOperation::UpdateThreadMetadata(p) => {- update_metadata::update_thread_metadata(ctx, data, &link, p).await?- }- BackfillOperation::BackfillAttachment(p) => {- backfill_attachment::backfill_attachment(ctx, &access_token, &link, p).await?- }- };+ Ok(Some(JobContext {+ link,+ backfill_job,+ access_token,+ }))+}- Ok(())+/// Looks up a link by id, mapping the absence into a NonRetryable error+/// (the message names a link that doesn't exist; retrying won't help).+async fn fetch_link(ctx: &PubSubContext, link_id: Uuid) -> Result<link::Link, ProcessingError> {+ match email_db_client::links::get::fetch_link_by_id(&ctx.db, link_id).await {+ Ok(Some(link)) => Ok(link),+ Ok(None) => {+ let err_msg = format!("Link not found for link_id: {link_id}");+ tracing::error!("{}", err_msg);+ Err(ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::LinkNotFound,+ source: anyhow::anyhow!(err_msg),+ }))+ }+ Err(e) => Err(ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e,+ })),+ }}/// Extracts backfill message from the SQS message body@@ -143,29 +264,3 @@ fn extract_backfill_message(Ok(backfill_message)}--// set unprocessed records to cancelled if the job was cancelled-async fn handle_cancel_backfill_job(- ctx: &PubSubContext,- data: &BackfillPubsubMessage,-) -> anyhow::Result<()> {- let _ = ctx- .redis_client- .delete_backfill_job_progress(data.job_id)- .await;-- match &data.backfill_operation {- BackfillOperation::BackfillMessage(p) => {- let _ = ctx- .redis_client- .delete_backfill_thread_progress(data.job_id, &p.thread_provider_id)- .await;- Ok(())- }- BackfillOperation::Init- | BackfillOperation::ListThreads(_)- | BackfillOperation::BackfillThread(_)- | BackfillOperation::UpdateThreadMetadata(_)- | BackfillOperation::BackfillAttachment(_) => Ok(()),- }-}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rsindex be13bbe166..7a165abcee 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs@@ -1,6 +1,6 @@use crate::pubsub::backfill::increment_counters::incr_completed_threads;use crate::pubsub::context::PubSubContext;-use models_email::email::service::backfill::{BackfillPubsubMessage, UpdateMetadataPayload};+use models_email::email::service::backfill::{JobScopedPayload, UpdateMetadataPayload};use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use sqs_client::search::SearchQueueMessage;@@ -13,10 +13,10 @@ use sqs_client::search::email::EmailThreadMessage;#[tracing::instrument(skip(ctx))]pub async fn update_thread_metadata(ctx: &PubSubContext,- data: &BackfillPubsubMessage,+ scope: &JobScopedPayload<UpdateMetadataPayload>,link: &link::Link,- p: &UpdateMetadataPayload,) -> Result<(), ProcessingError> {+ let p = &scope.payload;let mut tx = ctx.db.begin().await.map_err(|e| {ProcessingError::Retryable(DetailedError {reason: FailureReason::DatabaseQueryFailed,@@ -78,7 +78,7 @@ pub async fn update_thread_metadata(})})?;- incr_completed_threads(ctx, link, data.job_id).await?;+ incr_completed_threads(ctx, link, scope.job_id).await?;// notify search-service about the new threadlet search_message = SearchQueueMessage::ExtractEmailThreadMessage(EmailThreadMessage {diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rsindex 80a54c5bd7..d91f93a231 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs@@ -1,5 +1,5 @@use crate::pubsub::backfill::process;-use crate::pubsub::context::{NotificationIngressType, PubSubContext};+use crate::pubsub::context::{CrmServiceType, NotificationIngressType, PubSubContext};use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;@@ -26,6 +26,7 @@ pub async fn run_worker(connection_gateway_client: ConnectionGatewayClient,dss_client: DocumentStorageServiceClient,system_properties_service: Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,+ crm_service: CrmServiceType,notifications_enabled: bool,) {let ctx = PubSubContext {@@ -41,6 +42,7 @@ pub async fn run_worker(connection_gateway_client,dss_client,system_properties_service,+ crm_service,notifications_enabled,retry_worker: false,};diff --git a/rust/cloud-storage/email_service/src/pubsub/context.rs b/rust/cloud-storage/email_service/src/pubsub/context.rsindex 4781655705..3f2a5bdcea 100644--- a/rust/cloud-storage/email_service/src/pubsub/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/context.rs@@ -3,6 +3,8 @@ use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;use contacts::domain::service::SqsContactsIngress;use contacts::outbound::ingress::SqsContactsQueue;+use crm::domain::service::CrmServiceImpl;+use crm::outbound::companies_repo::CompaniesRepositoryImpl;use document_storage_service_client::DocumentStorageServiceClient;use gmail_client::GmailClient;use notification::domain::service::SqsNotificationIngress;@@ -15,6 +17,9 @@ 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>;+#[derive(Clone)]pub struct PubSubContext {pub db: PgPool,@@ -29,6 +34,7 @@ pub struct PubSubContext {pub connection_gateway_client: ConnectionGatewayClient,pub dss_client: DocumentStorageServiceClient,pub system_properties_service: Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,+ pub crm_service: CrmServiceType,pub notifications_enabled: bool,pub retry_worker: bool,}diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rsindex 894a9fd46f..f5b1564610 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rs@@ -1,4 +1,4 @@-use crate::pubsub::context::{NotificationIngressType, PubSubContext};+use crate::pubsub::context::{CrmServiceType, NotificationIngressType, PubSubContext};use crate::pubsub::inbox_sync::process;use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;@@ -26,6 +26,7 @@ pub async fn run_worker(connection_gateway_client: ConnectionGatewayClient,dss_client: DocumentStorageServiceClient,system_properties_service: Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,+ crm_service: CrmServiceType,notifications_enabled: bool,retry_worker: bool,) {@@ -42,6 +43,7 @@ pub async fn run_worker(connection_gateway_client,dss_client,system_properties_service,+ crm_service,notifications_enabled,retry_worker,};diff --git a/rust/cloud-storage/macro_db_client/migrations/20260514120000_crm_contact_sources.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260514120000_crm_contact_sources.down.sqlnew file mode 100644index 0000000000..f4705a1a95--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260514120000_crm_contact_sources.down.sql@@ -0,0 +1,3 @@+DROP INDEX IF EXISTS crm_contact_sources_link_id_idx;+DROP INDEX IF EXISTS crm_contact_sources_contact_id_idx;+DROP TABLE IF EXISTS crm_contact_sources;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260514120000_crm_contact_sources.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260514120000_crm_contact_sources.up.sqlnew file mode 100644index 0000000000..5b54697bf0--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260514120000_crm_contact_sources.up.sql@@ -0,0 +1,14 @@+CREATE TABLE IF NOT EXISTS crm_contact_sources+(+ id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),+ contact_id UUID NOT NULL REFERENCES crm_contacts (id) ON DELETE CASCADE,+ link_id UUID NOT NULL REFERENCES email_links (id) ON DELETE CASCADE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (contact_id, link_id)+);++CREATE INDEX IF NOT EXISTS crm_contact_sources_contact_id_idx+ ON crm_contact_sources (contact_id);++CREATE INDEX IF NOT EXISTS crm_contact_sources_link_id_idx+ ON crm_contact_sources (link_id);diff --git a/rust/cloud-storage/macro_db_client/migrations/20260514130000_crm_domains_team_id.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260514130000_crm_domains_team_id.down.sqlnew file mode 100644index 0000000000..e01d813ce4--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260514130000_crm_domains_team_id.down.sql@@ -0,0 +1,4 @@+DROP INDEX IF EXISTS crm_domains_team_id_lower_domain_unique;++ALTER TABLE crm_domains+ DROP COLUMN IF EXISTS team_id;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260514130000_crm_domains_team_id.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260514130000_crm_domains_team_id.up.sqlnew file mode 100644index 0000000000..7e2f4a3ee9--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260514130000_crm_domains_team_id.up.sql@@ -0,0 +1,25 @@+-- Denormalize team_id onto crm_domains so we can enforce+-- UNIQUE(team_id, LOWER(domain)) directly. Without this, the upsert path in+-- crm::outbound::companies_repo::populate_contact races: two concurrent+-- transactions can both SELECT-and-see-nothing for the same (team, domain)+-- and both INSERT a new crm_companies row, leaving the team with duplicate+-- companies for the same domain.++ALTER TABLE crm_domains+ ADD COLUMN IF NOT EXISTS team_id UUID REFERENCES team (id) ON DELETE CASCADE;++-- Backfill from the parent crm_companies row. In practice the v1 PR has not+-- shipped to prod yet so the table is empty, but the UPDATE is cheap and+-- keeps the migration safe to apply against any environment that already has+-- crm_companies/crm_domains rows.+UPDATE crm_domains d+SET team_id = c.team_id+FROM crm_companies c+WHERE d.company_id = c.id+ AND d.team_id IS NULL;++ALTER TABLE crm_domains+ ALTER COLUMN team_id SET NOT NULL;++CREATE UNIQUE INDEX IF NOT EXISTS crm_domains_team_id_lower_domain_unique+ ON crm_domains (team_id, LOWER(domain));diff --git a/rust/cloud-storage/models_email/src/email/service/backfill.rs b/rust/cloud-storage/models_email/src/email/service/backfill.rsindex e8473bdd37..94946798cc 100644--- a/rust/cloud-storage/models_email/src/email/service/backfill.rs+++ b/rust/cloud-storage/models_email/src/email/service/backfill.rs@@ -2,6 +2,7 @@ use crate::email::db::backfill as db_backfill;use crate::email::service::thread::ListThreadsPayload;use crate::service::attachment::AttachmentUploadArgs;use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize};use sqlx::FromRow;use strum::{AsRefStr, Display, EnumString};@@ -20,40 +21,113 @@ pub struct BackfillMessagePayload {pub message_provider_id: String,}+/// Scope envelope for backfill operations that belong to a tracked backfill+/// job (Init, ListThreads, BackfillThread, BackfillMessage,+/// UpdateThreadMetadata, BackfillAttachment). Carries the `link_id` and+/// `job_id` the operation needs alongside its variant-specific payload.+/// The inner payload is `#[serde(flatten)]`-ed so the JSON shape stays the+/// same as if `link_id`/`job_id` and the payload fields were siblings.+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]+pub struct JobScopedPayload<P> {+ pub link_id: Uuid,+ pub job_id: Uuid,+ #[serde(flatten)]+ pub payload: P,+}++/// Scope envelope for backfill operations that are scoped to a single+/// `email_link` but not to a backfill job (e.g. `PopulateCrmContact`).+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]+pub struct LinkScopedPayload<P> {+ pub link_id: Uuid,+ #[serde(flatten)]+ pub payload: P,+}++/// Empty payload for [`BackfillOperation::Init`]. The variant only needs the+/// shared `link_id`/`job_id` from `JobScopedPayload`; this struct exists so+/// every job-scoped variant has the same `JobScopedPayload<…>` shape.+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Default)]+pub struct InitPayload {}+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]#[serde(rename_all = "snake_case")]pub enum BackfillOperation {// Populates total_threads and sends the first ListThreads message- Init,+ Init(JobScopedPayload<InitPayload>),// Each ListThreads operation gets a batch of 500 thread_ids from the gmail api// and sends a BackfillThread message for each thread_id in the batch. If there// are still threads left to fetch, it will send another ListThreads message.- ListThreads(ListThreadsPayload),+ ListThreads(JobScopedPayload<ListThreadsPayload>),// Creates the thread object in the database, fetches the message ids for the thread// from the gmail api, and sends a BackfillMessage message for each message_id.- BackfillThread(BackfillThreadPayload),+ BackfillThread(JobScopedPayload<BackfillThreadPayload>),// Creates a message object in the database. If the message is the last message in// the thread to be processed, it sends an UpdateThreadMetadata message for the thread.- BackfillMessage(BackfillMessagePayload),+ BackfillMessage(JobScopedPayload<BackfillMessagePayload>),// Updates the thread metadata in the database. If it's the last thread to be processed,// it sets the backfill job status to complete. Sends BackfillAttachment messages for each// attachment requiring backfill, except for the criteria of attachments in any threads// with a participant the user has previously emailed. This criteria we can only know after// backfill completes. Once backfill is completed it sends a BackfillAttachment message// for each of those attachments.- UpdateThreadMetadata(UpdateMetadataPayload),+ UpdateThreadMetadata(JobScopedPayload<UpdateMetadataPayload>),// Uploads the message attachment as a Macro document.- BackfillAttachment(BackfillAttachmentPayload),+ BackfillAttachment(JobScopedPayload<BackfillAttachmentPayload>),+ // Idempotently records a contact the requesting user has emailed into the+ // CRM tables (crm_companies, crm_domains, crm_contacts, crm_contact_sources).+ // Fanned out one-per-recipient from BackfillMessage when the message was+ // 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>),+ // 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),+}++impl BackfillOperation {+ /// Returns the link_id this operation is scoped to, or `None` for+ /// user-scoped operations that resolve the link themselves.+ pub fn link_id(&self) -> Option<Uuid> {+ match self {+ BackfillOperation::Init(s) => Some(s.link_id),+ BackfillOperation::ListThreads(s) => Some(s.link_id),+ BackfillOperation::BackfillThread(s) => Some(s.link_id),+ BackfillOperation::BackfillMessage(s) => Some(s.link_id),+ BackfillOperation::UpdateThreadMetadata(s) => Some(s.link_id),+ BackfillOperation::BackfillAttachment(s) => Some(s.link_id),+ BackfillOperation::PopulateCrmContact(s) => Some(s.link_id),+ BackfillOperation::PopulateCrmForUser(_) => None,+ }+ }++ /// Returns the backfill job_id this operation belongs to, or `None`+ /// for operations that don't participate in a tracked backfill job.+ pub fn job_id(&self) -> Option<Uuid> {+ match self {+ BackfillOperation::Init(s) => Some(s.job_id),+ BackfillOperation::ListThreads(s) => Some(s.job_id),+ BackfillOperation::BackfillThread(s) => Some(s.job_id),+ 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+ }+ }+ }}// the object we send on the backfill pubsub queue#[derive(Debug, Deserialize, Serialize)]#[serde(rename_all = "camelCase")]pub struct BackfillPubsubMessage {- pub link_id: Uuid,- // the id of the backfill job in the backfill_job table- pub job_id: Uuid,- // the operation being performed (init, backfill_thread, backfill_message)+ // the operation being performed (init, backfill_thread, backfill_message,+ // populate_crm_contact, populate_crm_for_user). Each variant carries its+ // own link_id/job_id/macro_id as needed — see JobScopedPayload,+ // LinkScopedPayload, and PopulateCrmForUserPayload.pub backfill_operation: BackfillOperation,}@@ -178,3 +252,13 @@ pub struct UpdateMetadataPayload {pub struct BackfillAttachmentPayload {pub metadata: AttachmentUploadArgs,}++#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]+pub struct PopulateCrmContactPayload {+ pub contact_email: String,+}++#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]+pub struct PopulateCrmForUserPayload {+ pub macro_id: MacroUserIdStr<'static>,+}diff --git a/rust/cloud-storage/teams/Cargo.toml b/rust/cloud-storage/teams/Cargo.tomlindex 1766c1d028..2de7cc905c 100644--- a/rust/cloud-storage/teams/Cargo.toml+++ b/rust/cloud-storage/teams/Cargo.toml@@ -23,7 +23,13 @@ axum = []default = ["ai_tools", "axum", "inbound", "outbound", "ports"]inbound = ["axum", "ports"]-outbound = ["dep:sqlx", "dep:url", "ports"]+outbound = [+ "dep:sqlx",+ "dep:sqs_client",+ "dep:models_email",+ "dep:url",+ "ports",+]ports = ["dep:model-entity","dep:model_notifications",@@ -73,6 +79,10 @@ notification = { path = "../notification", optional = true, default-features = f# Outbound dependenciessqlx = { workspace = true, optional = true }url = { workspace = true, optional = true }+sqs_client = { path = "../sqs_client", default-features = false, features = [+ "email",+], optional = true }+models_email = { path = "../models_email", optional = true }[dev-dependencies]macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/rust/cloud-storage/teams/src/domain.rs b/rust/cloud-storage/teams/src/domain.rsindex 195d9cfde4..d3585a73a3 100644--- a/rust/cloud-storage/teams/src/domain.rs+++ b/rust/cloud-storage/teams/src/domain.rs@@ -1,4 +1,5 @@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/populate_crm_enqueuer.rs b/rust/cloud-storage/teams/src/domain/populate_crm_enqueuer.rsnew file mode 100644index 0000000000..61d285ecd5--- /dev/null+++ b/rust/cloud-storage/teams/src/domain/populate_crm_enqueuer.rs@@ -0,0 +1,47 @@+//! 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 88e71bc292..8adc076a04 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -30,18 +30,20 @@ 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>+pub struct TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,+ PCE: PopulateCrmEnqueuer,{/// The underlying team repositoryteam_repository: TR,@@ -53,15 +55,19 @@ 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,}-impl<TR, CR, TCR, URPS, NI> Clone for TeamServiceImpl<TR, CR, TCR, URPS, NI>+impl<TR, CR, TCR, URPS, NI, PCE> Clone for TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,+ PCE: PopulateCrmEnqueuer,{fn clone(&self) -> Self {Self {@@ -70,17 +76,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(),}}}-impl<TR, CR, TCR, URPS, NI> TeamServiceImpl<TR, CR, TCR, URPS, NI>+impl<TR, CR, TCR, URPS, NI, PCE> TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,+ PCE: PopulateCrmEnqueuer,{/// Creates a new TeamServicepub fn new(@@ -89,6 +97,7 @@ whereteam_channels_repository: TCR,user_roles_and_permissions_service: URPS,notification_ingress: Arc<NI>,+ populate_crm_enqueuer: PCE,) -> Self {Self {team_repository,@@ -96,17 +105,19 @@ whereteam_channels_repository,user_roles_and_permissions_service,notification_ingress,+ populate_crm_enqueuer,}}}-impl<TR, CR, TCR, URPS, NI> TeamServiceImpl<TR, CR, TCR, URPS, NI>+impl<TR, CR, TCR, URPS, NI, PCE> TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,+ PCE: PopulateCrmEnqueuer,{/// 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@@ -211,13 +222,14 @@ impl GetTeamSubscriptionError {}}-impl<TR, CR, TCR, URPS, NI> TeamMembersService for TeamServiceImpl<TR, CR, TCR, URPS, NI>+impl<TR, CR, TCR, URPS, NI, PCE> TeamMembersService for TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,+ PCE: PopulateCrmEnqueuer,{#[tracing::instrument(skip(self), err)]async fn list_team_members(@@ -234,13 +246,14 @@ where}}-impl<TR, CR, TCR, URPS, NI> TeamService for TeamServiceImpl<TR, CR, TCR, URPS, NI>+impl<TR, CR, TCR, URPS, NI, PCE> TeamService for TeamServiceImpl<TR, CR, TCR, URPS, NI, PCE>whereTR: TeamRepository,CR: CustomerRepository,TCR: TeamChannelsRepository,URPS: UserRolesAndPermissionsService,NI: NotificationIngress,+ PCE: PopulateCrmEnqueuer,{#[tracing::instrument(skip(self), err)]async fn create_team(@@ -248,7 +261,27 @@ whereuser_id: &MacroUserIdStr<'_>,team_name: &str,) -> Result<Team, CreateTeamError> {- self.team_repository.create_team(user_id, team_name).await+ let team = self.team_repository.create_team(user_id, team_name).await?;++ // Best-effort: ask the email service to seed CRM tables from this+ // user's historical sent mail. Log and swallow failures — the team+ // is already committed and the email-service consumer is idempotent,+ // 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+ .enqueue_populate_crm_for_user(user_id)+ .await+ {+ tracing::error!(+ error = ?e,+ team_id = %team.id,+ macro_id = %user_id,+ "Failed to enqueue PopulateCrmForUser after create_team; CRM tables will not be seeded from sent-mail history (per-message fan-out will still cover future sends)"+ );+ }++ Ok(team)}#[tracing::instrument(skip(self), err)]@@ -473,6 +506,24 @@ where.add_team_member_to_channels(&team_member.team_id, user_id).await?;+ // Best-effort: ask the email service to seed CRM tables from this+ // user's historical sent mail. Log and swallow failures — the join+ // is already committed and the email-service consumer is idempotent,+ // 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+ .enqueue_populate_crm_for_user(user_id)+ .await+ {+ tracing::error!(+ error = ?e,+ team_id = %team_member.team_id,+ macro_id = %user_id,+ "Failed to enqueue PopulateCrmForUser after join_team; CRM tables will not be seeded from sent-mail history (per-message fan-out will still cover future sends)"+ );+ }+Ok(team_member)}diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rsindex ef5cd89b3b..6703e21527 100644--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs@@ -20,6 +20,8 @@ use roles_and_permissions::domain::{port::UserRolesAndPermissionsService,};+use crate::domain::populate_crm_enqueuer::NoOpPopulateCrmEnqueuer;+fn test_team_receipt<T: RequiredPermission>(team_id: uuid::Uuid,user_id: &MacroUserIdStr<'_>,@@ -578,6 +580,7 @@ fn build_service(MockTeamChannelsRepository,MockUserRolesAndPermissionsService,notification_ingress.clone(),+ NoOpPopulateCrmEnqueuer,);(service, notification_ingress)}@@ -736,6 +739,7 @@ fn build_service_with_team(MockTeamChannelsRepository,MockUserRolesAndPermissionsService,notification_ingress,+ NoOpPopulateCrmEnqueuer,);(service, role_calls, name_calls)}diff --git a/rust/cloud-storage/teams/src/outbound.rs b/rust/cloud-storage/teams/src/outbound.rsindex f60665a3c3..2455af2b40 100644--- a/rust/cloud-storage/teams/src/outbound.rs+++ b/rust/cloud-storage/teams/src/outbound.rs@@ -1,3 +1,4 @@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/populate_crm_enqueuer.rs b/rust/cloud-storage/teams/src/outbound/populate_crm_enqueuer.rsnew file mode 100644index 0000000000..ce3011ae5c--- /dev/null+++ b/rust/cloud-storage/teams/src/outbound/populate_crm_enqueuer.rs@@ -0,0 +1,54 @@+//! 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+ }+}