Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(search): re-index OpenSearch when contact names change (#2600)

gbirmanff616b8a430b
diff --git a/infra/stacks/search-processing-service/Pulumi.dev.yaml b/infra/stacks/search-processing-service/Pulumi.dev.yaml
index 447c26a0c0..fa0a4d3789 100644
--- a/infra/stacks/search-processing-service/Pulumi.dev.yaml
+++ b/infra/stacks/search-processing-service/Pulumi.dev.yaml
@@ -1,6 +1,6 @@
config:
aws:region: us-east-1
- search-processing-service:database_url_key: macro-db-readonly-dev
+ search-processing-service:database_url_key: macro-db-dev
search-processing-service:opensearch_password_key: macro-opensearch-password-dev
search-processing-service:internal_auth_key: document-storage-service-auth-key-dev
search-processing-service:sync_service_auth_key: sync-service-key-dev
diff --git a/infra/stacks/search-processing-service/Pulumi.prod.yaml b/infra/stacks/search-processing-service/Pulumi.prod.yaml
index 255dfcd79b..2765ad6159 100644
--- a/infra/stacks/search-processing-service/Pulumi.prod.yaml
+++ b/infra/stacks/search-processing-service/Pulumi.prod.yaml
@@ -1,6 +1,6 @@
config:
aws:region: us-east-1
- search-processing-service:database_url_key: macro-db-readonly-prod
+ search-processing-service:database_url_key: macro-db-prod
search-processing-service:opensearch_password_key: macro-opensearch-password-prod
search-processing-service:internal_auth_key: document-storage-service-auth-key-prod
search-processing-service:sync_service_auth_key: sync-service-key-prod
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-40bfe125ad0bde96466e2a8ed9083c72877347fafb9fbcde0935ac10290b7cb0.json b/rust/cloud-storage/email_db_client/.sqlx/query-40bfe125ad0bde96466e2a8ed9083c72877347fafb9fbcde0935ac10290b7cb0.json
new file mode 100644
index 0000000000..0cbe128b65
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-40bfe125ad0bde96466e2a8ed9083c72877347fafb9fbcde0935ac10290b7cb0.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT m.thread_id as \"thread_id!\"\n FROM email_messages m\n WHERE m.from_contact_id = ANY($1)\n UNION\n SELECT DISTINCT m.thread_id as \"thread_id!\"\n FROM email_messages m\n JOIN email_message_recipients mr ON m.id = mr.message_id\n WHERE mr.contact_id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "thread_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "40bfe125ad0bde96466e2a8ed9083c72877347fafb9fbcde0935ac10290b7cb0"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-5202dbabd4943bf87bcaab8c34b9a5ebb7f76933011fe8607aff109ccf1705a0.json b/rust/cloud-storage/email_db_client/.sqlx/query-5202dbabd4943bf87bcaab8c34b9a5ebb7f76933011fe8607aff109ccf1705a0.json
new file mode 100644
index 0000000000..8b1dd1d4e9
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-5202dbabd4943bf87bcaab8c34b9a5ebb7f76933011fe8607aff109ccf1705a0.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, LOWER(email_address) as \"email_address!\", name\n FROM email_contacts\n WHERE (link_id, LOWER(email_address)) IN (\n SELECT * FROM UNNEST($1::uuid[], $2::varchar[])\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "email_address!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "name",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "VarcharArray"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ true
+ ]
+ },
+ "hash": "5202dbabd4943bf87bcaab8c34b9a5ebb7f76933011fe8607aff109ccf1705a0"
+}
diff --git a/rust/cloud-storage/email_db_client/fixtures/get_thread_ids_by_contact_ids.sql b/rust/cloud-storage/email_db_client/fixtures/get_thread_ids_by_contact_ids.sql
new file mode 100644
index 0000000000..a2f8dd7253
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/fixtures/get_thread_ids_by_contact_ids.sql
@@ -0,0 +1,114 @@
+-- SQL fixture for get_thread_ids_by_contact_ids tests
+
+------------------------------------------------------------
+-- Link
+------------------------------------------------------------
+
+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-000000000901', 'macro|[email protected]', '00000000-0000-0000-0000-000000000901',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+------------------------------------------------------------
+-- Contacts
+------------------------------------------------------------
+
+-- Contact A: will be a sender
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c9001',
+ '00000000-0000-0000-0000-000000000901',
+ 'Sender',
+ NOW(), NOW());
+
+-- Contact B: will be a recipient only
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c9002',
+ '00000000-0000-0000-0000-000000000901',
+ 'Recipient',
+ NOW(), NOW());
+
+-- Contact C: appears in both roles across threads
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c9003',
+ '00000000-0000-0000-0000-000000000901',
+ 'Both Roles',
+ NOW(), NOW());
+
+-- Contact D: orphan, not in any messages
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c9004',
+ '00000000-0000-0000-0000-000000000901',
+ 'Orphan',
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Threads
+------------------------------------------------------------
+
+-- Thread 1
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000009201',
+ '00000000-0000-0000-0000-000000000901',
+ true, false, NOW(), NOW());
+
+-- Thread 2
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000009202',
+ '00000000-0000-0000-0000-000000000901',
+ true, false, NOW(), NOW());
+
+-- Thread 3
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000009203',
+ '00000000-0000-0000-0000-000000000901',
+ true, false, NOW(), NOW());
+
+------------------------------------------------------------
+-- Messages
+------------------------------------------------------------
+
+-- Message 1: in Thread 1, Contact A is sender
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000009501',
+ '00000000-0000-0000-0000-000000009201',
+ '00000000-0000-0000-0000-000000000901',
+ 'provider-msg-9501',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c9001',
+ '2025-01-05 10:00:00 +00:00',
+ false, false, false, false, NOW(), NOW());
+
+-- Message 1 recipients: Contact B is TO
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
+VALUES ('00000000-0000-0000-0000-000000009501', '00000000-0000-0000-0000-0000000c9002', 'TO');
+
+-- Message 2: in Thread 2, Contact C is sender
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000009502',
+ '00000000-0000-0000-0000-000000009202',
+ '00000000-0000-0000-0000-000000000901',
+ 'provider-msg-9502',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c9003',
+ '2025-01-05 11:00:00 +00:00',
+ false, false, false, false, NOW(), NOW());
+
+-- Message 3: in Thread 3, Contact A is sender, Contact C is recipient
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000009503',
+ '00000000-0000-0000-0000-000000009203',
+ '00000000-0000-0000-0000-000000000901',
+ 'provider-msg-9503',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c9001',
+ '2025-01-05 12:00:00 +00:00',
+ false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
+VALUES ('00000000-0000-0000-0000-000000009503', '00000000-0000-0000-0000-0000000c9003', 'TO');
diff --git a/rust/cloud-storage/email_db_client/fixtures/upsert_sync_contacts.sql b/rust/cloud-storage/email_db_client/fixtures/upsert_sync_contacts.sql
new file mode 100644
index 0000000000..a2b9270519
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/fixtures/upsert_sync_contacts.sql
@@ -0,0 +1,37 @@
+-- SQL fixture for upsert_contacts (sync) name change detection tests
+
+------------------------------------------------------------
+-- Link
+------------------------------------------------------------
+
+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-000000000801', 'macro|[email protected]', '00000000-0000-0000-0000-000000000801',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+------------------------------------------------------------
+-- Pre-existing contacts
+------------------------------------------------------------
+
+-- Contact with a name (will test name change)
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c8001',
+ '00000000-0000-0000-0000-000000000801',
+ 'Old Alice',
+ NOW(), NOW());
+
+-- Contact with no name (will test null -> name)
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c8002',
+ '00000000-0000-0000-0000-000000000801',
+ NULL,
+ NOW(), NOW());
+
+-- Contact whose name won't change
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c8003',
+ '00000000-0000-0000-0000-000000000801',
+ 'Charlie',
+ NOW(), NOW());
diff --git a/rust/cloud-storage/email_db_client/src/contacts/upsert_sync.rs b/rust/cloud-storage/email_db_client/src/contacts/upsert_sync.rs
index ec40b6c676..5b546f9d28 100644
--- a/rust/cloud-storage/email_db_client/src/contacts/upsert_sync.rs
+++ b/rust/cloud-storage/email_db_client/src/contacts/upsert_sync.rs
@@ -1,14 +1,23 @@
+#[cfg(test)]
+mod test;
+
use crate::parse::service_to_db::map_new_contact_to_db;
use models_email::db;
use models_email::service::contact::Contact;
use sqlx::PgPool;
+use sqlx::types::Uuid;
+use std::collections::HashMap;
/// Upsert methods used by contact sync process, triggered by initial backfill and daily cron.
-/// Upserts multiple contacts into the contacts table
+/// Upserts multiple contacts into the contacts table.
+/// Returns (rows_affected, contact_ids_with_name_changes).
#[tracing::instrument(skip(pool, contacts), err)]
-pub async fn upsert_contacts(pool: &PgPool, contacts: &[Contact]) -> anyhow::Result<u64> {
+pub async fn upsert_contacts(
+ pool: &PgPool,
+ contacts: &[Contact],
+) -> anyhow::Result<(u64, Vec<Uuid>)> {
if contacts.is_empty() {
- return Ok(0);
+ return Ok((0, Vec::new()));
}
let db_contacts: Vec<db::contact::Contact> =
@@ -18,7 +27,7 @@ pub async fn upsert_contacts(pool: &PgPool, contacts: &[Contact]) -> anyhow::Res
let mut ids = Vec::new();
let mut link_ids = Vec::new();
let mut email_addresses = Vec::new();
- let mut names = Vec::new();
+ let mut names: Vec<Option<String>> = Vec::new();
let mut original_photo_urls = Vec::new();
let mut sfs_photo_urls = Vec::new();
@@ -38,8 +47,28 @@ pub async fn upsert_contacts(pool: &PgPool, contacts: &[Contact]) -> anyhow::Res
if link_ids.is_empty() {
tracing::warn!("No contacts with valid email addresses to insert");
- return Ok(0);
+ return Ok((0, Vec::new()));
}
+
+ let existing_contacts = sqlx::query!(
+ r#"
+ SELECT id, LOWER(email_address) as "email_address!", name
+ FROM email_contacts
+ WHERE (link_id, LOWER(email_address)) IN (
+ SELECT * FROM UNNEST($1::uuid[], $2::varchar[])
+ )
+ "#,
+ &link_ids,
+ &email_addresses
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let old_names: HashMap<String, (Uuid, Option<String>)> = existing_contacts
+ .into_iter()
+ .map(|row| (row.email_address, (row.id, row.name)))
+ .collect();
+
let result = sqlx::query!(
r#"
INSERT INTO email_contacts (id, link_id, email_address, name, original_photo_url, sfs_photo_url, updated_at)
@@ -62,5 +91,20 @@ pub async fn upsert_contacts(pool: &PgPool, contacts: &[Contact]) -> anyhow::Res
.execute(pool)
.await?;
- Ok(result.rows_affected())
+ let changed_contact_ids: Vec<Uuid> = email_addresses
+ .iter()
+ .zip(names.iter())
+ .filter_map(|(email, new_name)| {
+ let (id, old_name) = old_names.get(email.as_str())?;
+ // Mirror the COALESCE(EXCLUDED.name, email_contacts.name) logic
+ let effective_new: Option<&String> = new_name.as_ref().or(old_name.as_ref());
+ if effective_new != old_name.as_ref() {
+ Some(*id)
+ } else {
+ None
+ }
+ })
+ .collect();
+
+ Ok((result.rows_affected(), changed_contact_ids))
}
diff --git a/rust/cloud-storage/email_db_client/src/contacts/upsert_sync/test.rs b/rust/cloud-storage/email_db_client/src/contacts/upsert_sync/test.rs
new file mode 100644
index 0000000000..f357d82041
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/contacts/upsert_sync/test.rs
@@ -0,0 +1,163 @@
+use super::*;
+use anyhow::Result;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+
+const LINK_ID: &str = "00000000-0000-0000-0000-000000000801";
+const ALICE_CONTACT_ID: &str = "00000000-0000-0000-0000-0000000c8001";
+const BOB_CONTACT_ID: &str = "00000000-0000-0000-0000-0000000c8002";
+fn make_contact(link_id: Uuid, email: &str, name: Option<&str>) -> Contact {
+ Contact {
+ id: macro_uuid::generate_uuid_v7(),
+ link_id,
+ email_address: Some(email.to_string()),
+ name: name.map(|n| n.to_string()),
+ original_photo_url: None,
+ sfs_photo_url: None,
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("upsert_sync_contacts"))
+)]
+async fn detects_name_change(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str(LINK_ID)?;
+ let alice_id = Uuid::parse_str(ALICE_CONTACT_ID)?;
+
+ // Alice: "Old Alice" -> "New Alice"
+ let contacts = vec![make_contact(
+ link_id,
+ Some("New Alice"),
+ )];
+
+ let (rows, changed) = upsert_contacts(&pool, &contacts).await?;
+ assert!(rows > 0);
+ assert_eq!(changed.len(), 1);
+ assert_eq!(changed[0], alice_id);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("upsert_sync_contacts"))
+)]
+async fn detects_null_to_name(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str(LINK_ID)?;
+ let bob_id = Uuid::parse_str(BOB_CONTACT_ID)?;
+
+ // Bob: NULL -> "Bob Named"
+ let contacts = vec![make_contact(link_id, "[email protected]", Some("Bob Named"))];
+
+ let (_, changed) = upsert_contacts(&pool, &contacts).await?;
+ assert_eq!(changed.len(), 1);
+ assert_eq!(changed[0], bob_id);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("upsert_sync_contacts"))
+)]
+async fn no_change_when_name_is_same(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str(LINK_ID)?;
+
+ // Charlie: "Charlie" -> "Charlie" (no change)
+ let contacts = vec![make_contact(
+ link_id,
+ Some("Charlie"),
+ )];
+
+ let (_, changed) = upsert_contacts(&pool, &contacts).await?;
+ assert!(changed.is_empty());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("upsert_sync_contacts"))
+)]
+async fn no_change_when_new_name_is_null_and_old_exists(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str(LINK_ID)?;
+
+ // Alice: "Old Alice" -> NULL (COALESCE keeps "Old Alice")
+ let contacts = vec![make_contact(link_id, "[email protected]", None)];
+
+ let (_, changed) = upsert_contacts(&pool, &contacts).await?;
+ assert!(changed.is_empty());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("upsert_sync_contacts"))
+)]
+async fn new_contact_not_in_changed_ids(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str(LINK_ID)?;
+
+ // Brand new contact, doesn't exist yet
+ let contacts = vec![make_contact(
+ link_id,
+ Some("New Person"),
+ )];
+
+ let (rows, changed) = upsert_contacts(&pool, &contacts).await?;
+ assert_eq!(rows, 1);
+ assert!(changed.is_empty());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("upsert_sync_contacts"))
+)]
+async fn mixed_batch_only_returns_changed(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str(LINK_ID)?;
+ let alice_id = Uuid::parse_str(ALICE_CONTACT_ID)?;
+ let bob_id = Uuid::parse_str(BOB_CONTACT_ID)?;
+
+ let contacts = vec![
+ make_contact(link_id, "[email protected]", Some("New Alice")), // name changed
+ make_contact(link_id, "[email protected]", Some("Bob Named")), // null -> name
+ make_contact(link_id, "[email protected]", Some("Charlie")), // unchanged
+ make_contact(link_id, "[email protected]", Some("New")), // new contact
+ ];
+
+ let (_, changed) = upsert_contacts(&pool, &contacts).await?;
+ assert_eq!(changed.len(), 2);
+ assert!(changed.contains(&alice_id));
+ assert!(changed.contains(&bob_id));
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn empty_input_returns_empty(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let (rows, changed) = upsert_contacts(&pool, &[]).await?;
+ assert_eq!(rows, 0);
+ assert!(changed.is_empty());
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_db_client/src/threads/get.rs b/rust/cloud-storage/email_db_client/src/threads/get.rs
index a04e4fd569..d142c6c4f9 100644
--- a/rust/cloud-storage/email_db_client/src/threads/get.rs
+++ b/rust/cloud-storage/email_db_client/src/threads/get.rs
@@ -334,6 +334,35 @@ pub async fn get_all_thread_ids_paginated(
Ok(result)
}
+/// Returns distinct thread IDs where any of the given contact IDs appear as a sender or recipient.
+#[tracing::instrument(skip(pool), err)]
+pub async fn get_thread_ids_by_contact_ids(
+ pool: &PgPool,
+ contact_ids: &[Uuid],
+) -> anyhow::Result<Vec<Uuid>> {
+ if contact_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let thread_ids = sqlx::query_scalar!(
+ r#"
+ SELECT DISTINCT m.thread_id as "thread_id!"
+ FROM email_messages m
+ WHERE m.from_contact_id = ANY($1)
+ UNION
+ SELECT DISTINCT m.thread_id as "thread_id!"
+ FROM email_messages m
+ JOIN email_message_recipients mr ON m.id = mr.message_id
+ WHERE mr.contact_id = ANY($1)
+ "#,
+ contact_ids
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(thread_ids)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -488,4 +517,110 @@ mod tests {
Ok(())
}
+
+ #[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_thread_ids_by_contact_ids"))
+ )]
+ async fn test_get_thread_ids_by_sender_contact(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ // Contact A is sender in Thread 1 and Thread 3
+ let sender_id = uuid!("00000000-0000-0000-0000-0000000c9001");
+ let result = get_thread_ids_by_contact_ids(&pool, &[sender_id]).await?;
+
+ assert_eq!(result.len(), 2);
+ assert!(result.contains(&uuid!("00000000-0000-0000-0000-000000009201")));
+ assert!(result.contains(&uuid!("00000000-0000-0000-0000-000000009203")));
+
+ Ok(())
+ }
+
+ #[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_thread_ids_by_contact_ids"))
+ )]
+ async fn test_get_thread_ids_by_recipient_contact(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ // Contact B is a recipient in Thread 1 only
+ let recipient_id = uuid!("00000000-0000-0000-0000-0000000c9002");
+ let result = get_thread_ids_by_contact_ids(&pool, &[recipient_id]).await?;
+
+ assert_eq!(result.len(), 1);
+ assert!(result.contains(&uuid!("00000000-0000-0000-0000-000000009201")));
+
+ Ok(())
+ }
+
+ #[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_thread_ids_by_contact_ids"))
+ )]
+ async fn test_get_thread_ids_by_contact_in_both_roles(
+ pool: Pool<Postgres>,
+ ) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ // Contact C is sender in Thread 2 and recipient in Thread 3
+ let both_id = uuid!("00000000-0000-0000-0000-0000000c9003");
+ let result = get_thread_ids_by_contact_ids(&pool, &[both_id]).await?;
+
+ assert_eq!(result.len(), 2);
+ assert!(result.contains(&uuid!("00000000-0000-0000-0000-000000009202")));
+ assert!(result.contains(&uuid!("00000000-0000-0000-0000-000000009203")));
+
+ Ok(())
+ }
+
+ #[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_thread_ids_by_contact_ids"))
+ )]
+ async fn test_get_thread_ids_by_orphan_contact(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ // Contact D has no messages
+ let orphan_id = uuid!("00000000-0000-0000-0000-0000000c9004");
+ let result = get_thread_ids_by_contact_ids(&pool, &[orphan_id]).await?;
+
+ assert!(result.is_empty());
+
+ Ok(())
+ }
+
+ #[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_thread_ids_by_contact_ids"))
+ )]
+ async fn test_get_thread_ids_by_multiple_contacts_dedupes(
+ pool: Pool<Postgres>,
+ ) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ // Contact A (sender in Thread 1,3) + Contact C (sender in Thread 2, recipient in Thread 3)
+ // Thread 3 should only appear once
+ let contact_a = uuid!("00000000-0000-0000-0000-0000000c9001");
+ let contact_c = uuid!("00000000-0000-0000-0000-0000000c9003");
+ let result = get_thread_ids_by_contact_ids(&pool, &[contact_a, contact_c]).await?;
+
+ assert_eq!(result.len(), 3);
+ assert!(result.contains(&uuid!("00000000-0000-0000-0000-000000009201")));
+ assert!(result.contains(&uuid!("00000000-0000-0000-0000-000000009202")));
+ assert!(result.contains(&uuid!("00000000-0000-0000-0000-000000009203")));
+
+ Ok(())
+ }
+
+ #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+ async fn test_get_thread_ids_by_contact_ids_empty_input(
+ pool: Pool<Postgres>,
+ ) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let result = get_thread_ids_by_contact_ids(&pool, &[]).await?;
+ assert!(result.is_empty());
+
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/email_service/src/util/sync_contacts.rs b/rust/cloud-storage/email_service/src/util/sync_contacts.rs
index 8fa1fb03b3..e9913436d1 100644
--- a/rust/cloud-storage/email_service/src/util/sync_contacts.rs
+++ b/rust/cloud-storage/email_service/src/util/sync_contacts.rs
@@ -8,6 +8,8 @@ use models_email::service::pubsub::SFSUploaderMessage;
use models_email::service::sync_token::SyncTokens;
use sqlx::PgPool;
use sqs_client::SQS;
+use sqs_client::search::SearchQueueMessage;
+use sqs_client::search::email::EmailThreadBatchMessage;
use std::collections::HashSet;
use std::time::Instant;
@@ -158,13 +160,14 @@ async fn process_and_store_contacts(
let db_start = Instant::now();
// Insert the processed contacts into the database without sfs_urls
- email_db_client::contacts::upsert_sync::upsert_contacts(db, &contacts)
- .await
- .map_err(|e| {
- let error_message = "Unable to upsert contacts into DB";
- tracing::error!(error = ?e, link_id = %link.id, error_message);
- anyhow!(error_message)
- })?;
+ let (_rows_affected, changed_contact_ids) =
+ email_db_client::contacts::upsert_sync::upsert_contacts(db, &contacts)
+ .await
+ .map_err(|e| {
+ let error_message = "Unable to upsert contacts into DB";
+ tracing::error!(error = ?e, link_id = %link.id, error_message);
+ anyhow!(error_message)
+ })?;
tracing::info!(
duration = ?db_start.elapsed(),
@@ -173,6 +176,10 @@ async fn process_and_store_contacts(
"Inserted contacts into DB"
);
+ if !changed_contact_ids.is_empty() {
+ reindex_threads_for_changed_contacts(db, sqs_client, link, &changed_contact_ids).await;
+ }
+
if cfg!(not(feature = "sfs_map")) {
return Ok(());
}
@@ -205,3 +212,57 @@ async fn process_and_store_contacts(
Ok(())
}
+
+const REINDEX_BATCH_SIZE: usize = 50;
+
+#[tracing::instrument(skip(db, sqs_client, link, changed_contact_ids))]
+async fn reindex_threads_for_changed_contacts(
+ db: &PgPool,
+ sqs_client: &SQS,
+ link: &Link,
+ changed_contact_ids: &[uuid::Uuid],
+) {
+ let thread_ids = match email_db_client::threads::get::get_thread_ids_by_contact_ids(
+ db,
+ changed_contact_ids,
+ )
+ .await
+ {
+ Ok(ids) => ids,
+ Err(e) => {
+ tracing::error!(error=?e, link_id=%link.id, "Failed to get thread IDs for changed contacts");
+ return;
+ }
+ };
+
+ if thread_ids.is_empty() {
+ return;
+ }
+
+ let macro_user_id = link.macro_id.to_string();
+
+ tracing::info!(
+ num_threads = thread_ids.len(),
+ num_changed_contacts = changed_contact_ids.len(),
+ link_id = %link.id,
+ "Re-indexing threads for contacts with name changes"
+ );
+
+ let messages: Vec<SearchQueueMessage> = thread_ids
+ .chunks(REINDEX_BATCH_SIZE)
+ .map(|chunk| {
+ SearchQueueMessage::ExtractEmailThreadBatch(EmailThreadBatchMessage {
+ thread_ids: chunk.iter().map(|id| id.to_string()).collect(),
+ macro_user_id: macro_user_id.clone(),
+ index_override: None,
+ })
+ })
+ .collect();
+
+ if let Err(e) = sqs_client
+ .bulk_send_message_to_search_event_queue(messages)
+ .await
+ {
+ tracing::error!(error=?e, link_id=%link.id, "Failed to enqueue search re-index messages for contact name changes");
+ }
+}