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(email-service): sync email contacts to contacts service (#266)

Evan Hutnik76d041c99776
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.ts
index ac1357740f..732e967754 100644
--- a/infra/stacks/email-service/index.ts
+++ b/infra/stacks/email-service/index.ts
@@ -170,6 +170,23 @@ const insightContextQueueName: pulumi.Output<string> = insightServiceStack
.getOutput('contextQueueName')
.apply((name) => name as string);
+// Retrieve name of queue used Contacts Service
+const contactsServiceStack: pulumi.StackReference = new pulumi.StackReference(
+ 'contacts-service-stack',
+ {
+ name: `macro-inc/contacts-service/${stack}`,
+ }
+);
+
+const contactsQueueName: pulumi.Output<string> = contactsServiceStack
+ .getOutput('contactsQueueName')
+ .apply((arn) => arn as string);
+
+// Get ARN to allow sending messages to contacts Queue
+const contactsQueueArn: pulumi.Output<string> = contactsServiceStack
+ .getOutput('contactsQueueArn')
+ .apply((arn) => arn as string);
+
const MACRO_API_TOKENS = getMacroApiToken();
const cfKeyPair = new tls.PrivateKey(`cf-dist-email-key-pair-${stack}`, {
@@ -200,6 +217,7 @@ const queueArns = [
insightContextQueueArn,
backfillQueueArn,
sfsUploaderQueueArn,
+ contactsQueueArn,
];
const emailService = new EmailService('email-service', {
@@ -351,6 +369,10 @@ const emailService = new EmailService('email-service', {
name: 'CLOUDFRONT_SIGNER_PRIVATE_KEY',
value: pulumi.interpolate`${CLOUDFRONT_PRIVATE_KEY}`,
},
+ {
+ name: 'CONTACTS_QUEUE',
+ value: pulumi.interpolate`${contactsQueueName}`,
+ },
],
});
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 1680d51156..f2080a92a0 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2818,6 +2818,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
+ "email_utils",
"futures",
"macro_db_migrator",
"macro_uuid",
@@ -2887,6 +2888,7 @@ dependencies = [
"ego-tree",
"email",
"email_db_client",
+ "email_utils",
"frecency",
"futures",
"gmail_client",
@@ -2970,6 +2972,10 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "email_utils"
+version = "0.1.0"
+
[[package]]
name = "email_validator"
version = "0.1.0"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index dfae9b9f96..3aaa6ccf23 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -32,6 +32,7 @@ members = [
"email_service",
"email_service_client",
"email_suppression_handler",
+ "email_utils",
"email_validator",
"experiment_service",
"frecency",
diff --git a/rust/cloud-storage/contacts_db_client/migrations/20251120181854_fix_check.sql b/rust/cloud-storage/contacts_db_client/migrations/20251120181854_fix_check.sql
new file mode 100644
index 0000000000..f0ba761588
--- /dev/null
+++ b/rust/cloud-storage/contacts_db_client/migrations/20251120181854_fix_check.sql
@@ -0,0 +1,6 @@
+-- Drop the existing CHECK constraint
+ALTER TABLE connections DROP CONSTRAINT connections_check;
+
+-- Add the new CHECK constraint with binary collation
+ALTER TABLE connections ADD CONSTRAINT connections_check
+ CHECK (user1 <= user2 COLLATE "C");
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-bcbaaa06fffa75a82e66030d42e2aaa89d56232566edc15d9e9b819b9b02aea9.json b/rust/cloud-storage/email_db_client/.sqlx/query-bcbaaa06fffa75a82e66030d42e2aaa89d56232566edc15d9e9b819b9b02aea9.json
new file mode 100644
index 0000000000..ed20c30bb8
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-bcbaaa06fffa75a82e66030d42e2aaa89d56232566edc15d9e9b819b9b02aea9.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT\n c.email_address as \"email_address!\"\n FROM\n email_messages m\n JOIN\n email_message_recipients mr ON m.id = mr.message_id\n JOIN\n email_contacts c ON mr.contact_id = c.id\n WHERE\n m.link_id = $1\n AND m.is_sent = TRUE\n AND mr.contact_id IS NOT NULL\n ORDER BY\n c.email_address\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "email_address!",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "bcbaaa06fffa75a82e66030d42e2aaa89d56232566edc15d9e9b819b9b02aea9"
+}
diff --git a/rust/cloud-storage/email_db_client/Cargo.toml b/rust/cloud-storage/email_db_client/Cargo.toml
index c9256ba5b6..57dcae0566 100644
--- a/rust/cloud-storage/email_db_client/Cargo.toml
+++ b/rust/cloud-storage/email_db_client/Cargo.toml
@@ -7,6 +7,7 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true }
+email_utils = { path = "../email_utils"}
futures = { workspace = true }
macro_uuid = { path = "../macro_uuid" }
models_email = { path = "../models_email" }
diff --git a/rust/cloud-storage/email_db_client/src/contacts/get.rs b/rust/cloud-storage/email_db_client/src/contacts/get.rs
index 44e90ee88f..0f795232e4 100644
--- a/rust/cloud-storage/email_db_client/src/contacts/get.rs
+++ b/rust/cloud-storage/email_db_client/src/contacts/get.rs
@@ -329,6 +329,42 @@ pub async fn fetch_contacts_by_link_id(
Ok(db_contacts.into_iter().map(Into::into).collect())
}
+/// returns all non-generic email addresses the passed link has sent emails to.
+#[tracing::instrument(skip(pool))]
+pub async fn fetch_contacts_emails_by_link_id(
+ pool: &PgPool,
+ link_id: Uuid,
+) -> anyhow::Result<Vec<String>> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT DISTINCT
+ c.email_address as "email_address!"
+ FROM
+ email_messages m
+ JOIN
+ email_message_recipients mr ON m.id = mr.message_id
+ JOIN
+ email_contacts c ON mr.contact_id = c.id
+ WHERE
+ m.link_id = $1
+ AND m.is_sent = TRUE
+ AND mr.contact_id IS NOT NULL
+ ORDER BY
+ c.email_address
+ "#,
+ link_id
+ )
+ .fetch_all(pool)
+ .await
+ .context("Failed to fetch contacts for link ID")?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| row.email_address)
+ .filter(|e| !email_utils::is_generic_email(e))
+ .collect())
+}
+
/// Fetches contacts who sent messages in the specified threads, organized by thread ID
/// Contacts are ordered chronologically by message creation time
#[tracing::instrument(skip(executor), err)]
diff --git a/rust/cloud-storage/email_db_client/src/contacts/normalize.rs b/rust/cloud-storage/email_db_client/src/contacts/normalize.rs
index 024c7aaedd..dbfe8902a5 100644
--- a/rust/cloud-storage/email_db_client/src/contacts/normalize.rs
+++ b/rust/cloud-storage/email_db_client/src/contacts/normalize.rs
@@ -3,7 +3,7 @@ use once_cell::sync::Lazy;
use regex::Regex;
pub fn normalize_contact(contact: ContactPhotoless) -> ContactPhotoless {
- let normalized_name = if is_generic_email(&contact.email_address) {
+ let normalized_name = if email_utils::is_generic_email(&contact.email_address) {
None
} else {
contact
@@ -20,175 +20,6 @@ pub fn normalize_contact(contact: ContactPhotoless) -> ContactPhotoless {
}
}
-/// Checks if an email address is likely a generic/automated system email
-///
-/// This function identifies common patterns in email addresses that typically
-/// indicate automated senders rather than individual users.
-fn is_generic_email(email: &str) -> bool {
- let email_lower = email.to_lowercase();
-
- // Common automated email prefixes
- let automated_prefixes = [
- "reply",
- "noreply",
- "no-reply",
- "do-not-reply",
- "donotreply",
- "auto",
- "automated",
- "alert",
- "alerts",
- "notification",
- "notifications",
- "info",
- "information",
- "news",
- "newsletter",
- "updates",
- "support",
- "help",
- "helpdesk",
- "service",
- "services",
- "system",
- "admin",
- "administrator",
- "account",
- "accounts",
- "billing",
- "contact",
- "team",
- "no_reply",
- "do_not_reply",
- "mailer",
- "mail",
- "postmaster",
- "robot",
- "confirm",
- "confirmation",
- "verify",
- "verification",
- "security",
- "secure",
- "webmaster",
- "customercare",
- "customer-care",
- "customer.care",
- "customerservice",
- "customer-service",
- "customer.service",
- "feedback",
- "hello",
- "hi",
- "welcome",
- "marketing",
- "careers",
- "jobs",
- "applications",
- "receipts",
- "receipt",
- "order",
- "orders",
- "shipping",
- "delivery",
- "track",
- "tracking",
- "sales",
- "dev",
- "developer",
- "api",
- "test",
- "testing",
- "noreply-",
- "no-reply-",
- "no.reply.",
- "donotreply-",
- "do-not-reply-",
- "do.not.reply.",
- ];
-
- // Check if email starts with any of the automated prefixes
- // We check specifically for prefix@ pattern to avoid matching personal emails
- // that might contain these words elsewhere
- for prefix in automated_prefixes {
- if email_lower.starts_with(prefix)
- && (email_lower.contains(&format!("{}@", prefix))
- || email_lower.contains(&format!("{}-@", prefix))
- || email_lower.contains(&format!("{}.@", prefix))
- || email_lower.contains(&format!("{}+@", prefix))
- || email_lower.contains(&format!("{}=@", prefix))
- || email_lower.contains(&format!("{}_@", prefix)))
- {
- return true;
- }
- }
-
- // Check for common patterns for system accounts
- if email_lower.contains("@")
- && (email_lower.contains("noreply")
- || email_lower.contains("no-reply")
- || email_lower.contains("no.reply")
- || email_lower.contains("do-not-reply")
- || email_lower.contains("donotreply")
- || email_lower.contains("system")
- || email_lower.contains("notification")
- || email_lower.contains("automated")
- || email_lower.contains("no_reply")
- || email_lower.contains("do_not_reply"))
- {
- return true;
- }
-
- // Check for specific domains or addresses that typically send automated emails
- let system_domains = [
- "@sendgrid.net",
- "@mailchimp.com",
- "@sendgrid.com",
- "@amazonses.com",
- "@email.amazonses.com",
- "@bounce.amazonses.com",
- "@sparkpost.com",
- "@mailgun.org",
- "@mg.mailgun.org",
- "@postman.com",
- "@salesforce.com",
- "@salesforceiq.com",
- "@hubspot.com",
- "@marketo.com",
- "@mailjet.com",
- "@sendgrid.net",
- "@constant.com",
- "@constantcontact.com",
- ];
-
- for domain in system_domains {
- if email_lower.ends_with(domain) {
- return true;
- }
- }
-
- // Check common automated email patterns where @ is preceded by numbers or codes
- if let Some(at_pos) = email_lower.find('@') {
- let local_part = &email_lower[0..at_pos];
-
- // Check if local part consists only of numbers or contains certain patterns
- if local_part
- .chars()
- .all(|c| c.is_numeric() || c == '.' || c == '-' || c == '_')
- && local_part.chars().any(|c| c.is_numeric())
- {
- return true;
- }
-
- // Check for common notification-type IDs
- if local_part.starts_with("id") && local_part.chars().skip(2).all(|c| c.is_numeric()) {
- return true;
- }
- }
-
- false
-}
-
/// Removes service suffixes from a contact name and normalizes spaces
///
/// This function detects and removes:
@@ -222,67 +53,6 @@ fn remove_name_suffix(name: &str) -> String {
SPECIFIC_SUFFIX_PATTERN.replace(&name, "").to_string()
}
-#[cfg(test)]
-mod tests {
- use crate::contacts::normalize::is_generic_email;
-
- #[test]
- fn test_is_generic_email() {
- // Test original "reply" pattern
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
-
- // Test additional common system email prefixes
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
-
- // Test with dot and hyphen variants
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
-
- // Test with service provider domains
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
-
- // Test with numeric and code patterns
- assert!(is_generic_email("[email protected]"));
- assert!(is_generic_email("[email protected]"));
-
- // Test non-automated emails (should return false)
- assert!(!is_generic_email("[email protected]"));
- assert!(!is_generic_email("[email protected]"));
- assert!(!is_generic_email("[email protected]"));
- assert!(!is_generic_email("[email protected]"));
- assert!(!is_generic_email("[email protected]")); // Contains "reply" but not as a prefix/pattern
- assert!(!is_generic_email("[email protected]")); // Contains "support" but not as a pattern
- assert!(!is_generic_email("[email protected]")); // Contains "information" but not as a pattern
- }
-}
-
#[test]
fn test_remove_name_suffix() {
// Test "via X" pattern (without parentheses)
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index ed691b868a..56458cdea6 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -9,6 +9,10 @@ version = "0.1.0"
name = "email_service"
path = "src/main.rs"
+[[bin]]
+name = "backfill_contacts"
+path = "src/bin/backfill_contacts/backfill_contacts.rs"
+
[[bin]]
name = "backfill_gmail_attachments"
path = "src/bin/backfill_gmail_attachments/backfill_gmail_attachments.rs"
@@ -22,6 +26,7 @@ disable_attachment_upload = []
disable_connection_gateway = []
disable_gmail_webhook_auth = []
disable_sfs_map = []
+disable_contacts_sync = []
local_queue = []
[dependencies]
@@ -40,6 +45,7 @@ document_storage_service_client = { path = "../document_storage_service_client"
ego-tree = { workspace = true }
email = { path = "../email", features = ["axum"] }
email_db_client = { path = "../email_db_client" }
+email_utils = { path = "../email_utils"}
frecency = { path = "../frecency", features = ["postgres"] }
futures = { workspace = true }
gmail_client = { path = "../gmail_client" }
@@ -80,7 +86,7 @@ sha2 = { workspace = true }
sqlx = { workspace = true }
sqlx-core = { workspace = true }
sqs_client = { path = "../sqs_client", default-features = false, features = [
-
+ "contacts",
"email",
"gmail",
"insight_context",
diff --git a/rust/cloud-storage/email_service/justfile b/rust/cloud-storage/email_service/justfile
index 561fb9eaa1..6b4368dba3 100644
--- a/rust/cloud-storage/email_service/justfile
+++ b/rust/cloud-storage/email_service/justfile
@@ -40,6 +40,8 @@ create-queues:
--attributes FifoQueue=true,ContentBasedDeduplication=true
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
--queue-name sfs-uploader-queue --attributes VisibilityTimeout=60
+ AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
+ --queue-name contacts-queue
purge-queues:
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
@@ -56,6 +58,8 @@ purge-queues:
--queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/insight-service-queue-dev.fifo
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
--queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/sfs-uploader-queue
+ AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
+ --queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/contacts-queue
create-bucket:
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 s3 mb \
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_contacts/README.md b/rust/cloud-storage/email_service/src/bin/backfill_contacts/README.md
new file mode 100644
index 0000000000..cbdcbd3066
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_contacts/README.md
@@ -0,0 +1,18 @@
+# Backfill Contacts Script
+
+This binary is used to backfill a user's email contacts into contacts_service.
+
+Specifically, it creates contacts for any email the user has previously sent an email to.
+
+## Required Environment Variables
+
+| Variable | Description | Required |
+|------------------|-------------------------------------------------------------|----------|
+| `DATABASE_URL` | The connection string for the PostgreSQL database | Yes |
+| `MACRO_IDS` | The Macro IDs of the user accounts to backfill contacts for | Yes |
+| `CONTACTS_QUEUE` | URL of queue to put messages on for contacts_service | Yes |
+
+## Setup
+
+1. Ensure all required environment variables are set
+2. Run the binary using cargo
\ No newline at end of file
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_contacts/backfill_contacts.rs b/rust/cloud-storage/email_service/src/bin/backfill_contacts/backfill_contacts.rs
new file mode 100644
index 0000000000..4a4e1db838
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_contacts/backfill_contacts.rs
@@ -0,0 +1,57 @@
+mod config;
+mod process;
+
+use anyhow::Context;
+use macro_entrypoint::MacroEntrypoint;
+use sqlx::postgres::PgPoolOptions;
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ println!("Loading configuration...");
+ MacroEntrypoint::default().init();
+ let config = config::Config::from_env().context("Failed to load configuration")?;
+
+ println!("Connecting to the database...");
+ let db_pool = PgPoolOptions::new()
+ .min_connections(5)
+ .max_connections(60)
+ .connect(&config.database_url)
+ .await
+ .context("Could not connect to db")?;
+
+ let macro_ids: Vec<String> = config
+ .macro_ids
+ .split(',')
+ .map(|id| id.trim().to_string())
+ .collect();
+
+ let aws_config = aws_config::defaults(aws_config::BehaviorVersion::latest())
+ .region("us-east-1")
+ .load()
+ .await;
+
+ let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
+ .contacts_queue(&config.contacts_queue);
+
+ println!("Processing {} macro IDs: {:?}", macro_ids.len(), macro_ids);
+
+ for (index, macro_id) in macro_ids.iter().enumerate() {
+ println!(
+ "\n=== Processing macro ID {} ({}/{}) ===",
+ macro_id,
+ index + 1,
+ macro_ids.len()
+ );
+
+ match process::process_macro_id(&db_pool, &sqs_client, macro_id).await {
+ Ok(()) => {
+ println!("Completed processing for {}.", macro_id);
+ }
+ Err(e) => {
+ panic!("Failed to process macro ID {}: {:?}", macro_id, e);
+ }
+ }
+ }
+
+ println!("\n=== All macro IDs processed ===");
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_contacts/config.rs b/rust/cloud-storage/email_service/src/bin/backfill_contacts/config.rs
new file mode 100644
index 0000000000..7a61b51741
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_contacts/config.rs
@@ -0,0 +1,20 @@
+use anyhow::Context;
+
+/// Holds all configuration loaded from environment variables.
+pub struct Config {
+ pub macro_ids: String,
+ pub database_url: String,
+ pub contacts_queue: String,
+}
+
+impl Config {
+ /// Creates a new `Config` instance by reading from environment variables.
+ /// Returns an error if any required variable is not set.
+ pub fn from_env() -> anyhow::Result<Self> {
+ Ok(Self {
+ macro_ids: std::env::var("MACRO_IDS").context("MACRO_IDS not set")?, // Changed
+ database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
+ contacts_queue: std::env::var("CONTACTS_QUEUE").context("CONTACTS_QUEUE not set")?,
+ })
+ }
+}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs b/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs
new file mode 100644
index 0000000000..5af7ade479
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs
@@ -0,0 +1,42 @@
+use model::contacts::ConnectionsMessage;
+use sqs_client::SQS;
+
+/// Process contacts for a single macro ID
+pub async fn process_macro_id(
+ db_pool: &sqlx::PgPool,
+ sqs_client: &SQS,
+ macro_id: &str,
+) -> anyhow::Result<()> {
+ let link = email_db_client::links::get::fetch_link_by_macro_id(db_pool, macro_id)
+ .await?
+ .unwrap();
+ let contact_emails =
+ email_db_client::contacts::get::fetch_contacts_emails_by_link_id(db_pool, link.id).await?;
+ println!(
+ "Found {} contacts to process for {}.",
+ contact_emails.len(),
+ macro_id
+ );
+
+ if contact_emails.is_empty() {
+ println!("No contacts found for {}.", macro_id);
+ return Ok(());
+ }
+
+ let mut users = vec![link.macro_id.clone()];
+ users.extend(
+ contact_emails
+ .iter()
+ .map(|email| format!("macro|{}", email)),
+ );
+
+ let connections = (1..users.len()).map(|i| (0, i)).collect::<Vec<_>>();
+
+ let connections_message = ConnectionsMessage { users, connections };
+
+ sqs_client
+ .enqueue_contacts_add_connection(connections_message)
+ .await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/config.rs b/rust/cloud-storage/email_service/src/config.rs
index ce09b18cc9..9c02451353 100644
--- a/rust/cloud-storage/email_service/src/config.rs
+++ b/rust/cloud-storage/email_service/src/config.rs
@@ -43,6 +43,9 @@ pub struct Config {
/// The SQS queue name for the sfs_uploader process
pub sfs_uploader_queue: String,
+ /// The SQS queue name for contacts service
+ pub contacts_queue: String,
+
/// The SQS bucket for storing attachments
pub attachment_bucket: String,
@@ -147,6 +150,9 @@ impl Config {
let backfill_queue =
std::env::var("BACKFILL_QUEUE").context("BACKFILL_QUEUE must be provided")?;
+ let contacts_queue =
+ std::env::var("CONTACTS_QUEUE").context("CONTACTS_QUEUE must be provided")?;
+
let sfs_uploader_queue =
std::env::var("SFS_UPLOADER_QUEUE").context("SFS_UPLOADER_QUEUE must be provided")?;
@@ -244,6 +250,7 @@ impl Config {
notification_queue,
backfill_queue,
sfs_uploader_queue,
+ contacts_queue,
attachment_bucket,
notifications_enabled,
queue_max_messages,
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index ae3f769ebe..a68945645a 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -101,7 +101,8 @@ async fn main() -> anyhow::Result<()> {
.insight_context_queue(&config.insight_context_queue)
.email_backfill_queue(&config.backfill_queue)
.email_scheduled_queue(&config.email_scheduled_queue)
- .sfs_uploader_queue(&config.sfs_uploader_queue);
+ .sfs_uploader_queue(&config.sfs_uploader_queue)
+ .contacts_queue(&config.contacts_queue);
let macro_notify_client = macro_notify::MacroNotify::new(
config.notification_queue.clone(),
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.rs
index 9d6c02ebd7..20c91058c7 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
@@ -1,5 +1,6 @@
use crate::pubsub::context::PubSubContext;
use crate::util::backfill::backfill_insights::backfill_email_insights;
+use model::contacts::ConnectionsMessage;
use model::insight_context::email_insights::BackfillEmailInsightsFilter;
use models_email::service::attachment::AttachmentUploadMetadata;
use models_email::service::backfill::{
@@ -109,29 +110,97 @@ async fn handle_job_completed(
})
})?;
+ handle_attachment_upload(ctx, link, job_id).await?;
+ handle_contacts_sync(ctx, link).await?;
+
+ Ok(())
+}
+
+#[tracing::instrument(skip(ctx))]
+async fn handle_attachment_upload(
+ ctx: &PubSubContext,
+ link: &Link,
+ job_id: Uuid,
+) -> Result<(), ProcessingError> {
// temporarily only enabling for macro emails for testing
- if link.macro_id.ends_with("@macro.com") && !cfg!(feature = "disable_attachment_upload") {
- let attachments =
- email_db_client::attachments::provider::upload::fetch_job_attachments_for_backfill(
- &ctx.db, link.id,
- )
+ if !link.macro_id.ends_with("@macro.com") || cfg!(feature = "disable_attachment_upload") {
+ return Ok(());
+ }
+
+ let attachments =
+ email_db_client::attachments::provider::upload::fetch_job_attachments_for_backfill(
+ &ctx.db, link.id,
+ )
+ .await
+ .map_err(|e| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch job attachment backfill metadata".to_string()),
+ })
+ })?;
+
+ tracing::info!(
+ "Found {} condition 5 attachments to backfill for job {}",
+ attachments.len(),
+ job_id
+ );
+
+ send_attachment_backfill_messages(ctx, link.id, job_id, attachments).await
+}
+
+#[tracing::instrument(skip(ctx))]
+async fn handle_contacts_sync(ctx: &PubSubContext, link: &Link) -> Result<(), ProcessingError> {
+ if cfg!(feature = "disable_contacts_sync") {
+ return Ok(());
+ }
+
+ let email_addresses =
+ email_db_client::contacts::get::fetch_contacts_emails_by_link_id(&ctx.db, link.id)
.await
.map_err(|e| {
ProcessingError::NonRetryable(DetailedError {
reason: FailureReason::DatabaseQueryFailed,
- source: e
- .context("Failed to fetch job attachment backfill metadata".to_string()),
+ source: e.context("Failed to fetch contact email addresses".to_string()),
})
})?;
- tracing::info!(
- "Found {} condition 5 attachments to backfill for job {}",
- attachments.len(),
- job_id
- );
+ let length = email_addresses.len();
- send_attachment_backfill_messages(ctx, link.id, job_id, attachments).await?;
- }
+ tracing::info!(
+ "Populating {} contacts for macro email {}",
+ length,
+ link.macro_id
+ );
+
+ let mut users = vec![link.macro_id.clone()];
+ users.extend(
+ email_addresses
+ .iter()
+ .map(|email| format!("macro|{}", email)),
+ );
+
+ let connections = (1..users.len()).map(|i| (0, i)).collect::<Vec<_>>();
+
+ let connections_message = ConnectionsMessage { users, connections };
+
+ ctx.sqs_client
+ .enqueue_contacts_add_connection(connections_message)
+ .await
+ .map_err(|e| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::SqsEnqueueFailed,
+ source: e.context(format!(
+ "Failed to enqueue contacts message for {}",
+ email_addresses.join(", ")
+ )),
+ })
+ })?;
+
+ tracing::info!(
+ "Successfully populated {} contacts for macro email {}",
+ length,
+ link.macro_id
+ );
Ok(())
}
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
index 68ba521829..a14d653893 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
@@ -7,6 +7,7 @@ use email_db_client::threads;
use email_db_client::threads::get::get_outbound_threads_by_thread_ids;
use futures::future::join_all;
use insight_service_client::InsightContextProvider;
+use model::contacts::ConnectionsMessage;
use model::insight_context::email_insights::{
EMAIL_INSIGHT_PROVIDER_SOURCE_NAME, EmailInfo, GenerateEmailInsightContext, NewMessagePayload,
NewMessagesPayload,
@@ -69,6 +70,19 @@ pub async fn upsert_message(
// will always exist because we just fetched it
let provider_thread_id = message.provider_thread_id.clone().unwrap();
+ let is_sent = message.is_sent;
+
+ // deduped list of all non-generic emails the message was sent to
+ let recipient_emails = message
+ .cc
+ .iter()
+ .map(|c| c.email.clone())
+ .chain(message.to.iter().map(|t| t.email.clone()))
+ .collect::<std::collections::HashSet<_>>()
+ .into_iter()
+ .filter(|e| !email_utils::is_generic_email(e))
+ .collect::<Vec<_>>();
+
// determine if message's thread already exists in the database
let thread_provider_to_db_map = threads::get::get_threads_by_link_id_and_provider_ids(
&ctx.db,
@@ -130,44 +144,131 @@ pub async fn upsert_message(
// notify downstream services of new messages
notify_for_new_messages(ctx, link, new_message_provider_ids).await?;
+ handle_attachment_upload(
+ ctx,
+ &gmail_access_token,
+ link,
+ payload,
+ message_attachment_count,
+ )
+ .await?;
+
+ handle_contacts_sync(
+ ctx,
+ link,
+ &recipient_emails,
+ is_sent,
+ &payload.provider_message_id,
+ )
+ .await?;
+
+ Ok(())
+}
+
+#[tracing::instrument(skip(ctx, gmail_access_token))]
+async fn handle_attachment_upload(
+ ctx: &PubSubContext,
+ gmail_access_token: &str,
+ link: &link::Link,
+ payload: &UpsertMessagePayload,
+ message_attachment_count: usize,
+) -> result::Result<(), ProcessingError> {
// temporarily only for macro emails, for testing purposes
- if link.macro_id.ends_with("@macro.com")
- && !cfg!(feature = "disable_attachment_upload")
- && message_attachment_count > 0
+ if !link.macro_id.ends_with("@macro.com")
+ || cfg!(feature = "disable_attachment_upload")
+ || message_attachment_count == 0
{
- // upload attachments to Macro
- let attachments = email_db_client::attachments::provider::upload::fetch_insertable_attachments_for_new_email(
+ return Ok(());
+ }
+
+ // upload attachments to Macro
+ let attachments =
+ email_db_client::attachments::provider::upload::fetch_insertable_attachments_for_new_email(
&ctx.db,
- &payload.provider_message_id
- ).await
- .map_err(|e| {
- ProcessingError::Retryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to fetch attachments to insert".to_string()),
- })
- })?;
+ &payload.provider_message_id,
+ )
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch attachments to insert".to_string()),
+ })
+ })?;
- if !attachments.is_empty() {
- tracing::info!(
- "Uploading attachments ({:?}) to Macro for new email",
- attachments
- .iter()
- .map(|a| a.attachment_db_id)
- .collect::<Vec<_>>()
- );
- }
+ if !attachments.is_empty() {
+ tracing::info!(
+ "Uploading attachments ({:?}) to Macro for new email",
+ attachments
+ .iter()
+ .map(|a| a.attachment_db_id)
+ .collect::<Vec<_>>()
+ );
+ }
- for attachment in attachments {
- // keep processing if it fails, best effort
- if let Err(e) = upload_attachment(ctx, &gmail_access_token, link, &attachment).await {
- tracing::error!("Failed to upload attachment to Macro: {e}");
- }
+ for attachment in attachments {
+ // keep processing if it fails, best effort
+ if let Err(e) = upload_attachment(ctx, gmail_access_token, link, &attachment).await {
+ tracing::error!("Failed to upload attachment to Macro: {e}");
}
}
Ok(())
}
+#[tracing::instrument(skip(ctx, link, recipient_emails))]
+async fn handle_contacts_sync(
+ ctx: &PubSubContext,
+ link: &link::Link,
+ recipient_emails: &[String],
+ is_sent: bool,
+ provider_message_id: &str,
+) -> result::Result<(), ProcessingError> {
+ // if the user sent the message, upsert contacts for its recipients in contacts-service.
+ if !cfg!(feature = "disable_contacts_sync") || !is_sent || recipient_emails.is_empty() {
+ return Ok(());
+ }
+
+ tracing::info!(
+ "Upserting contacts {:?} for new sent message with id {}",
+ recipient_emails,
+ provider_message_id
+ );
+
+ // Create users list starting with the sender, then all recipients
+ let mut users = vec![link.macro_id.clone()];
+ users.extend(
+ recipient_emails
+ .iter()
+ .map(|email| format!("macro|{}", email)),
+ );
+
+ // Create connections from sender (index 0) to each recipient
+ let connections = (1..users.len()).map(|i| (0, i)).collect::<Vec<_>>();
+
+ let connections_message = ConnectionsMessage { users, connections };
+
+ ctx.sqs_client
+ .enqueue_contacts_add_connection(connections_message)
+ .await
+ .map_err(|e| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::SqsEnqueueFailed,
+ source: e.context(format!(
+ "Failed to enqueue contacts message for {}",
+ link.macro_id
+ )),
+ })
+ })?;
+
+ tracing::info!(
+ "Successfully upserted contacts {:?} for new sent message with id {}",
+ recipient_emails,
+ provider_message_id
+ );
+
+ Ok(())
+}
+
/// Sends new message context to the insight service
async fn generate_email_insights_for_new_messages(
ctx: &PubSubContext,
diff --git a/rust/cloud-storage/email_utils/Cargo.toml b/rust/cloud-storage/email_utils/Cargo.toml
new file mode 100644
index 0000000000..ece607dce1
--- /dev/null
+++ b/rust/cloud-storage/email_utils/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "email_utils"
+version = "0.1.0"
+publish = false
+edition = "2024"
+
+[dependencies]
diff --git a/rust/cloud-storage/email_utils/src/lib.rs b/rust/cloud-storage/email_utils/src/lib.rs
new file mode 100644
index 0000000000..38074b91d7
--- /dev/null
+++ b/rust/cloud-storage/email_utils/src/lib.rs
@@ -0,0 +1,178 @@
+#[cfg(test)]
+mod tests;
+
+/// Checks if an email address is likely a generic/automated system email
+///
+/// This function identifies common patterns in email addresses that typically
+/// indicate automated senders rather than individual users.
+pub fn is_generic_email(email: &str) -> bool {
+ let email_lower = email.to_lowercase();
+
+ // if it's really long, it's probably an autogenerated email address
+ if email.len() > 50 {
+ return true;
+ }
+
+ // Common automated email prefixes
+ let automated_prefixes = [
+ "reply",
+ "noreply",
+ "no-reply",
+ "do-not-reply",
+ "donotreply",
+ "auto",
+ "automated",
+ "alert",
+ "alerts",
+ "notification",
+ "notifications",
+ "info",
+ "information",
+ "news",
+ "newsletter",
+ "updates",
+ "support",
+ "help",
+ "helpdesk",
+ "service",
+ "services",
+ "system",
+ "admin",
+ "administrator",
+ "account",
+ "accounts",
+ "billing",
+ "contact",
+ "team",
+ "no_reply",
+ "do_not_reply",
+ "mailer",
+ "mail",
+ "postmaster",
+ "robot",
+ "confirm",
+ "confirmation",
+ "verify",
+ "verification",
+ "security",
+ "secure",
+ "webmaster",
+ "customercare",
+ "customer-care",
+ "customer.care",
+ "customerservice",
+ "customer-service",
+ "customer.service",
+ "feedback",
+ "hello",
+ "hi",
+ "welcome",
+ "marketing",
+ "careers",
+ "jobs",
+ "applications",
+ "receipts",
+ "receipt",
+ "order",
+ "orders",
+ "shipping",
+ "delivery",
+ "track",
+ "tracking",
+ "sales",
+ "dev",
+ "developer",
+ "api",
+ "test",
+ "testing",
+ "noreply-",
+ "no-reply-",
+ "no.reply.",
+ "donotreply-",
+ "do-not-reply-",
+ "do.not.reply.",
+ ];
+
+ // Check if email starts with any of the automated prefixes
+ // We check specifically for prefix@ pattern to avoid matching personal emails
+ // that might contain these words elsewhere
+ for prefix in automated_prefixes {
+ if email_lower.starts_with(prefix)
+ && (email_lower.contains(&format!("{}@", prefix))
+ || email_lower.contains(&format!("{}-", prefix))
+ || email_lower.contains(&format!("{}.", prefix))
+ || email_lower.contains(&format!("{}+", prefix))
+ || email_lower.contains(&format!("{}=", prefix))
+ || email_lower.contains(&format!("{}_", prefix)))
+ {
+ return true;
+ }
+ }
+
+ // Check for common patterns for system accounts
+ if email_lower.contains("@")
+ && (email_lower.contains("noreply")
+ || email_lower.contains("no-reply")
+ || email_lower.contains("no.reply")
+ || email_lower.contains("no_reply")
+ || email_lower.contains("do-not-reply")
+ || email_lower.contains("donotreply")
+ || email_lower.contains("system")
+ || email_lower.contains("notification")
+ || email_lower.contains("automated")
+ || email_lower.contains("unsub")
+ || email_lower.contains("support")
+ || email_lower.contains("do_not_reply"))
+ {
+ return true;
+ }
+
+ // Check for specific domains or addresses that typically send automated emails
+ let system_domains = [
+ "@sendgrid.net",
+ "@mailchimp.com",
+ "@sendgrid.com",
+ "@amazonses.com",
+ "@email.amazonses.com",
+ "@bounce.amazonses.com",
+ "@sparkpost.com",
+ "@mailgun.org",
+ "@mg.mailgun.org",
+ "@postman.com",
+ "@salesforce.com",
+ "@salesforceiq.com",
+ "@hubspot.com",
+ "@marketo.com",
+ "@mailjet.com",
+ "@sendgrid.net",
+ "@constant.com",
+ "@constantcontact.com",
+ ];
+
+ for domain in system_domains {
+ if email_lower.ends_with(domain) {
+ return true;
+ }
+ }
+
+ // Check common automated email patterns where @ is preceded by numbers or codes
+ if let Some(at_pos) = email_lower.find('@') {
+ let local_part = &email_lower[0..at_pos];
+
+ // Check if local part consists only of numbers or contains certain patterns
+ if local_part
+ .chars()
+ .all(|c| c.is_numeric() || c == '.' || c == '-' || c == '_')
+ && local_part.chars().any(|c| c.is_numeric())
+ {
+ return true;
+ }
+
+ // Check for common notification-type IDs
+ if local_part.starts_with("id") && local_part.chars().skip(2).all(|c| c.is_numeric()) {
+ return true;
+ }
+ }
+
+ false
+}
diff --git a/rust/cloud-storage/email_utils/src/tests.rs b/rust/cloud-storage/email_utils/src/tests.rs
new file mode 100644
index 0000000000..2100c47579
--- /dev/null
+++ b/rust/cloud-storage/email_utils/src/tests.rs
@@ -0,0 +1,62 @@
+use crate::is_generic_email;
+
+#[test]
+fn test_is_generic_email() {
+ // Test original "reply" pattern
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email(
+ "32.mrtvirzriftueqkpj53gqqkinfzdiukcifng4s3bfvlvo4krnfpxqzdpinjxo2keonat2pi=@unsubscribe2.customer.io"
+ ));
+ assert!(is_generic_email(
+ "reply-107199600-1441644_html-1962870046-524000040-59174@e.atlassian.com"
+ ));
+
+ // Test additional common system email prefixes
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+
+ // Test with dot and hyphen variants
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+
+ // Test with service provider domains
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+
+ // Test with numeric and code patterns
+ assert!(is_generic_email("[email protected]"));
+ assert!(is_generic_email("[email protected]"));
+
+ // Test non-automated emails (should return false)
+ assert!(!is_generic_email("[email protected]"));
+ assert!(!is_generic_email("[email protected]"));
+ assert!(!is_generic_email("[email protected]"));
+ assert!(!is_generic_email("[email protected]"));
+ assert!(!is_generic_email("[email protected]")); // Contains "reply" but not as a prefix/pattern
+ assert!(!is_generic_email("[email protected]")); // Contains "information" but not as a pattern
+}
diff --git a/rust/cloud-storage/sqs_client/src/contacts.rs b/rust/cloud-storage/sqs_client/src/contacts.rs
index cd341e0b13..80c8fde4e6 100644
--- a/rust/cloud-storage/sqs_client/src/contacts.rs
+++ b/rust/cloud-storage/sqs_client/src/contacts.rs
@@ -1,5 +1,7 @@
use crate::SQS;
-use model::contacts::{AddParticipantsMessageBody, CreateGroupMessageBody, Message};
+use model::contacts::{
+ AddParticipantsMessageBody, ConnectionsMessage, CreateGroupMessageBody, Message,
+};
impl SQS {
pub fn contacts_queue(mut self, contacts_queue: &str) -> Self {
@@ -45,6 +47,22 @@ impl SQS {
Err(anyhow::anyhow!("contacts_queue is not configured"))
}
+
+ #[tracing::instrument(skip(self))]
+ pub async fn enqueue_contacts_add_connection(
+ &self,
+ connections_message: ConnectionsMessage,
+ ) -> anyhow::Result<()> {
+ if let Some(contacts_queue) = &self.contacts_queue {
+ return enqueue_contacts_add_connection(
+ &self.inner,
+ contacts_queue,
+ connections_message,
+ )
+ .await;
+ }
+ Err(anyhow::anyhow!("contacts_queue is not configured"))
+ }
}
#[tracing::instrument(skip(sqs_client, participants))]
@@ -92,3 +110,20 @@ pub async fn enqueue_contacts_add_participants(
.await?;
Ok(())
}
+
+#[tracing::instrument(skip(sqs_client, queue_url))]
+pub async fn enqueue_contacts_add_connection(
+ sqs_client: &aws_sdk_sqs::Client,
+ queue_url: &str,
+ connections_message: ConnectionsMessage,
+) -> anyhow::Result<()> {
+ let message = Message::AddConnection(connections_message);
+ let message_str = serde_json::to_string(&message)?;
+ sqs_client
+ .send_message()
+ .queue_url(queue_url)
+ .message_body(message_str)
+ .send()
+ .await?;
+ Ok(())
+}