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
Remove email_contact_search crate from workspace (#2599)
gbirman5aa2f6770d36
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 59b75813e5..4fb9ce45b5 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3570,24 +3570,6 @@ dependencies = ["uuid",]-[[package]]-name = "email_contact_search"-version = "0.1.0"-dependencies = [- "anyhow",- "cached",- "chrono",- "macro_db_migrator",- "macro_user_id",- "models_search_cursor",- "serde",- "sqlx",- "thiserror 2.0.17",- "tokio",- "tracing",- "uuid",-]-[[package]]name = "email_db_client"version = "0.1.0"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 52e1920d7c..d56fcfe9ac 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -37,7 +37,6 @@ members = ["documents","docx_unzip_handler","dynamodb_client",- "email_contact_search","email_db_client","email_refresh_handler","email_scheduled_handler",diff --git a/rust/cloud-storage/email_contact_search/.sqlx/query-de211130c2f52ea8c722382e14f1667389a880beb4e63ce85625b3901670e540.json b/rust/cloud-storage/email_contact_search/.sqlx/query-de211130c2f52ea8c722382e14f1667389a880beb4e63ce85625b3901670e540.jsondeleted file mode 100644index 4fe5ff4b88..0000000000--- a/rust/cloud-storage/email_contact_search/.sqlx/query-de211130c2f52ea8c722382e14f1667389a880beb4e63ce85625b3901670e540.json+++ /dev/null@@ -1,48 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n ecsi.thread_id as \"thread_id!\",\n ecsi.message_id as \"message_id!\",\n ecsi.contact_name as \"contact_name?\",\n ecsi.contact_email as \"contact_email!\",\n ecsi.contact_type as \"contact_type!\"\n FROM email_contact_search_index ecsi\n WHERE ecsi.link_id = (SELECT id FROM email_links WHERE macro_id = $1)\n AND ecsi.thread_id = ANY($2)\n AND (ecsi.contact_name ILIKE $3 OR ecsi.contact_email ILIKE $3)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "thread_id!",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "message_id!",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "contact_name?",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "contact_email!",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "contact_type!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "UuidArray",- "Text"- ]- },- "nullable": [- false,- false,- true,- false,- false- ]- },- "hash": "de211130c2f52ea8c722382e14f1667389a880beb4e63ce85625b3901670e540"-}diff --git a/rust/cloud-storage/email_contact_search/.sqlx/query-eae7fe5dd206f2147ef8f9e7c38c3dd2cc18f500c92b8912c8ba1376fc302d16.json b/rust/cloud-storage/email_contact_search/.sqlx/query-eae7fe5dd206f2147ef8f9e7c38c3dd2cc18f500c92b8912c8ba1376fc302d16.jsondeleted file mode 100644index 7ced9951e5..0000000000--- a/rust/cloud-storage/email_contact_search/.sqlx/query-eae7fe5dd206f2147ef8f9e7c38c3dd2cc18f500c92b8912c8ba1376fc302d16.json+++ /dev/null@@ -1,33 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT t.id as \"thread_id!\", t.latest_non_spam_message_ts as \"updated_at!\"\n FROM email_threads t\n WHERE t.id IN (\n SELECT DISTINCT ecsi.thread_id\n FROM email_contact_search_index ecsi\n WHERE ecsi.link_id = (SELECT id FROM email_links WHERE macro_id = $1)\n AND (ecsi.contact_name ILIKE $2 OR ecsi.contact_email ILIKE $2)\n )\n AND t.latest_non_spam_message_ts IS NOT NULL\n AND (\n $4::timestamptz IS NULL\n OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)\n )\n AND (\n $6::bool IS NULL\n OR $6::bool = (NOT (\n EXISTS (\n SELECT 1 FROM email_messages em_dep\n JOIN email_message_labels ml_dep ON ml_dep.message_id = em_dep.id\n JOIN email_labels l_dep ON ml_dep.label_id = l_dep.id\n WHERE em_dep.thread_id = t.id\n AND l_dep.name IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')\n )\n AND NOT EXISTS (\n SELECT 1 FROM email_messages em_pri\n JOIN email_message_labels ml_pri ON ml_pri.message_id = em_pri.id\n JOIN email_labels l_pri ON ml_pri.label_id = l_pri.id\n WHERE em_pri.thread_id = t.id\n AND l_pri.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')\n )\n ))\n )\n ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC\n LIMIT $3\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "thread_id!",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "updated_at!",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Text",- "Text",- "Int8",- "Timestamptz",- "Uuid",- "Bool"- ]- },- "nullable": [- false,- true- ]- },- "hash": "eae7fe5dd206f2147ef8f9e7c38c3dd2cc18f500c92b8912c8ba1376fc302d16"-}diff --git a/rust/cloud-storage/email_contact_search/Cargo.toml b/rust/cloud-storage/email_contact_search/Cargo.tomldeleted file mode 100644index a88155a0c9..0000000000--- a/rust/cloud-storage/email_contact_search/Cargo.toml+++ /dev/null@@ -1,21 +0,0 @@-[package]-edition = "2024"-name = "email_contact_search"-publish = false-version = "0.1.0"--[dependencies]-anyhow = { workspace = true }-cached = { workspace = true }-chrono = { workspace = true }-macro_user_id = { path = "../macro_user_id" }-models_search_cursor = { path = "../models_search_cursor" }-serde = { workspace = true }-sqlx = { workspace = true }-thiserror = { workspace = true }-tracing = { workspace = true }-uuid = { workspace = true }--[dev-dependencies]-macro_db_migrator = { path = "../macro_db_migrator" }-tokio = { workspace = true }diff --git a/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sql b/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sqldeleted file mode 100644index 4e6549185f..0000000000--- a/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sql+++ /dev/null@@ -1,137 +0,0 @@--- Test macro_users-INSERT INTO "macro_user" (id, username, email, stripe_customer_id)-VALUES- ('b1111111-1111-1111-1111-111111111111', 'user1', '[email protected]', 'stripe_id_1'),- ('b2222222-2222-2222-2222-222222222222', 'user2', '[email protected]', 'stripe_id_2');---- Test users-INSERT INTO "User" (id, email, name, macro_user_id)-VALUES- ('macro|[email protected]', '[email protected]', 'Test User 1', 'b1111111-1111-1111-1111-111111111111'),- ('macro|[email protected]', '[email protected]', 'Test User 2', 'b2222222-2222-2222-2222-222222222222');---- Email links (email account connections for each user)-INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)-VALUES- ('00000000-0000-0001-0000-000000000001', 'macro|[email protected]', 'fa_user1', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),- ('00000000-0000-0002-0000-000000000002', 'macro|[email protected]', 'fa_user2', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');---- Email contacts with various names for testing-INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)-VALUES- -- Contacts for user1's link- ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Alice Smith', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),- ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Bob Johnson', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),- ('cccccccc-cccc-cccc-cccc-cccccccccccc', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Charlie Brown', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),- ('dddddddd-dddd-dddd-dddd-dddddddddddd', '00000000-0000-0001-0000-000000000001', '[email protected]', 'David Miller', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),- -- Contact with NULL name (should use message-level override)- ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '00000000-0000-0001-0000-000000000001', '[email protected]', NULL, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),-- -- Contacts for cursor tie-breaking tests- ('a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Sam Taylor', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),- ('a2a2a2a2-a2a2-a2a2-a2a2-a2a2a2a2a2a2', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Pat Taylor', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),-- -- Contacts for user2's link (for isolation testing)- ('ffffffff-ffff-ffff-ffff-ffffffffffff', '00000000-0000-0002-0000-000000000002', '[email protected]', 'Frank Wilson', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');---- Email threads for user1-INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)-VALUES- -- Thread 1: Most recent (latest_non_spam_message_ts: 2024-12-06)- ('11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-06 10:00:00+00', '2024-01-01 10:00:00+00', '2024-12-06 10:00:00+00'),-- -- Thread 2: Second most recent (latest_non_spam_message_ts: 2024-12-05)- ('22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-05 10:00:00+00', '2024-02-01 10:00:00+00', '2024-12-05 10:00:00+00'),-- -- Thread 3: Third most recent (latest_non_spam_message_ts: 2024-12-04)- ('33333333-3333-3333-3333-333333333333', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-04 10:00:00+00', '2024-03-01 10:00:00+00', '2024-12-04 10:00:00+00'),-- -- Thread 4: Fourth most recent (latest_non_spam_message_ts: 2024-12-03)- ('44444444-4444-4444-4444-444444444444', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-03 10:00:00+00', '2024-04-01 10:00:00+00', '2024-12-03 10:00:00+00'),-- -- Thread 5: Thread with NULL latest_non_spam_message_ts- ('55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', true, false, NULL, '2024-05-01 10:00:00+00', '2024-05-01 10:00:00+00'),-- -- Threads 6 and 7: Same latest_non_spam_message_ts for cursor tie-breaking tests- -- Thread 7 has a higher UUID so it sorts first in DESC order- ('77777777-7777-7777-7777-777777777777', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-02 10:00:00+00', '2024-06-01 10:00:00+00', '2024-12-02 10:00:00+00'),- ('66666666-6666-6666-6666-666666666666', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-02 10:00:00+00', '2024-06-01 10:00:00+00', '2024-12-02 10:00:00+00');---- Email threads for user2 (for isolation testing)-INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)-VALUES- ('99999999-9999-9999-9999-999999999999', '00000000-0000-0002-0000-000000000002', true, false, '2024-12-09 10:00:00+00', '2024-09-01 10:00:00+00', '2024-12-09 10:00:00+00');---- Email messages for user1's threads--- Thread 1: Alice is the sender-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)-VALUES- ('10000000-0001-0000-0000-000000000001', '11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'Subject 1', '2024-01-01 10:00:00+00', false, false, '2024-01-01 10:00:00+00', '2024-01-01 10:00:00+00');---- Thread 2: Bob is the sender, Alice and Charlie are recipients-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)-VALUES- ('10000000-0002-0000-0000-000000000001', '22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NULL, 'Subject 2', '2024-02-01 10:00:00+00', false, false, '2024-02-01 10:00:00+00', '2024-02-01 10:00:00+00');---- Thread 3: Charlie is the sender with message-level name override-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)-VALUES- ('10000000-0003-0000-0000-000000000001', '33333333-3333-3333-3333-333333333333', '00000000-0000-0001-0000-000000000001', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'Charles B. Brown', 'Subject 3', '2024-03-01 10:00:00+00', false, false, '2024-03-01 10:00:00+00', '2024-03-01 10:00:00+00');---- Thread 4: Emily is the sender (has NULL name in contact, uses from_name override)-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)-VALUES- ('10000000-0004-0000-0000-000000000001', '44444444-4444-4444-4444-444444444444', '00000000-0000-0001-0000-000000000001', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'Emily Davis', 'Subject 4', '2024-04-01 10:00:00+00', false, false, '2024-04-01 10:00:00+00', '2024-04-01 10:00:00+00');---- Thread 5: David is sender-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)-VALUES- ('10000000-0005-0000-0000-000000000001', '55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', 'dddddddd-dddd-dddd-dddd-dddddddddddd', NULL, 'Subject 5', '2024-05-01 10:00:00+00', false, false, '2024-05-01 10:00:00+00', '2024-05-01 10:00:00+00');---- Thread 6: Sam Taylor is the sender (tied timestamp with thread 7)-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)-VALUES- ('10000000-0006-0000-0000-000000000001', '66666666-6666-6666-6666-666666666666', '00000000-0000-0001-0000-000000000001', 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', NULL, 'Subject 6', '2024-06-01 10:00:00+00', false, false, '2024-06-01 10:00:00+00', '2024-06-01 10:00:00+00');---- Thread 7: Pat Taylor is the sender (tied timestamp with thread 6)-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)-VALUES- ('10000000-0007-0000-0000-000000000001', '77777777-7777-7777-7777-777777777777', '00000000-0000-0001-0000-000000000001', 'a2a2a2a2-a2a2-a2a2-a2a2-a2a2a2a2a2a2', NULL, 'Subject 7', '2024-06-01 10:00:00+00', false, false, '2024-06-01 10:00:00+00', '2024-06-01 10:00:00+00');---- Email messages for user2's threads (for isolation testing)-INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)-VALUES- ('10000000-0009-0000-0000-000000000001', '99999999-9999-9999-9999-999999999999', '00000000-0000-0002-0000-000000000002', 'ffffffff-ffff-ffff-ffff-ffffffffffff', NULL, 'User2 Subject', '2024-09-01 10:00:00+00', false, false, '2024-09-01 10:00:00+00', '2024-09-01 10:00:00+00');---- Message recipients for Thread 1: Alice TO, Bob CC-INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)-VALUES- ('10000000-0001-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'TO', NULL),- ('10000000-0001-0000-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'CC', NULL);---- Message recipients for Thread 2: Alice TO, Charlie CC, David BCC-INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)-VALUES- ('10000000-0002-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'TO', NULL),- ('10000000-0002-0000-0000-000000000001', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'CC', NULL),- ('10000000-0002-0000-0000-000000000001', 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'BCC', NULL);---- Message recipients for Thread 3: Bob TO with name override-INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)-VALUES- ('10000000-0003-0000-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'TO', 'Robert J.');---- Message recipients for Thread 4: David TO-INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)-VALUES- ('10000000-0004-0000-0000-000000000001', 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'TO', NULL);---- Message recipients for Thread 5: Emily TO-INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)-VALUES- ('10000000-0005-0000-0000-000000000001', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'TO', NULL);---- Message recipients for user2's thread-INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)-VALUES- ('10000000-0009-0000-0000-000000000001', 'ffffffff-ffff-ffff-ffff-ffffffffffff', 'TO', NULL);diff --git a/rust/cloud-storage/email_contact_search/src/lib.rs b/rust/cloud-storage/email_contact_search/src/lib.rsdeleted file mode 100644index ea83843278..0000000000--- a/rust/cloud-storage/email_contact_search/src/lib.rs+++ /dev/null@@ -1,248 +0,0 @@-#![deny(missing_docs)]--//! This crate contains the queries to search over macrodb for your email contacts--#[cfg(not(test))]-use cached::proc_macro::cached;-use chrono::{DateTime, Utc};-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};-use models_search_cursor::{- PaginatedResult, SearchCursorAttributes, SearchCursorOption, SearchMethodCursor,-};-use sqlx::{Pool, Postgres};--/// Errors for email contact search crate-#[derive(Debug, thiserror::Error)]-pub enum EmailContactSearchError {- /// Database error- #[error("database error occurred {0}")]- DatabaseError(#[from] sqlx::Error),- /// Empty search term- #[error("empty search term provided")]- EmptySearchTerm,-}--/// The contact type for the match-#[derive(Debug, Clone, serde::Serialize)]-pub enum ContactType {- /// To- To,- /// From- From,- /// Cc- Cc,- /// Bcc- Bcc,-}--/// Email thread contact match result-#[derive(Debug, Clone, serde::Serialize)]-pub struct EmailContactMatchThreadResult {- /// The id of the thread- pub thread_id: uuid::Uuid,- /// The id of the message where the match was found- pub message_id: uuid::Uuid,- /// The contact name that was matched on- pub contact_name: Option<String>,- /// The contact email address- pub contact_email: String,- /// The contact type of the match- pub contact_type: ContactType,- /// The timestamp used for cursor-based pagination- pub updated_at: DateTime<Utc>,-}--impl SearchCursorAttributes for EmailContactMatchThreadResult {- fn entity_id(&self) -> uuid::Uuid {- self.thread_id- }-- fn updated_at(&self) -> DateTime<Utc> {- self.updated_at- }-}--/// Helper struct for paginating by unique threads-struct ThreadPaginationEntry {- thread_id: uuid::Uuid,- updated_at: DateTime<Utc>,-}--impl SearchCursorAttributes for ThreadPaginationEntry {- fn entity_id(&self) -> uuid::Uuid {- self.thread_id- }-- fn updated_at(&self) -> DateTime<Utc> {- self.updated_at- }-}--/// Search over your email contacts to find potential contact name matches-#[tracing::instrument(skip(db), err)]-#[cfg_attr(- not(test),- cached(- time = 30,- result = true,- key = "String",- convert = r#"{ format!("{}-{}-{}-{}-{:?}", macro_user_id.as_ref(), term, limit, cursor.as_ref().map(|c| format!("{}-{}", c.entity_id, c.updated_at)).unwrap_or_default(), importance) }"#- )-)]-pub async fn search_email_contacts<'a>(- db: &Pool<Postgres>,- macro_user_id: MacroUserId<Lowercase<'a>>,- term: String,- limit: u32,- cursor: Option<SearchMethodCursor>,- importance: Option<bool>,-) -> Result<PaginatedResult<EmailContactMatchThreadResult>, EmailContactSearchError> {- if term.is_empty() {- return Err(EmailContactSearchError::EmptySearchTerm);- }-- let search_pattern = format!("%{term}%");-- let (cursor_updated_at, cursor_entity_id) = cursor- .as_ref()- .map(|c| (Some(c.updated_at), Some(c.entity_id)))- .unwrap_or((None, None));-- // Fetch limit + 1 to determine if there are more results- let fetch_limit = limit as i64 + 1;-- // Find threads with matching contacts, sorted by most recent activity.- // Uses trigram indexes on contact_name/email for the ILIKE search, then- // joins email_threads for timestamp-based ordering and cursor pagination.- let thread_rows = sqlx::query!(- r#"- SELECT t.id as "thread_id!", t.latest_non_spam_message_ts as "updated_at!"- FROM email_threads t- WHERE t.id IN (- SELECT DISTINCT ecsi.thread_id- FROM email_contact_search_index ecsi- WHERE ecsi.link_id = (SELECT id FROM email_links WHERE macro_id = $1)- AND (ecsi.contact_name ILIKE $2 OR ecsi.contact_email ILIKE $2)- )- AND t.latest_non_spam_message_ts IS NOT NULL- AND (- $4::timestamptz IS NULL- OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)- )- AND (- $6::bool IS NULL- OR $6::bool = (NOT (- EXISTS (- SELECT 1 FROM email_messages em_dep- JOIN email_message_labels ml_dep ON ml_dep.message_id = em_dep.id- JOIN email_labels l_dep ON ml_dep.label_id = l_dep.id- WHERE em_dep.thread_id = t.id- AND l_dep.name IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')- )- AND NOT EXISTS (- SELECT 1 FROM email_messages em_pri- JOIN email_message_labels ml_pri ON ml_pri.message_id = em_pri.id- JOIN email_labels l_pri ON ml_pri.label_id = l_pri.id- WHERE em_pri.thread_id = t.id- AND l_pri.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')- )- ))- )- ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC- LIMIT $3- "#,- macro_user_id.as_ref(),- search_pattern,- fetch_limit,- cursor_updated_at,- cursor_entity_id,- importance,- )- .fetch_all(db)- .await?;-- let thread_entries: Vec<ThreadPaginationEntry> = thread_rows- .iter()- .map(|row| ThreadPaginationEntry {- thread_id: row.thread_id,- updated_at: row.updated_at,- })- .collect();-- let paginated_threads = SearchCursorOption::paginate(thread_entries, limit as usize);-- let thread_ids: Vec<uuid::Uuid> = paginated_threads- .items- .iter()- .map(|t| t.thread_id)- .collect();-- if thread_ids.is_empty() {- return Ok(PaginatedResult {- items: vec![],- cursor: paginated_threads.cursor,- });- }-- let thread_ts_map: std::collections::HashMap<uuid::Uuid, DateTime<Utc>> = paginated_threads- .items- .iter()- .map(|t| (t.thread_id, t.updated_at))- .collect();-- // Fetch contact details for the paginated threads using the idx_ecsi_link_thread- // btree index. This avoids re-running the expensive trigram scan from the previous query.- let contact_rows = sqlx::query!(- r#"- SELECT- ecsi.thread_id as "thread_id!",- ecsi.message_id as "message_id!",- ecsi.contact_name as "contact_name?",- ecsi.contact_email as "contact_email!",- ecsi.contact_type as "contact_type!"- FROM email_contact_search_index ecsi- WHERE ecsi.link_id = (SELECT id FROM email_links WHERE macro_id = $1)- AND ecsi.thread_id = ANY($2)- AND (ecsi.contact_name ILIKE $3 OR ecsi.contact_email ILIKE $3)- "#,- macro_user_id.as_ref(),- &thread_ids,- search_pattern,- )- .fetch_all(db)- .await?;-- let mut results: Vec<EmailContactMatchThreadResult> = contact_rows- .into_iter()- .filter_map(|row| {- let updated_at = *thread_ts_map.get(&row.thread_id)?;- Some(EmailContactMatchThreadResult {- thread_id: row.thread_id,- message_id: row.message_id,- contact_name: row.contact_name,- contact_email: row.contact_email,- contact_type: match row.contact_type.as_str() {- "TO" => ContactType::To,- "CC" => ContactType::Cc,- "BCC" => ContactType::Bcc,- _ => ContactType::From,- },- updated_at,- })- })- .collect();-- results.sort_by(|a, b| {- b.updated_at- .cmp(&a.updated_at)- .then(b.thread_id.cmp(&a.thread_id))- });-- Ok(PaginatedResult {- items: results,- cursor: paginated_threads.cursor,- })-}--#[cfg(test)]-mod test;diff --git a/rust/cloud-storage/email_contact_search/src/test.rs b/rust/cloud-storage/email_contact_search/src/test.rsdeleted file mode 100644index 09bd8fabd2..0000000000--- a/rust/cloud-storage/email_contact_search/src/test.rs+++ /dev/null@@ -1,579 +0,0 @@-//! Tests for email contact search module--use macro_db_migrator::MACRO_DB_MIGRATIONS;-use macro_user_id::user_id::MacroUserId;-use models_search_cursor::SearchCursorOption;-use sqlx::{Pool, Postgres};--use super::*;--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_empty_term(pool: Pool<Postgres>) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- let result = search_email_contacts(&pool, user_id, "".to_string(), 10, None, None).await;-- assert!(result.is_err());- assert!(matches!(- result.unwrap_err(),- EmailContactSearchError::EmptySearchTerm- ));-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_finds_sender_by_name(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "Alice" - should find Thread 1 where Alice is the sender- let response =- search_email_contacts(&pool, user_id, "Alice".to_string(), 10, None, None).await?;-- // Should find matches (Alice is sender in thread 1, recipient in threads 1 and 2)- assert!(!response.items.is_empty());-- // Check that we have a From match for Alice- let from_match = response.items.iter().find(|r| {- matches!(r.contact_type, ContactType::From)- && r.contact_name.as_deref() == Some("Alice Smith")- });- assert!(from_match.is_some());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_finds_recipients(pool: Pool<Postgres>) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "Bob" - should find threads where Bob is a recipient- let response = search_email_contacts(&pool, user_id, "Bob".to_string(), 10, None, None).await?;-- assert!(!response.items.is_empty());-- // Check for CC match (Bob is CC in thread 1)- let cc_match = response.items.iter().find(|r| {- matches!(r.contact_type, ContactType::Cc)- && r.contact_name.as_deref() == Some("Bob Johnson")- && r.thread_id.to_string() == "11111111-1111-1111-1111-111111111111"- });- assert!(cc_match.is_some());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_finds_bcc_recipients(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "David" - should find thread 2 where David is BCC- let response =- search_email_contacts(&pool, user_id, "David".to_string(), 10, None, None).await?;-- assert!(!response.items.is_empty());-- // Check for BCC match- let bcc_match = response.items.iter().find(|r| {- matches!(r.contact_type, ContactType::Bcc)- && r.contact_name.as_deref() == Some("David Miller")- && r.thread_id.to_string() == "22222222-2222-2222-2222-222222222222"- });- assert!(bcc_match.is_some());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_sorted_by_latest_message(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "Smith" - Alice Smith appears in multiple threads- let response =- search_email_contacts(&pool, user_id, "Smith".to_string(), 10, None, None).await?;-- assert!(!response.items.is_empty());-- // Thread 11111111 has latest_non_spam_message_ts: 2024-12-06 (most recent)- // Thread 22222222 has latest_non_spam_message_ts: 2024-12-05 (second most recent)- // Results should be sorted by latest_non_spam_message_ts DESC- if response.items.len() >= 2 {- assert_eq!(- response.items[0].thread_id.to_string(),- "11111111-1111-1111-1111-111111111111"- );- }-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search with different cases- let response_lower =- search_email_contacts(&pool, user_id.clone(), "alice".to_string(), 10, None, None).await?;- let response_upper =- search_email_contacts(&pool, user_id.clone(), "ALICE".to_string(), 10, None, None).await?;- let response_mixed =- search_email_contacts(&pool, user_id, "AlIcE".to_string(), 10, None, None).await?;-- // All should return the same number of results- assert_eq!(response_lower.items.len(), response_upper.items.len());- assert_eq!(response_lower.items.len(), response_mixed.items.len());- assert!(!response_lower.items.is_empty());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_partial_match(pool: Pool<Postgres>) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for partial term "John" should match "Bob Johnson"- let response =- search_email_contacts(&pool, user_id, "John".to_string(), 10, None, None).await?;-- assert!(!response.items.is_empty());- assert!(response.items.iter().any(|r| {- r.contact_name- .as_ref()- .map_or(false, |n| n.contains("Johnson"))- }));-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_pagination_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search with limit of 2 threads - may return multiple rows per thread (one per contact match)- let response = search_email_contacts(&pool, user_id, "a".to_string(), 2, None, None).await?;-- // Limit applies to threads, not rows - verify we get at most 2 unique threads- let unique_threads: std::collections::HashSet<_> =- response.items.iter().map(|r| r.thread_id).collect();- assert!(unique_threads.len() <= 2);-- // Should have more results available- assert!(response.cursor.has_more());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_pagination_cursor(pool: Pool<Postgres>) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // First page with limit of 2- let first_response =- search_email_contacts(&pool, user_id.clone(), "a".to_string(), 2, None, None).await?;-- // Count unique threads in first page- let first_threads: std::collections::HashSet<_> =- first_response.items.iter().map(|r| r.thread_id).collect();- assert!(first_threads.len() <= 2);- assert!(first_response.cursor.has_more());-- // Extract cursor for second page- let cursor = match first_response.cursor {- SearchCursorOption::NotDone(c) => c,- SearchCursorOption::Done => panic!("Expected more results"),- };-- // Second page using cursor- let second_response =- search_email_contacts(&pool, user_id.clone(), "a".to_string(), 2, cursor, None).await?;-- // Count unique threads in second page- let second_threads: std::collections::HashSet<_> =- second_response.items.iter().map(|r| r.thread_id).collect();-- // Verify no overlap between pages- assert!(first_threads.is_disjoint(&second_threads));-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_user_isolation(pool: Pool<Postgres>) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "Frank" - Frank belongs to user2, not user1- let response =- search_email_contacts(&pool, user_id, "Frank".to_string(), 10, None, None).await?;-- // Should return 0 results (Frank is not accessible to user1)- assert_eq!(response.items.len(), 0);- assert!(response.cursor.is_done());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_no_results(pool: Pool<Postgres>) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for a name that doesn't exist- let response = search_email_contacts(- &pool,- user_id,- "NonexistentPerson".to_string(),- 10,- None,- None,- )- .await?;-- assert_eq!(response.items.len(), 0);- assert!(response.cursor.is_done());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_includes_email_address(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "Alice"- let response =- search_email_contacts(&pool, user_id, "Alice".to_string(), 10, None, None).await?;-- assert!(!response.items.is_empty());-- // Check that email address is included- let alice_result = response- .items- .iter()- .find(|r| r.contact_name.as_deref() == Some("Alice Smith"))- .unwrap();- assert_eq!(alice_result.contact_email, "[email protected]");-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_uses_message_level_name_override(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "Charles" - Thread 3 has from_name = "Charles B. Brown" which overrides contact name "Charlie Brown"- let response = search_email_contacts(- &pool,- user_id.clone(),- "Charles".to_string(),- 10,- None,- None,- )- .await?;-- // Should find the message with from_name override- let charles_match = response- .items- .iter()- .find(|r| r.contact_name.as_deref() == Some("Charles B. Brown"));- assert!(charles_match.is_some());-- // The returned name should be the from_name (override), not the contact name- assert_eq!(- charles_match.unwrap().contact_name.as_deref(),- Some("Charles B. Brown")- );-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_searches_both_from_name_and_contact_name(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "Charlie" - should find thread 3 because the contact name is "Charlie Brown"- // even though the from_name is "Charles B. Brown"- let response =- search_email_contacts(&pool, user_id, "Charlie".to_string(), 10, None, None).await?;-- // Should find thread 3's sender by searching the contact name- let charlie_from_match = response.items.iter().find(|r| {- matches!(r.contact_type, ContactType::From)- && r.thread_id.to_string() == "33333333-3333-3333-3333-333333333333"- });- assert!(charlie_from_match.is_some());-- // But the displayed name should still be the from_name override- assert_eq!(- charlie_from_match.unwrap().contact_name.as_deref(),- Some("Charles B. Brown")- );-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_recipient_name_override(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "Robert" - Thread 3 has recipient with name override "Robert J." for Bob Johnson- let response =- search_email_contacts(&pool, user_id, "Robert".to_string(), 10, None, None).await?;-- // Should find the recipient with name override- let robert_match = response- .items- .iter()- .find(|r| r.contact_name.as_deref() == Some("Robert J."));- assert!(robert_match.is_some());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_pagination_by_thread(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "Smith" - matches Alice Smith who appears in:- // - Thread 1 (Dec 6) as sender and TO recipient- // - Thread 2 (Dec 5) as TO recipient- // This ensures we have 2 threads to paginate over-- // Get first thread (limit=1, cursor=None) - should be Thread 1 (most recent)- let page1 =- search_email_contacts(&pool, user_id.clone(), "Smith".to_string(), 1, None, None).await?;-- // All results on page 1 should be from Thread 1 (the most recent)- assert!(!page1.items.is_empty());- let page1_thread_ids: std::collections::HashSet<_> =- page1.items.iter().map(|r| r.thread_id).collect();- assert_eq!(page1_thread_ids.len(), 1);- assert!(- page1_thread_ids- .contains(&uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap())- );- assert!(page1.cursor.has_more());-- // Extract cursor for page 2- let cursor1 = match page1.cursor {- SearchCursorOption::NotDone(c) => c,- SearchCursorOption::Done => panic!("Expected more results"),- };-- // Get second thread using cursor - should be Thread 2 (second most recent)- let page2 = search_email_contacts(- &pool,- user_id.clone(),- "Smith".to_string(),- 1,- cursor1,- None,- )- .await?;-- // All results on page 2 should be from Thread 2- assert!(!page2.items.is_empty());- let page2_thread_ids: std::collections::HashSet<_> =- page2.items.iter().map(|r| r.thread_id).collect();- assert_eq!(page2_thread_ids.len(), 1);- assert!(- page2_thread_ids- .contains(&uuid::Uuid::parse_str("22222222-2222-2222-2222-222222222222").unwrap())- );-- // Verify the two pages return different threads- assert!(page1_thread_ids.is_disjoint(&page2_thread_ids));-- // Page 2 should indicate no more results since there are only 2 threads matching "Smith"- assert!(page2.cursor.is_done());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_by_email_address(pool: Pool<Postgres>) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Search for "bob.johnson" - should match [email protected]- let response = search_email_contacts(- &pool,- user_id.clone(),- "bob.johnson".to_string(),- 10,- None,- None,- )- .await?;-- assert!(!response.items.is_empty());-- // Should find Bob Johnson by email address- let bob_match = response- .items- .iter()- .find(|r| r.contact_email == "[email protected]");- assert!(bob_match.is_some());-- // Search for partial email domain - should match all @example.com contacts- let domain_response =- search_email_contacts(&pool, user_id, "@example.com".to_string(), 10, None, None).await?;-- assert!(!domain_response.items.is_empty());-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../fixtures", scripts("email_contacts"))-)]-async fn test_search_email_contacts_cursor_tiebreak_on_identical_timestamps(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {- let user_id = MacroUserId::parse_from_str("macro|[email protected]")- .map(|l| l.lowercase())- .unwrap();-- // Threads 6 (66666666) and 7 (77777777) both have latest_non_spam_message_ts = 2024-12-02.- // ORDER BY ts DESC, id DESC means thread 7 (higher UUID) comes first.- let thread_7 = uuid::Uuid::parse_str("77777777-7777-7777-7777-777777777777").unwrap();- let thread_6 = uuid::Uuid::parse_str("66666666-6666-6666-6666-666666666666").unwrap();-- // Page 1: limit=1 should return thread 7- let page1 =- search_email_contacts(&pool, user_id.clone(), "Taylor".to_string(), 1, None, None).await?;-- let page1_thread_ids: Vec<_> = {- let mut seen = std::collections::HashSet::new();- page1- .items- .iter()- .filter(|r| seen.insert(r.thread_id))- .map(|r| r.thread_id)- .collect()- };- assert_eq!(page1_thread_ids, vec![thread_7]);- assert!(page1.cursor.has_more());-- // Page 2: should return thread 6- let cursor = match page1.cursor {- SearchCursorOption::NotDone(c) => c,- SearchCursorOption::Done => panic!("Expected more results"),- };-- let page2 =- search_email_contacts(&pool, user_id, "Taylor".to_string(), 1, cursor, None).await?;-- let page2_thread_ids: Vec<_> = {- let mut seen = std::collections::HashSet::new();- page2- .items- .iter()- .filter(|r| seen.insert(r.thread_id))- .map(|r| r.thread_id)- .collect()- };- assert_eq!(page2_thread_ids, vec![thread_6]);- assert!(page2.cursor.is_done());-- Ok(())-}diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex bcc3274b31..b9688530ca 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -75,7 +75,6 @@ setup_test_envs:echo "DATABASE_URL={{ MACRODB }}" >> ./system_properties/.envecho "DATABASE_URL={{ MACRODB }}" >> ./properties/.envecho "DATABASE_URL={{ MACRODB }}" >> ./name_search/.env- echo "DATABASE_URL={{ MACRODB }}" >> ./email_contact_search/.envecho "DATABASE_URL={{ MACRODB }}" >> ./email_scheduled_handler/.envecho "DATABASE_URL={{ MACRODB }}" >> ./saved_views/.envecho "DATABASE_URL={{ MACRODB }}" >> ./channels/.env