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): Upload email attachments as Macro docs (#159)
Evan Hutnikb8d30b41d10a
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 38b30ad26a..6d1d10c78c 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2833,6 +2833,7 @@ dependencies = ["macro_notify","macro_user_id","macro_uuid",+ "mime_guess","model","model-entity","model_notifications",@@ -2846,6 +2847,7 @@ dependencies = ["secretsmanager_client","serde","serde_json",+ "sha2","sqlx","sqlx-core","sqs_client",diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-ef2a07e87db8a0cad371d7c5df36edeaec2153579d54c7bc4153ffca231930bc.json b/rust/cloud-storage/email_db_client/.sqlx/query-ef2a07e87db8a0cad371d7c5df36edeaec2153579d54c7bc4153ffca231930bc.jsonnew file mode 100644index 0000000000..acee8efe17--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-ef2a07e87db8a0cad371d7c5df36edeaec2153579d54c7bc4153ffca231930bc.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT document_id\n FROM document_email\n WHERE email_attachment_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "document_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "ef2a07e87db8a0cad371d7c5df36edeaec2153579d54c7bc4153ffca231930bc"+}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.sqlnew file mode 100644index 0000000000..ee9a3b488a--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/fetch_insertable_attachments_for_new_email.sql@@ -0,0 +1,382 @@++-- SQL fixture for fetch_insertable_attachments_for_new_email tests+-- This file seeds scenarios to test all conditions for new email attachment insertion:+-- 1. User sent the message (is_sent = true)+-- 2. Message has IMPORTANT label+-- 3. Message from same domain as user+-- 4. Message from whitelisted domain+-- 5. User has previously contacted a thread participant+-- Also tests document_email exclusion logic++-- NOTE:+-- - All UUIDs are hard-coded so tests can reference them+-- - User email: [email protected]++------------------------------------------------------------+-- User 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-00000000001a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001a',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++------------------------------------------------------------+-- Labels+------------------------------------------------------------++-- IMPORTANT label+INSERT INTO email_labels (id, provider_label_id, link_id, name, message_list_visibility, label_list_visibility, type, created_at)+VALUES ('00000000-0000-0000-0000-0000000a0001',+ 'IMPORTANT',+ '00000000-0000-0000-0000-00000000001a',+ 'IMPORTANT',+ 'Show',+ 'LabelShow',+ 'System',+ NOW());++------------------------------------------------------------+-- Contacts+------------------------------------------------------------++-- Same domain contact ([email protected] -> [email protected])+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0001',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(), NOW());++-- Different domain contact+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0002',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(), NOW());++-- Previously contacted person+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0003',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(), NOW());++-- Never contacted person+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0004',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(), NOW());++-- Whitelisted domain contact (docusign.com)+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0005',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(), NOW());++------------------------------------------------------------+-- Threads+------------------------------------------------------------++-- Thread 1: For condition 1 testing (sent message)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000101',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 2: For condition 2 testing (IMPORTANT label)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000102',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 3: For condition 3 testing (same domain)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000103',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 4: For condition 5 testing (previously contacted)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000104',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 5: For establishing "previously contacted" relationship+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000105',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 6: Control thread (no conditions met)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000106',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 7: For document_email exclusion testing+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000107',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 8: For condition 4 testing (whitelisted domain)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000108',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++------------------------------------------------------------+-- Thread 5: Establish "previously contacted" relationship+------------------------------------------------------------++-- User sent message to [email protected] (establishes relationship)+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-0000000e0501',+ '00000000-0000-0000-0000-000000000105',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-501',+ TRUE, -- is_sent = true+ NULL, -- from_contact_id is NULL for sent messages+ '2025-01-01 10:00:00 +00:00',+ false, false, false, false, NOW(), NOW());++-- Add recipient for the sent message+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)+VALUES ('00000000-0000-0000-0000-0000000e0501',+ '00000000-0000-0000-0000-0000000c0003', -- [email protected]+ 'TO');++------------------------------------------------------------+-- Thread 1: Condition 1 - User sent message (is_sent = true)+------------------------------------------------------------++-- Target message with attachment (user sent this)+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-0000000e0101',+ '00000000-0000-0000-0000-000000000101',+ '00000000-0000-0000-0000-00000000001a',+ 'target-msg-101',+ TRUE, -- This makes condition 1 true for the thread+ NULL,+ '2025-01-02 10:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Valid attachment (should be returned)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0101',+ '00000000-0000-0000-0000-0000000e0101',+ 'provider-att-101',+ 'sent_message_doc.pdf',+ 'application/pdf',+ NOW());++-- Filtered attachments (should NOT be returned)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0102',+ '00000000-0000-0000-0000-0000000e0101',+ 'provider-att-102',+ 'image.jpg',+ 'image/jpeg',+ NOW()),+ ('00000000-0000-0000-0000-0000001a0103',+ '00000000-0000-0000-0000-0000000e0101',+ 'provider-att-103',+ 'archive.zip',+ 'application/zip',+ NOW());++------------------------------------------------------------+-- Thread 2: Condition 2 - IMPORTANT label+------------------------------------------------------------++-- Target message with attachment (has IMPORTANT label)+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-0000000e0201',+ '00000000-0000-0000-0000-000000000102',+ '00000000-0000-0000-0000-00000000001a',+ 'target-msg-201',+ FALSE,+ '00000000-0000-0000-0000-0000000c0002', -- from [email protected]+ '2025-01-02 11:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Associate IMPORTANT label+INSERT INTO email_message_labels (message_id, label_id)+VALUES ('00000000-0000-0000-0000-0000000e0201',+ '00000000-0000-0000-0000-0000000a0001');++-- Valid attachment (should be returned)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000002a0201',+ '00000000-0000-0000-0000-0000000e0201',+ 'provider-att-201',+ 'important_doc.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 3: Condition 3 - Same domain sender+------------------------------------------------------------++-- Target message with attachment (from same domain)+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-0000000e0301',+ '00000000-0000-0000-0000-000000000103',+ '00000000-0000-0000-0000-00000000001a',+ 'target-msg-301',+ FALSE,+ '00000000-0000-0000-0000-0000000c0001', -- from [email protected]+ '2025-01-02 12:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Valid attachment (should be returned)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000003a0301',+ '00000000-0000-0000-0000-0000000e0301',+ 'provider-att-301',+ 'same_domain_doc.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 4: Condition 5 - Previously contacted participant+------------------------------------------------------------++-- Target message with attachment+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-0000000e0401',+ '00000000-0000-0000-0000-000000000104',+ '00000000-0000-0000-0000-00000000001a',+ 'target-msg-401',+ FALSE,+ '00000000-0000-0000-0000-0000000c0003', -- from [email protected]+ '2025-01-02 13:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Valid attachment (should be returned by second query)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000004a0401',+ '00000000-0000-0000-0000-0000000e0401',+ 'provider-att-401',+ 'previously_contacted_doc.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 6: Control - No conditions met+------------------------------------------------------------++-- Target message with attachment (no conditions met)+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-0000000e0601',+ '00000000-0000-0000-0000-000000000106',+ '00000000-0000-0000-0000-00000000001a',+ 'target-msg-601',+ FALSE,+ '00000000-0000-0000-0000-0000000c0004', -- from [email protected]+ '2025-01-02 14:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- This attachment should NOT be returned+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000006a0601',+ '00000000-0000-0000-0000-0000000e0601',+ 'provider-att-601',+ 'excluded_doc.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 7: Document_email exclusion testing+------------------------------------------------------------++-- Target message with attachment that's already in document_email+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-0000000e0701',+ '00000000-0000-0000-0000-000000000107',+ '00000000-0000-0000-0000-00000000001a',+ 'target-msg-701',+ TRUE, -- is_sent = true (condition 1 met)+ NULL,+ '2025-01-02 15:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Attachment that already exists in document_email (should be excluded)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000007a0701',+ '00000000-0000-0000-0000-0000000e0701',+ 'provider-att-701',+ 'already_uploaded_doc.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 8: Condition 4 - Whitelisted domain+------------------------------------------------------------++-- Target message with attachment (from whitelisted domain)+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-0000000e0801',+ '00000000-0000-0000-0000-000000000108',+ '00000000-0000-0000-0000-00000000001a',+ 'target-msg-801',+ FALSE,+ '00000000-0000-0000-0000-0000000c0005', -- from [email protected]+ '2025-01-02 16:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Valid attachment (should be returned due to whitelisted domain)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000008a0801',+ '00000000-0000-0000-0000-0000000e0801',+ 'provider-att-801',+ 'whitelisted_domain_doc.pdf',+ 'application/pdf',+ NOW());++-- Macro user for the User table foreign key+INSERT INTO "macro_user" (id, username, email, stripe_customer_id)+VALUES ('00000000-0000-0000-0000-00000000001a',+ 'user_a',+ '[email protected]',+ 'cus_test123');++-- User for the document owner+INSERT INTO "User" (id, email, name, macro_user_id)+VALUES ('00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ 'User A',+ '00000000-0000-0000-0000-00000000001a');++INSERT INTO "Document" (id, name, owner, "fileType", uploaded, "createdAt", "updatedAt")+VALUES ('00000000-0000-0000-0000-00000000d701',+ 'already_uploaded_doc.pdf',+ '00000000-0000-0000-0000-00000000001a',+ 'application/pdf',+ true,+ NOW(),+ NOW());+++-- Simulate document_email entry (attachment already uploaded)+INSERT INTO document_email (document_id, email_attachment_id)+VALUES ('00000000-0000-0000-0000-00000000d701',+ '00000000-0000-0000-0000-0000007a0701');++------------------------------------------------------------+-- Additional messages in threads to test EXISTS logic+------------------------------------------------------------+++------------------------------------------------------------+-- End of fixture+------------------------------------------------------------\ No newline at end of filediff --git a/rust/cloud-storage/email_db_client/fixtures/fetch_job_attachments_for_backfill.sql b/rust/cloud-storage/email_db_client/fixtures/fetch_job_attachments_for_backfill.sqlnew file mode 100644index 0000000000..fb7aca7df5--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/fetch_job_attachments_for_backfill.sql@@ -0,0 +1,245 @@+-- SQL fixture for fetch_job_attachments_for_backfill tests+-- This file seeds scenarios to test the job-level attachment backfill logic:+-- - Attachments from threads with previously contacted participants (should be included)+-- - Attachments from threads with no previously contacted participants (should be excluded)+-- - Various filter scenarios (mime types, filenames)++-- NOTE:+-- - All UUIDs are hard-coded so tests can reference them.+-- - User email: [email protected]++------------------------------------------------------------+-- User 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-00000000001a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001a',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++------------------------------------------------------------+-- Contacts+------------------------------------------------------------++-- Previously contacted person (user sent email to this person)+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0001',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(), NOW());++-- Person user has never contacted before+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0002',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(), NOW());++-- Another previously contacted person+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0003',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(), NOW());++------------------------------------------------------------+-- Threads+------------------------------------------------------------++-- Thread 1: Contains previously contacted participant (should include attachments)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000101',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 2: Contains NO previously contacted participants (should exclude attachments)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000102',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 3: Mixed - has both contacted and non-contacted participants (should include)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000103',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++-- Thread 4: User sent message establishing "previously contacted" relationship+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000104',+ '00000000-0000-0000-0000-00000000001a',+ false, false, NOW(), NOW());++------------------------------------------------------------+-- Thread 4: Establish "previously contacted" relationships+------------------------------------------------------------++-- User sent message to [email protected] (creates the relationship)+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-0000000e0401',+ '00000000-0000-0000-0000-000000000104',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-401',+ TRUE, -- is_sent = true (user sent this)+ NULL, -- from_contact_id is NULL for sent messages+ '2025-01-01 10:00:00 +00:00',+ false, false, false, false, NOW(), NOW());++-- Add recipient for the sent message+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)+VALUES ('00000000-0000-0000-0000-0000000e0401',+ '00000000-0000-0000-0000-0000000c0001', -- [email protected]+ 'TO');++-- User sent message to [email protected] (creates another relationship)+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-0000000e0402',+ '00000000-0000-0000-0000-000000000104',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-402',+ TRUE, -- is_sent = true+ NULL,+ '2025-01-01 11: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-0000000e0402',+ '00000000-0000-0000-0000-0000000c0003', -- [email protected]+ 'TO');++------------------------------------------------------------+-- Thread 1: With previously contacted participant+------------------------------------------------------------++-- Message from previously contacted person (should include its attachments)+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-0000000e0101',+ '00000000-0000-0000-0000-000000000101',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-101',+ FALSE,+ '00000000-0000-0000-0000-0000000c0001', -- from [email protected]+ '2025-01-02 10:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Valid attachment (should be returned)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0101',+ '00000000-0000-0000-0000-0000000e0101',+ 'provider-att-101',+ 'valid_document.pdf',+ 'application/pdf',+ NOW());++-- Filtered attachment (should NOT be returned - image)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0102',+ '00000000-0000-0000-0000-0000000e0101',+ 'provider-att-102',+ 'image.jpg',+ 'image/jpeg',+ NOW());++-- Filtered attachment (should NOT be returned - zip)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0103',+ '00000000-0000-0000-0000-0000000e0101',+ 'provider-att-103',+ 'archive.zip',+ 'application/zip',+ NOW());++-- Filtered attachment (should NOT be returned - ics)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0104',+ '00000000-0000-0000-0000-0000000e0101',+ 'provider-att-104',+ 'calendar.ics',+ 'application/ics',+ NOW());++-- Filtered attachment (should NOT be returned - no filename)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0105',+ '00000000-0000-0000-0000-0000000e0101',+ 'provider-att-105',+ NULL,+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 2: With NO previously contacted participants+------------------------------------------------------------++-- Message from never contacted person (should NOT include its attachments)+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-0000000e0201',+ '00000000-0000-0000-0000-000000000102',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-201',+ FALSE,+ '00000000-0000-0000-0000-0000000c0002', -- from [email protected]+ '2025-01-02 11:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- This attachment should NOT be returned (thread has no previously contacted participants)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000002a0201',+ '00000000-0000-0000-0000-0000000e0201',+ 'provider-att-201',+ 'excluded_document.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 3: Mixed participants (has both contacted and non-contacted)+------------------------------------------------------------++-- Message from previously contacted person+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-0000000e0301',+ '00000000-0000-0000-0000-000000000103',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-301',+ FALSE,+ '00000000-0000-0000-0000-0000000c0003', -- from [email protected]+ '2025-01-02 12:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- This attachment should be returned (thread has at least one previously contacted participant)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000003a0301',+ '00000000-0000-0000-0000-0000000e0301',+ 'provider-att-301',+ 'mixed_thread_doc.pdf',+ 'application/pdf',+ NOW());++-- Message from never contacted person in same thread+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-0000000e0302',+ '00000000-0000-0000-0000-000000000103',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-302',+ FALSE,+ '00000000-0000-0000-0000-0000000c0002', -- from [email protected]+ '2025-01-02 13:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- This attachment should ALSO be returned (same thread, has contacted participant)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, created_at)+VALUES ('00000000-0000-0000-0000-0000003a0302',+ '00000000-0000-0000-0000-0000000e0302',+ 'provider-att-302',+ 'also_included_doc.docx',+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ NOW());++------------------------------------------------------------+-- End of fixture+------------------------------------------------------------\ No newline at end of filediff --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.sqlnew file mode 100644index 0000000000..f68f7ae7ad--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/fetch_thread_attachments_for_backfill.sql@@ -0,0 +1,373 @@++-- SQL fixture for fetch_thread_attachments_for_backfill tests+-- This file seeds:+-- - 5 threads (4 matching the conditions, 1 control with no matches)+-- - Messages, contacts, labels, attachments++-- NOTE:+-- - Adjust column lists and extra NOT NULL fields according to your actual schema.+-- - All UUIDs are hard-coded so tests can reference them.++------------------------------------------------------------+-- Common: links + threads+------------------------------------------------------------++-- Link A: user email is [email protected]+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at,+ updated_at)+VALUES ('00000000-0000-0000-0000-00000000001a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001a',+ '[email protected]', 'GMAIL', true, '2025-11-11 17:48:26.664688 +00:00',+ '2025-11-11 17:48:26.664688 +00:00');++-- Thread 1: used for condition 1 (is_sent = true)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000101',+ '00000000-0000-0000-0000-00000000001a',+ false,+ false,+ NOW(),+ NOW());++-- Thread 2: used for condition 2 (IMPORTANT label)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000102',+ '00000000-0000-0000-0000-00000000001a',+ false,+ false,+ NOW(),+ NOW());++-- Thread 3: used for condition 3 (same-domain from contact)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000103',+ '00000000-0000-0000-0000-00000000001a',+ false,+ false,+ NOW(),+ NOW());++-- Thread 4: control thread: no messages satisfy any condition+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000104',+ '00000000-0000-0000-0000-00000000001a',+ false,+ false,+ NOW(),+ NOW());++-- Thread 5: used for condition 4 (whitelisted domain)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000105',+ '00000000-0000-0000-0000-00000000001a',+ false,+ false,+ NOW(),+ NOW());++------------------------------------------------------------+-- Labels+------------------------------------------------------------++-- IMPORTANT label+INSERT INTO email_labels (id, provider_label_id, link_id, name, message_list_visibility, label_list_visibility, type, created_at)+VALUES ('00000000-0000-0000-0000-0000000a0001',+ 'IMPORTANT',+ '00000000-0000-0000-0000-00000000001a',+ 'IMPORTANT',+ 'Show',+ 'LabelShow',+ 'System',+ NOW());++------------------------------------------------------------+-- Contacts+------------------------------------------------------------++-- Contact with same domain as [email protected]+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0001',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(),+ NOW());++-- Contact with different domain+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0002',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(),+ NOW());++-- Contact with whitelisted domain (docusign.com)+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0003',+ '00000000-0000-0000-0000-00000000001a',+ '[email protected]',+ NOW(),+ NOW());++------------------------------------------------------------+-- Thread 1: Condition 1 - is_sent = true+------------------------------------------------------------++-- Message: is_sent = true, no labels, from_contact_id = NULL+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-0000000b0001',+ '00000000-0000-0000-0000-000000000101',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-101',+ TRUE,+ NULL,+ NOW(),+ true,+ false,+ false,+ false,+ NOW(),+ NOW());++-- Valid attachment (should be returned)+INSERT INTO email_attachments (id,+ message_id,+ provider_attachment_id,+ filename,+ mime_type,+ created_at)+VALUES ('00000000-0000-0000-0000-0000001a0101',+ '00000000-0000-0000-0000-0000000b0001',+ 'provider-att-101',+ 'sent_doc.pdf',+ 'application/pdf',+ NOW());++-- Filtered attachments (should NOT be returned)+INSERT INTO email_attachments (id,+ message_id,+ provider_attachment_id,+ filename,+ mime_type,+ created_at)+VALUES ('00000000-0000-0000-0000-0000001a0102',+ '00000000-0000-0000-0000-0000000b0001',+ 'provider-att-102',+ 'image_attachment.png',+ 'image/png',+ NOW()),+ ('00000000-0000-0000-0000-0000001a0103',+ '00000000-0000-0000-0000-0000000b0001',+ 'provider-att-103',+ 'archive.zip',+ 'application/zip',+ NOW()),+ ('00000000-0000-0000-0000-0000001a0104',+ '00000000-0000-0000-0000-0000000b0001',+ 'provider-att-104',+ 'calendar.ics',+ 'application/ics',+ NOW());++------------------------------------------------------------+-- Thread 2: Condition 2 - IMPORTANT label+------------------------------------------------------------++-- Message: is_sent = false, but labeled IMPORTANT+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-0000002a0201',+ '00000000-0000-0000-0000-000000000102',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-201',+ FALSE,+ NULL,+ NOW(),+ true,+ false,+ false,+ false,+ NOW(),+ NOW());++-- Associate IMPORTANT label+INSERT INTO email_message_labels (message_id, label_id)+VALUES ('00000000-0000-0000-0000-0000002a0201',+ '00000000-0000-0000-0000-0000000a0001');++-- Valid attachment (should be returned)+INSERT INTO email_attachments (id,+ message_id,+ provider_attachment_id,+ filename,+ mime_type,+ created_at)+VALUES ('00000000-0000-0000-0000-0000002a0201',+ '00000000-0000-0000-0000-0000002a0201',+ 'provider-att-201',+ 'important_doc.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 3: Condition 3 - same-domain from contact+------------------------------------------------------------++-- Message: is_sent = false, from contact with same domain as link's email+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-00000000e301',+ '00000000-0000-0000-0000-000000000103',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-301',+ FALSE,+ '00000000-0000-0000-0000-0000000c0001',+ NOW(),+ true,+ false,+ false,+ false,+ NOW(),+ NOW());++-- Valid attachment (should be returned)+INSERT INTO email_attachments (id,+ message_id,+ provider_attachment_id,+ filename,+ mime_type,+ created_at)+VALUES ('00000000-0000-0000-0000-0000003a0301',+ '00000000-0000-0000-0000-00000000e301',+ 'provider-att-301',+ 'same_domain_doc.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 4: No condition met (no attachments should be returned)+------------------------------------------------------------++-- Message: is_sent = false, from different-domain contact, no labels+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-00000000e401',+ '00000000-0000-0000-0000-000000000104',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-401',+ FALSE,+ '00000000-0000-0000-0000-0000000c0002',+ NOW(),+ true,+ false,+ false,+ false,+ NOW(),+ NOW());++-- Attachments exist but should not be returned because EXISTS condition fails+INSERT INTO email_attachments (id,+ message_id,+ provider_attachment_id,+ filename,+ mime_type,+ created_at)+VALUES ('00000000-0000-0000-0000-0000004a0401',+ '00000000-0000-0000-0000-00000000e401',+ 'provider-att-401',+ 'unmatched_doc.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- Thread 5: Condition 4 - whitelisted domain+------------------------------------------------------------++-- Message: is_sent = false, from whitelisted domain contact (docusign.com), no labels+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-00000000e501',+ '00000000-0000-0000-0000-000000000105',+ '00000000-0000-0000-0000-00000000001a',+ 'provider-msg-501',+ FALSE,+ '00000000-0000-0000-0000-0000000c0003',+ NOW(),+ true,+ false,+ false,+ false,+ NOW(),+ NOW());++-- Valid attachment (should be returned due to whitelisted domain)+INSERT INTO email_attachments (id,+ message_id,+ provider_attachment_id,+ filename,+ mime_type,+ created_at)+VALUES ('00000000-0000-0000-0000-0000005a0501',+ '00000000-0000-0000-0000-00000000e501',+ 'provider-att-501',+ 'docusign_doc.pdf',+ 'application/pdf',+ NOW());++------------------------------------------------------------+-- End of fixture+------------------------------------------------------------\ No newline at end of filediff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rsindex 24ae295395..ded4ded816 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs@@ -1,3 +1,6 @@+pub mod upload;+pub mod upload_filters;+use crate::parse::db_to_service::map_db_attachment_to_service;use crate::parse::service_to_db::map_service_attachments_to_db;use anyhow::Context;@@ -305,3 +308,23 @@ pub async fn get_attachments_by_thread_ids(Ok(result)}++/// return if record exists for email attachment+#[tracing::instrument(skip(db), err)]+pub async fn document_email_record_exists(+ db: &Pool<Postgres>,+ email_attachment_id: Uuid,+) -> anyhow::Result<bool> {+ let exists = sqlx::query!(+ r#"+ SELECT document_id+ FROM document_email+ WHERE email_attachment_id = $1+ "#,+ email_attachment_id,+ )+ .fetch_optional(db)+ .await?;++ Ok(exists.is_some())+}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.rsnew file mode 100644index 0000000000..63a8299696--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs@@ -0,0 +1,359 @@+use crate::attachments::provider::upload_filters::{+ ATTACHMENT_MIME_TYPE_FILTERS, ATTACHMENT_WHITELISTED_DOMAINS,+};+use models_email::service::attachment::AttachmentUploadMetadata;+use sqlx::types::Uuid;+use sqlx::{Pool, Postgres, Row};++/// fetch attachments for a thread to upload to Macro during the backfill process.+/// all attachments for a thread should be uploaded if any message in the thread meets any of the+/// following criteria:+/// 1. the user sent the message+/// 2. the message has the IMPORTANT label+/// 3. the message came from someone with the same domain as the user+/// 4. the domain the email was sent from is part of the whitelisted domains+///+/// we also upload attachments for any threads where at least one participant is someone the user has+/// sent a message to in the past. but those attachments are fetched once backfill is complete, in+/// a different call.+#[tracing::instrument(skip(db), err)]+pub async fn fetch_thread_attachments_for_backfill(+ db: &Pool<Postgres>,+ thread_id: Uuid,+) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {+ let query = format!(+ r#"+ SELECT+ a.id AS attachment_db_id,+ m.provider_id as email_provider_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+ FROM email_attachments a+ JOIN email_messages m ON a.message_id = m.id+ WHERE m.thread_id = $1+ -- attachment mime type filters injected below+ {}+ AND EXISTS ( -- only fetch if at least one message in the thread meets any of the criteria+ SELECT 1+ FROM email_messages m2+ LEFT JOIN email_message_labels ml ON m2.id = ml.message_id+ LEFT JOIN email_labels l ON ml.label_id = l.id+ LEFT JOIN email_contacts c ON m2.from_contact_id = c.id+ JOIN email_threads t ON m2.thread_id = t.id+ JOIN email_links link ON t.link_id = link.id+ WHERE m2.thread_id = $1+ AND (+ m2.is_sent = true -- condition 1+ OR l.name = 'IMPORTANT' -- condition 2+ OR (+ -- condition 3+ c.email_address IS NOT NULL+ AND RIGHT(c.email_address, LENGTH(RIGHT(link.email_address,+ LENGTH(link.email_address) - POSITION('@' IN link.email_address)))) =+ RIGHT(link.email_address, LENGTH(link.email_address) - POSITION('@' IN link.email_address))+ )+ -- whitelisted domain check injected below+ {}+ )+ )+ ORDER BY a.id+ "#,+ ATTACHMENT_MIME_TYPE_FILTERS, ATTACHMENT_WHITELISTED_DOMAINS+ );++ let rows = sqlx::query(&query).bind(thread_id).fetch_all(db).await?;++ let attachments = rows+ .into_iter()+ .map(|row| AttachmentUploadMetadata {+ attachment_db_id: row.get("attachment_db_id"),+ email_provider_id: row.get("email_provider_id"),+ provider_attachment_id: row.get("provider_attachment_id"),+ filename: row.get("filename"),+ mime_type: row.get("mime_type"),+ internal_date_ts: row.get("internal_date_ts"),+ })+ .collect();++ Ok(attachments)+}++/// Fetch attachment metadata across all threads for the user where at least one participant+/// is someone the user has previously contacted (excluding the user themselves).+/// This is called after email backfill completion to identify additional attachments+/// that should be uploaded based on the user's interaction history. This isn't done at time of thread+/// completion like fetch_thread_attachments_for_backfill because this can only be known at time+/// of job completion, as we don't know everyone the user has sent messages to until all their+/// messages have been backfilled.+///+/// There will be overlap between the attachments returned by this query and the ones returned by+/// fetch_attachment_threads_for_backfill, but the BackfillAttachment job has logic to ensure+/// duplicate attachments are not inserted by checking the DocumentEmail table.+#[tracing::instrument(skip(db), err)]+pub async fn fetch_job_attachments_for_backfill(+ db: &Pool<Postgres>,+ link_id: Uuid,+) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {+ let query = format!(+ r#"+ -- Step 1: Get the user's own email address from the link_id. This is our exclusion criteria.+ WITH+ user_email AS (+ SELECT email_address+ FROM public.email_links+ WHERE id = $1+ ),++ -- Step 2: Create a distinct list of OTHER people this user has ever sent mail to.+ previously_contacted_emails AS (+ SELECT DISTINCT ec.email_address+ FROM public.email_messages em+ JOIN public.email_message_recipients emr ON em.id = emr.message_id+ JOIN public.email_contacts ec ON emr.contact_id = ec.id+ WHERE em.link_id = $1+ AND em.is_sent = true+ AND ec.email_address != (SELECT email_address FROM user_email)+ ),++ -- Step 3: For each thread, create a complete list of OTHER participant email addresses.+ thread_participants AS (+ -- Get all senders in each thread (excluding the user)+ SELECT DISTINCT em.thread_id, ec.email_address+ FROM public.email_messages em+ JOIN public.email_contacts ec ON em.from_contact_id = ec.id+ WHERE em.link_id = $1+ AND ec.email_address != (SELECT email_address FROM user_email)++ UNION++ -- Get all recipients in each thread (excluding the user)+ SELECT DISTINCT em.thread_id, ec.email_address+ FROM public.email_messages em+ JOIN public.email_message_recipients emr ON em.id = emr.message_id+ JOIN public.email_contacts ec ON emr.contact_id = ec.id+ WHERE em.link_id = $1+ AND ec.email_address != (SELECT email_address FROM user_email)+ )++ -- Final Step: Select attachments from threads where AT LEAST ONE of the OTHER participants+ -- is in the list of OTHER previously_contacted_emails.+ SELECT+ a.id AS attachment_db_id,+ m.provider_id as email_provider_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+ FROM public.email_attachments a+ JOIN public.email_messages m ON a.message_id = m.id+ JOIN public.email_contacts from_contact ON m.from_contact_id = from_contact.id+ WHERE m.thread_id IN (+ SELECT DISTINCT tp.thread_id+ FROM thread_participants tp+ INNER JOIN previously_contacted_emails pce ON tp.email_address = pce.email_address+ )+ -- attachment mime type filters injected below+ {}+ AND a.filename IS NOT NULL+ ORDER BY m.internal_date_ts DESC+ "#,+ ATTACHMENT_MIME_TYPE_FILTERS+ );++ let rows = sqlx::query(&query).bind(link_id).fetch_all(db).await?;++ let attachments = rows+ .into_iter()+ .map(|row| AttachmentUploadMetadata {+ attachment_db_id: row.get("attachment_db_id"),+ email_provider_id: row.get("email_provider_id"),+ provider_attachment_id: row.get("provider_attachment_id"),+ filename: row.get("filename"),+ mime_type: row.get("mime_type"),+ internal_date_ts: row.get("internal_date_ts"),+ })+ .collect();++ Ok(attachments)+}++/// fetch attachments for a specific message to upload to Macro. This is called when a new email is+/// inserted for a user. Attachments for the message should be uploaded if any message in the+/// message's thread meets any of the following criteria:+/// 1. the user sent the message+/// 2. the message has the IMPORTANT label+/// 3. the message came from someone with the same domain as the user+/// 4. the domain the email was sent from is part of the whitelisted domains+/// 5. the user has previously sent a message to any participant in the thread+///+/// For simplicity's sake, conditions 1 2 3 and 4 are evaluated in the first query, and condition 5+/// is evaluated in a separate query. These queries are very similar to fetch_thread_attachments_for_backfill+/// and fetch_job_attachments_for_backfill respectively, except they also verify the attachment+/// doesn't already exist in document_email table.+#[tracing::instrument(skip(db), err)]+pub async fn fetch_insertable_attachments_for_new_email(+ db: &Pool<Postgres>,+ message_provider_id: &str,+) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {+ // query for conditions 1 2 and 3+ let query1 = format!(+ r#"+ SELECT+ a.id AS attachment_db_id,+ m.provider_id as email_provider_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+ FROM email_attachments a+ JOIN email_messages m ON a.message_id = m.id+ LEFT JOIN document_email de ON de.email_attachment_id = a.id+ WHERE m.provider_id = $1+ -- attachment mime type filters injected below+ {}+ AND de.email_attachment_id IS NULL+ AND EXISTS ( -- only fetch if at least one message in the thread meets any of the criteria+ SELECT 1+ FROM email_messages m2+ LEFT JOIN email_message_labels ml ON m2.id = ml.message_id+ LEFT JOIN email_labels l ON ml.label_id = l.id+ LEFT JOIN email_contacts c ON m2.from_contact_id = c.id+ JOIN email_threads t ON m2.thread_id = t.id+ JOIN email_links link ON t.link_id = link.id+ WHERE m2.thread_id = m.thread_id -- check against the message's thread+ AND (+ m2.is_sent = true -- condition 1+ OR l.name = 'IMPORTANT' -- condition 2+ OR (+ -- condition 3+ c.email_address IS NOT NULL+ AND RIGHT(c.email_address, LENGTH(RIGHT(link.email_address,+ LENGTH(link.email_address) - POSITION('@' IN link.email_address)))) =+ RIGHT(link.email_address, LENGTH(link.email_address) - POSITION('@' IN link.email_address))+ )+ -- whitelisted domain check injected below+ {}+ )+ )+ ORDER BY a.id+ "#,+ ATTACHMENT_MIME_TYPE_FILTERS, ATTACHMENT_WHITELISTED_DOMAINS+ );++ let rows = sqlx::query(&query1)+ .bind(message_provider_id)+ .fetch_all(db)+ .await?;++ let attachments: Vec<AttachmentUploadMetadata> = rows+ .into_iter()+ .map(|row| AttachmentUploadMetadata {+ attachment_db_id: row.get("attachment_db_id"),+ email_provider_id: row.get("email_provider_id"),+ provider_attachment_id: row.get("provider_attachment_id"),+ filename: row.get("filename"),+ mime_type: row.get("mime_type"),+ internal_date_ts: row.get("internal_date_ts"),+ })+ .collect();++ // if one or more condition has already been met, return - don't need to check condition 5+ if !attachments.is_empty() {+ return Ok(attachments);+ }++ // query for condition 4+ let query2 = format!(+ r#"+ -- Step 1: Get the user's own email address and thread_id from the message+ WITH+ message_info AS (+ SELECT m.thread_id, l.email_address as user_email, m.link_id+ FROM public.email_messages m+ JOIN public.email_threads t ON m.thread_id = t.id+ JOIN public.email_links l ON t.link_id = l.id+ WHERE m.provider_id = $1+ ),++ -- Step 2: Create a distinct list of OTHER people this user has ever sent mail to.+ previously_contacted_emails AS (+ SELECT DISTINCT ec.email_address+ FROM public.email_messages em+ JOIN public.email_message_recipients emr ON em.id = emr.message_id+ JOIN public.email_contacts ec ON emr.contact_id = ec.id+ WHERE em.link_id = (SELECT link_id FROM message_info)+ AND em.is_sent = true+ AND ec.email_address != (SELECT user_email FROM message_info)+ ),++ -- Step 3: For the message's thread, create a complete list of OTHER participant email addresses.+ thread_participants AS (+ -- Get all senders in the thread (excluding the user)+ SELECT DISTINCT ec.email_address+ FROM public.email_messages em+ JOIN public.email_contacts ec ON em.from_contact_id = ec.id+ WHERE em.thread_id = (SELECT thread_id FROM message_info)+ AND ec.email_address != (SELECT user_email FROM message_info)++ UNION++ -- Get all recipients in the thread (excluding the user)+ SELECT DISTINCT ec.email_address+ FROM public.email_messages em+ JOIN public.email_message_recipients emr ON em.id = emr.message_id+ JOIN public.email_contacts ec ON emr.contact_id = ec.id+ WHERE em.thread_id = (SELECT thread_id FROM message_info)+ AND ec.email_address != (SELECT user_email FROM message_info)+ )++ -- Final Step: Select attachments from the specific message if AT LEAST ONE of the OTHER participants+ -- in the thread is in the list of OTHER previously_contacted_emails.+ SELECT+ a.id AS attachment_db_id,+ m.provider_id as email_provider_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+ FROM public.email_attachments a+ JOIN public.email_messages m ON a.message_id = m.id+ LEFT JOIN public.document_email de ON de.email_attachment_id = a.id+ WHERE m.provider_id = $1+ AND de.email_attachment_id IS NULL+ AND EXISTS (+ SELECT 1+ FROM thread_participants tp+ INNER JOIN previously_contacted_emails pce ON tp.email_address = pce.email_address+ )+ -- attachment mime type filters injected below+ {}+ AND a.filename IS NOT NULL+ ORDER BY a.id+ "#,+ ATTACHMENT_MIME_TYPE_FILTERS+ );++ let rows = sqlx::query(&query2)+ .bind(message_provider_id)+ .fetch_all(db)+ .await?;++ let attachments = rows+ .into_iter()+ .map(|row| AttachmentUploadMetadata {+ attachment_db_id: row.get("attachment_db_id"),+ email_provider_id: row.get("email_provider_id"),+ provider_attachment_id: row.get("provider_attachment_id"),+ filename: row.get("filename"),+ mime_type: row.get("mime_type"),+ internal_date_ts: row.get("internal_date_ts"),+ })+ .collect();++ Ok(attachments)+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/upload/test.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/upload/test.rsnew file mode 100644index 0000000000..5835f9480c--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/upload/test.rs@@ -0,0 +1,376 @@+use super::*;+use anyhow::Result;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_thread_attachments_for_backfill")+ )+)]+// should return attachments for thread with sent message+async fn thread_attachments_for_backfill_condition_1(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE++ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000101")?;+ let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;++ // Only the application/pdf attachment should be included+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "sent_doc.pdf");+ assert_eq!(res[0].mime_type, "application/pdf");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_thread_attachments_for_backfill")+ )+)]+// should return attachments for thread with important labeled message+async fn thread_attachments_for_backfill_condition_2(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE++ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000102")?;+ let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;++ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "important_doc.pdf");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_thread_attachments_for_backfill")+ )+)]+// should return attachments for thread with same domain contact message+async fn thread_attachments_for_backfill_condition_3(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE++ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000103")?;+ let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;++ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "same_domain_doc.pdf");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_thread_attachments_for_backfill")+ )+)]+// should return empty when no messages match any condition+async fn thread_attachments_for_backfill_no_matching_messages(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE++ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000104")?;+ let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;++ assert!(res.is_empty());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_thread_attachments_for_backfill")+ )+)]+// should return attachments for thread with whitelisted domain message+async fn thread_attachments_for_backfill_condition_4(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE++ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000105")?;+ let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;++ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "docusign_doc.pdf");+ assert_eq!(res[0].mime_type, "application/pdf");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_job_attachments_for_backfill")+ )+)]+async fn job_attachments_for_backfill_includes_previously_contacted_participants(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001a")?;+ let res = fetch_job_attachments_for_backfill(&pool, link_id).await?;++ // Should return 3 attachments:+ // 1. valid_document.pdf from Thread 1 (previously contacted participant)+ // 2. mixed_thread_doc.pdf from Thread 3 (has previously contacted participant)+ // 3. also_included_doc.docx from Thread 3 (same thread as #2)+ assert_eq!(res.len(), 3);++ // Check that the correct attachments are returned+ let filenames: Vec<&str> = res.iter().map(|a| a.filename.as_str()).collect();+ assert!(filenames.contains(&"valid_document.pdf"));+ assert!(filenames.contains(&"mixed_thread_doc.pdf"));+ assert!(filenames.contains(&"also_included_doc.docx"));++ // Verify excluded_document.pdf is NOT included (from thread with no contacted participants)+ assert!(!filenames.contains(&"excluded_document.pdf"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_condition_1_user_sent_message(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test condition 1: user sent the message+ let message_provider_id = "target-msg-101";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should return 1 attachment (sent_message_doc.pdf)+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "sent_message_doc.pdf");+ assert_eq!(res[0].mime_type, "application/pdf");+ assert_eq!(res[0].email_provider_id, "target-msg-101");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_condition_2_important_label(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test condition 2: message has IMPORTANT label+ let message_provider_id = "target-msg-201";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should return 1 attachment (important_doc.pdf)+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "important_doc.pdf");+ assert_eq!(res[0].mime_type, "application/pdf");+ assert_eq!(res[0].email_provider_id, "target-msg-201");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_condition_3_same_domain(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test condition 3: message from same domain as user+ let message_provider_id = "target-msg-301";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should return 1 attachment (same_domain_doc.pdf)+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "same_domain_doc.pdf");+ assert_eq!(res[0].mime_type, "application/pdf");+ assert_eq!(res[0].email_provider_id, "target-msg-301");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_condition_4_whitelisted_domain(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test condition 4: message from whitelisted domain+ let message_provider_id = "target-msg-801";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should return 1 attachment (whitelisted_domain_doc.pdf)+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "whitelisted_domain_doc.pdf");+ assert_eq!(res[0].mime_type, "application/pdf");+ assert_eq!(res[0].email_provider_id, "target-msg-801");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_condition_5_previously_contacted(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test condition 4: user has previously contacted a thread participant+ let message_provider_id = "target-msg-401";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should return 1 attachment (previously_contacted_doc.pdf)+ // This should be found by the second query (condition 4)+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "previously_contacted_doc.pdf");+ assert_eq!(res[0].mime_type, "application/pdf");+ assert_eq!(res[0].email_provider_id, "target-msg-401");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_no_conditions_met(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test control case: no conditions met+ let message_provider_id = "target-msg-601";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should return 0 attachments+ assert_eq!(res.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_excludes_already_uploaded(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test document_email exclusion+ let message_provider_id = "target-msg-701";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should return 0 attachments (attachment already exists in document_email)+ assert_eq!(res.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_filters_mime_types(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test that filtered mime types are excluded+ let message_provider_id = "target-msg-101";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should only return PDF, not image or zip+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "sent_message_doc.pdf");+ assert_eq!(res[0].mime_type, "application/pdf");++ // Verify no filtered mime types are present+ for attachment in &res {+ assert!(!attachment.mime_type.starts_with("image/"));+ assert!(!attachment.mime_type.contains("zip"));+ assert_ne!(attachment.mime_type, "application/ics");+ assert_ne!(attachment.mime_type, "application/x-sharing-metadata-xml");+ }++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_thread_exists_logic(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test that attachments are returned when ANY message in the thread meets conditions+ // Even if the specific target message doesn't meet the condition itself++ // target-msg-202 is in Thread 2, which contains target-msg-201 with IMPORTANT label+ let message_provider_id = "other-msg-202";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should return 0 because other-msg-202 has no attachments+ // But the EXISTS clause should still evaluate to true due to target-msg-201 having IMPORTANT+ assert_eq!(res.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_insertable_attachments_for_new_email")+ )+)]+async fn insertable_attachments_returns_first_query_when_available(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ // Test that when first query (conditions 1-3) returns results,+ // the second query (condition 4) is not executed++ // Use a message that meets condition 1 (is_sent = true)+ let message_provider_id = "target-msg-101";+ let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;++ // Should return result from first query+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "sent_message_doc.pdf");++ Ok(())+}diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/upload_filters.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/upload_filters.rsnew file mode 100644index 0000000000..9123aeadf8--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/upload_filters.rs@@ -0,0 +1,100 @@+/// only insert attachments with these mime types.+pub const ATTACHMENT_MIME_TYPE_FILTERS: &str = r#"+ AND (+ a.mime_type IN (+ 'application/pdf',+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ 'application/msword',+ 'text/html',+ 'text/plain',+ 'pdf'+ )+ OR (+ a.mime_type = 'application/octet-stream'+ AND UPPER(SUBSTRING(a.filename FROM '\.([^.]+)$')) IN ('PDF', 'DOC', 'DOCX', 'TXT', 'HTML')+ )+ )+"#;++/// always insert attachments sent from these domains.+pub const ATTACHMENT_WHITELISTED_DOMAINS: &str = r#"+ OR (+ -- condition 4: email from whitelisted domain+ c.email_address IS NOT NULL+ AND (+ c.email_address LIKE '%@docusign.com'+ OR c.email_address LIKE '%@hellosign.com'+ OR c.email_address LIKE '%@dropboxsign.com'+ OR c.email_address LIKE '%@adobesign.com'+ OR c.email_address LIKE '%@signnow.com'+ OR c.email_address LIKE '%@pandadoc.com'+ OR c.email_address LIKE '%@quickbooks.com'+ OR c.email_address LIKE '%@xero.com'+ OR c.email_address LIKE '%@stripe.com'+ OR c.email_address LIKE '%@paypal.com'+ OR c.email_address LIKE '%@squareup.com'+ OR c.email_address LIKE '%@bill.com'+ OR c.email_address LIKE '%@gusto.com'+ OR c.email_address LIKE '%@justworks.com'+ OR c.email_address LIKE '%@rippling.com'+ OR c.email_address LIKE '%@intuit.com'+ OR c.email_address LIKE '%@chase.com'+ OR c.email_address LIKE '%@bankofamerica.com'+ OR c.email_address LIKE '%@wellsfargo.com'+ OR c.email_address LIKE '%@capitalone.com'+ OR c.email_address LIKE '%@amex.com'+ OR c.email_address LIKE '%@citibank.com'+ OR c.email_address LIKE '%@robinhood.com'+ OR c.email_address LIKE '%@etrade.com'+ OR c.email_address LIKE '%@fidelity.com'+ OR c.email_address LIKE '%@schwab.com'+ OR c.email_address LIKE '%@interactivebrokers.com'+ OR c.email_address LIKE '%@vanguard.com'+ OR c.email_address LIKE '%@plaid.com'+ OR c.email_address LIKE '%@irs.gov'+ OR c.email_address LIKE '%@ssa.gov'+ OR c.email_address LIKE '%@uscis.gov'+ OR c.email_address LIKE '%@treasury.gov'+ OR c.email_address LIKE '%@efiletexas.gov'+ OR c.email_address LIKE '%@efilemanager.com'+ OR c.email_address LIKE '%@efile.ca.gov'+ OR c.email_address LIKE '%@sec.gov'+ OR c.email_address LIKE '%@greenhouse.io'+ OR c.email_address LIKE '%@lever.co'+ OR c.email_address LIKE '%@bamboohr.com'+ OR c.email_address LIKE '%@workday.com'+ OR c.email_address LIKE '%@sap.com'+ OR c.email_address LIKE '%@indeed.com'+ OR c.email_address LIKE '%@linkedin.com'+ OR c.email_address LIKE '%@ziprecruiter.com'+ OR c.email_address LIKE '%@docusign.net'+ OR c.email_address LIKE '%@dropbox.com'+ OR c.email_address LIKE '%@box.com'+ OR c.email_address LIKE '%@drive.google.com'+ OR c.email_address LIKE '%@sharepoint.com'+ OR c.email_address LIKE '%@onedrive.live.com'+ OR c.email_address LIKE '%@wetransfer.com'+ OR c.email_address LIKE '%@figma.com'+ OR c.email_address LIKE '%@canva.com'+ OR c.email_address LIKE '%@notion.so'+ OR c.email_address LIKE '%@clickup.com'+ OR c.email_address LIKE '%@airtable.com'+ OR c.email_address LIKE '%@unitedhealthcare.com'+ OR c.email_address LIKE '%@aetna.com'+ OR c.email_address LIKE '%@cigna.com'+ OR c.email_address LIKE '%@metlife.com'+ OR c.email_address LIKE '%@anthem.com'+ OR c.email_address LIKE '%@oscarhealth.com'+ OR c.email_address LIKE '%@delta-dental.com'+ OR c.email_address LIKE '%@vanguardbenefits.com'+ OR c.email_address LIKE '%@fidelitybenefits.com'+ OR c.email_address LIKE '%@aws.amazon.com'+ OR c.email_address LIKE '%@cloudflare.com'+ OR c.email_address LIKE '%@digitalocean.com'+ OR c.email_address LIKE '%@github.com'+ OR c.email_address LIKE '%@gitlab.com'+ OR c.email_address LIKE '%@atlassian.com'+ OR c.email_address LIKE '%@openai.com'+ OR c.email_address LIKE '%@anthropic.com'+ )+ )"#;diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex 5f8369dea5..5da01e36d0 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_gmail_attachments"+path = "src/bin/backfill_gmail_attachments.rs"+[[bin]]name = "backfill_search"path = "src/bin/backfill_search.rs"@@ -54,6 +58,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, feamacro_notify = { path = "../macro_notify" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }+mime_guess = "2.0.5"model = { path = "../model" }model-entity = { path = "../model-entity" }model_notifications = { path = "../model_notifications" }@@ -67,6 +72,7 @@ reqwest = { workspace = true, features = ["stream"] }s3_client = { path = "../s3_client" }schemars = { workspace = true }scraper = { workspace = true }+sha2 = { workspace = true }secretsmanager_client = { path = "../secretsmanager_client" }serde = { workspace = true }serde_json = { workspace = true }diff --git a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments.rs b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments.rsnew file mode 100644index 0000000000..4f057b25be--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments.rs@@ -0,0 +1,584 @@+//! # Attachment Backfill Utility+//!+//! This binary is used to find and upload relevant email attachments for a given user account.+//! It fetches attachment metadata from the local database based on several heuristics,+//! downloads the actual attachment data from Gmail, and uploads it to a document storage service.+//!+//! ## Required Environment Variables:+//! - `DATABASE_URL`: The connection string for the PostgreSQL database.+//! - `DSS_URL`: The URL for the Document Storage Service.+//! - `GMAIL_ACCESS_TOKEN`: An OAuth token to access the user's Gmail account.+//! - `INTERNAL_AUTH_KEY`: An access token for authenticating with internal Macro services.+//! - `MACRO_ID_SOURCE`: The Macro ID of the user account to fetch relevant attachments from.+//! - `MACRO_ID_DESTINATION`: The destination Macro ID for document storage.+//! - `UPLOAD_CONCURRENCY`: Number of concurrent uploads to process (optional, defaults to 10).++use crate::processing::AttachmentProcessor;+use anyhow::Context;+use futures::{StreamExt, stream};+use std::sync::Arc;+use std::sync::atomic::{AtomicUsize, Ordering};++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ // 1. Load configuration from environment variables. Fails early if anything is missing.+ println!("Loading configuration...");+ let config = config::Config::from_env().context("Failed to load configuration")?;++ // 2. Establish a connection pool to the database.+ println!("Connecting to the database...");+ let db_pool = database::create_db_pool(&config.database_url, config.upload_concurrency as u32)+ .await+ .context("Failed to create database pool")?;++ // 3. Set up clients for external services.+ let dss_client = document_storage_service_client::DocumentStorageServiceClient::new(+ config.internal_auth_key.clone(),+ config.dss_url.clone(),+ );+ let gmail_client = gmail_client::GmailClient::new("unused".to_string());++ // 4. Fetch the link_id associated with the user's account.+ let link_id =+ email_db_client::links::get::fetch_link_by_macro_id(&db_pool, &config.macro_id_source)+ .await?+ .ok_or_else(|| anyhow::anyhow!("No link found for macro account source"))?+ .id;++ // 5. Fetch all relevant attachment metadata from the database.+ println!("Fetching unique attachment metadata from database...");+ let attachments = database::fetch_unique_attachments(&db_pool, link_id)+ .await+ .context("Failed to fetch attachment metadata")?;+ println!("Found {} unique attachments to process.", attachments.len());++ // 6. Process and upload each attachment.+ let processor = Arc::new(processing::AttachmentProcessor::new(+ db_pool.clone(),+ dss_client,+ gmail_client,+ config.gmail_access_token.clone(),+ config.macro_id_destination.clone(),+ ));++ let success_count = Arc::new(AtomicUsize::new(0));+ let total_attachments = attachments.len();++ println!("Starting concurrent upload process...");++ stream::iter(attachments.into_iter().enumerate())+ .for_each_concurrent(config.upload_concurrency, |(index, attachment)| {+ let processor: Arc<AttachmentProcessor> = Arc::clone(&processor);+ let success_count = Arc::clone(&success_count);++ async move {+ match processor.upload(&attachment).await {+ Ok(_) => {+ success_count.fetch_add(1, Ordering::Relaxed);+ println!("Successfully uploaded '{}' (index: {})", attachment.filename, index);+ }+ Err(e) => {+ // ignore weird file types. annoying game of whack a mole+ if e.to_string().contains("file extension") {+ println!(+ "Skipping '{}' (index: {}) due to unsupported mime type {}",+ attachment.filename, index, attachment.mime_type+ );+ return;+ }+ panic!(+ "Failed to upload attachment - filename: {}, provider_attachment_id: {}, provider_message_id: {}, index: {}, error: {:?}",+ attachment.filename,+ attachment.provider_attachment_id,+ attachment.email_provider_id,+ index,+ e+ );+ }+ }+ }+ })+ .await;++ let final_success_count = success_count.load(Ordering::SeqCst);+ println!(+ "Processing complete. Successfully uploaded {} out of {} attachments.",+ final_success_count, total_attachments+ );++ Ok(())+}++// --- Data Models ---++mod models {+ use sqlx::FromRow;+ use sqlx::types::chrono::{DateTime, Utc};+ use uuid::Uuid;++ /// Represents the metadata for an email attachment stored in our database.+ #[derive(Clone, Debug, FromRow)]+ pub struct AttachmentMetadata {+ pub attachment_db_id: Uuid,+ pub email_provider_id: String,+ pub provider_attachment_id: String,+ pub mime_type: String,+ pub filename: String,+ pub internal_date_ts: DateTime<Utc>,+ }+}++// --- Configuration ---++mod config {+ use anyhow::{Context, Result};++ /// Holds all configuration loaded from environment variables.+ pub struct Config {+ pub dss_url: String,+ pub gmail_access_token: String,+ pub internal_auth_key: String,+ pub macro_id_destination: String,+ pub macro_id_source: String,+ pub database_url: String,+ pub upload_concurrency: usize,+ }++ 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() -> Result<Self> {+ let upload_concurrency =+ std::env::var("UPLOAD_CONCURRENCY").context("UPLOAD_CONCURRENCY not set")?;+ let upload_concurrency = upload_concurrency+ .parse::<usize>()+ .context("UPLOAD_CONCURRENCY is not a number")?;++ Ok(Self {+ dss_url: std::env::var("DSS_URL").context("DSS_URL not set")?,+ gmail_access_token: std::env::var("GMAIL_ACCESS_TOKEN")+ .context("GMAIL_ACCESS_TOKEN not set")?,+ internal_auth_key: std::env::var("INTERNAL_AUTH_KEY")+ .context("INTERNAL_AUTH_KEY not set")?,+ macro_id_destination: std::env::var("MACRO_ID_DESTINATION")+ .context("MACRO_ID_DESTINATION not set")?,+ macro_id_source: std::env::var("MACRO_ID_SOURCE")+ .context("MACRO_ID_SOURCE not set")?,+ database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,+ upload_concurrency,+ })+ }+ }+}++// --- Database Operations ---++mod database {+ use super::models::AttachmentMetadata;+ use anyhow::Context;+ use email_db_client::attachments::provider::upload_filters::{+ ATTACHMENT_MIME_TYPE_FILTERS, ATTACHMENT_WHITELISTED_DOMAINS,+ };+ use sqlx::PgPool;+ use sqlx::postgres::PgPoolOptions;+ use uuid::Uuid;++ /// Attachments for a thread should be uploaded if any message in the+ /// thread meets any of the following criteria:+ /// 1. the user sent the message+ /// 2. the message has the IMPORTANT label+ /// 3. the message came from someone with the same domain as the user+ /// 4. the domain the email was sent from is part of the whitelisted domains+ /// 5. the user has previously sent a message to any participant in the thread+ ///+ ///+ ///+ /// Combined query for conditions 1, 2, 3, and 4 - similar to fetch_insertable_attachments_for_new_email+ /// but modified to work for all threads for a given link_id instead of a specific message+ const COMBINED_CONDITIONS_QUERY_PREFIX: &str = r#"+ SELECT DISTINCT+ a.id AS attachment_db_id,+ m.provider_id as email_provider_id,+ a.provider_attachment_id,+ a.mime_type,+ a.filename,+ m.internal_date_ts+ FROM email_attachments a+ JOIN email_messages m ON a.message_id = m.id+ JOIN email_threads t ON m.thread_id = t.id+ WHERE t.link_id = $1+ AND a.filename IS NOT NULL+ "#;++ const COMBINED_CONDITIONS_QUERY_SUFFIX: &str = r#"+ AND EXISTS ( -- only fetch if at least one message in the thread meets any of the criteria+ SELECT 1+ FROM email_messages m2+ LEFT JOIN email_message_labels ml ON m2.id = ml.message_id+ LEFT JOIN email_labels l ON ml.label_id = l.id+ LEFT JOIN email_contacts c ON m2.from_contact_id = c.id+ JOIN email_links link ON t.link_id = link.id+ WHERE m2.thread_id = t.id -- check against the thread+ AND (+ m2.is_sent = true -- condition 1+ OR l.name = 'IMPORTANT' -- condition 2+ OR (+ -- condition 3: same domain+ c.email_address IS NOT NULL+ AND RIGHT(c.email_address, LENGTH(RIGHT(link.email_address,+ LENGTH(link.email_address) - POSITION('@' IN link.email_address)))) =+ RIGHT(link.email_address, LENGTH(link.email_address) - POSITION('@' IN link.email_address))+ )+ "#;++ const COMBINED_CONDITIONS_QUERY_END: &str = r#"+ )+ )+ ORDER BY m.internal_date_ts DESC+ "#;++ /// Condition 5 Query: Thread involves a recipient the user has previously sent mail to.+ const PREVIOUSLY_CONTACTED_CONDITION_PREFIX: &str = r#"+WITH+-- Step 1: Get the user's own email address from the link_id. This is our exclusion criteria.+user_email AS (+ SELECT+ email_address+ FROM+ public.email_links+ WHERE+ id = $1 -- Your link_id+),++-- Step 2: Create a distinct list of OTHER people this user has ever sent mail to.+previously_contacted_emails AS (+ SELECT DISTINCT+ ec.email_address+ FROM+ public.email_messages em+ JOIN+ public.email_message_recipients emr ON em.id = emr.message_id+ JOIN+ public.email_contacts ec ON emr.contact_id = ec.id+ WHERE+ em.link_id = $1+ AND em.is_sent = true+ AND ec.email_address != (SELECT email_address FROM user_email)+),++-- Step 3: For each thread, create a complete list of OTHER participant email addresses.+thread_participants AS (+ -- Get all senders in each thread (excluding the user)+ SELECT DISTINCT+ em.thread_id,+ ec.email_address+ FROM+ public.email_messages em+ JOIN+ public.email_contacts ec ON em.from_contact_id = ec.id+ WHERE+ em.link_id = $1+ AND ec.email_address != (SELECT email_address FROM user_email)++ UNION++ -- Get all recipients in each thread (excluding the user)+ SELECT DISTINCT+ em.thread_id,+ ec.email_address+ FROM+ public.email_messages em+ JOIN+ public.email_message_recipients emr ON em.id = emr.message_id+ JOIN+ public.email_contacts ec ON emr.contact_id = ec.id+ WHERE+ em.link_id = $1+ AND ec.email_address != (SELECT email_address FROM user_email)+)++-- Final Step: Select attachments from threads where AT LEAST ONE of the OTHER participants+-- is in the list of OTHER previously_contacted_emails.+SELECT+ a.id AS attachment_db_id,+ m.provider_id as email_provider_id,+ a.provider_attachment_id,+ a.filename,+ a.mime_type,+ m.internal_date_ts+FROM+ public.email_attachments a+JOIN+ public.email_messages m ON a.message_id = m.id+JOIN+ public.email_contacts from_contact ON m.from_contact_id = from_contact.id+WHERE+ m.thread_id IN (+ SELECT DISTINCT+ tp.thread_id+ FROM+ thread_participants tp+ INNER JOIN+ previously_contacted_emails pce ON tp.email_address = pce.email_address+ )+ -- Apply standard filters at the very end+ AND a.filename IS NOT NULL+ "#;++ const PREVIOUSLY_CONTACTED_CONDITION_SUFFIX: &str = r#"+ORDER BY+ m.internal_date_ts DESC;+ "#;++ /// Creates and returns a new PostgreSQL connection pool.+ pub async fn create_db_pool(+ database_url: &str,+ min_connections: u32,+ ) -> anyhow::Result<PgPool> {+ PgPoolOptions::new()+ .min_connections(min_connections)+ .max_connections(60)+ .connect(database_url)+ .await+ .context("Could not connect to db")+ }++ /// Fetches attachments from the database that match one of several conditions.+ /// Uses a combined query for conditions 1-4, and a separate query for condition 5.+ pub async fn fetch_unique_attachments(+ db: &PgPool,+ link_id: Uuid,+ ) -> anyhow::Result<Vec<AttachmentMetadata>> {+ let mut attachments = Vec::new();++ // Combined query for conditions 1-4: User sent, IMPORTANT label, same domain, whitelisted domains+ // Build the query by concatenating the parts with the filter constants+ let combined_query = format!(+ "{}{}{}{}{}",+ COMBINED_CONDITIONS_QUERY_PREFIX,+ ATTACHMENT_MIME_TYPE_FILTERS,+ COMBINED_CONDITIONS_QUERY_SUFFIX,+ ATTACHMENT_WHITELISTED_DOMAINS,+ COMBINED_CONDITIONS_QUERY_END+ );++ let rows_combined = sqlx::query_as::<_, AttachmentMetadata>(&combined_query)+ .bind(link_id)+ .fetch_all(db)+ .await+ .with_context(|| "Failed to fetch attachments for conditions 1-4 (combined query)")?;++ println!("Conditions 1-4 returned {} rows", rows_combined.len());+ attachments.extend(rows_combined);++ // Query for condition 5: Previously contacted participants+ let previously_contacted_query = format!(+ "{}{}{}",+ PREVIOUSLY_CONTACTED_CONDITION_PREFIX,+ ATTACHMENT_MIME_TYPE_FILTERS,+ PREVIOUSLY_CONTACTED_CONDITION_SUFFIX+ );++ let rows5 = sqlx::query_as::<_, AttachmentMetadata>(&previously_contacted_query)+ .bind(link_id)+ .fetch_all(db)+ .await+ .with_context(+ || "Failed to fetch attachments for condition 5 (previously contacted)",+ )?;++ println!("Condition 5 returned {} rows", rows5.len());++ attachments.extend(rows5);++ // Deduplicate by attachment_db_id+ let mut unique_attachments = std::collections::HashMap::new();+ for attachment in attachments {+ unique_attachments.insert(attachment.attachment_db_id, attachment);+ }++ let mut result: Vec<AttachmentMetadata> = unique_attachments.into_values().collect();+ result.sort_by(|a, b| b.internal_date_ts.cmp(&a.internal_date_ts));++ println!("Total unique rows: {}", result.len());++ Ok(result)+ }+}++// --- Attachment Processing and Uploading ---++mod processing {+ use super::models::AttachmentMetadata;+ use anyhow::{Context, bail};+ use base64::{Engine as _, engine::general_purpose::STANDARD};+ use model::document::response::CreateDocumentRequest;+ use sha2::{Digest, Sha256};+ use sqlx::PgPool;+ use tracing::instrument;++ /// A helper struct to manage clients and tokens required for processing.+ pub struct AttachmentProcessor {+ db: PgPool,+ dss_client: document_storage_service_client::DocumentStorageServiceClient,+ gmail_client: gmail_client::GmailClient,+ gmail_access_token: String,+ macro_id_destination: String,+ }++ impl AttachmentProcessor {+ pub fn new(+ db: PgPool,+ dss_client: document_storage_service_client::DocumentStorageServiceClient,+ gmail_client: gmail_client::GmailClient,+ gmail_access_token: String,+ macro_id_destination: String,+ ) -> Self {+ Self {+ db,+ dss_client,+ gmail_client,+ gmail_access_token,+ macro_id_destination,+ }+ }++ /// Orchestrates the full upload process for a single attachment.+ #[instrument(skip(self), fields(file_name = %attachment.filename, mime_type = %attachment.mime_type))]+ pub async fn upload(&self, attachment: &AttachmentMetadata) -> anyhow::Result<()> {+ let exists = email_db_client::attachments::provider::document_email_record_exists(+ &self.db,+ attachment.attachment_db_id,+ )+ .await?;+ if exists {+ println!(+ "Attachment {} already exists in DSS, skipping",+ attachment.attachment_db_id+ );+ return Ok(());+ }++ // 1. Fetch attachment data from Gmail.+ let data = self.fetch_gmail_data(attachment).await?;++ // 2. Calculate hashes required for validation.+ let (sha256_hex, sha256_base64) = Self::calculate_hashes(&data);++ // 3. Get a presigned URL from the Document Storage Service.+ let (presigned_url, content_type) =+ self.get_presigned_url(attachment, &sha256_hex).await?;++ // 4. Upload the data to the presigned URL (e.g., S3).+ self.upload_to_storage(&presigned_url, &content_type, &sha256_base64, data)+ .await?;++ Ok(())+ }++ /// Fetches the raw attachment data from the Gmail API.+ async fn fetch_gmail_data(+ &self,+ attachment: &AttachmentMetadata,+ ) -> anyhow::Result<Vec<u8>> {+ self.gmail_client+ .get_attachment_data(+ &self.gmail_access_token,+ &attachment.email_provider_id,+ &attachment.provider_attachment_id,+ )+ .await+ .context("Failed to get attachment data from Gmail")+ }++ /// Calculates the hex and base64 encoded SHA256 hash of the attachment data.+ fn calculate_hashes(data: &[u8]) -> (String, String) {+ let mut hasher = Sha256::new();+ hasher.update(data);+ let hash_bytes = hasher.finalize();++ let hex_hash = format!("{:x}", hash_bytes);+ let base64_hash = STANDARD.encode(hash_bytes);++ (hex_hash, base64_hash)+ }++ /// Requests a pre-signed upload URL from the Document Storage Service.+ async fn get_presigned_url(+ &self,+ attachment: &AttachmentMetadata,+ sha256_hex: &str,+ ) -> anyhow::Result<(String, String)> {+ let file_name = attachment+ .filename+ .split('.')+ .next()+ .unwrap_or(&attachment.filename)+ .to_string();++ let file_type = mime_guess::get_mime_extensions_str(&attachment.mime_type)+ .and_then(|exts| exts.first().map(|s| s.to_string()))+ .context("Could not determine file extension from MIME type")?;++ let dss_response = self+ .dss_client+ .create_document_internal(+ CreateDocumentRequest {+ id: None,+ sha: sha256_hex.to_string(),+ document_name: file_name,+ file_type: Some(file_type),+ mime_type: Some(attachment.mime_type.clone()),+ document_family_id: None,+ branched_from_id: None,+ branched_from_version_id: None,+ job_id: None,+ project_id: None,+ created_at: Some(attachment.internal_date_ts),+ email_attachment_id: Some(attachment.attachment_db_id),+ },+ &self.macro_id_destination,+ )+ .await+ .context("DSS create_document call failed")?;++ let presigned_url = dss_response+ .data+ .document_response+ .presigned_url+ .context("DSS response did not include a presigned URL")?;++ Ok((presigned_url, dss_response.data.content_type))+ }++ /// Performs the final PUT request to upload the file data to cloud storage.+ async fn upload_to_storage(+ &self,+ url: &str,+ content_type: &str,+ sha256_base64: &str,+ data: Vec<u8>,+ ) -> anyhow::Result<()> {+ let response = reqwest::Client::new()+ .put(url)+ .header("content-type", content_type)+ .header("x-amz-checksum-sha256", sha256_base64)+ .body(data)+ .send()+ .await+ .context("HTTP request to presigned URL failed")?;++ if !response.status().is_success() {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ bail!(+ "Upload to storage failed with status {}. Body: {}",+ status,+ body+ );+ }++ Ok(())+ }+ }+}diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rsindex 275fdf207c..fecf5481f1 100644--- a/rust/cloud-storage/email_service/src/main.rs+++ b/rust/cloud-storage/email_service/src/main.rs@@ -206,6 +206,7 @@ async fn main() -> anyhow::Result<()> {let macro_notify_client_webhook = macro_notify_client.clone();let sfs_client_webhook = sfs_client.clone();let connection_gateway_client_webhook = connection_gateway_client.clone();+ let dss_client_webhook = dss_client.clone();tokio::spawn(async move {pubsub::webhook::worker::run_worker(db_webhook,@@ -217,6 +218,7 @@ async fn main() -> anyhow::Result<()> {macro_notify_client_webhook,sfs_client_webhook,connection_gateway_client_webhook,+ dss_client_webhook,config.notifications_enabled,).await;@@ -236,6 +238,7 @@ async fn main() -> anyhow::Result<()> {let macro_notify_client_backfill = macro_notify_client.clone();let sfs_client_backfill = sfs_client.clone();let connection_gateway_client_backfill = connection_gateway_client.clone();+ let dss_client_backfill = dss_client.clone();tokio::spawn(async move {pubsub::backfill::worker::run_worker(db_backfill,@@ -247,6 +250,7 @@ async fn main() -> anyhow::Result<()> {macro_notify_client_backfill,sfs_client_backfill,connection_gateway_client_backfill,+ dss_client_backfill,config.notifications_enabled,).await;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.rsnew file mode 100644index 0000000000..b70cfda2be--- /dev/null+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs@@ -0,0 +1,39 @@+use crate::pubsub::context::PubSubContext;+use crate::pubsub::upload_attachment::upload_attachment;+use models_email::service::backfill::BackfillAttachmentPayload;+use models_email::service::link;+use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};+use uuid::Uuid;++/// this step is invoked by the UpdateMetadata step. it uploads the specified attachment as a+/// Macro document for the user. first checks the attachment doesn't already exist by querying+/// document_email table before fetching and uploading the attachment data.+#[tracing::instrument(skip(ctx, access_token))]+pub async fn backfill_attachment(+ ctx: &PubSubContext,+ access_token: &str,+ link: &link::Link,+ p: &BackfillAttachmentPayload,+) -> Result<(), ProcessingError> {+ // Check if a document for this attachment already exists before uploading.+ if attachment_document_exists(ctx, p.metadata.attachment_db_id).await? {+ return Ok(());+ }++ upload_attachment(ctx, access_token, link, &p.metadata).await+}++/// Checks the database to see if a document has already been created for this attachment.+async fn attachment_document_exists(+ ctx: &PubSubContext,+ attachment_db_id: Uuid,+) -> Result<bool, ProcessingError> {+ email_db_client::attachments::provider::document_email_record_exists(&ctx.db, attachment_db_id)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to query for document email record"),+ })+ })+}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rsindex f3ad58e301..b395cb187f 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs@@ -67,5 +67,5 @@ pub async fn backfill_message(})?;// Handle all success-related operations- increment_counters::incr_completed_messages(ctx, link.id, data.job_id, p).await+ increment_counters::incr_completed_messages(ctx, link, data.job_id, p).await}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rsindex dfbc9961b9..dda5ccf6d7 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs@@ -40,7 +40,7 @@ pub async fn backfill_thread(// if the thread already exists, skip backfilling and update redis countersif !existing_threads.is_empty() {- incr_completed_threads(ctx, &link.macro_id, data.job_id).await?;+ incr_completed_threads(ctx, link, data.job_id).await?;return 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 f28643ae00..68c6966d71 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@@ -1,10 +1,11 @@-use crate::pubsub::backfill::increment_counters;-use crate::pubsub::backfill::increment_counters::incr_completed_threads;+use crate::pubsub::backfill::increment_counters::{+ incr_completed_messages, incr_completed_threads,+};use crate::pubsub::context::PubSubContext;use models_email::email::service::backfill::{BackfillJobStatus, BackfillMessagePayload, BackfillOperation, BackfillPubsubMessage,};-use models_email::email::service::pubsub::{DetailedError, ProcessingError};+use models_email::email::service::pubsub::DetailedError;use sqs_worker::cleanup_message;use uuid::Uuid;@@ -19,7 +20,7 @@ pub async fn handle_non_retryable_error(tracing::error!(error = %e, "Non-retryable error processing message. The message will be deleted.");match &data.backfill_operation {- BackfillOperation::Init => {+ BackfillOperation::Init | BackfillOperation::ListThreads(_) => {// update backfill job status to failedif let Err(db_err) = email_db_client::backfill::job::update::update_backfill_job_status(&ctx.db,@@ -34,30 +35,13 @@ pub async fn handle_non_retryable_error();}}- BackfillOperation::ListThreads(_) => {- // update backfill job status to failed- if let Err(db_err) = email_db_client::backfill::job::update::update_backfill_job_status(- &ctx.db,- data.job_id,- BackfillJobStatus::Failed,- )- .await- {- tracing::error!(- error = %db_err,- "Failed to update backfill job status to Failed"- );- }- }- BackfillOperation::BackfillThread(_) => {+ BackfillOperation::BackfillThread(_) | BackfillOperation::UpdateThreadMetadata(_) => {handle_thread_failure(ctx, data.link_id, data.job_id).await;}BackfillOperation::BackfillMessage(p) => {- handle_message_failure(ctx, data, p).await?;- }- BackfillOperation::UpdateThreadMetadata(_) => {- handle_thread_failure(ctx, data.link_id, data.job_id).await;+ handle_message_failure(ctx, data, p).await;}+ BackfillOperation::BackfillAttachment(_) => {}}cleanup_message(&ctx.sqs_worker, message).await?;@@ -96,6 +80,12 @@ pub async fn handle_retryable_error("Retryable error backfilling thread");}+ BackfillOperation::BackfillAttachment(p) => {+ tracing::debug!(+ attachment_db_id = %p.metadata.attachment_db_id,+ "Retryable error backfilling attachment"+ )+ }}Ok(())}@@ -121,7 +111,7 @@ async fn handle_thread_failure(ctx: &PubSubContext, link_id: Uuid, job_id: Uuid)}};- if let Err(err) = incr_completed_threads(ctx, &link.macro_id, job_id).await {+ if let Err(err) = incr_completed_threads(ctx, &link, job_id).await {tracing::error!(error = %err,job_id = job_id.to_string(),@@ -135,6 +125,31 @@ pub async fn handle_message_failure(ctx: &PubSubContext,data: &BackfillPubsubMessage,p: &BackfillMessagePayload,-) -> Result<(), ProcessingError> {- increment_counters::incr_completed_messages(ctx, data.link_id, data.job_id, p).await+) {+ let link = match email_db_client::links::get::fetch_link_by_id(&ctx.db, data.link_id).await {+ Ok(Some(link)) => link,+ Ok(None) => {+ tracing::error!(+ link_id = data.link_id.to_string(),+ job_id = data.job_id.to_string(),+ "Link not found"+ );+ return;+ }+ Err(db_err) => {+ tracing::error!(+ error = %db_err,+ "Failed to fetch link"+ );+ return;+ }+ };++ if let Err(err) = incr_completed_messages(ctx, &link, data.job_id, p).await {+ tracing::error!(+ error = %err,+ job_id = data.job_id.to_string(),+ "Failed to check if thread is completed in handle message failure"+ );+ }}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rsindex 071e6a1dbe..315710fdd6 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,19 +1,21 @@use crate::pubsub::context::PubSubContext;use crate::util::backfill::backfill_insights::backfill_email_insights;use model::insight_context::email_insights::BackfillEmailInsightsFilter;+use models_email::service::attachment::AttachmentUploadMetadata;use models_email::service::backfill::{- BackfillJobStatus, BackfillMessagePayload, BackfillOperation, BackfillPubsubMessage,- UpdateMetadataPayload,+ BackfillAttachmentPayload, BackfillJobStatus, BackfillMessagePayload, BackfillOperation,+ BackfillPubsubMessage, UpdateMetadataPayload,};+use models_email::service::link::Link;use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use uuid::Uuid;-// called when a thread has completed processing. checks if it is the last thread to be processed-// for the job, and if so, performs the necessary actions for job completion.+/// called when a thread has completed processing. checks if it is the last thread to be processed+/// for the job, and if so, performs the necessary actions for job completion.#[tracing::instrument(skip(ctx))]pub async fn incr_completed_threads(ctx: &PubSubContext,- macro_id: &str,+ link: &Link,job_id: Uuid,) -> Result<(), ProcessingError> {let all_threads_processed = ctx@@ -28,44 +30,11 @@ pub async fn incr_completed_threads(})?;if all_threads_processed {- tracing::info!("Backfill complete for job {}", job_id);- email_db_client::backfill::job::update::update_backfill_job_status(- &ctx.db,- job_id,- BackfillJobStatus::Complete,- )- .await- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to update thread status to complete"),- })- })?;-- tracing::info!("Backfilling email insights for user {}", macro_id);- let backfill_email_insights_filter = BackfillEmailInsightsFilter {- user_ids: Some(vec![macro_id.to_string()]),- user_thread_limit: None,- };-- let backfill_res = backfill_email_insights(- ctx.sqs_client.clone(),- &ctx.db,- backfill_email_insights_filter,- )- .await- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to backfill email insights"),- })- })?;-tracing::info!(- "Backfilled email insights for user {} with job ids: {:?}",- macro_id,- backfill_res.job_ids+ job_id = job_id.to_string(),+ "All threads for job have been processed");+ handle_job_completed(ctx, link, job_id).await?;}Ok(())@@ -75,7 +44,7 @@ pub async fn incr_completed_threads(#[tracing::instrument(skip(ctx))]pub async fn incr_completed_messages(ctx: &PubSubContext,- link_id: Uuid,+ link: &Link,job_id: Uuid,p: &BackfillMessagePayload,) -> Result<(), ProcessingError> {@@ -94,15 +63,159 @@ pub async fn incr_completed_messages(})?;if thread_backfill_complete {- let new_payload = UpdateMetadataPayload {- thread_provider_id: p.thread_provider_id.clone(),- thread_db_id: p.thread_db_id,+ handle_thread_completed(ctx, link, job_id, p).await?;+ }++ Ok(())+}++/// performs actions when all threads and messages have been backfilled for the user.+#[tracing::instrument(skip(ctx))]+async fn handle_job_completed(+ ctx: &PubSubContext,+ link: &Link,+ job_id: Uuid,+) -> Result<(), ProcessingError> {+ tracing::info!("Backfill complete for job {}", job_id);+ email_db_client::backfill::job::update::update_backfill_job_status(+ &ctx.db,+ job_id,+ BackfillJobStatus::Complete,+ )+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to update thread status to complete"),+ })+ })?;++ tracing::info!("Backfilling email insights for user {}", link.macro_id);+ let backfill_email_insights_filter = BackfillEmailInsightsFilter {+ user_ids: Some(vec![link.macro_id.to_string()]),+ user_thread_limit: None,+ };++ backfill_email_insights(+ ctx.sqs_client.clone(),+ &ctx.db,+ backfill_email_insights_filter,+ )+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to backfill email insights"),+ })+ })?;++ if link.macro_id.ends_with("@macro.com") {+ 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?;+ }++ Ok(())+}++/// when a thread is done being backfilled, update its metadata and backfill its attachments.+#[tracing::instrument(skip(ctx))]+async fn handle_thread_completed(+ ctx: &PubSubContext,+ link: &Link,+ job_id: Uuid,+ p: &BackfillMessagePayload,+) -> Result<(), ProcessingError> {+ let new_payload = UpdateMetadataPayload {+ thread_provider_id: p.thread_provider_id.clone(),+ thread_db_id: p.thread_db_id,+ };++ let ps_message = BackfillPubsubMessage {+ link_id: link.id,+ job_id,+ backfill_operation: BackfillOperation::UpdateThreadMetadata(new_payload),+ };++ ctx.sqs_client+ .enqueue_email_backfill_message(ps_message)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: e.context("Failed to enqueue metadata message".to_string()),+ })+ })?;++ if link.macro_id.ends_with("@macro.com") {+ let attachments =+ email_db_client::attachments::provider::upload::fetch_thread_attachments_for_backfill(+ &ctx.db,+ p.thread_db_id,+ )+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e+ .context("Failed to fetch thread attachment backfill metadata".to_string()),+ })+ })?;+ if !attachments.is_empty() {+ tracing::info!(+ "Found {} attachments to backfill for thread {}",+ attachments.len(),+ p.thread_db_id+ );+ }++ send_attachment_backfill_messages(ctx, link.id, job_id, attachments).await?;+ }++ Ok(())+}++/// Creates BackfillAttachmentPayload messages and enqueues them via SQS for the given attachments+#[tracing::instrument(skip(ctx, attachments))]+async fn send_attachment_backfill_messages(+ ctx: &PubSubContext,+ link_id: Uuid,+ job_id: Uuid,+ attachments: Vec<AttachmentUploadMetadata>,+) -> Result<(), ProcessingError> {+ for attachment in attachments {+ 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,+ },};let ps_message = BackfillPubsubMessage {link_id,job_id,- backfill_operation: BackfillOperation::UpdateThreadMetadata(new_payload),+ backfill_operation: BackfillOperation::BackfillAttachment(new_payload),};ctx.sqs_client@@ -111,7 +224,7 @@ pub async fn incr_completed_messages(.map_err(|e| {ProcessingError::NonRetryable(DetailedError {reason: FailureReason::SqsEnqueueFailed,- source: e.context("Failed to enqueue metadata message".to_string()),+ source: e.context("Failed to enqueue attachment backfill message".to_string()),})})?;}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rsindex 324ab44df9..183c7df440 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs@@ -1,3 +1,4 @@+mod backfill_attachment;mod backfill_message;mod backfill_thread;mod error_handlers;diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rsindex b8ad3532b0..d7de3e4315 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs@@ -1,5 +1,6 @@use crate::pubsub::backfill::{- backfill_message, backfill_thread, error_handlers, init, list_threads, update_metadata,+ backfill_attachment, backfill_message, backfill_thread, error_handlers, init, list_threads,+ update_metadata,};use crate::pubsub::context::PubSubContext;use crate::util::gmail::auth::fetch_gmail_access_token_from_link;@@ -120,6 +121,9 @@ async fn inner_process_message(BackfillOperation::UpdateThreadMetadata(p) => {update_metadata::update_thread_metadata(ctx, data, &link, p).await?}+ BackfillOperation::BackfillAttachment(p) => {+ backfill_attachment::backfill_attachment(ctx, &access_token, &link, p).await?+ }};Ok(())@@ -150,9 +154,6 @@ async fn handle_cancel_backfill_job(.await;match &data.backfill_operation {- BackfillOperation::Init => Ok(()),- BackfillOperation::ListThreads(_) => Ok(()),- BackfillOperation::BackfillThread(_) => Ok(()),BackfillOperation::BackfillMessage(p) => {let _ = ctx.redis_client@@ -160,6 +161,10 @@ async fn handle_cancel_backfill_job(.await;Ok(())}- BackfillOperation::UpdateThreadMetadata(_) => Ok(()),+ BackfillOperation::Init+ | BackfillOperation::ListThreads(_)+ | BackfillOperation::BackfillThread(_)+ | BackfillOperation::UpdateThreadMetadata(_)+ | BackfillOperation::BackfillAttachment(_) => Ok(()),}}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rsindex 32e5793765..fb9f4dbc92 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs@@ -78,6 +78,8 @@ pub async fn update_thread_metadata(})})?;+ incr_completed_threads(ctx, link, data.job_id).await?;+// notify search-service about the new threadlet search_message = SearchQueueMessage::ExtractEmailThreadMessage(EmailThreadMessage {thread_id: p.thread_db_id.clone().to_string(),@@ -94,7 +96,5 @@ pub async fn update_thread_metadata(})})?;- incr_completed_threads(ctx, &link.macro_id, data.job_id).await?;-Ok(())}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rsindex 41da8d612a..b66b7e481b 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs@@ -3,6 +3,7 @@ use crate::pubsub::context::PubSubContext;use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;+use document_storage_service_client::DocumentStorageServiceClient;use futures::StreamExt;use macro_notify::MacroNotifyClient;use static_file_service_client::StaticFileServiceClient;@@ -19,6 +20,7 @@ pub async fn run_worker(macro_notify_client: MacroNotifyClient,sfs_client: StaticFileServiceClient,connection_gateway_client: ConnectionGatewayClient,+ dss_client: DocumentStorageServiceClient,notifications_enabled: bool,) {let ctx = PubSubContext {@@ -31,6 +33,7 @@ pub async fn run_worker(macro_notify_client,sfs_client,connection_gateway_client,+ dss_client,notifications_enabled,};diff --git a/rust/cloud-storage/email_service/src/pubsub/context.rs b/rust/cloud-storage/email_service/src/pubsub/context.rsindex 5036e35081..29f0166cab 100644--- a/rust/cloud-storage/email_service/src/pubsub/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/context.rs@@ -1,6 +1,7 @@use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;+use document_storage_service_client::DocumentStorageServiceClient;use gmail_client::GmailClient;use macro_notify::MacroNotifyClient;use sqlx::PgPool;@@ -17,5 +18,6 @@ pub struct PubSubContext {pub macro_notify_client: MacroNotifyClient,pub sfs_client: StaticFileServiceClient,pub connection_gateway_client: ConnectionGatewayClient,+ pub dss_client: DocumentStorageServiceClient,pub notifications_enabled: bool,}diff --git a/rust/cloud-storage/email_service/src/pubsub/mod.rs b/rust/cloud-storage/email_service/src/pubsub/mod.rsindex 1f129877fe..af080b678a 100644--- a/rust/cloud-storage/email_service/src/pubsub/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/mod.rs@@ -3,5 +3,6 @@ pub(crate) mod context;pub(crate) mod refresh;pub(crate) mod scheduled;pub(crate) mod sfs_uploader;+pub(crate) mod upload_attachment;mod util;pub(crate) mod webhook;diff --git a/rust/cloud-storage/email_service/src/pubsub/upload_attachment.rs b/rust/cloud-storage/email_service/src/pubsub/upload_attachment.rsnew file mode 100644index 0000000000..1c142b8ccf--- /dev/null+++ b/rust/cloud-storage/email_service/src/pubsub/upload_attachment.rs@@ -0,0 +1,191 @@+use crate::pubsub::context::PubSubContext;+use crate::pubsub::util::check_gmail_rate_limit;+use anyhow::{Context, anyhow};+use base64::Engine;+use base64::engine::general_purpose::STANDARD;+use model::document::response::{CreateDocumentRequest, CreateDocumentResponse};+use models_email::gmail::operations::GmailApiOperation;+use models_email::service::attachment::AttachmentUploadMetadata;+use models_email::service::link;+use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};+use sha2::{Digest, Sha256};++/// Upload an email attachment to DSS as a document.+#[tracing::instrument(skip(ctx, access_token))]+pub async fn upload_attachment(+ ctx: &PubSubContext,+ access_token: &str,+ link: &link::Link,+ p: &AttachmentUploadMetadata,+) -> Result<(), ProcessingError> {+ // 1. Check rate limits before making a Gmail API call.+ check_gmail_rate_limit(+ &ctx.redis_client,+ link.id,+ GmailApiOperation::MessagesAttachmentsGet,+ true,+ )+ .await?;++ // 2. Fetch the raw attachment data from Gmail.+ let attachment_data = fetch_gmail_attachment_data(ctx, access_token, p).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)?;++ // 5. Create the document record in DSS and get a presigned URL for the upload.+ let dss_response =+ create_dss_document_record(ctx, link, p, &hex_hash, &file_name, &file_type).await?;++ // 6. Upload the attachment data to the presigned URL.+ upload_data_to_presigned_url(dss_response, attachment_data, &base64_hash).await?;++ Ok(())+}++/// Fetches the raw attachment data from the Gmail API.+async fn fetch_gmail_attachment_data(+ ctx: &PubSubContext,+ access_token: &str,+ p: &AttachmentUploadMetadata,+) -> Result<Vec<u8>, ProcessingError> {+ ctx.gmail_client+ .get_attachment_data(+ access_token,+ &p.email_provider_id,+ &p.provider_attachment_id,+ )+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::GmailApiFailed,+ source: e.context("Failed to fetch attachment data from Gmail"),+ })+ })+}++/// Calculates the SHA256 hash of the attachment data in both hex and base64 formats.+fn calculate_hashes(data: &[u8]) -> (String, String) {+ let mut hasher = Sha256::new();+ hasher.update(data);+ let hash_bytes = hasher.finalize();++ let hex_hash = format!("{:x}", hash_bytes);+ let base64_hash = STANDARD.encode(hash_bytes);++ (hex_hash, base64_hash)+}++/// Determines the file name (without extension) and file type (extension) from the payload.+fn determine_file_metadata(+ p: &AttachmentUploadMetadata,+) -> Result<(String, String), ProcessingError> {+ let file_name = p+ .filename+ .split('.')+ .next()+ .unwrap_or(&p.filename)+ .to_string();++ let file_type = mime_guess::get_mime_extensions_str(&p.mime_type)+ .and_then(|exts| exts.first().map(|s| s.to_string()))+ .ok_or_else(|| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::AttachmentParsingFailed,+ source: anyhow!(+ "Failed to determine file extension from mime type: {}",+ p.mime_type+ ),+ })+ })?;++ Ok((file_name, file_type))+}++/// Creates a document record in the Document Storage Service (DSS) and returns the response,+/// which includes the presigned URL for the upload.+async fn create_dss_document_record(+ ctx: &PubSubContext,+ link: &link::Link,+ p: &AttachmentUploadMetadata,+ hex_hash: &str,+ file_name: &str,+ file_type: &str,+) -> Result<CreateDocumentResponse, ProcessingError> {+ let request = CreateDocumentRequest {+ id: None,+ sha: hex_hash.to_string(),+ document_name: file_name.to_string(),+ file_type: Some(file_type.to_string()),+ mime_type: Some(p.mime_type.clone()),+ document_family_id: None,+ branched_from_id: None,+ branched_from_version_id: None,+ job_id: None,+ project_id: None,+ created_at: Some(p.internal_date_ts),+ email_attachment_id: Some(p.attachment_db_id),+ };++ ctx.dss_client+ .create_document_internal(request, &link.macro_id)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DSSUploadFailed,+ source: e.context("Failed to create document record in DSS"),+ })+ })+}++/// Uploads the provided data to the presigned URL from the DSS response.+async fn upload_data_to_presigned_url(+ dss_response: CreateDocumentResponse,+ attachment_data: Vec<u8>,+ base64_hash: &str,+) -> Result<(), ProcessingError> {+ let presigned_url = dss_response+ .data+ .document_response+ .presigned_url+ .context("DSS response did not include a presigned URL")+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DSSUploadFailed,+ source: e,+ })+ })?;++ let response = reqwest::Client::new()+ .put(presigned_url)+ .header("content-type", dss_response.data.content_type)+ .header("x-amz-checksum-sha256", base64_hash)+ .body(attachment_data)+ .send()+ .await+ .context("HTTP PUT request to presigned URL failed")+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DSSUploadFailed,+ source: e,+ })+ })?;++ if !response.status().is_success() {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ return Err(ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DSSUploadFailed,+ source: anyhow!(+ "Failed to upload attachment to presigned url: {} {}",+ status,+ body+ ),+ }));+ }++ 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.rsindex 369a0e6ffa..c10dcaa6c6 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@@ -1,4 +1,5 @@use crate::pubsub::context::PubSubContext;+use crate::pubsub::upload_attachment::upload_attachment;use crate::pubsub::util::{cg_refresh_email, check_gmail_rate_limit};use crate::pubsub::webhook::process;use crate::util::process_pre_insert::{process_message_pre_insert, process_threads_pre_insert};@@ -128,6 +129,38 @@ pub async fn upsert_message(// notify downstream services of new messagesnotify_for_new_messages(ctx, link, new_message_provider_ids).await?;+ // internal only, for now+ if link.macro_id.ends_with("@macro.com") {+ // 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()),+ })+ })?;++ 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}");+ }+ }+ }+Ok(())}diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/worker.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/worker.rsindex 105f9944ce..a21d40b7cd 100644--- a/rust/cloud-storage/email_service/src/pubsub/webhook/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/worker.rs@@ -3,6 +3,7 @@ use crate::pubsub::webhook::process;use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;+use document_storage_service_client::DocumentStorageServiceClient;use futures::StreamExt;use macro_notify::MacroNotifyClient;use static_file_service_client::StaticFileServiceClient;@@ -19,6 +20,7 @@ pub async fn run_worker(macro_notify_client: MacroNotifyClient,sfs_client: StaticFileServiceClient,connection_gateway_client: ConnectionGatewayClient,+ dss_client: DocumentStorageServiceClient,notifications_enabled: bool,) {let ctx = PubSubContext {@@ -31,6 +33,7 @@ pub async fn run_worker(macro_notify_client,sfs_client,connection_gateway_client,+ dss_client,notifications_enabled,};diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-238fe2bbda3f3455e9fbbda9519b661393cfffe033edd3eb7f0eeb49dcc64a87.json b/rust/cloud-storage/macro_db_client/.sqlx/query-95dda7d94d399b451c4ba4a78ed6809895c255a103ca296451cbfe6c99833e8f.jsonsimilarity index 61%rename from rust/cloud-storage/macro_db_client/.sqlx/query-238fe2bbda3f3455e9fbbda9519b661393cfffe033edd3eb7f0eeb49dcc64a87.jsonrename to rust/cloud-storage/macro_db_client/.sqlx/query-95dda7d94d399b451c4ba4a78ed6809895c255a103ca296451cbfe6c99833e8f.jsonindex af89902a82..e4c1284d23 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-238fe2bbda3f3455e9fbbda9519b661393cfffe033edd3eb7f0eeb49dcc64a87.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-95dda7d94d399b451c4ba4a78ed6809895c255a103ca296451cbfe6c99833e8f.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO \"document_email\" (document_id, email_attachment_id)\n VALUES ($1, $2)\n ",+ "query": "\n INSERT INTO \"document_email\" (document_id, email_attachment_id)\n VALUES ($1, $2) \n ","describe": {"columns": [],"parameters": {@@ -11,5 +11,5 @@},"nullable": []},- "hash": "238fe2bbda3f3455e9fbbda9519b661393cfffe033edd3eb7f0eeb49dcc64a87"+ "hash": "95dda7d94d399b451c4ba4a78ed6809895c255a103ca296451cbfe6c99833e8f"}diff --git a/rust/cloud-storage/macro_db_client/src/document/document_email.rs b/rust/cloud-storage/macro_db_client/src/document/document_email.rsindex a1394ba91b..487f03b93a 100644--- a/rust/cloud-storage/macro_db_client/src/document/document_email.rs+++ b/rust/cloud-storage/macro_db_client/src/document/document_email.rs@@ -1,6 +1,7 @@use uuid::Uuid;/// create record in document_email table, linking the document (an email attachment) and email message+#[tracing::instrument(skip(transaction), err)]pub async fn create_document_email_record(transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,document_id: &str,@@ -9,17 +10,13 @@ pub async fn create_document_email_record(sqlx::query!(r#"INSERT INTO "document_email" (document_id, email_attachment_id)- VALUES ($1, $2)+ VALUES ($1, $2)"#,document_id,email_attachment_id,).execute(&mut **transaction)- .await- .map_err(|err| {- tracing::error!(error=?err, "unable to create document email record");- anyhow::anyhow!("unable to create document email record: {}", err)- })?;+ .await?;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 9dd053d102..4dc54f15fc 100644--- a/rust/cloud-storage/models_email/src/email/service/attachment.rs+++ b/rust/cloud-storage/models_email/src/email/service/attachment.rs@@ -1,6 +1,8 @@+use chrono::{DateTime, Utc};use schemars::JsonSchema;use serde::{Deserialize, Serialize};use serde_with::serde_as;+use sqlx::FromRow;use utoipa::ToSchema;use uuid::Uuid;@@ -35,3 +37,14 @@ pub struct AttachmentMacro {pub item_id: Uuid,pub item_type: String,}++/// The metadata of an attachment we need to upload it to DSS.+#[derive(Clone, Debug, FromRow, Eq, PartialEq, Serialize, Deserialize)]+pub struct AttachmentUploadMetadata {+ pub attachment_db_id: Uuid,+ pub email_provider_id: String,+ pub provider_attachment_id: String,+ pub mime_type: String,+ pub filename: String,+ pub internal_date_ts: DateTime<Utc>,+}diff --git a/rust/cloud-storage/models_email/src/email/service/backfill.rs b/rust/cloud-storage/models_email/src/email/service/backfill.rsindex bf2df30f20..57e81c0576 100644--- a/rust/cloud-storage/models_email/src/email/service/backfill.rs+++ b/rust/cloud-storage/models_email/src/email/service/backfill.rs@@ -1,5 +1,6 @@use crate::email::db::backfill as db_backfill;use crate::email::service::thread::ListThreadsPayload;+use crate::service::attachment::AttachmentUploadMetadata;use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};use sqlx::FromRow;@@ -35,8 +36,14 @@ pub enum BackfillOperation {// the thread to be processed, it sends an UpdateThreadMetadata message for the thread.BackfillMessage(BackfillMessagePayload),// Updates the thread metadata in the database. If it's the last thread to be processed,- // it sets the backfill job status to complete.+ // it sets the backfill job status to complete. Sends BackfillAttachment messages for each+ // attachment requiring backfill, except for the criteria of attachments in any threads+ // with a participant the user has previously emailed. This criteria we can only know after+ // backfill completes. Once backfill is completed it sends a BackfillAttachment message+ // for each of those attachments.UpdateThreadMetadata(UpdateMetadataPayload),+ // Uploads the message attachment as a Macro document.+ BackfillAttachment(BackfillAttachmentPayload),}// the object we send on the backfill pubsub queue@@ -166,3 +173,8 @@ pub struct UpdateMetadataPayload {pub thread_provider_id: String,pub thread_db_id: Uuid,}++#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]+pub struct BackfillAttachmentPayload {+ pub metadata: AttachmentUploadMetadata,+}diff --git a/rust/cloud-storage/models_email/src/email/service/pubsub.rs b/rust/cloud-storage/models_email/src/email/service/pubsub.rsindex 44536a5be0..1fbb1899d5 100644--- a/rust/cloud-storage/models_email/src/email/service/pubsub.rs+++ b/rust/cloud-storage/models_email/src/email/service/pubsub.rs@@ -33,6 +33,8 @@ pub enum FailureReason {GmailApiFailed,GmailApiRateLimited,OutdatedHistoryId,+ AttachmentParsingFailed,+ DSSUploadFailed,}/// The message we send from the email_refresh_handler lambda to the service via SQS to refresh