Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email-service): Add entity properties for uploaded email attachments (#504)
Evan Hutnikb44ab1a15ed9
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 82a752cb37..5344e95fe1 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3031,6 +3031,7 @@ dependencies = ["models_opensearch","models_pagination","models_permissions",+ "models_properties","redis","reqwest","s3_client",@@ -3046,6 +3047,7 @@ dependencies = ["sqs_worker","static_file_service_client","strum_macros",+ "system_properties","thiserror 2.0.17","tokio","tower 0.5.2",@@ -8621,6 +8623,7 @@ version = "0.1.0"dependencies = ["anyhow","macro_db_migrator",+ "macro_user_id","macro_uuid","models_properties","serde",diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-6e4fcdd716bd4ede49c7bdf7c23518c7f030dabda7317a2f1453cd2617629d58.json b/rust/cloud-storage/email_db_client/.sqlx/query-8a72f7a40f3e48b76158dd067cdff99f4c525078a5bf5a2fe810ee39cbf977d8.jsonsimilarity index 54%rename from rust/cloud-storage/email_db_client/.sqlx/query-6e4fcdd716bd4ede49c7bdf7c23518c7f030dabda7317a2f1453cd2617629d58.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-8a72f7a40f3e48b76158dd067cdff99f4c525078a5bf5a2fe810ee39cbf977d8.jsonindex efbec5c18e..d5d8e6d3bf 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-6e4fcdd716bd4ede49c7bdf7c23518c7f030dabda7317a2f1453cd2617629d58.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-8a72f7a40f3e48b76158dd067cdff99f4c525078a5bf5a2fe810ee39cbf977d8.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n a.id AS attachment_db_id,\n m.provider_id as \"email_provider_id!\",\n a.provider_attachment_id as \"provider_attachment_id!\",\n a.filename as \"filename!\",\n a.mime_type as \"mime_type!\",\n m.internal_date_ts as \"internal_date_ts!\"\n FROM email_attachments a\n JOIN email_messages m ON a.message_id = m.id\n JOIN email_threads t ON m.thread_id = t.id\n WHERE a.id = $1 AND t.link_id = $2\n ",+ "query": "\n SELECT\n a.id AS attachment_db_id,\n m.provider_id as \"email_provider_id!\",\n a.provider_attachment_id as \"provider_attachment_id!\",\n a.filename as \"filename!\",\n a.mime_type as \"mime_type!\",\n m.internal_date_ts as \"internal_date_ts!\",\n m.id as message_db_id,\n m.thread_id as thread_db_id,\n from_contact.email_address as sender_email,\n m.subject as subject\n FROM email_attachments a\n JOIN email_messages m ON a.message_id = m.id\n JOIN email_contacts from_contact ON m.from_contact_id = from_contact.id\n JOIN email_threads t ON m.thread_id = t.id\n WHERE a.id = $1 AND t.link_id = $2\n ","describe": {"columns": [{@@ -32,6 +32,26 @@"ordinal": 5,"name": "internal_date_ts!","type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "message_db_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 7,+ "name": "thread_db_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 8,+ "name": "sender_email",+ "type_info": "Varchar"+ },+ {+ "ordinal": 9,+ "name": "subject",+ "type_info": "Text"}],"parameters": {@@ -46,8 +66,12 @@true,true,true,+ true,+ false,+ false,+ false,true]},- "hash": "6e4fcdd716bd4ede49c7bdf7c23518c7f030dabda7317a2f1453cd2617629d58"+ "hash": "8a72f7a40f3e48b76158dd067cdff99f4c525078a5bf5a2fe810ee39cbf977d8"}diff --git a/rust/cloud-storage/email_db_client/fixtures/fetch_insertable_attachments_for_new_email.sql b/rust/cloud-storage/email_db_client/fixtures/fetch_insertable_attachments_for_new_email.sqlindex ee9a3b488a..936f9151fe 100644--- a/rust/cloud-storage/email_db_client/fixtures/fetch_insertable_attachments_for_new_email.sql+++ b/rust/cloud-storage/email_db_client/fixtures/fetch_insertable_attachments_for_new_email.sql@@ -160,7 +160,7 @@ VALUES ('00000000-0000-0000-0000-0000000e0101','00000000-0000-0000-0000-00000000001a','target-msg-101',TRUE, -- This makes condition 1 true for the thread- NULL,+ '00000000-0000-0000-0000-0000000c0002','2025-01-02 10:00:00 +00:00',true, false, false, false, NOW(), NOW());diff --git a/rust/cloud-storage/email_db_client/fixtures/fetch_thread_attachments_for_backfill.sql b/rust/cloud-storage/email_db_client/fixtures/fetch_thread_attachments_for_backfill.sqlindex f68f7ae7ad..1bc9856309 100644--- a/rust/cloud-storage/email_db_client/fixtures/fetch_thread_attachments_for_backfill.sql+++ b/rust/cloud-storage/email_db_client/fixtures/fetch_thread_attachments_for_backfill.sql@@ -130,7 +130,7 @@ VALUES ('00000000-0000-0000-0000-0000000b0001','00000000-0000-0000-0000-00000000001a','provider-msg-101',TRUE,- NULL,+ '00000000-0000-0000-0000-0000000c0002',NOW(),true,false,@@ -202,7 +202,7 @@ VALUES ('00000000-0000-0000-0000-0000002a0201','00000000-0000-0000-0000-00000000001a','provider-msg-201',FALSE,- NULL,+ '00000000-0000-0000-0000-0000000c0002',NOW(),true,false,diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rsindex 8501f29436..80bdc0b607 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs@@ -29,9 +29,14 @@ pub async fn fetch_thread_attachments_for_backfill(a.provider_attachment_id as provider_attachment_id,a.filename as filename,a.mime_type as mime_type,- m.internal_date_ts as internal_date_ts+ m.internal_date_ts as internal_date_ts,+ m.id as message_db_id,+ m.thread_id as thread_db_id,+ from_contact.email_address as sender_email,+ m.subject as subjectFROM email_attachments aJOIN email_messages m ON a.message_id = m.id+ JOIN email_contacts from_contact ON m.from_contact_id = from_contact.idWHERE m.thread_id = $1-- attachment mime type filters injected below{}@@ -74,6 +79,10 @@ pub async fn fetch_thread_attachments_for_backfill(filename: row.get("filename"),mime_type: row.get("mime_type"),internal_date_ts: row.get("internal_date_ts"),+ message_db_id: row.get("message_db_id"),+ thread_db_id: row.get("thread_db_id"),+ sender_email: row.get("sender_email"),+ subject: row.get("subject"),}).collect();@@ -145,7 +154,11 @@ pub async fn fetch_job_attachments_for_backfill(a.provider_attachment_id as provider_attachment_id,a.filename as filename,a.mime_type as mime_type,- m.internal_date_ts as internal_date_ts+ m.internal_date_ts as internal_date_ts,+ m.id as message_db_id,+ m.thread_id as thread_db_id,+ from_contact.email_address as sender_email,+ m.subject as subjectFROM public.email_attachments aJOIN public.email_messages m ON a.message_id = m.idJOIN public.email_contacts from_contact ON m.from_contact_id = from_contact.id@@ -173,6 +186,10 @@ pub async fn fetch_job_attachments_for_backfill(filename: row.get("filename"),mime_type: row.get("mime_type"),internal_date_ts: row.get("internal_date_ts"),+ message_db_id: row.get("message_db_id"),+ thread_db_id: row.get("thread_db_id"),+ sender_email: row.get("sender_email"),+ subject: row.get("subject"),}).collect();@@ -206,9 +223,14 @@ pub async fn fetch_insertable_attachments_for_new_email(a.provider_attachment_id as provider_attachment_id,a.filename as filename,a.mime_type as mime_type,- m.internal_date_ts as internal_date_ts+ m.internal_date_ts as internal_date_ts,+ m.id as message_db_id,+ m.thread_id as thread_db_id,+ from_contact.email_address as sender_email,+ m.subject as subjectFROM email_attachments aJOIN email_messages m ON a.message_id = m.id+ JOIN email_contacts from_contact ON m.from_contact_id = from_contact.idLEFT JOIN document_email de ON de.email_attachment_id = a.idWHERE m.provider_id = $1-- attachment mime type filters injected below@@ -256,6 +278,10 @@ pub async fn fetch_insertable_attachments_for_new_email(filename: row.get("filename"),mime_type: row.get("mime_type"),internal_date_ts: row.get("internal_date_ts"),+ message_db_id: row.get("message_db_id"),+ thread_db_id: row.get("thread_db_id"),+ sender_email: row.get("sender_email"),+ subject: row.get("subject"),}).collect();@@ -316,9 +342,14 @@ pub async fn fetch_insertable_attachments_for_new_email(a.provider_attachment_id as provider_attachment_id,a.filename as filename,a.mime_type as mime_type,- m.internal_date_ts as internal_date_ts+ m.internal_date_ts as internal_date_ts,+ m.id as message_db_id,+ m.thread_id as thread_db_id,+ from_contact.email_address as sender_email,+ m.subject as subjectFROM public.email_attachments aJOIN public.email_messages m ON a.message_id = m.id+ JOIN public.email_contacts from_contact ON m.from_contact_id = from_contact.idLEFT JOIN public.document_email de ON de.email_attachment_id = a.idWHERE m.provider_id = $1AND de.email_attachment_id IS NULL@@ -349,6 +380,10 @@ pub async fn fetch_insertable_attachments_for_new_email(filename: row.get("filename"),mime_type: row.get("mime_type"),internal_date_ts: row.get("internal_date_ts"),+ message_db_id: row.get("message_db_id"),+ thread_db_id: row.get("thread_db_id"),+ sender_email: row.get("sender_email"),+ subject: row.get("subject"),}).collect();@@ -369,9 +404,14 @@ pub async fn fetch_attachment_upload_metadata_by_id(a.provider_attachment_id as "provider_attachment_id!",a.filename as "filename!",a.mime_type as "mime_type!",- m.internal_date_ts as "internal_date_ts!"+ m.internal_date_ts as "internal_date_ts!",+ m.id as message_db_id,+ m.thread_id as thread_db_id,+ from_contact.email_address as sender_email,+ m.subject as subjectFROM email_attachments aJOIN email_messages m ON a.message_id = m.id+ JOIN email_contacts from_contact ON m.from_contact_id = from_contact.idJOIN email_threads t ON m.thread_id = t.idWHERE a.id = $1 AND t.link_id = $2"#,diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex d34138eb1f..1f23920d4d 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -82,6 +82,7 @@ models_email = { path = "../models_email" }models_opensearch = { path = "../models_opensearch" }models_pagination = { path = "../models_pagination", features = ["axum"] }models_permissions = { path = "../models_permissions" }+models_properties = { path = "../models_properties" }redis = { workspace = true, features = ["cluster-async","tokio-native-tls-comp",@@ -106,6 +107,7 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [sqs_worker = { path = "../sqs_worker" }static_file_service_client = { path = "../static_file_service_client" }strum_macros = { workspace = true }+system_properties = { path = "../system_properties" }thiserror = { workspace = true }tokio = { workspace = true }tower = { workspace = true }diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rsindex 2795ba0481..5a007a0aef 100644--- a/rust/cloud-storage/email_service/src/api/context.rs+++ b/rust/cloud-storage/email_service/src/api/context.rs@@ -8,6 +8,7 @@ use macro_middleware::auth::internal_access::InternalApiSecretKey;use secretsmanager_client::LocalOrRemoteSecret;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;+use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};#[derive(Clone, FromRef)]pub(crate) struct ApiContext {@@ -19,6 +20,7 @@ pub(crate) struct ApiContext {pub s3_client: Arc<s3_client::S3>,pub sfs_client: Arc<StaticFileServiceClient>,pub dss_client: Arc<DocumentStorageServiceClient>,+ pub system_properties_service: Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,pub jwt_args: JwtValidationArgs,pub config: Arc<Config>,pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rsindex 2e27ce7564..897bc9d0a6 100644--- a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs@@ -1,11 +1,13 @@use crate::api::context::ApiContext;-use crate::util::upload_attachment::upload_attachment;+use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};use axum::extract::{Path, State};use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::{Extension, Json};use model::response::ErrorResponse;+use models_email::db::address::EmailRecipientType;use models_email::email::service::link::Link;+use models_email::service::attachment::AttachmentUploadArgs;use strum_macros::AsRefStr;use thiserror::Error;use utoipa::ToSchema;@@ -94,17 +96,37 @@ pub async fn handler(.map_err(GetAttachmentDocumentIdError::DatabaseError)?.ok_or(GetAttachmentDocumentIdError::AttachmentNotFound)?;- let document_id = upload_attachment(- &ctx.redis_client,- &ctx.gmail_client,- &ctx.dss_client,- &gmail_token,- &link,- &attachment_metadata,- false,+ let recipients = email_db_client::contacts::get::fetch_db_recipients(+ &ctx.db,+ attachment_metadata.message_db_id,).await- .map_err(GetAttachmentDocumentIdError::UploadError)?;+ .map_err(GetAttachmentDocumentIdError::DatabaseError)?;++ let recipient_emails: Vec<String> = recipients+ .iter()+ .filter(|(_, recipient_type)| *recipient_type == EmailRecipientType::To)+ .filter_map(|(contact, _)| contact.email_address.clone())+ .collect();++ let attachment_upload_args = AttachmentUploadArgs {+ attachment_metadata,+ recipient_emails,+ backfill: false,+ };++ let ctx_upload = UploadAttachmentContext {+ redis_client: &ctx.redis_client,+ gmail_client: &ctx.gmail_client,+ dss_client: &ctx.dss_client,+ system_properties_service: &ctx.system_properties_service,+ access_token: &gmail_token,+ link: &link,+ };++ let document_id = upload_attachment(ctx_upload, &attachment_upload_args)+ .await+ .map_err(GetAttachmentDocumentIdError::UploadError)?;Ok(Json(GetAttachmentDocumentIDResponse {attachment_id,diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rsindex cebb52540a..bec29ae4b8 100644--- a/rust/cloud-storage/email_service/src/main.rs+++ b/rust/cloud-storage/email_service/src/main.rs@@ -12,6 +12,7 @@ use secretsmanager_client::{LocalOrRemoteSecret, SecretManager};use sqlx::postgres::PgPoolOptions;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;+use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};mod api;mod config;@@ -211,6 +212,10 @@ async fn main() -> anyhow::Result<()> {config.connection_gateway_url.clone(),);+ let system_properties_service = Arc::new(SystemPropertiesServiceImpl::new(+ PgSystemPropertiesRepository::new(db.clone()),+ ));+// process user inbox updates from gmail webhook queue, triggered by update pubsub messages from Googlefor worker in webhook_workers {let db_webhook = db.clone();@@ -222,6 +227,7 @@ async fn main() -> anyhow::Result<()> {let sfs_client_webhook = sfs_client.clone();let connection_gateway_client_webhook = connection_gateway_client.clone();let dss_client_webhook = dss_client.clone();+ let system_properties_service_webhook = system_properties_service.clone();tokio::spawn(async move {pubsub::webhook::worker::run_worker(db_webhook,@@ -234,6 +240,7 @@ async fn main() -> anyhow::Result<()> {sfs_client_webhook,connection_gateway_client_webhook,dss_client_webhook,+ system_properties_service_webhook,config.notifications_enabled,false,)@@ -256,6 +263,7 @@ async fn main() -> anyhow::Result<()> {let sfs_client_webhook = sfs_client.clone();let connection_gateway_client_webhook = connection_gateway_client.clone();let dss_client_webhook = dss_client.clone();+ let system_properties_service_webhook = system_properties_service.clone();tokio::spawn(async move {pubsub::webhook::worker::run_worker(db_webhook,@@ -268,6 +276,7 @@ async fn main() -> anyhow::Result<()> {sfs_client_webhook,connection_gateway_client_webhook,dss_client_webhook,+ system_properties_service_webhook,config.notifications_enabled,true,)@@ -290,6 +299,7 @@ async fn main() -> anyhow::Result<()> {let sfs_client_backfill = sfs_client.clone();let connection_gateway_client_backfill = connection_gateway_client.clone();let dss_client_backfill = dss_client.clone();+ let system_properties_service_backfill = system_properties_service.clone();tokio::spawn(async move {pubsub::backfill::worker::run_worker(db_backfill,@@ -302,6 +312,7 @@ async fn main() -> anyhow::Result<()> {sfs_client_backfill,connection_gateway_client_backfill,dss_client_backfill,+ system_properties_service_backfill,config.notifications_enabled,).await;@@ -380,6 +391,7 @@ async fn main() -> anyhow::Result<()> {gmail_client: Arc::new(gmail_client),s3_client: Arc::new(s3_client),dss_client: Arc::new(dss_client),+ system_properties_service,jwt_args,internal_auth_key: LocalOrRemoteSecret::Local(internal_auth_key),email_service: EmailPreviewState::new(EmailServiceImpl::new(diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rsindex 479211b64a..87835bde13 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs@@ -1,5 +1,5 @@use crate::pubsub::context::PubSubContext;-use crate::util::upload_attachment::upload_attachment;+use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};use models_email::service::backfill::BackfillAttachmentPayload;use models_email::service::link;use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};@@ -16,26 +16,35 @@ pub async fn backfill_attachment(p: &BackfillAttachmentPayload,) -> Result<(), ProcessingError> {// Check if a document for this attachment already exists before uploading.- if attachment_document_exists(ctx, link.id, p.metadata.attachment_db_id).await? {+ if attachment_document_exists(+ ctx,+ link.id,+ p.metadata.attachment_metadata.attachment_db_id,+ )+ .await?+ {return Ok(());}- upload_attachment(- &ctx.redis_client,- &ctx.gmail_client,- &ctx.dss_client,+ let ctx_upload = UploadAttachmentContext {+ redis_client: &ctx.redis_client,+ gmail_client: &ctx.gmail_client,+ dss_client: &ctx.dss_client,+ system_properties_service: &ctx.system_properties_service,access_token,link,- &p.metadata,- true,- )- .await- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::GmailApiFailed,- source: e.context("Failed to fetch attachment data from Gmail"),- })- })?;+ };++ let attachment_args = p.metadata.clone();++ upload_attachment(ctx_upload, &attachment_args)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::GmailApiFailed,+ source: e.context("Failed to fetch attachment data from Gmail"),+ })+ })?;Ok(())}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rsindex 68c6966d71..4186571388 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs@@ -82,7 +82,7 @@ pub async fn handle_retryable_error(}BackfillOperation::BackfillAttachment(p) => {tracing::debug!(- attachment_db_id = %p.metadata.attachment_db_id,+ attachment_db_id = %p.metadata.attachment_metadata.attachment_db_id,"Retryable error backfilling attachment")}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rsindex 6a5e22e944..652ef4552d 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@@ -2,7 +2,8 @@ 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::db::address::EmailRecipientType;+use models_email::service::attachment::{AttachmentUploadArgs, AttachmentUploadMetadata};use models_email::service::backfill::{BackfillAttachmentPayload, BackfillJobStatus, BackfillMessagePayload, BackfillOperation,BackfillPubsubMessage, UpdateMetadataPayload,@@ -139,13 +140,17 @@ async fn handle_attachment_upload(})})?;- tracing::info!(- "Found {} condition 5 attachments to backfill for job {}",- attachments.len(),- job_id- );+ if !attachments.is_empty() {+ tracing::debug!(+ "Found {} condition 5 attachments to backfill for job {}",+ attachments.len(),+ job_id+ );- send_attachment_backfill_messages(ctx, link.id, job_id, attachments).await+ send_attachment_backfill_messages(ctx, link.id, job_id, attachments).await?;+ }++ Ok(())}#[tracing::instrument(skip(ctx))]@@ -249,15 +254,16 @@ async fn handle_thread_completed(.context("Failed to fetch thread attachment backfill metadata".to_string()),})})?;+if !attachments.is_empty() {- tracing::info!(+ tracing::debug!("Found {} attachments to backfill for thread {}",attachments.len(),p.thread_db_id);- }- send_attachment_backfill_messages(ctx, link.id, job_id, attachments).await?;+ send_attachment_backfill_messages(ctx, link.id, job_id, attachments).await?;+ }}Ok(())@@ -271,16 +277,46 @@ async fn send_attachment_backfill_messages(job_id: Uuid,attachments: Vec<AttachmentUploadMetadata>,) -> Result<(), ProcessingError> {+ if attachments.is_empty() {+ return Ok(());+ }++ let message_ids = attachments+ .iter()+ .map(|a| a.message_db_id)+ .collect::<Vec<_>>();++ let message_recipients =+ email_db_client::contacts::get::fetch_db_recipients_in_bulk(&ctx.db, &message_ids)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context(+ "Failed to fetch db recipients for thread attachment backfill".to_string(),+ ),+ })+ })?;+for attachment in attachments {+ // get the email addresses of the recipients of the message+ let recipient_emails: Vec<String> = message_recipients+ .get(&attachment.message_db_id)+ .map(|v| v.as_slice())+ .unwrap_or(&[])+ .iter()+ .filter(|(_, recipient_type)| *recipient_type == EmailRecipientType::To)+ .filter_map(|(contact, _)| contact.email_address.clone())+ .collect();++ let attachment_upload_args = AttachmentUploadArgs {+ recipient_emails,+ attachment_metadata: attachment,+ backfill: true,+ };+let new_payload = BackfillAttachmentPayload {- metadata: AttachmentUploadMetadata {- attachment_db_id: attachment.attachment_db_id,- email_provider_id: attachment.email_provider_id,- provider_attachment_id: attachment.provider_attachment_id,- mime_type: attachment.mime_type,- filename: attachment.filename,- internal_date_ts: attachment.internal_date_ts,- },+ metadata: attachment_upload_args,};let ps_message = BackfillPubsubMessage {diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rsindex 9d4f663c67..f1fec07252 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs@@ -7,6 +7,8 @@ use document_storage_service_client::DocumentStorageServiceClient;use futures::StreamExt;use macro_notify::MacroNotifyClient;use static_file_service_client::StaticFileServiceClient;+use std::sync::Arc;+use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};/// method that ingests sqs messages and calls the process function for each#[expect(clippy::too_many_arguments, reason = "too annoying to fix right now")]@@ -21,6 +23,7 @@ pub async fn run_worker(sfs_client: StaticFileServiceClient,connection_gateway_client: ConnectionGatewayClient,dss_client: DocumentStorageServiceClient,+ system_properties_service: Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,notifications_enabled: bool,) {let ctx = PubSubContext {@@ -34,6 +37,7 @@ pub async fn run_worker(sfs_client,connection_gateway_client,dss_client,+ system_properties_service,notifications_enabled,retry_worker: false,};diff --git a/rust/cloud-storage/email_service/src/pubsub/context.rs b/rust/cloud-storage/email_service/src/pubsub/context.rsindex a79d5dd13e..f236598265 100644--- a/rust/cloud-storage/email_service/src/pubsub/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/context.rs@@ -6,6 +6,8 @@ use gmail_client::GmailClient;use macro_notify::MacroNotifyClient;use sqlx::PgPool;use static_file_service_client::StaticFileServiceClient;+use std::sync::Arc;+use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};#[derive(Clone)]pub struct PubSubContext {@@ -19,6 +21,7 @@ pub struct PubSubContext {pub sfs_client: StaticFileServiceClient,pub connection_gateway_client: ConnectionGatewayClient,pub dss_client: DocumentStorageServiceClient,+ pub system_properties_service: Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,pub notifications_enabled: bool,pub retry_worker: bool,}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.rsindex 0cdea7ac64..11477eed61 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@@ -3,7 +3,7 @@ use crate::pubsub::util::cg_refresh_email;use crate::pubsub::webhook::process;use crate::pubsub::webhook::process::check_gmail_rate_limit_webhook;use crate::util::process_pre_insert::{process_message_pre_insert, process_threads_pre_insert};-use crate::util::upload_attachment::upload_attachment;+use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};use email_db_client::threads;use email_db_client::threads::get::get_outbound_threads_by_thread_ids;use email_utils::dedupe_emails;@@ -18,12 +18,14 @@ use model::insight_context::email_insights::{use model_notifications::{NewEmailMetadata, NotificationEntity, NotificationEvent, NotificationQueueMessage,};+use models_email::db::address::EmailRecipientType;use models_email::email::service;use models_email::email::service::link;use models_email::email::service::message::SimpleMessage;use models_email::email::service::thread::UserThreadIds;use models_email::gmail::operations::GmailApiOperation;use models_email::gmail::webhook::{UpsertMessagePayload, WebhookOperation};+use models_email::service::attachment::AttachmentUploadArgs;use models_email::service::message::Message;use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use models_opensearch::SearchEntityType;@@ -217,22 +219,55 @@ async fn handle_attachment_upload(.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.redis_client,- &ctx.gmail_client,- &ctx.dss_client,- gmail_access_token,- link,- &attachment,- false,- )- .await- {- tracing::error!("Failed to upload attachment to Macro: {e}");+ let message_ids = attachments+ .iter()+ .map(|a| a.message_db_id)+ .collect::<Vec<_>>();++ let message_recipients =+ email_db_client::contacts::get::fetch_db_recipients_in_bulk(&ctx.db, &message_ids)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context(+ "Failed to fetch db recipients for thread attachment backfill"+ .to_string(),+ ),+ })+ })?;++ for attachment in attachments {+ // get the email addresses of the recipients of the message+ let recipient_emails: Vec<String> = message_recipients+ .get(&attachment.message_db_id)+ .map(|v| v.as_slice())+ .unwrap_or(&[])+ .iter()+ .filter(|(_, recipient_type)| *recipient_type == EmailRecipientType::To)+ .filter_map(|(contact, _)| contact.email_address.clone())+ .collect();++ let attachment_upload_args = AttachmentUploadArgs {+ recipient_emails,+ attachment_metadata: attachment,+ backfill: false,+ };++ let ctx_upload = UploadAttachmentContext {+ redis_client: &ctx.redis_client,+ gmail_client: &ctx.gmail_client,+ dss_client: &ctx.dss_client,+ system_properties_service: &ctx.system_properties_service,+ access_token: gmail_access_token,+ link,+ };++ // keep processing if it fails, best effort+ if let Err(e) = upload_attachment(ctx_upload, &attachment_upload_args).await {+ tracing::error!("Failed to upload attachment to Macro: {e}");+ }}}diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/worker.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/worker.rsindex 92b01f4216..b8c8d14a74 100644--- a/rust/cloud-storage/email_service/src/pubsub/webhook/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/worker.rs@@ -7,6 +7,8 @@ use document_storage_service_client::DocumentStorageServiceClient;use futures::StreamExt;use macro_notify::MacroNotifyClient;use static_file_service_client::StaticFileServiceClient;+use std::sync::Arc;+use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};/// method that ingests sqs messages and calls the process function for each#[expect(clippy::too_many_arguments, reason = "too annoying to fix right now")]@@ -21,6 +23,7 @@ pub async fn run_worker(sfs_client: StaticFileServiceClient,connection_gateway_client: ConnectionGatewayClient,dss_client: DocumentStorageServiceClient,+ system_properties_service: Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,notifications_enabled: bool,retry_worker: bool,) {@@ -35,6 +38,7 @@ pub async fn run_worker(sfs_client,connection_gateway_client,dss_client,+ system_properties_service,notifications_enabled,retry_worker,};diff --git a/rust/cloud-storage/email_service/src/util/upload_attachment.rs b/rust/cloud-storage/email_service/src/util/upload_attachment.rsindex f1b88d54b4..dc35419b7b 100644--- a/rust/cloud-storage/email_service/src/util/upload_attachment.rs+++ b/rust/cloud-storage/email_service/src/util/upload_attachment.rs@@ -5,27 +5,40 @@ use base64::Engine;use base64::engine::general_purpose::STANDARD;use document_storage_service_client::DocumentStorageServiceClient;use gmail_client::GmailClient;+use macro_user_id::cowlike::ArcCowStr;+use macro_user_id::user_id::MacroUserId;use model::document::response::{CreateDocumentRequest, CreateDocumentResponse};use models_email::gmail::operations::GmailApiOperation;-use models_email::service::attachment::AttachmentUploadMetadata;+use models_email::service::attachment::{AttachmentUploadArgs, AttachmentUploadMetadata};use models_email::service::link;use sha2::{Digest, Sha256};+use std::sync::Arc;+use system_properties::{+ EmailAttachmentInput, EmailAttachmentProperty, PgSystemPropertiesRepository, SourceEntity,+ SystemPropertiesService, SystemPropertiesServiceImpl,+};++/// Context required for uploading an email attachment.+pub struct UploadAttachmentContext<'a> {+ pub redis_client: &'a RedisClient,+ pub gmail_client: &'a GmailClient,+ pub dss_client: &'a DocumentStorageServiceClient,+ pub system_properties_service:+ &'a Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,+ pub access_token: &'a str,+ pub link: &'a link::Link,+}/// Upload an email attachment to DSS as a document.-#[tracing::instrument(skip(redis_client, gmail_client, dss_client, access_token), err)]+#[tracing::instrument(skip(ctx, attachment_args), err)]pub async fn upload_attachment(- redis_client: &RedisClient,- gmail_client: &GmailClient,- dss_client: &DocumentStorageServiceClient,- access_token: &str,- link: &link::Link,- p: &AttachmentUploadMetadata,- backfill: bool,+ ctx: UploadAttachmentContext<'_>,+ attachment_args: &AttachmentUploadArgs,) -> anyhow::Result<String> {// 1. Check rate limits before making a Gmail API call.check_gmail_rate_limit(- redis_client,- link.id,+ ctx.redis_client,+ ctx.link.id,GmailApiOperation::MessagesAttachmentsGet,true,)@@ -33,17 +46,28 @@ pub async fn upload_attachment(.context("Rate limit check failed")?;// 2. Fetch the raw attachment data from Gmail.- let attachment_data = fetch_gmail_attachment_data(gmail_client, access_token, p).await?;+ let attachment_data = fetch_gmail_attachment_data(+ ctx.gmail_client,+ ctx.access_token,+ &attachment_args.attachment_metadata,+ )+ .await?;// 3. Calculate hashes required for the upload process.let (hex_hash, base64_hash) = calculate_hashes(&attachment_data);// 4. Determine file metadata from the payload.- let (file_name, file_type) = determine_file_metadata(p)?;+ let (file_name, file_type) = determine_file_metadata(&attachment_args.attachment_metadata)?;// 5. Create the document record in DSS and get a presigned URL for the upload.let dss_response = create_dss_document_record(- dss_client, link, p, &hex_hash, &file_name, &file_type, backfill,+ ctx.dss_client,+ ctx.link,+ &attachment_args.attachment_metadata,+ &hex_hash,+ &file_name,+ &file_type,+ attachment_args.backfill,).await?;@@ -55,7 +79,12 @@ pub async fn upload_attachment(.data.document_response.document_metadata- .document_id;+ .document_id+ .clone();++ // 8. Set properties for attachment+ set_email_attachment_properties(ctx.system_properties_service, &document_id, attachment_args)+ .await?;Ok(document_id)}@@ -180,3 +209,63 @@ async fn upload_data_to_presigned_url(Ok(())}++/// Sets email attachment properties for the uploaded document.+#[tracing::instrument(skip(system_properties_service, p))]+async fn set_email_attachment_properties(+ system_properties_service: &Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,+ document_id: &str,+ p: &AttachmentUploadArgs,+) -> anyhow::Result<()> {+ let sender_email = format!("macro|{}", p.attachment_metadata.sender_email);+ let sender = MacroUserId::parse_from_str(&sender_email)+ .with_context(|| {+ format!(+ "Failed to parse sender email {} into macro user id",+ p.attachment_metadata.sender_email+ )+ })?+ .lowercase();++ // parse_from_str only accepts &str, so we need to store prefixed emails somewhere that outlives parsing+ let prefixed_emails: Vec<String> = p+ .recipient_emails+ .iter()+ .map(|email| format!("macro|{}", email))+ .collect();++ let recipients: Result<Vec<MacroUserId<ArcCowStr>>, _> = prefixed_emails+ .iter()+ .map(|email| {+ MacroUserId::parse_from_str(email).with_context(|| {+ format!(+ "Failed to parse recipient email {} into macro user id",+ )+ })+ })+ .collect();++ let recipients: Vec<_> = recipients?.into_iter().map(|id| id.lowercase()).collect();++ system_properties_service+ .set_email_attachment_properties(vec![EmailAttachmentInput {+ entity_id: document_id.to_string(),+ properties: EmailAttachmentProperty {+ source: Some(SourceEntity {+ entity_type: models_properties::EntityType::Thread,+ entity_id: p.attachment_metadata.thread_db_id.to_string(),+ specific_message_id: Some(p.attachment_metadata.message_db_id.to_string()),+ }),+ // TODO: companies support+ companies: None,+ sender: Some(sender),+ recipients: Some(recipients),+ subject: p.attachment_metadata.subject.clone(),+ },+ }])+ .await+ .context("Failed to set email attachment properties")?;++ Ok(())+}diff --git a/rust/cloud-storage/models_email/src/email/service/attachment.rs b/rust/cloud-storage/models_email/src/email/service/attachment.rsindex 4dc54f15fc..425a91838c 100644--- a/rust/cloud-storage/models_email/src/email/service/attachment.rs+++ b/rust/cloud-storage/models_email/src/email/service/attachment.rs@@ -47,4 +47,15 @@ pub struct AttachmentUploadMetadata {pub mime_type: String,pub filename: String,pub internal_date_ts: DateTime<Utc>,+ pub message_db_id: Uuid,+ pub thread_db_id: Uuid,+ pub sender_email: String,+ pub subject: Option<String>,+}++#[derive(Clone, Debug, FromRow, Eq, PartialEq, Serialize, Deserialize)]+pub struct AttachmentUploadArgs {+ pub attachment_metadata: AttachmentUploadMetadata,+ pub recipient_emails: Vec<String>,+ pub backfill: bool,}diff --git a/rust/cloud-storage/models_email/src/email/service/backfill.rs b/rust/cloud-storage/models_email/src/email/service/backfill.rsindex 57e81c0576..e8473bdd37 100644--- a/rust/cloud-storage/models_email/src/email/service/backfill.rs+++ b/rust/cloud-storage/models_email/src/email/service/backfill.rs@@ -1,6 +1,6 @@use crate::email::db::backfill as db_backfill;use crate::email::service::thread::ListThreadsPayload;-use crate::service::attachment::AttachmentUploadMetadata;+use crate::service::attachment::AttachmentUploadArgs;use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};use sqlx::FromRow;@@ -176,5 +176,5 @@ pub struct UpdateMetadataPayload {#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]pub struct BackfillAttachmentPayload {- pub metadata: AttachmentUploadMetadata,+ pub metadata: AttachmentUploadArgs,}diff --git a/rust/cloud-storage/system_properties/Cargo.toml b/rust/cloud-storage/system_properties/Cargo.tomlindex e584b70a55..d7d136adea 100644--- a/rust/cloud-storage/system_properties/Cargo.toml+++ b/rust/cloud-storage/system_properties/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[dependencies]+macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }models_properties = { path = "../models_properties" }serde = { workspace = true }diff --git a/rust/cloud-storage/system_properties/src/domain/model/inbound/email_attachment.rs b/rust/cloud-storage/system_properties/src/domain/model/inbound/email_attachment.rsindex d393b326e8..a811c44b53 100644--- a/rust/cloud-storage/system_properties/src/domain/model/inbound/email_attachment.rs+++ b/rust/cloud-storage/system_properties/src/domain/model/inbound/email_attachment.rs@@ -1,27 +1,29 @@//! Email attachment property types.use super::source_entity::SourceEntity;+use macro_user_id::lowercased::Lowercase;+use macro_user_id::user_id::MacroUserId;/// Email attachment properties to set on an entity.#[derive(Debug, Clone, Default)]-pub struct EmailAttachmentProperty {+pub struct EmailAttachmentProperty<'a> {/// Source entity reference (single).pub source: Option<SourceEntity>,/// Company entity IDs.pub companies: Option<Vec<String>>,/// Sender user ID.- pub sender: Option<String>,+ pub sender: Option<MacroUserId<Lowercase<'a>>>,/// Recipient user IDs.- pub recipients: Option<Vec<String>>,+ pub recipients: Option<Vec<MacroUserId<Lowercase<'a>>>>,/// Subject line.pub subject: Option<String>,}/// Input for bulk email attachment property setting.#[derive(Debug, Clone)]-pub struct EmailAttachmentInput {+pub struct EmailAttachmentInput<'a> {/// The entity ID to set properties on.pub entity_id: String,/// The properties to set.- pub properties: EmailAttachmentProperty,+ pub properties: EmailAttachmentProperty<'a>,}diff --git a/rust/cloud-storage/system_properties/src/domain/service.rs b/rust/cloud-storage/system_properties/src/domain/service.rsindex be04cf2847..80caeaebca 100644--- a/rust/cloud-storage/system_properties/src/domain/service.rs+++ b/rust/cloud-storage/system_properties/src/domain/service.rs@@ -67,7 +67,7 @@ where#[tracing::instrument(skip(self, items))]async fn set_email_attachment_properties(&self,- items: Vec<EmailAttachmentInput>,+ items: Vec<EmailAttachmentInput<'_>>,) -> Result<(), SystemPropertyError> {let rows: Vec<PropertyRow> = items.into_iter()@@ -142,7 +142,7 @@ fn collect_email_property_rows(entity_type,SystemPropertyKey::Sender.uuid(),EntityType::User,- vec![user_id],+ vec![user_id.as_ref().to_string()],None,));}@@ -154,7 +154,10 @@ fn collect_email_property_rows(entity_type,SystemPropertyKey::Recipients.uuid(),EntityType::User,- user_ids,+ user_ids+ .iter()+ .map(|s| s.as_ref().to_string())+ .collect::<Vec<_>>(),None,));}