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 image/video attachments to sfs (#532)
Evan Hutnik33e849e1190e
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-eee0620b946c10cea326b4366f8c10cbb956bb5b08284fe066df2bea429a89ed.json b/rust/cloud-storage/email_db_client/.sqlx/query-3882543383ad2d4b7819015d1f849026c42f10cc167b1ef714f78dc283f04b25.jsonsimilarity index 66%rename from rust/cloud-storage/email_db_client/.sqlx/query-eee0620b946c10cea326b4366f8c10cbb956bb5b08284fe066df2bea429a89ed.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-3882543383ad2d4b7819015d1f849026c42f10cc167b1ef714f78dc283f04b25.jsonindex eccbfb347f..173c76332c 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-eee0620b946c10cea326b4366f8c10cbb956bb5b08284fe066df2bea429a89ed.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-3882543383ad2d4b7819015d1f849026c42f10cc167b1ef714f78dc283f04b25.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at\n FROM email_attachments\n WHERE message_id = $1\n ",+ "query": "\n SELECT ea.id, ea.message_id, ea.provider_attachment_id, ea.filename, ea.mime_type, ea.size_bytes, ea.content_id, eas.sfs_id, ea.created_at\n FROM email_attachments ea\n LEFT JOIN email_attachments_sfs eas ON ea.id = eas.attachment_id\n WHERE ea.message_id = $1\n ORDER BY ea.filename NULLS LAST\n ","describe": {"columns": [{@@ -40,6 +40,11 @@},{"ordinal": 7,+ "name": "sfs_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 8,"name": "created_at","type_info": "Timestamptz"}@@ -57,8 +62,9 @@true,true,true,+ false,false]},- "hash": "eee0620b946c10cea326b4366f8c10cbb956bb5b08284fe066df2bea429a89ed"+ "hash": "3882543383ad2d4b7819015d1f849026c42f10cc167b1ef714f78dc283f04b25"}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-86caa3151bd2472063de16c0efa487f1bad05eef9b43ed19a7f824298e860510.json b/rust/cloud-storage/email_db_client/.sqlx/query-396f7708decb9786f762606d2e52e42c16c6f9d67848ffd823e25a2ebbb01f42.jsonsimilarity index 68%rename from rust/cloud-storage/email_db_client/.sqlx/query-86caa3151bd2472063de16c0efa487f1bad05eef9b43ed19a7f824298e860510.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-396f7708decb9786f762606d2e52e42c16c6f9d67848ffd823e25a2ebbb01f42.jsonindex ded6de420f..62a683a3a8 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-86caa3151bd2472063de16c0efa487f1bad05eef9b43ed19a7f824298e860510.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-396f7708decb9786f762606d2e52e42c16c6f9d67848ffd823e25a2ebbb01f42.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at\n FROM email_attachments\n WHERE message_id = $1\n ORDER BY filename NULLS LAST\n ",+ "query": "\n SELECT ea.id, ea.message_id, ea.provider_attachment_id, ea.filename, ea.mime_type, ea.size_bytes, ea.content_id, eas.sfs_id, ea.created_at\n FROM email_attachments ea LEFT JOIN email_attachments_sfs eas on ea.id = eas.attachment_id\n WHERE message_id = $1\n ","describe": {"columns": [{@@ -40,6 +40,11 @@},{"ordinal": 7,+ "name": "sfs_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 8,"name": "created_at","type_info": "Timestamptz"}@@ -57,8 +62,9 @@true,true,true,+ false,false]},- "hash": "86caa3151bd2472063de16c0efa487f1bad05eef9b43ed19a7f824298e860510"+ "hash": "396f7708decb9786f762606d2e52e42c16c6f9d67848ffd823e25a2ebbb01f42"}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-704f8353c3a52412d8cbab60b9b32edf0d811d09c54b66522e38366cdefd98a6.json b/rust/cloud-storage/email_db_client/.sqlx/query-704f8353c3a52412d8cbab60b9b32edf0d811d09c54b66522e38366cdefd98a6.jsonnew file mode 100644index 0000000000..65a9a6fecc--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-704f8353c3a52412d8cbab60b9b32edf0d811d09c54b66522e38366cdefd98a6.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_attachments_sfs (id, attachment_id, sfs_id)\n VALUES ($1, $2, $3)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "704f8353c3a52412d8cbab60b9b32edf0d811d09c54b66522e38366cdefd98a6"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-18de30211e9a662e583d2b7a3b6d226d4bf62c08423710421188a090306f1b62.json b/rust/cloud-storage/email_db_client/.sqlx/query-7a97bb0e12628cc97e6e2555cf246cf0339ffbcece51c12635989df120793dfb.jsonsimilarity index 71%rename from rust/cloud-storage/email_db_client/.sqlx/query-18de30211e9a662e583d2b7a3b6d226d4bf62c08423710421188a090306f1b62.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-7a97bb0e12628cc97e6e2555cf246cf0339ffbcece51c12635989df120793dfb.jsonindex 0c198d085e..167982651f 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-18de30211e9a662e583d2b7a3b6d226d4bf62c08423710421188a090306f1b62.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-7a97bb0e12628cc97e6e2555cf246cf0339ffbcece51c12635989df120793dfb.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT \n a.id, a.message_id, a.provider_attachment_id, \n a.filename, a.mime_type, a.size_bytes, \n a.content_id, a.created_at, m.provider_id as \"message_provider_id!\"\n FROM email_attachments a\n JOIN email_messages m ON a.message_id = m.id\n WHERE a.id = $1 AND m.link_id = $2\n ",+ "query": "\n SELECT \n a.id, a.message_id, a.provider_attachment_id, \n a.filename, a.mime_type, a.size_bytes, \n a.content_id, eas.sfs_id as \"sfs_id?\", a.created_at, m.provider_id as \"message_provider_id!\"\n FROM email_attachments a\n JOIN email_messages m ON a.message_id = m.id\n LEFT JOIN email_attachments_sfs eas ON a.id = eas.attachment_id\n WHERE a.id = $1 AND m.link_id = $2\n ","describe": {"columns": [{@@ -40,11 +40,16 @@},{"ordinal": 7,+ "name": "sfs_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 8,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 9,"name": "message_provider_id!","type_info": "Text"}@@ -64,8 +69,9 @@true,true,false,+ false,true]},- "hash": "18de30211e9a662e583d2b7a3b6d226d4bf62c08423710421188a090306f1b62"+ "hash": "7a97bb0e12628cc97e6e2555cf246cf0339ffbcece51c12635989df120793dfb"}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-ae59bee78e23ab95aeca755209a2a4692dc496ab829ccce7a7a5ff13a9b8a885.json b/rust/cloud-storage/email_db_client/.sqlx/query-d9f818ade03e85f7f57ff02b2093b46ac7899be8421cdd83e5dd46f5b8211fd2.jsonsimilarity index 68%rename from rust/cloud-storage/email_db_client/.sqlx/query-ae59bee78e23ab95aeca755209a2a4692dc496ab829ccce7a7a5ff13a9b8a885.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-d9f818ade03e85f7f57ff02b2093b46ac7899be8421cdd83e5dd46f5b8211fd2.jsonindex 7b17237a68..3bf2c1efc4 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-ae59bee78e23ab95aeca755209a2a4692dc496ab829ccce7a7a5ff13a9b8a885.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-d9f818ade03e85f7f57ff02b2093b46ac7899be8421cdd83e5dd46f5b8211fd2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT \n a.id,\n a.message_id,\n a.provider_attachment_id,\n a.filename,\n a.mime_type,\n a.size_bytes,\n a.content_id,\n a.created_at,\n m.thread_id\n FROM \n email_attachments a\n JOIN\n email_messages m ON a.message_id = m.id\n WHERE \n m.thread_id = ANY($1)\n ORDER BY \n a.created_at ASC\n ",+ "query": "\n SELECT \n a.id,\n a.message_id,\n a.provider_attachment_id,\n a.filename,\n a.mime_type,\n a.size_bytes,\n a.content_id,\n eas.sfs_id as \"sfs_id?\",\n a.created_at,\n m.thread_id\n FROM \n email_attachments a\n JOIN\n email_messages m ON a.message_id = m.id\n LEFT JOIN\n email_attachments_sfs eas ON a.id = eas.attachment_id\n WHERE\n m.thread_id = ANY($1)\n ORDER BY \n a.created_at ASC\n ","describe": {"columns": [{@@ -40,11 +40,16 @@},{"ordinal": 7,+ "name": "sfs_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 8,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 9,"name": "thread_id","type_info": "Uuid"}@@ -63,8 +68,9 @@true,true,false,+ false,false]},- "hash": "ae59bee78e23ab95aeca755209a2a4692dc496ab829ccce7a7a5ff13a9b8a885"+ "hash": "d9f818ade03e85f7f57ff02b2093b46ac7899be8421cdd83e5dd46f5b8211fd2"}diff --git a/rust/cloud-storage/email_db_client/fixtures/fetch_new_email_media.sql b/rust/cloud-storage/email_db_client/fixtures/fetch_new_email_media.sqlnew file mode 100644index 0000000000..1ad56dd750--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/fetch_new_email_media.sql@@ -0,0 +1,129 @@+-- SQL fixture for new_email_media_atts tests+-- This fixture tests that media attachments are fetched for new emails+-- and that already uploaded attachments (in email_attachments_sfs) are excluded++-- 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-00000000003a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000003a',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++-- Contact+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c3001',+ '00000000-0000-0000-0000-00000000003a',+ '[email protected]',+ NOW(), NOW());++-- Threads+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000301',+ '00000000-0000-0000-0000-00000000003a',+ false, false, NOW(), NOW()),+ ('00000000-0000-0000-0000-000000000302',+ '00000000-0000-0000-0000-00000000003a',+ false, false, NOW(), NOW()),+ ('00000000-0000-0000-0000-000000000303',+ '00000000-0000-0000-0000-00000000003a',+ false, false, NOW(), NOW());++------------------------------------------------------------+-- Thread 1: New email with media attachments (not yet uploaded)+------------------------------------------------------------++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-0000000e3001',+ '00000000-0000-0000-0000-000000000301',+ '00000000-0000-0000-0000-00000000003a',+ 'new-media-msg-301',+ FALSE,+ '00000000-0000-0000-0000-0000000c3001',+ '2025-01-01 10:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Image attachment (should be included)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000003a3001',+ '00000000-0000-0000-0000-0000000e3001',+ 'provider-att-3001',+ 'new_photo.jpg',+ 'image/jpeg',+ NULL,+ NOW());++-- Video attachment (should be included)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000003a3002',+ '00000000-0000-0000-0000-0000000e3001',+ 'provider-att-3002',+ 'new_video.mp4',+ 'video/mp4',+ NULL,+ NOW());++------------------------------------------------------------+-- Thread 2: Email with media already uploaded to SFS+------------------------------------------------------------++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-0000000e3002',+ '00000000-0000-0000-0000-000000000302',+ '00000000-0000-0000-0000-00000000003a',+ 'new-media-msg-302',+ FALSE,+ '00000000-0000-0000-0000-0000000c3001',+ '2025-01-01 11:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Image already in SFS (should NOT be included)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000003a3003',+ '00000000-0000-0000-0000-0000000e3002',+ 'provider-att-3003',+ 'existing_photo.jpg',+ 'image/jpeg',+ NULL,+ NOW());++-- Simulate that this attachment is already in SFS+INSERT INTO email_attachments_sfs (id, attachment_id, sfs_id, created_at)+VALUES ('00000000-0000-0000-0000-0000003a3003',+'00000000-0000-0000-0000-0000003a3003',+ '00000000-0000-aaaa-0000-0000003a3003',+ NOW());++------------------------------------------------------------+-- Thread 3: Email with inline images (should be filtered)+------------------------------------------------------------++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-0000000e3003',+ '00000000-0000-0000-0000-000000000303',+ '00000000-0000-0000-0000-00000000003a',+ 'new-media-msg-303',+ FALSE,+ '00000000-0000-0000-0000-0000000c3001',+ '2025-01-01 12:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Inline image (should NOT be included)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000003a3004',+ '00000000-0000-0000-0000-0000000e3003',+ 'provider-att-3004',+ 'inline_image.png',+ 'image/png',+ 'inline-123',+ NOW());++-- Non-inline image (should be included)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000003a3005',+ '00000000-0000-0000-0000-0000000e3003',+ 'provider-att-3005',+ 'attachment_image.png',+ 'image/png',+ NULL,+ NOW());\ No newline at end of filediff --git a/rust/cloud-storage/email_db_client/fixtures/fetch_thread_media_for_backfill.sql b/rust/cloud-storage/email_db_client/fixtures/fetch_thread_media_for_backfill.sqlnew file mode 100644index 0000000000..ddf47ae002--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/fetch_thread_media_for_backfill.sql@@ -0,0 +1,170 @@++-- SQL fixture for thread_media_atts_for_backfill tests+-- This fixture tests that media attachments (images, videos) are fetched+-- regardless of thread conditions, and that inline images are properly filtered out++-- 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-00000000002a', 'macro|[email protected]', '00000000-0000-0000-0000-00000000002a',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++-- Contact+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c2001',+ '00000000-0000-0000-0000-00000000002a',+ '[email protected]',+ NOW(), NOW());++-- Thread 1: Contains media attachments+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000201',+ '00000000-0000-0000-0000-00000000002a',+ false, false, NOW(), NOW());++-- Thread 2: Contains inline images (should be filtered out)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000202',+ '00000000-0000-0000-0000-00000000002a',+ false, false, NOW(), NOW());++-- Thread 3: Contains mixed media types+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000203',+ '00000000-0000-0000-0000-00000000002a',+ false, false, NOW(), NOW());++-- Thread 4: Empty thread+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000204',+ '00000000-0000-0000-0000-00000000002a',+ false, false, NOW(), NOW());++------------------------------------------------------------+-- Thread 1: Contains valid media 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-0000000e2001',+ '00000000-0000-0000-0000-000000000201',+ '00000000-0000-0000-0000-00000000002a',+ 'media-msg-201',+ FALSE,+ '00000000-0000-0000-0000-0000000c2001',+ '2025-01-01 10:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Non-inline image (should be included)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000002a2001',+ '00000000-0000-0000-0000-0000000e2001',+ 'provider-att-2001',+ 'photo.jpg',+ 'image/jpeg',+ NULL, -- not inline+ NOW());++-- Video (should be included)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000002a2002',+ '00000000-0000-0000-0000-0000000e2001',+ 'provider-att-2002',+ 'video.mp4',+ 'video/mp4',+ NULL,+ NOW());++-- Document (should NOT be included - filtered by ATTACHMENT_MIME_TYPE_FILTERS_WITH_MEDIA)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000002a2003',+ '00000000-0000-0000-0000-0000000e2001',+ 'provider-att-2003',+ 'document.pdf',+ 'application/pdf',+ NULL,+ NOW());++------------------------------------------------------------+-- Thread 2: Contains inline images (should be filtered out)+------------------------------------------------------------++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-0000000e2002',+ '00000000-0000-0000-0000-000000000202',+ '00000000-0000-0000-0000-00000000002a',+ 'media-msg-202',+ FALSE,+ '00000000-0000-0000-0000-0000000c2001',+ '2025-01-01 11:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Inline image (should NOT be included due to content_id)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000002a2004',+ '00000000-0000-0000-0000-0000000e2002',+ 'provider-att-2004',+ 'inline_image.png',+ 'image/png',+ 'inline-content-id-123', -- inline attachment+ NOW());++------------------------------------------------------------+-- Thread 3: Contains mixed media types+------------------------------------------------------------++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-0000000e2003',+ '00000000-0000-0000-0000-000000000203',+ '00000000-0000-0000-0000-00000000002a',+ 'media-msg-203',+ FALSE,+ '00000000-0000-0000-0000-0000000c2001',+ '2025-01-01 12:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- PNG image+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000002a2005',+ '00000000-0000-0000-0000-0000000e2003',+ 'provider-att-2005',+ 'screenshot.png',+ 'image/png',+ NULL,+ NOW());++-- GIF image+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000002a2006',+ '00000000-0000-0000-0000-0000000e2003',+ 'provider-att-2006',+ 'animation.gif',+ 'image/gif',+ NULL,+ NOW());++-- MOV video+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000002a2007',+ '00000000-0000-0000-0000-0000000e2003',+ 'provider-att-2007',+ 'clip.mov',+ 'video/quicktime',+ NULL,+ NOW());++------------------------------------------------------------+-- Thread 4: Empty thread with message but no 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-0000000e2004',+ '00000000-0000-0000-0000-000000000204',+ '00000000-0000-0000-0000-00000000002a',+ 'media-msg-204',+ FALSE,+ '00000000-0000-0000-0000-0000000c2001',+ '2025-01-01 13:00:00 +00:00',+ false, false, false, false, NOW(), NOW());\ No newline at end of filediff --git a/rust/cloud-storage/email_db_client/src/attachments/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/mod.rsindex afcbf504a1..4e019a5465 100644--- a/rust/cloud-storage/email_db_client/src/attachments/mod.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/mod.rs@@ -1,2 +1,4 @@pub mod marco;pub mod provider;++pub mod sfs;diff --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 505f53299e..181347542e 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@@ -26,8 +26,8 @@ pub async fn insert_attachments(let existing_attachments = sqlx::query_as!(db::attachment::Attachment,r#"- SELECT id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at- FROM email_attachments+ SELECT ea.id, ea.message_id, ea.provider_attachment_id, ea.filename, ea.mime_type, ea.size_bytes, ea.content_id, eas.sfs_id, ea.created_at+ FROM email_attachments ea LEFT JOIN email_attachments_sfs eas on ea.id = eas.attachment_idWHERE message_id = $1"#,message_id@@ -162,10 +162,11 @@ pub async fn fetch_db_attachments(sqlx::query_as!(db::attachment::Attachment,r#"- SELECT id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at- FROM email_attachments- WHERE message_id = $1- ORDER BY filename NULLS LAST+ SELECT ea.id, ea.message_id, ea.provider_attachment_id, ea.filename, ea.mime_type, ea.size_bytes, ea.content_id, eas.sfs_id, ea.created_at+ FROM email_attachments ea+ LEFT JOIN email_attachments_sfs eas ON ea.id = eas.attachment_id+ WHERE ea.message_id = $1+ ORDER BY ea.filename NULLS LAST"#,message_db_id)@@ -197,15 +198,16 @@ pub async fn fetch_attachment_by_id(attachment_id: Uuid,link_id: Uuid,) -> anyhow::Result<Option<(service::attachment::Attachment, String)>> {- // Modified query to include message.provider_id+ // Modified query to include message.provider_id and sfs_idlet result = sqlx::query!(r#"SELECTa.id, a.message_id, a.provider_attachment_id,a.filename, a.mime_type, a.size_bytes,- a.content_id, a.created_at, m.provider_id as "message_provider_id!"+ a.content_id, eas.sfs_id as "sfs_id?", a.created_at, m.provider_id as "message_provider_id!"FROM email_attachments aJOIN email_messages m ON a.message_id = m.id+ LEFT JOIN email_attachments_sfs eas ON a.id = eas.attachment_idWHERE a.id = $1 AND m.link_id = $2"#,attachment_id,@@ -231,6 +233,7 @@ pub async fn fetch_attachment_by_id(mime_type: record.mime_type,size_bytes: record.size_bytes,content_id: record.content_id,+ sfs_id: record.sfs_id,created_at: record.created_at,};@@ -263,13 +266,16 @@ pub async fn get_attachments_by_thread_ids(a.mime_type,a.size_bytes,a.content_id,+ eas.sfs_id as "sfs_id?",a.created_at,m.thread_idFROMemail_attachments aJOINemail_messages m ON a.message_id = m.id- WHERE+ LEFT JOIN+ email_attachments_sfs eas ON a.id = eas.attachment_id+ WHEREm.thread_id = ANY($1)ORDER BYa.created_at ASC@@ -293,6 +299,7 @@ pub async fn get_attachments_by_thread_ids(mime_type: record.mime_type,size_bytes: record.size_bytes,content_id: record.content_id,+ sfs_id: record.sfs_id,created_at: record.created_at,};diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rsindex 80bdc0b607..16d9a9a4ea 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs@@ -1,5 +1,6 @@use crate::attachments::provider::upload_filters::{- ATTACHMENT_MIME_TYPE_FILTERS, ATTACHMENT_WHITELISTED_DOMAINS,+ ATTACHMENT_MIME_TYPE_FILTERS, ATTACHMENT_MIME_TYPE_FILTERS_WITH_MEDIA,+ ATTACHMENT_WHITELISTED_DOMAINS,};use models_email::service::attachment::AttachmentUploadMetadata;use sqlx::types::Uuid;@@ -17,7 +18,7 @@ use sqlx::{Pool, Postgres, Row};/// 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(+pub async fn thread_document_atts_for_backfill(db: &Pool<Postgres>,thread_id: Uuid,) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {@@ -72,18 +73,48 @@ pub async fn fetch_thread_attachments_for_backfill(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"),- message_db_id: row.get("message_db_id"),- thread_db_id: row.get("thread_db_id"),- sender_email: row.get("sender_email"),- subject: row.get("subject"),- })+ .map(map_row_to_attachment_metadata)+ .collect();++ Ok(attachments)+}++/// fetch videos and non-inline images from a thread for insertion into sfs. we insert them into+/// sfs so we can display thumbnails for them in the FE.+#[tracing::instrument(skip(db), err)]+pub async fn thread_media_atts_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,+ m.id as message_db_id,+ m.thread_id as thread_db_id,+ from_contact.email_address as sender_email,+ m.subject as subject+ FROM email_attachments a+ JOIN email_messages m ON a.message_id = m.id+ JOIN email_contacts from_contact ON m.from_contact_id = from_contact.id+ WHERE m.thread_id = $1+ -- attachment mime type filters injected below+ AND {}+ ORDER BY a.id+ "#,+ ATTACHMENT_MIME_TYPE_FILTERS_WITH_MEDIA+ );++ let rows = sqlx::query(&query).bind(thread_id).fetch_all(db).await?;++ let attachments = rows+ .into_iter()+ .map(map_row_to_attachment_metadata).collect();Ok(attachments)@@ -93,7 +124,7 @@ pub async fn fetch_thread_attachments_for_backfill(/// 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+/// completion like thread_document_atts_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.///@@ -179,18 +210,7 @@ pub async fn fetch_job_attachments_for_backfill(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"),- message_db_id: row.get("message_db_id"),- thread_db_id: row.get("thread_db_id"),- sender_email: row.get("sender_email"),- subject: row.get("subject"),- })+ .map(map_row_to_attachment_metadata).collect();Ok(attachments)@@ -210,7 +230,7 @@ pub async fn fetch_job_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(+pub async fn new_email_document_atts(db: &Pool<Postgres>,message_provider_id: &str,) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {@@ -271,18 +291,7 @@ pub async fn fetch_insertable_attachments_for_new_email(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"),- message_db_id: row.get("message_db_id"),- thread_db_id: row.get("thread_db_id"),- sender_email: row.get("sender_email"),- subject: row.get("subject"),- })+ .map(map_row_to_attachment_metadata).collect();// if one or more condition has already been met, return - don't need to check condition 5@@ -373,18 +382,53 @@ pub async fn fetch_insertable_attachments_for_new_email(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"),- message_db_id: row.get("message_db_id"),- thread_db_id: row.get("thread_db_id"),- sender_email: row.get("sender_email"),- subject: row.get("subject"),- })+ .map(map_row_to_attachment_metadata)+ .collect();++ Ok(attachments)+}++/// fetch videos and non-inline images for a new email for insertion into sfs. we insert them into+/// sfs so we can display thumbnails for them in the FE.+#[tracing::instrument(skip(db), err)]+pub async fn new_email_media_atts(+ db: &Pool<Postgres>,+ message_provider_id: &str,+) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {+ 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,+ m.id as message_db_id,+ m.thread_id as thread_db_id,+ from_contact.email_address as sender_email,+ m.subject as subject+ FROM email_attachments a+ JOIN email_messages m ON a.message_id = m.id+ JOIN email_contacts from_contact ON m.from_contact_id = from_contact.id+ LEFT JOIN email_attachments_sfs eas ON eas.attachment_id = a.id+ WHERE m.provider_id = $1+ -- attachment mime type filters injected below+ AND {}+ AND eas.attachment_id IS NULL+ ORDER BY a.id+ "#,+ ATTACHMENT_MIME_TYPE_FILTERS_WITH_MEDIA+ );++ let rows = sqlx::query(&query1)+ .bind(message_provider_id)+ .fetch_all(db)+ .await?;++ let attachments: Vec<AttachmentUploadMetadata> = rows+ .into_iter()+ .map(map_row_to_attachment_metadata).collect();Ok(attachments)@@ -424,5 +468,21 @@ pub async fn fetch_attachment_upload_metadata_by_id(Ok(row)}+/// Helper function to map a database row to AttachmentUploadMetadata+fn map_row_to_attachment_metadata(row: sqlx::postgres::PgRow) -> AttachmentUploadMetadata {+ 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"),+ message_db_id: row.get("message_db_id"),+ thread_db_id: row.get("thread_db_id"),+ sender_email: row.get("sender_email"),+ subject: row.get("subject"),+ }+}+#[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.rsindex 5835f9480c..d2a6d7b75b 100644--- 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.rs@@ -14,7 +14,7 @@ async fn thread_attachments_for_backfill_condition_1(pool: Pool<Postgres>) -> Reconst _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDElet thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000101")?;- let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;+ let res = thread_document_atts_for_backfill(&pool, thread_id).await?;// Only the application/pdf attachment should be includedassert_eq!(res.len(), 1);@@ -36,7 +36,7 @@ async fn thread_attachments_for_backfill_condition_2(pool: Pool<Postgres>) -> Reconst _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDElet thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000102")?;- let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;+ let res = thread_document_atts_for_backfill(&pool, thread_id).await?;assert_eq!(res.len(), 1);assert_eq!(res[0].filename, "important_doc.pdf");@@ -56,7 +56,7 @@ async fn thread_attachments_for_backfill_condition_3(pool: Pool<Postgres>) -> Reconst _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDElet thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000103")?;- let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;+ let res = thread_document_atts_for_backfill(&pool, thread_id).await?;assert_eq!(res.len(), 1);assert_eq!(res[0].filename, "same_domain_doc.pdf");@@ -76,7 +76,7 @@ async fn thread_attachments_for_backfill_no_matching_messages(pool: Pool<Postgreconst _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDElet thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000104")?;- let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;+ let res = thread_document_atts_for_backfill(&pool, thread_id).await?;assert!(res.is_empty());@@ -95,7 +95,7 @@ async fn thread_attachments_for_backfill_condition_4(pool: Pool<Postgres>) -> Reconst _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDElet thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000105")?;- let res = fetch_thread_attachments_for_backfill(&pool, thread_id).await?;+ let res = thread_document_atts_for_backfill(&pool, thread_id).await?;assert_eq!(res.len(), 1);assert_eq!(res[0].filename, "docusign_doc.pdf");@@ -149,7 +149,7 @@ async fn insertable_attachments_condition_1_user_sent_message(pool: Pool<Postgre// Test condition 1: user sent the messagelet message_provider_id = "target-msg-101";- let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;+ let res = new_email_document_atts(&pool, message_provider_id).await?;// Should return 1 attachment (sent_message_doc.pdf)assert_eq!(res.len(), 1);@@ -172,7 +172,7 @@ async fn insertable_attachments_condition_2_important_label(pool: Pool<Postgres>// Test condition 2: message has IMPORTANT labellet message_provider_id = "target-msg-201";- let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;+ let res = new_email_document_atts(&pool, message_provider_id).await?;// Should return 1 attachment (important_doc.pdf)assert_eq!(res.len(), 1);@@ -195,7 +195,7 @@ async fn insertable_attachments_condition_3_same_domain(pool: Pool<Postgres>) ->// Test condition 3: message from same domain as userlet message_provider_id = "target-msg-301";- let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;+ let res = new_email_document_atts(&pool, message_provider_id).await?;// Should return 1 attachment (same_domain_doc.pdf)assert_eq!(res.len(), 1);@@ -218,7 +218,7 @@ async fn insertable_attachments_condition_4_whitelisted_domain(pool: Pool<Postgr// Test condition 4: message from whitelisted domainlet message_provider_id = "target-msg-801";- let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;+ let res = new_email_document_atts(&pool, message_provider_id).await?;// Should return 1 attachment (whitelisted_domain_doc.pdf)assert_eq!(res.len(), 1);@@ -243,7 +243,7 @@ async fn insertable_attachments_condition_5_previously_contacted(// Test condition 4: user has previously contacted a thread participantlet message_provider_id = "target-msg-401";- let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;+ let res = new_email_document_atts(&pool, message_provider_id).await?;// Should return 1 attachment (previously_contacted_doc.pdf)// This should be found by the second query (condition 4)@@ -267,7 +267,7 @@ async fn insertable_attachments_no_conditions_met(pool: Pool<Postgres>) -> Resul// Test control case: no conditions metlet message_provider_id = "target-msg-601";- let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;+ let res = new_email_document_atts(&pool, message_provider_id).await?;// Should return 0 attachmentsassert_eq!(res.len(), 0);@@ -287,7 +287,7 @@ async fn insertable_attachments_excludes_already_uploaded(pool: Pool<Postgres>)// Test document_email exclusionlet message_provider_id = "target-msg-701";- let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;+ let res = new_email_document_atts(&pool, message_provider_id).await?;// Should return 0 attachments (attachment already exists in document_email)assert_eq!(res.len(), 0);@@ -307,7 +307,7 @@ async fn insertable_attachments_filters_mime_types(pool: Pool<Postgres>) -> Resu// Test that filtered mime types are excludedlet message_provider_id = "target-msg-101";- let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;+ let res = new_email_document_atts(&pool, message_provider_id).await?;// Should only return PDF, not image or zipassert_eq!(res.len(), 1);@@ -340,7 +340,7 @@ async fn insertable_attachments_thread_exists_logic(pool: Pool<Postgres>) -> Res// target-msg-202 is in Thread 2, which contains target-msg-201 with IMPORTANT labellet message_provider_id = "other-msg-202";- let res = fetch_insertable_attachments_for_new_email(&pool, message_provider_id).await?;+ let res = new_email_document_atts(&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@@ -366,7 +366,7 @@ async fn insertable_attachments_returns_first_query_when_available(// 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?;+ let res = new_email_document_atts(&pool, message_provider_id).await?;// Should return result from first queryassert_eq!(res.len(), 1);@@ -374,3 +374,170 @@ async fn insertable_attachments_returns_first_query_when_available(Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_thread_media_for_backfill")+ )+)]+async fn thread_media_for_backfill_includes_non_inline_images_and_videos(+ pool: Pool<Postgres>,+) -> Result<()> {+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000201")?;+ let res = thread_media_atts_for_backfill(&pool, thread_id).await?;++ // Should return 2 attachments: photo.jpg and video.mp4+ // Should NOT include document.pdf (filtered out)+ assert_eq!(res.len(), 2);++ let filenames: Vec<&str> = res.iter().map(|a| a.filename.as_str()).collect();+ assert!(filenames.contains(&"photo.jpg"));+ assert!(filenames.contains(&"video.mp4"));+ assert!(!filenames.contains(&"document.pdf"));++ // Verify mime types+ for attachment in &res {+ assert!(+ attachment.mime_type.starts_with("image/")+ || attachment.mime_type.starts_with("video/")+ );+ }++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_thread_media_for_backfill")+ )+)]+async fn thread_media_for_backfill_filters_inline_images(pool: Pool<Postgres>) -> Result<()> {+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000202")?;+ let res = thread_media_atts_for_backfill(&pool, thread_id).await?;++ // Should return 0 attachments (inline image is filtered out)+ assert_eq!(res.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_thread_media_for_backfill")+ )+)]+async fn thread_media_for_backfill_handles_multiple_media_types(+ pool: Pool<Postgres>,+) -> Result<()> {+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000203")?;+ let res = thread_media_atts_for_backfill(&pool, thread_id).await?;++ // Should return 3 attachments: PNG, GIF, MOV+ assert_eq!(res.len(), 3);++ let filenames: Vec<&str> = res.iter().map(|a| a.filename.as_str()).collect();+ assert!(filenames.contains(&"screenshot.png"));+ assert!(filenames.contains(&"animation.gif"));+ assert!(filenames.contains(&"clip.mov"));++ // Verify mime types are correct+ let mime_types: Vec<&str> = res.iter().map(|a| a.mime_type.as_str()).collect();+ assert!(mime_types.contains(&"image/png"));+ assert!(mime_types.contains(&"image/gif"));+ assert!(mime_types.contains(&"video/quicktime"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("fetch_thread_media_for_backfill")+ )+)]+async fn thread_media_for_backfill_returns_empty_for_thread_without_media(+ pool: Pool<Postgres>,+) -> Result<()> {+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000204")?;+ let res = thread_media_atts_for_backfill(&pool, thread_id).await?;++ // Should return 0 attachments+ assert_eq!(res.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("fetch_new_email_media"))+)]+async fn new_email_media_includes_non_inline_attachments(pool: Pool<Postgres>) -> Result<()> {+ let message_provider_id = "new-media-msg-301";+ let res = new_email_media_atts(&pool, message_provider_id).await?;++ // Should return 2 attachments: new_photo.jpg and new_video.mp4+ assert_eq!(res.len(), 2);++ let filenames: Vec<&str> = res.iter().map(|a| a.filename.as_str()).collect();+ assert!(filenames.contains(&"new_photo.jpg"));+ assert!(filenames.contains(&"new_video.mp4"));++ // Verify mime types+ let mime_types: Vec<&str> = res.iter().map(|a| a.mime_type.as_str()).collect();+ assert!(mime_types.contains(&"image/jpeg"));+ assert!(mime_types.contains(&"video/mp4"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("fetch_new_email_media"))+)]+async fn new_email_media_excludes_already_uploaded_to_sfs(pool: Pool<Postgres>) -> Result<()> {+ let message_provider_id = "new-media-msg-302";+ let res = new_email_media_atts(&pool, message_provider_id).await?;++ // Should return 0 attachments (attachment already exists in email_attachments_sfs)+ assert_eq!(res.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("fetch_new_email_media"))+)]+async fn new_email_media_filters_inline_images(pool: Pool<Postgres>) -> Result<()> {+ let message_provider_id = "new-media-msg-303";+ let res = new_email_media_atts(&pool, message_provider_id).await?;++ // Should return 1 attachment: attachment_image.png+ // Should NOT include inline_image.png (has content_id)+ assert_eq!(res.len(), 1);+ assert_eq!(res[0].filename, "attachment_image.png");+ assert_eq!(res[0].mime_type, "image/png");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("fetch_new_email_media"))+)]+async fn new_email_media_returns_empty_for_nonexistent_message(pool: Pool<Postgres>) -> Result<()> {+ let message_provider_id = "nonexistent-msg-id";+ let res = new_email_media_atts(&pool, message_provider_id).await?;++ // Should return 0 attachments+ assert_eq!(res.len(), 0);++ 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.rsindex 9123aeadf8..24db136444 100644--- 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.rs@@ -16,6 +16,11 @@ pub const ATTACHMENT_MIME_TYPE_FILTERS: &str = r#")"#;+/// Attachment mime type filters including videos and non-inline images+pub const ATTACHMENT_MIME_TYPE_FILTERS_WITH_MEDIA: &str = r#"+ ((a.mime_type LIKE 'image/%' AND a.content_id IS NULL) OR a.mime_type LIKE 'video/%')+"#;+/// always insert attachments sent from these domains.pub const ATTACHMENT_WHITELISTED_DOMAINS: &str = r#"OR (diff --git a/rust/cloud-storage/email_db_client/src/attachments/sfs/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/sfs/mod.rsnew file mode 100644index 0000000000..0a15834ddf--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/attachments/sfs/mod.rs@@ -0,0 +1,35 @@+use anyhow::Context;+use models_email::{db, service};+use sqlx::{Executor, Postgres};++/// Inserts an attachment SFS record into the database+#[tracing::instrument(skip(executor))]+pub async fn insert_attachment_sfs<'e, E>(+ executor: E,+ attachment_sfs: &service::attachment::AttachmentSfs,+) -> anyhow::Result<()>+where+ E: Executor<'e, Database = Postgres>,+{+ let db_attachment_sfs: db::attachment::AttachmentSfs = attachment_sfs.clone().into();++ sqlx::query!(+ r#"+ INSERT INTO email_attachments_sfs (id, attachment_id, sfs_id)+ VALUES ($1, $2, $3)+ "#,+ db_attachment_sfs.id,+ db_attachment_sfs.attachment_id,+ db_attachment_sfs.sfs_id,+ )+ .execute(executor)+ .await+ .with_context(|| {+ format!(+ "Failed to insert attachment SFS record with id {}",+ attachment_sfs.id+ )+ })?;++ Ok(())+}diff --git a/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs b/rust/cloud-storage/email_db_client/src/parse/db_to_service.rsindex 0e12139518..c5c4f21f23 100644--- a/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs+++ b/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs@@ -78,6 +78,7 @@ pub fn map_db_attachment_to_service(mime_type: db_att.mime_type,size_bytes: db_att.size_bytes,content_id: db_att.content_id,+ sfs_id: db_att.sfs_id,}}diff --git a/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs b/rust/cloud-storage/email_db_client/src/parse/service_to_db.rsindex 7df5b94368..d2141c0c4a 100644--- a/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs+++ b/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs@@ -134,6 +134,7 @@ pub fn map_service_attachments_to_db(mime_type: service_attachment.mime_type.clone(),size_bytes: service_attachment.size_bytes,content_id: service_attachment.content_id.clone(),+ sfs_id: service_attachment.sfs_id,created_at: Utc::now(),}).collect()diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rsindex 897bc9d0a6..914ac201d9 100644--- a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs@@ -116,9 +116,11 @@ pub async fn handler(};let ctx_upload = UploadAttachmentContext {+ db: &ctx.db,redis_client: &ctx.redis_client,gmail_client: &ctx.gmail_client,dss_client: &ctx.dss_client,+ sfs_client: &ctx.sfs_client,system_properties_service: &ctx.system_properties_service,access_token: &gmail_token,link: &link,diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rsindex 87835bde13..6f32d76152 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs@@ -27,9 +27,11 @@ pub async fn backfill_attachment(}let ctx_upload = UploadAttachmentContext {+ db: &ctx.db,redis_client: &ctx.redis_client,gmail_client: &ctx.gmail_client,dss_client: &ctx.dss_client,+ sfs_client: &ctx.sfs_client,system_properties_service: &ctx.system_properties_service,access_token,link,@@ -42,7 +44,7 @@ pub async fn backfill_attachment(.map_err(|e| {ProcessingError::NonRetryable(DetailedError {reason: FailureReason::GmailApiFailed,- source: e.context("Failed to fetch attachment data from Gmail"),+ source: e.context("Failed to upload attachment"),})})?;diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rsindex 652ef4552d..09f1d31a82 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@@ -239,32 +239,7 @@ async fn handle_thread_completed(})})?;- // temporarily only for macro emails, for testing- if link.macro_id.as_ref().ends_with("@macro.com") && !cfg!(not(feature = "attachment_upload")) {- 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::debug!(- "Found {} attachments to backfill for thread {}",- attachments.len(),- p.thread_db_id- );-- send_attachment_backfill_messages(ctx, link.id, job_id, attachments).await?;- }- }+ handle_thread_attachment_upload(ctx, link, job_id, p.thread_db_id).await?;Ok(())}@@ -338,3 +313,48 @@ async fn send_attachment_backfill_messages(Ok(())}++#[tracing::instrument(skip(ctx))]+async fn handle_thread_attachment_upload(+ ctx: &PubSubContext,+ link: &Link,+ job_id: Uuid,+ thread_db_id: Uuid,+) -> Result<(), ProcessingError> {+ // temporarily only for macro emails, for testing+ if !link.macro_id.as_ref().ends_with("@macro.com") || cfg!(not(feature = "attachment_upload")) {+ return Ok(());+ }++ let (attachments, attachments2) = tokio::try_join!(+ email_db_client::attachments::provider::upload::thread_document_atts_for_backfill(+ &ctx.db,+ thread_db_id,+ ),+ email_db_client::attachments::provider::upload::thread_media_atts_for_backfill(+ &ctx.db,+ thread_db_id,+ )+ )+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to fetch thread attachment backfill metadata".to_string()),+ })+ })?;++ let mut all_attachments = attachments;+ all_attachments.extend(attachments2);++ if !all_attachments.is_empty() {+ tracing::debug!(+ "Found {} attachments to backfill for thread {}",+ all_attachments.len(),+ thread_db_id+ );++ send_attachment_backfill_messages(ctx, link.id, job_id, all_attachments).await?;+ }++ 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 11477eed61..db5bade8a1 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@@ -198,19 +198,25 @@ async fn handle_attachment_upload(}// upload attachments to Macro- let attachments =- email_db_client::attachments::provider::upload::fetch_insertable_attachments_for_new_email(+ let (document_atts, media_atts) = tokio::try_join!(+ email_db_client::attachments::provider::upload::new_email_document_atts(+ &ctx.db,+ &payload.provider_message_id,+ ),+ email_db_client::attachments::provider::upload::new_email_media_atts(&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()),- })- })?;+ )+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to fetch attachments to insert".to_string()),+ })+ })?;+ let mut attachments = document_atts;+ attachments.extend(media_atts);if !attachments.is_empty() {tracing::info!("Uploading attachments ({:?}) to Macro for new email",@@ -256,9 +262,11 @@ async fn handle_attachment_upload(};let ctx_upload = UploadAttachmentContext {+ db: &ctx.db,redis_client: &ctx.redis_client,gmail_client: &ctx.gmail_client,dss_client: &ctx.dss_client,+ sfs_client: &ctx.sfs_client,system_properties_service: &ctx.system_properties_service,access_token: gmail_access_token,link,diff --git a/rust/cloud-storage/email_service/src/util/upload_attachment.rs b/rust/cloud-storage/email_service/src/util/upload_attachment.rsindex dc35419b7b..769d442b94 100644--- a/rust/cloud-storage/email_service/src/util/upload_attachment.rs+++ b/rust/cloud-storage/email_service/src/util/upload_attachment.rs@@ -9,31 +9,37 @@ use macro_user_id::cowlike::ArcCowStr;use macro_user_id::user_id::MacroUserId;use model::document::response::{CreateDocumentRequest, CreateDocumentResponse};use models_email::gmail::operations::GmailApiOperation;-use models_email::service::attachment::{AttachmentUploadArgs, AttachmentUploadMetadata};+use models_email::service::attachment::{+ AttachmentSfs, AttachmentUploadArgs, AttachmentUploadMetadata,+};use models_email::service::link;use sha2::{Digest, Sha256};+use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;use system_properties::{EmailAttachmentInput, EmailAttachmentProperty, PgSystemPropertiesRepository, SourceEntity,SystemPropertiesService, SystemPropertiesServiceImpl,};+use uuid::Uuid;/// Context required for uploading an email attachment.pub struct UploadAttachmentContext<'a> {+ pub db: &'a sqlx::Pool<sqlx::Postgres>,pub redis_client: &'a RedisClient,pub gmail_client: &'a GmailClient,pub dss_client: &'a DocumentStorageServiceClient,+ pub sfs_client: &'a StaticFileServiceClient,pub system_properties_service:&'a Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,pub access_token: &'a str,pub link: &'a link::Link,}-/// Upload an email attachment to DSS as a document.-#[tracing::instrument(skip(ctx, attachment_args), err)]+/// Upload an email attachment to DSS as a document or SFS as media.+#[tracing::instrument(skip(ctx, args), err)]pub async fn upload_attachment(ctx: UploadAttachmentContext<'_>,- attachment_args: &AttachmentUploadArgs,+ args: &AttachmentUploadArgs,) -> anyhow::Result<String> {// 1. Check rate limits before making a Gmail API call.check_gmail_rate_limit(@@ -49,32 +55,80 @@ pub async fn upload_attachment(let attachment_data = fetch_gmail_attachment_data(ctx.gmail_client,ctx.access_token,- &attachment_args.attachment_metadata,+ &args.attachment_metadata,).await?;- // 3. Calculate hashes required for the upload process.+ let mime_type = args.attachment_metadata.mime_type.clone();++ if mime_type.starts_with("image/") || mime_type.starts_with("video/") {+ upload_media_attachment(&ctx, args, attachment_data, mime_type).await+ } else {+ upload_document_attachment(&ctx, args, attachment_data).await+ }+}++/// Uploads an image or video attachment to SFS.+#[tracing::instrument(skip(ctx, attachment_data), err)]+async fn upload_media_attachment(+ ctx: &UploadAttachmentContext<'_>,+ args: &AttachmentUploadArgs,+ attachment_data: Vec<u8>,+ mime_type: String,+) -> anyhow::Result<String> {+ // Upload to SFS+ let sfs_response = ctx+ .sfs_client+ .put_file_with_bytes("a", bytes::Bytes::from(attachment_data), mime_type)+ .await+ .context("Failed to upload media to SFS")?;++ // Store metadata in email_attachments_sfs table+ let attachment_sfs_id = macro_uuid::generate_uuid_v7();+ let sfs_id = Uuid::parse_str(&sfs_response.id).context("Failed to parse SFS ID as UUID")?;++ email_db_client::attachments::sfs::insert_attachment_sfs(+ ctx.db,+ &AttachmentSfs {+ id: attachment_sfs_id,+ attachment_id: Some(args.attachment_metadata.attachment_db_id),+ sfs_id,+ },+ )+ .await?;++ Ok(sfs_response.id)+}++/// Uploads a document attachment to DSS.+#[tracing::instrument(skip(ctx, attachment_data), err)]+async fn upload_document_attachment(+ ctx: &UploadAttachmentContext<'_>,+ args: &AttachmentUploadArgs,+ attachment_data: Vec<u8>,+) -> anyhow::Result<String> {+ // 1. 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(&attachment_args.attachment_metadata)?;+ // 2. Determine file metadata from the payload.+ let (file_name, file_type) = determine_file_metadata(&args.attachment_metadata)?;- // 5. Create the document record in DSS and get a presigned URL for the upload.+ // 3. Create the document record in DSS and get a presigned URL for the upload.let dss_response = create_dss_document_record(ctx.dss_client,ctx.link,- &attachment_args.attachment_metadata,+ &args.attachment_metadata,&hex_hash,&file_name,&file_type,- attachment_args.backfill,+ args.backfill,).await?;- // 6. Upload the attachment data to the presigned URL.+ // 4. Upload the attachment data to the presigned URL.upload_data_to_presigned_url(&dss_response, attachment_data, &base64_hash).await?;- // 7. Return document id to caller+ // 5. Get document idlet document_id = dss_response.data.document_response@@ -82,9 +136,8 @@ pub async fn upload_attachment(.document_id.clone();- // 8. Set properties for attachment- set_email_attachment_properties(ctx.system_properties_service, &document_id, attachment_args)- .await?;+ // 6. Set properties for attachment+ set_email_attachment_properties(ctx.system_properties_service, &document_id, args).await?;Ok(document_id)}diff --git a/rust/cloud-storage/gmail_client/src/parse/message.rs b/rust/cloud-storage/gmail_client/src/parse/message.rsindex 303c5e59c5..ba44c94707 100644--- a/rust/cloud-storage/gmail_client/src/parse/message.rs+++ b/rust/cloud-storage/gmail_client/src/parse/message.rs@@ -65,6 +65,7 @@ pub fn map_message_resource_to_service(mime_type: meta.mime_type,size_bytes: meta.size_bytes,content_id: meta.content_id,+ sfs_id: None,}}).collect();diff --git a/rust/cloud-storage/macro_db_client/migrations/20251209162953_email_attachments_sfs.sql b/rust/cloud-storage/macro_db_client/migrations/20251209162953_email_attachments_sfs.sqlnew file mode 100644index 0000000000..1b3e35d3ee--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20251209162953_email_attachments_sfs.sql@@ -0,0 +1,9 @@+CREATE TABLE "email_attachments_sfs"+(+ id UUID PRIMARY KEY,+ attachment_id UUID REFERENCES email_attachments (id) ON DELETE SET NULL,+ sfs_id UUID NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++CREATE INDEX idx_email_attachments_sfs_attachment_id ON email_attachments_sfs (attachment_id);\ No newline at end of filediff --git a/rust/cloud-storage/models_email/src/email/db/attachment.rs b/rust/cloud-storage/models_email/src/email/db/attachment.rsindex 466d312831..3c578f0af6 100644--- a/rust/cloud-storage/models_email/src/email/db/attachment.rs+++ b/rust/cloud-storage/models_email/src/email/db/attachment.rs@@ -15,6 +15,7 @@ pub struct Attachment {pub mime_type: Option<String>,pub size_bytes: Option<i64>,pub content_id: Option<String>,+ pub sfs_id: Option<Uuid>,pub created_at: DateTime<Utc>,}@@ -30,3 +31,20 @@ pub struct AttachmentMacro {pub item_type: String,pub created_at: DateTime<Utc>,}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AttachmentSfs {+ pub id: Uuid,+ pub attachment_id: Option<Uuid>,+ pub sfs_id: Uuid,+}++impl From<crate::service::attachment::AttachmentSfs> for AttachmentSfs {+ fn from(service: crate::service::attachment::AttachmentSfs) -> Self {+ Self {+ id: service.id,+ attachment_id: service.attachment_id,+ sfs_id: service.sfs_id,+ }+ }+}diff --git a/rust/cloud-storage/models_email/src/email/service/attachment.rs b/rust/cloud-storage/models_email/src/email/service/attachment.rsindex 425a91838c..681a25b3e7 100644--- a/rust/cloud-storage/models_email/src/email/service/attachment.rs+++ b/rust/cloud-storage/models_email/src/email/service/attachment.rs@@ -1,3 +1,4 @@+use crate::db;use chrono::{DateTime, Utc};use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -20,6 +21,8 @@ pub struct Attachment {pub filename: Option<String>,pub mime_type: Option<String>,pub size_bytes: Option<i64>,+ #[schemars(with = "Option<String>")]+ pub sfs_id: Option<Uuid>,pub content_id: Option<String>,}@@ -38,6 +41,23 @@ pub struct AttachmentMacro {pub item_type: String,}+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AttachmentSfs {+ pub id: Uuid,+ pub attachment_id: Option<Uuid>,+ pub sfs_id: Uuid,+}++impl From<db::attachment::AttachmentSfs> for AttachmentSfs {+ fn from(db: db::attachment::AttachmentSfs) -> Self {+ Self {+ id: db.id,+ attachment_id: db.attachment_id,+ sfs_id: db.sfs_id,+ }+ }+}+/// The metadata of an attachment we need to upload it to DSS.#[derive(Clone, Debug, FromRow, Eq, PartialEq, Serialize, Deserialize)]pub struct AttachmentUploadMetadata {