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
refactor(email-service): Contact upserting logic (#999)
Evan Hutnik0f56b5696c64
diff --git a/.gitignore b/.gitignoreindex 99e9cb7950..185a4ae060 100644--- a/.gitignore+++ b/.gitignore@@ -3,3 +3,4 @@**/.env.idea/**/.DS_Store+.run/diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-6549ab93934af3c098957525a8b881d278f23b46c3fd0aab051c989cb0759577.json b/rust/cloud-storage/email_db_client/.sqlx/query-6549ab93934af3c098957525a8b881d278f23b46c3fd0aab051c989cb0759577.jsondeleted file mode 100644index 79c25b02a7..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-6549ab93934af3c098957525a8b881d278f23b46c3fd0aab051c989cb0759577.json+++ /dev/null@@ -1,31 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH input_rows (id, link_id, email_address, name) AS (\n SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::text[], $4::text[])\n ORDER BY 3 -- Prevent deadlocks by using consistent ordering\n )\n INSERT INTO email_contacts (id, link_id, email_address, name)\n SELECT id, link_id, email_address, name FROM input_rows\n ON CONFLICT (link_id, email_address) DO UPDATE\n -- Don't overwrite existing name with name from an email, as existing name will be\n -- from the user's contacts list and thus will be more accurate.\n SET name = CASE\n WHEN email_contacts.name IS NULL AND EXCLUDED.name IS NOT NULL\n THEN EXCLUDED.name\n ELSE email_contacts.name\n END,\n updated_at = CASE\n WHEN email_contacts.name IS NULL AND EXCLUDED.name IS NOT NULL\n THEN NOW()\n ELSE email_contacts.updated_at\n END\n RETURNING id, email_address\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "email_address",- "type_info": "Varchar"- }- ],- "parameters": {- "Left": [- "UuidArray",- "UuidArray",- "TextArray",- "TextArray"- ]- },- "nullable": [- false,- false- ]- },- "hash": "6549ab93934af3c098957525a8b881d278f23b46c3fd0aab051c989cb0759577"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-a5ea0cf5ff502359e9ebc01d0f8758d171081c5aa35c785b178150aa9d8d3635.json b/rust/cloud-storage/email_db_client/.sqlx/query-a5ea0cf5ff502359e9ebc01d0f8758d171081c5aa35c785b178150aa9d8d3635.jsonnew file mode 100644index 0000000000..65601cffb9--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-a5ea0cf5ff502359e9ebc01d0f8758d171081c5aa35c785b178150aa9d8d3635.json@@ -0,0 +1,31 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_contacts (id, link_id, email_address, name)\n SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::text[], $4::text[])\n ON CONFLICT (link_id, email_address) DO NOTHING\n RETURNING id, email_address\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_address",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "UuidArray",+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "a5ea0cf5ff502359e9ebc01d0f8758d171081c5aa35c785b178150aa9d8d3635"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-b0c4750b13bbd3de768ac09f971094ac7f53c161f7054083964f472fa01dd83d.json b/rust/cloud-storage/email_db_client/.sqlx/query-b0c4750b13bbd3de768ac09f971094ac7f53c161f7054083964f472fa01dd83d.jsonnew file mode 100644index 0000000000..f91da73bfc--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-b0c4750b13bbd3de768ac09f971094ac7f53c161f7054083964f472fa01dd83d.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, email_address\n FROM email_contacts\n WHERE link_id = $1 AND email_address = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_address",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "b0c4750b13bbd3de768ac09f971094ac7f53c161f7054083964f472fa01dd83d"+}diff --git a/rust/cloud-storage/email_db_client/fixtures/upsert_message_contacts.sql b/rust/cloud-storage/email_db_client/fixtures/upsert_message_contacts.sqlnew file mode 100644index 0000000000..03b157961f--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/upsert_message_contacts.sql@@ -0,0 +1,68 @@+-- SQL fixture for insert_new_contacts and fetch_contacts_by_emails tests+-- This file seeds:+-- - 1 email link+-- - Pre-existing contacts for testing fetch and conflict handling++------------------------------------------------------------+-- Common: links+------------------------------------------------------------++-- Link A: user email is [email protected]+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000001a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001a',+ '[email protected]', 'GMAIL', true, '2025-11-11 17:48:26.664688 +00:00',+ '2025-11-11 17:48:26.664688 +00:00');++-- Link B: different user for isolation tests+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000001b', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001b',+ '[email protected]', 'GMAIL', true, '2025-11-11 17:48:26.664688 +00:00',+ '2025-11-11 17:48:26.664688 +00:00');++------------------------------------------------------------+-- Pre-existing contacts for Link A+------------------------------------------------------------++-- Contact 1: existing contact to test fetch+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0001',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ 'Existing Contact One',+ NOW(),+ NOW());++-- Contact 2: existing contact to test fetch with multiple emails+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0002',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ 'Existing Contact Two',+ NOW(),+ NOW());++-- Contact 3: existing contact with no name+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0003',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NULL,+ NOW(),+ NOW());++------------------------------------------------------------+-- Pre-existing contact for Link B (to test link isolation)+------------------------------------------------------------++-- Contact for Link B with same email as Link A contact+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0004',+ '00000000-0000-0000-0000-00000000001b',+ '[email protected]',+ 'Same Email Different Link',+ NOW(),+ NOW());++------------------------------------------------------------+-- End of fixture+------------------------------------------------------------\ No newline at end of filediff --git a/rust/cloud-storage/email_db_client/src/contacts/upsert_message.rs b/rust/cloud-storage/email_db_client/src/contacts/upsert_message.rsindex 020c2a89bc..994b766f26 100644--- a/rust/cloud-storage/email_db_client/src/contacts/upsert_message.rs+++ b/rust/cloud-storage/email_db_client/src/contacts/upsert_message.rs@@ -1,22 +1,22 @@+#[cfg(test)]+mod tests;+use crate::contacts::normalize;use anyhow::Context;use models_email::db;use models_email::db::contact::ContactPhotoless;use models_email::db::{address, message};+use sqlx::PgPool;use sqlx::types::Uuid;-use sqlx::{Executor, Postgres};-use std::collections::{HashMap, HashSet};+use std::collections::HashMap;/// upsert methods used when inserting individual threads/messages into the database./// wrapper around insert_email_address to format the data into a usable shape-pub async fn parse_and_upsert_message_contacts<'e, E>(- executor: E,+pub async fn parse_and_upsert_message_contacts(+ pool: &PgPool,link_id: Uuid,addresses_data: address::ParsedAddresses,-) -> anyhow::Result<address::UpsertedRecipients>-where- E: Executor<'e, Database = Postgres>,-{+) -> anyhow::Result<address::UpsertedRecipients> {// ensure we don't process the same email addresses more than oncelet mut unique_addresses_map: HashMap<String, Option<String>> = HashMap::new();@@ -49,7 +49,7 @@ where}).collect();- match upsert_message_contacts(executor, addresses_to_upsert).await {+ match upsert_message_contacts(pool, addresses_to_upsert).await {Ok(email_to_id_map) => {if let Some(ref from_addr) = addresses_data.from {let normalized_from = from_addr.email_address.to_lowercase();@@ -92,53 +92,114 @@ where}/// inserts email addresses into the database in a batch-#[tracing::instrument(skip(executor, contacts))]-async fn upsert_message_contacts<'e, E>(- executor: E,+#[tracing::instrument(skip(pool, contacts))]+async fn upsert_message_contacts(+ pool: &PgPool,contacts: Vec<ContactPhotoless>,-) -> anyhow::Result<HashMap<String, Uuid>>-where- E: Executor<'e, Database = Postgres>,-{+) -> anyhow::Result<HashMap<String, Uuid>> {if contacts.is_empty() {return Ok(HashMap::new());}+ let contacts: Vec<_> = contacts+ .into_iter()+ .map(normalize::normalize_contact)+ .collect();++ let link_id = contacts[0].link_id;+ let emails: Vec<String> = contacts.iter().map(|c| c.email_address.clone()).collect();++ // Step 1: Fetch existing (fast, no locks)+ let existing = fetch_contacts_by_emails(pool, link_id, &emails).await?;++ let mut result_map: HashMap<String, Uuid> = existing+ .into_iter()+ .map(|r| (r.email_address, r.id))+ .collect();++ // Step 2: Filter to contacts we don't have yet+ let new_contacts: Vec<_> = contacts+ .into_iter()+ .filter(|c| !result_map.contains_key(&c.email_address))+ .collect();++ if new_contacts.is_empty() {+ return Ok(result_map);+ }++ // Step 3: Try to insert new contacts+ let inserted = insert_new_contacts(pool, &new_contacts).await?;++ let new_emails: Vec<String> = new_contacts+ .iter()+ .map(|c| c.email_address.clone())+ .collect();++ for row in inserted {+ result_map.insert(row.email_address, row.id);+ }++ // Step 4: Any still missing? Fetch them (handles race condition)+ let still_missing: Vec<String> = new_emails+ .iter()+ .filter(|e| !result_map.contains_key(*e))+ .cloned()+ .collect();++ if !still_missing.is_empty() {+ let fetched = fetch_contacts_by_emails(pool, link_id, &still_missing).await?;++ for row in fetched {+ result_map.insert(row.email_address, row.id);+ }+ }++ Ok(result_map)+}++async fn fetch_contacts_by_emails(+ pool: &PgPool,+ link_id: Uuid,+ emails: &[String],+) -> anyhow::Result<Vec<address::FetchedAddressId>> {+ let results = sqlx::query_as!(+ address::FetchedAddressId,+ r#"+ SELECT id, email_address+ FROM email_contacts+ WHERE link_id = $1 AND email_address = ANY($2)+ "#,+ link_id,+ emails+ )+ .fetch_all(pool)+ .await?;++ Ok(results)+}++async fn insert_new_contacts(+ pool: &PgPool,+ contacts: &[ContactPhotoless],+) -> anyhow::Result<Vec<address::FetchedAddressId>> {let mut ids: Vec<Uuid> = Vec::with_capacity(contacts.len());let mut link_ids: Vec<Uuid> = Vec::with_capacity(contacts.len());let mut emails: Vec<String> = Vec::with_capacity(contacts.len());let mut names: Vec<Option<String>> = Vec::with_capacity(contacts.len());- for mut contact in contacts {- contact = normalize::normalize_contact(contact);+ for contact in contacts {ids.push(contact.id);link_ids.push(contact.link_id);- emails.push(contact.email_address);- names.push(contact.name);+ emails.push(contact.email_address.clone());+ names.push(contact.name.clone());}- let rows: Vec<address::FetchedAddressId> = sqlx::query_as!(- db::address::FetchedAddressId,+ let inserted = sqlx::query_as!(+ address::FetchedAddressId,r#"- WITH input_rows (id, link_id, email_address, name) AS (- SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::text[], $4::text[])- ORDER BY 3 -- Prevent deadlocks by using consistent ordering- )INSERT INTO email_contacts (id, link_id, email_address, name)- SELECT id, link_id, email_address, name FROM input_rows- ON CONFLICT (link_id, email_address) DO UPDATE- -- Don't overwrite existing name with name from an email, as existing name will be- -- from the user's contacts list and thus will be more accurate.- SET name = CASE- WHEN email_contacts.name IS NULL AND EXCLUDED.name IS NOT NULL- THEN EXCLUDED.name- ELSE email_contacts.name- END,- updated_at = CASE- WHEN email_contacts.name IS NULL AND EXCLUDED.name IS NOT NULL- THEN NOW()- ELSE email_contacts.updated_at- END+ SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::text[], $4::text[])+ ON CONFLICT (link_id, email_address) DO NOTHINGRETURNING id, email_address"#,&ids,@@ -146,25 +207,10 @@ where&emails,&names as _)- .fetch_all(executor)- .await- .with_context(|| "Failed during atomic batch upsert-and-return of email addresses")?;-- let email_to_id_map: HashMap<String, Uuid> = rows- .into_iter()- .map(|row| (row.email_address, row.id))- .collect();-- let unique_input_emails: HashSet<_> = emails.iter().collect();- if email_to_id_map.len() != unique_input_emails.len() {- tracing::warn!(- unique_input_emails = unique_input_emails.len(),- map_count = email_to_id_map.len(),- "Mismatch fetching email IDs after upsert. This can happen with highly concurrent, overlapping batches."- );- }+ .fetch_all(pool)+ .await?;- Ok(email_to_id_map)+ Ok(inserted)}/// inserts the recipients of an email into the database in a batchdiff --git a/rust/cloud-storage/email_db_client/src/contacts/upsert_message/tests.rs b/rust/cloud-storage/email_db_client/src/contacts/upsert_message/tests.rsnew file mode 100644index 0000000000..5135fa88e2--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/contacts/upsert_message/tests.rs@@ -0,0 +1,325 @@+use super::*;+use anyhow::Result;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_email::db::contact::ContactPhotoless;+use sqlx::{Pool, Postgres};++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should fetch existing contacts by their email addresses+async fn fetch_contacts_by_emails_returns_existing_contacts(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let emails = vec![+ "[email protected]".to_string(),+ "[email protected]".to_string(),+ ];++ let res = fetch_contacts_by_emails(&pool, link_id, &emails).await?;++ assert_eq!(res.len(), 2);++ let email_addresses: Vec<&str> = res.iter().map(|r| r.email_address.as_str()).collect();+ assert!(email_addresses.contains(&"[email protected]"));+ assert!(email_addresses.contains(&"[email protected]"));++ // Verify correct IDs are returned+ let expected_id_1 = Uuid::parse_str("00000000-0000-0000-0000-0000000c0001")?;+ let expected_id_2 = Uuid::parse_str("00000000-0000-0000-0000-0000000c0002")?;+ let ids: Vec<Uuid> = res.iter().map(|r| r.id).collect();+ assert!(ids.contains(&expected_id_1));+ assert!(ids.contains(&expected_id_2));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should return empty when no matching emails exist+async fn fetch_contacts_by_emails_returns_empty_for_nonexistent(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let emails = vec![+ "[email protected]".to_string(),+ "[email protected]".to_string(),+ ];++ let res = fetch_contacts_by_emails(&pool, link_id, &emails).await?;++ assert!(res.is_empty());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should only return contacts for the specified link_id+async fn fetch_contacts_by_emails_respects_link_id_isolation(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Link B has a contact with [email protected] but different ID+ let link_b_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001b")?;+ let emails = vec!["[email protected]".to_string()];++ let res = fetch_contacts_by_emails(&pool, link_b_id, &emails).await?;++ assert_eq!(res.len(), 1);+ // Should return Link B's contact, not Link A's+ let expected_link_b_contact_id = Uuid::parse_str("00000000-0000-0000-0000-0000000c0004")?;+ assert_eq!(res[0].id, expected_link_b_contact_id);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should return partial results when some emails exist and some don't+async fn fetch_contacts_by_emails_returns_partial_matches(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let emails = vec![+ "[email protected]".to_string(),+ "[email protected]".to_string(),+ ];++ let res = fetch_contacts_by_emails(&pool, link_id, &emails).await?;++ assert_eq!(res.len(), 1);+ assert_eq!(res[0].email_address, "[email protected]");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should successfully insert new contacts+async fn insert_new_contacts_creates_contacts(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let new_contact_id_1 = Uuid::parse_str("00000000-0000-0000-0000-0000000d0001")?;+ let new_contact_id_2 = Uuid::parse_str("00000000-0000-0000-0000-0000000d0002")?;++ let contacts = vec![+ ContactPhotoless {+ id: new_contact_id_1,+ link_id,+ email_address: "[email protected]".to_string(),+ name: Some("New Contact One".to_string()),+ },+ ContactPhotoless {+ id: new_contact_id_2,+ link_id,+ email_address: "[email protected]".to_string(),+ name: Some("New Contact Two".to_string()),+ },+ ];++ let res = insert_new_contacts(&pool, &contacts).await?;++ assert_eq!(res.len(), 2);++ let email_addresses: Vec<&str> = res.iter().map(|r| r.email_address.as_str()).collect();+ assert!(email_addresses.contains(&"[email protected]"));+ assert!(email_addresses.contains(&"[email protected]"));++ // Verify the correct IDs are returned+ let ids: Vec<Uuid> = res.iter().map(|r| r.id).collect();+ assert!(ids.contains(&new_contact_id_1));+ assert!(ids.contains(&new_contact_id_2));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should insert contacts with null names+async fn insert_new_contacts_handles_null_names(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let new_contact_id = Uuid::parse_str("00000000-0000-0000-0000-0000000d0003")?;++ let contacts = vec![ContactPhotoless {+ id: new_contact_id,+ link_id,+ email_address: "[email protected]".to_string(),+ name: None,+ }];++ let res = insert_new_contacts(&pool, &contacts).await?;++ assert_eq!(res.len(), 1);+ assert_eq!(res[0].email_address, "[email protected]");+ assert_eq!(res[0].id, new_contact_id);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should handle conflict by doing nothing and not returning conflicting rows+async fn insert_new_contacts_handles_conflict_on_existing_email(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let new_contact_id = Uuid::parse_str("00000000-0000-0000-0000-0000000d0004")?;++ // Try to insert a contact with an email that already exists+ let contacts = vec![ContactPhotoless {+ id: new_contact_id,+ link_id,+ email_address: "[email protected]".to_string(), // Already exists in fixture+ name: Some("Duplicate Contact".to_string()),+ }];++ let res = insert_new_contacts(&pool, &contacts).await?;++ // Should return empty because ON CONFLICT DO NOTHING doesn't return skipped rows+ assert!(res.is_empty());++ // Verify original contact is unchanged+ let fetch_res =+ fetch_contacts_by_emails(&pool, link_id, &["[email protected]".to_string()]).await?;+ assert_eq!(fetch_res.len(), 1);+ // Should still have the original ID+ let original_id = Uuid::parse_str("00000000-0000-0000-0000-0000000c0001")?;+ assert_eq!(fetch_res[0].id, original_id);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should insert new contacts and skip existing ones in a mixed batch+async fn insert_new_contacts_mixed_new_and_existing(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let new_contact_id = Uuid::parse_str("00000000-0000-0000-0000-0000000d0005")?;+ let conflict_contact_id = Uuid::parse_str("00000000-0000-0000-0000-0000000d0006")?;++ let contacts = vec![+ ContactPhotoless {+ id: new_contact_id,+ link_id,+ email_address: "[email protected]".to_string(),+ name: Some("Brand New Contact".to_string()),+ },+ ContactPhotoless {+ id: conflict_contact_id,+ link_id,+ email_address: "[email protected]".to_string(), // Already exists+ name: Some("Should Be Skipped".to_string()),+ },+ ];++ let res = insert_new_contacts(&pool, &contacts).await?;++ // Only the new contact should be returned+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].email_address, "[email protected]");+ assert_eq!(res[0].id, new_contact_id);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should return empty when inserting empty contacts slice+async fn insert_new_contacts_handles_empty_input(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let contacts: Vec<ContactPhotoless> = vec![];++ let res = insert_new_contacts(&pool, &contacts).await?;++ assert!(res.is_empty());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should handle empty emails slice in fetch+async fn fetch_contacts_by_emails_handles_empty_input(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let emails: Vec<String> = vec![];++ let res = fetch_contacts_by_emails(&pool, link_id, &emails).await?;++ assert!(res.is_empty());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("upsert_message_contacts"))+)]+// should allow same email for different link_ids+async fn insert_new_contacts_allows_same_email_different_links(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_a_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let link_b_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001b")?;+ let new_contact_id_a = Uuid::parse_str("00000000-0000-0000-0000-0000000d0007")?;+ let new_contact_id_b = Uuid::parse_str("00000000-0000-0000-0000-0000000d0008")?;++ // Insert same email for Link A+ let contacts_a = vec![ContactPhotoless {+ id: new_contact_id_a,+ link_id: link_a_id,+ email_address: "[email protected]".to_string(),+ name: Some("Contact for Link A".to_string()),+ }];++ let res_a = insert_new_contacts(&pool, &contacts_a).await?;+ assert_eq!(res_a.len(), 1);++ // Insert same email for Link B+ let contacts_b = vec![ContactPhotoless {+ id: new_contact_id_b,+ link_id: link_b_id,+ email_address: "[email protected]".to_string(),+ name: Some("Contact for Link B".to_string()),+ }];++ let res_b = insert_new_contacts(&pool, &contacts_b).await?;+ assert_eq!(res_b.len(), 1);++ // Both should exist with different IDs+ assert_eq!(res_a[0].id, new_contact_id_a);+ assert_eq!(res_b[0].id, new_contact_id_b);++ Ok(())+}diff --git a/rust/cloud-storage/email_db_client/src/messages/insert.rs b/rust/cloud-storage/email_db_client/src/messages/insert.rsindex 05d2b317bb..61d46db148 100644--- a/rust/cloud-storage/email_db_client/src/messages/insert.rs+++ b/rust/cloud-storage/email_db_client/src/messages/insert.rs@@ -224,25 +224,16 @@ pub async fn insert_message_to_send(thread_id: Uuid,from_contact_id: Option<Uuid>,is_draft: bool,+ // recipients need to be inserted ahead of time outside the tx, as they are shared+ // across messages and can cause deadlocks if inserted within.+ recipients: UpsertedRecipients,) -> anyhow::Result<()> {let message_db_id = service_message.db_id.unwrap_or_else(macro_uuid::generate_uuid_v7);- // Generate and insert recipients for message before sending.- // This ensures recipients are accessible to the frontend before Gmail sync message arrives with- // complete message details.- let addresses = addresses_from_message(service_message);-let db_message_to_send = map_message_to_send_to_db(service_message, message_db_id, thread_id);- let recipients = contacts::upsert_message::parse_and_upsert_message_contacts(- &mut *tx,- db_message_to_send.link_id,- addresses,- )- .await?;-// Insert the message into the databasesqlx::query!(r#"diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs b/rust/cloud-storage/email_service/src/api/email/drafts/create.rsindex 9e8e5881de..a25a9b21a5 100644--- a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs+++ b/rust/cloud-storage/email_service/src/api/email/drafts/create.rs@@ -4,10 +4,13 @@ use axum::extract::State;use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::{Extension, Json};+use email_db_client::contacts::upsert_message::parse_and_upsert_message_contacts;use email_db_client::messages::insert::insert_message_to_send;+use email_db_client::parse::service_to_db::addresses_from_message;use email_db_client::user_history::upsert_user_history;use model::response::ErrorResponse;use model::user::UserContext;+use models_email::email::db::address::UpsertedRecipients;use models_email::service::link::Link;use models_email::service::{message, thread};use sqlx::types::chrono::{DateTime, Utc};@@ -96,9 +99,16 @@ pub async fn handler(let from_email = link.email_address.0.as_ref();+ // Parse and upsert contacts before starting the transaction to avoid deadlocks.+ // Contacts are shared across messages so they must be inserted outside the transaction.+ let addresses = addresses_from_message(&draft);+ let recipients = parse_and_upsert_message_contacts(&ctx.db, link.id, addresses)+ .await+ .map_err(CreateDraftError::InsertError)?;+let mut tx = ctx.db.begin().await?;- let result = insert_draft(&mut tx, &mut draft, from_email).await;+ let result = insert_draft(&mut tx, &mut draft, from_email, recipients).await;match result {Ok(_) => {@@ -114,11 +124,12 @@ pub async fn handler(}}-#[tracing::instrument(skip(tx), err)]+#[tracing::instrument(skip(tx, recipients), err)]async fn insert_draft(tx: &mut sqlx::PgConnection,draft: &mut message::MessageToSend,from_email: &str,+ recipients: UpsertedRecipients,) -> anyhow::Result<()> {let link_id = draft.link_id;let now: DateTime<Utc> = Utc::now();@@ -151,7 +162,7 @@ async fn insert_draft(let from_email_id =email_db_client::contacts::get::fetch_id_by_email(tx, link_id, from_email).await?;- insert_message_to_send(tx, draft, thread_db_id, from_email_id, true).await?;+ insert_message_to_send(tx, draft, thread_db_id, from_email_id, true, recipients).await?;upsert_user_history(tx, link_id, thread_db_id).await?;diff --git a/rust/cloud-storage/email_service/src/api/email/messages/send.rs b/rust/cloud-storage/email_service/src/api/email/messages/send.rsindex f25febdcd0..a7d4963d8e 100644--- a/rust/cloud-storage/email_service/src/api/email/messages/send.rs+++ b/rust/cloud-storage/email_service/src/api/email/messages/send.rs@@ -7,10 +7,13 @@ use axum::response::{IntoResponse, Response};use axum::{Extension, Json};use base64::Engine;use base64::engine::general_purpose::URL_SAFE_NO_PAD;+use email_db_client::contacts::upsert_message::parse_and_upsert_message_contacts;use email_db_client::messages::insert::insert_message_to_send;+use email_db_client::parse::service_to_db::addresses_from_message;use email_service::util::gmail::send;use model::response::ErrorResponse;use model::user::UserContext;+use models_email::email::db::address::UpsertedRecipients;use models_email::email::service::address::ContactInfo;use models_email::email::service::{message, thread};use models_email::service::link::Link;@@ -175,10 +178,23 @@ pub async fn send_handler().await?;+ // Parse and upsert contacts before starting the transaction to avoid deadlocks.+ // Contacts are shared across messages so they must be inserted outside the transaction.+ let addresses = addresses_from_message(&message_to_send);+ let recipients = parse_and_upsert_message_contacts(&ctx.db, link.id, addresses)+ .await+ .context("Failed to upsert message contacts")?;+let mut tx = ctx.db.begin().await?;- let result =- insert_sent_message(&mut tx, &mut message_to_send, from_contact, before_send_ts).await;+ let result = insert_sent_message(+ &mut tx,+ &mut message_to_send,+ from_contact,+ before_send_ts,+ recipients,+ )+ .await;match result {Ok(_) => {@@ -224,6 +240,7 @@ async fn insert_sent_message(message_to_send: &mut message::MessageToSend,from_contact: ContactInfo,before_send_ts: DateTime<Utc>,+ recipients: UpsertedRecipients,) -> anyhow::Result<()> {let mut thread_db_id = message_to_send.thread_db_id;let thread_provider_id = message_to_send.provider_thread_id.clone();@@ -284,6 +301,7 @@ async fn insert_sent_message(thread_db_id.unwrap(),from_email_id,false,+ recipients,).await.context("unable to insert message to send")?;