Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(search): return pretty sender email contact info from search backend (#563)

Will Hutchinson64bea51338eb
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 18fb636984..50db3dfa2c 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -5578,6 +5578,7 @@ dependencies = [
"serde_json",
"strum",
"utoipa",
+ "uuid",
]
[[package]]
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-42d05e1c196ce37f6035ddea8be8cbbbd11313b1833204ca91863d34e89d716e.json b/rust/cloud-storage/email_db_client/.sqlx/query-42d05e1c196ce37f6035ddea8be8cbbbd11313b1833204ca91863d34e89d716e.json
new file mode 100644
index 0000000000..3351343eca
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-42d05e1c196ce37f6035ddea8be8cbbbd11313b1833204ca91863d34e89d716e.json
@@ -0,0 +1,71 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.thread_id,\n MIN(m.created_at) as \"earliest_created_at!\",\n MAX(m.created_at) as \"latest_updated_at!\",\n uh.updated_at as \"viewed_at?\",\n m.snippet,\n m.subject as \"subject?\",\n l.macro_id,\n latest_msg.sender as sender,\n latest_msg.pretty_sender as \"pretty_sender!\"\n FROM email_messages m\n LEFT JOIN email_user_history uh ON uh.thread_id = m.thread_id AND uh.link_id = $1\n LEFT JOIN email_links l ON l.id = m.link_id\n LEFT JOIN LATERAL (\n SELECT \n c.email_address as sender,\n COALESCE(c.name, c.email_address) as pretty_sender\n FROM email_messages m2\n LEFT JOIN email_contacts c ON c.id = m2.from_contact_id\n WHERE m2.thread_id = m.thread_id \n AND m2.link_id = $1\n ORDER BY m2.internal_date_ts DESC NULLS LAST\n LIMIT 1\n ) latest_msg ON true\n WHERE m.thread_id = ANY($2)\n AND m.link_id = $1\n GROUP BY m.thread_id, uh.updated_at, m.snippet, m.subject, l.macro_id, latest_msg.sender, latest_msg.pretty_sender\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "earliest_created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "latest_updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "snippet",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "subject?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "macro_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "sender",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 8,
+ "name": "pretty_sender!",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null,
+ false,
+ true,
+ true,
+ false,
+ false,
+ null
+ ]
+ },
+ "hash": "42d05e1c196ce37f6035ddea8be8cbbbd11313b1833204ca91863d34e89d716e"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-4fef13bb7ed412b7797054c7886b5f39a2c02943023e41ebb7f24d67804b5f86.json b/rust/cloud-storage/email_db_client/.sqlx/query-4fef13bb7ed412b7797054c7886b5f39a2c02943023e41ebb7f24d67804b5f86.json
deleted file mode 100644
index a197727611..0000000000
--- a/rust/cloud-storage/email_db_client/.sqlx/query-4fef13bb7ed412b7797054c7886b5f39a2c02943023e41ebb7f24d67804b5f86.json
+++ /dev/null
@@ -1,59 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n m.thread_id,\n MIN(m.created_at) as \"earliest_created_at!\",\n MAX(m.created_at) as \"latest_updated_at!\",\n uh.updated_at as \"viewed_at?\",\n m.snippet,\n m.subject as \"subject?\",\n l.macro_id\n FROM email_messages m\n LEFT JOIN email_user_history uh ON uh.thread_id = m.thread_id AND uh.link_id = $1\n LEFT JOIN email_links l ON l.id = m.link_id\n WHERE m.thread_id = ANY($2)\n AND m.link_id = $1\n GROUP BY m.thread_id, uh.updated_at, m.snippet, m.subject, l.macro_id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "thread_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "earliest_created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 2,
- "name": "latest_updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 3,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 4,
- "name": "snippet",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "subject?",
- "type_info": "Text"
- },
- {
- "ordinal": 6,
- "name": "macro_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "UuidArray"
- ]
- },
- "nullable": [
- false,
- null,
- null,
- false,
- true,
- true,
- false
- ]
- },
- "hash": "4fef13bb7ed412b7797054c7886b5f39a2c02943023e41ebb7f24d67804b5f86"
-}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-c4a1f6b77f876941ec74751bb5813c1328a3716c1d7adc6464b60ff6a3c3e932.json b/rust/cloud-storage/email_db_client/.sqlx/query-c4a1f6b77f876941ec74751bb5813c1328a3716c1d7adc6464b60ff6a3c3e932.json
new file mode 100644
index 0000000000..7291ffb268
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-c4a1f6b77f876941ec74751bb5813c1328a3716c1d7adc6464b60ff6a3c3e932.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.id as message_id,\n c.email_address as \"sender!\",\n COALESCE(c.name, c.email_address) as \"pretty_sender!\"\n FROM email_messages m\n LEFT JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.id = ANY($1)\n AND m.link_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "sender!",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "pretty_sender!",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null
+ ]
+ },
+ "hash": "c4a1f6b77f876941ec74751bb5813c1328a3716c1d7adc6464b60ff6a3c3e932"
+}
diff --git a/rust/cloud-storage/email_db_client/src/messages/get.rs b/rust/cloud-storage/email_db_client/src/messages/get.rs
index 555a726bae..0925cb5a86 100644
--- a/rust/cloud-storage/email_db_client/src/messages/get.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/get.rs
@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+
use crate::contacts;
use crate::labels::get;
use crate::parse::db_to_service;
@@ -5,10 +7,57 @@ use anyhow::Context;
use models_email::email::db;
use models_email::email::service::message::Message;
use models_email::service::address::ContactInfo;
-use models_email::service::message::MessageToSend;
+use models_email::service::message::{MessageSenderInfo, MessageToSend};
use sqlx::PgPool;
use sqlx::types::Uuid;
+/// Returns a map of message IDs to sender info for all found messages
+#[tracing::instrument(skip(pool), err)]
+pub async fn get_message_sender_and_pretty_sender(
+ pool: &PgPool,
+ link_id: Uuid,
+ message_ids: &[Uuid],
+) -> anyhow::Result<HashMap<Uuid, MessageSenderInfo>> {
+ // TODO: use NonEmpty
+ if message_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ m.id as message_id,
+ c.email_address as "sender!",
+ COALESCE(c.name, c.email_address) as "pretty_sender!"
+ FROM email_messages m
+ LEFT JOIN email_contacts c ON c.id = m.from_contact_id
+ WHERE m.id = ANY($1)
+ AND m.link_id = $2
+ "#,
+ message_ids,
+ link_id
+ )
+ .fetch_all(pool)
+ .await
+ .context("Failed to fetch message senders")?;
+
+ let mut result = HashMap::new();
+ for row in rows {
+ let message_id = row.message_id;
+ let sender = row.sender;
+ let pretty_sender = row.pretty_sender;
+ result.insert(
+ message_id,
+ MessageSenderInfo {
+ sender,
+ pretty_sender,
+ },
+ );
+ }
+
+ Ok(result)
+}
+
/// Returns a vector of (message_id, thread_id) tuples for all found messages
pub async fn get_message_thread_ids_by_provider_ids(
pool: &PgPool,
diff --git a/rust/cloud-storage/email_db_client/src/user_history/mod.rs b/rust/cloud-storage/email_db_client/src/user_history/mod.rs
index 2ef3f59a2d..a31154eba5 100644
--- a/rust/cloud-storage/email_db_client/src/user_history/mod.rs
+++ b/rust/cloud-storage/email_db_client/src/user_history/mod.rs
@@ -50,13 +50,26 @@ pub async fn get_thread_summary_info(
uh.updated_at as "viewed_at?",
m.snippet,
m.subject as "subject?",
- l.macro_id
+ l.macro_id,
+ latest_msg.sender as sender,
+ latest_msg.pretty_sender as "pretty_sender!"
FROM email_messages m
LEFT JOIN email_user_history uh ON uh.thread_id = m.thread_id AND uh.link_id = $1
LEFT JOIN email_links l ON l.id = m.link_id
+ LEFT JOIN LATERAL (
+ SELECT
+ c.email_address as sender,
+ COALESCE(c.name, c.email_address) as pretty_sender
+ FROM email_messages m2
+ LEFT JOIN email_contacts c ON c.id = m2.from_contact_id
+ WHERE m2.thread_id = m.thread_id
+ AND m2.link_id = $1
+ ORDER BY m2.internal_date_ts DESC NULLS LAST
+ LIMIT 1
+ ) latest_msg ON true
WHERE m.thread_id = ANY($2)
AND m.link_id = $1
- GROUP BY m.thread_id, uh.updated_at, m.snippet, m.subject, l.macro_id
+ GROUP BY m.thread_id, uh.updated_at, m.snippet, m.subject, l.macro_id, latest_msg.sender, latest_msg.pretty_sender
"#,
link_id,
thread_ids
@@ -82,6 +95,8 @@ pub async fn get_thread_summary_info(
None
}
}),
+ sender: row.sender,
+ pretty_sender: row.pretty_sender,
};
result.insert(row.thread_id, summary_info);
}
diff --git a/rust/cloud-storage/email_service/src/api/internal/get_message_senders.rs b/rust/cloud-storage/email_service/src/api/internal/get_message_senders.rs
new file mode 100644
index 0000000000..004c833558
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/internal/get_message_senders.rs
@@ -0,0 +1,58 @@
+use crate::api::ApiContext;
+
+use axum::{
+ extract::State,
+ http::StatusCode,
+ response::{IntoResponse, Json, Response},
+};
+use models_email::service::message::{MessageSendersRequest, MessageSendersResponse};
+use strum_macros::AsRefStr;
+use thiserror::Error;
+
+#[derive(Debug, Error, AsRefStr)]
+pub enum GetMessageSendersError {
+ #[error("Link not found for user {0}")]
+ LinkNotFound(String),
+
+ #[error("Database query failed")]
+ QueryError(#[from] anyhow::Error),
+}
+
+impl IntoResponse for GetMessageSendersError {
+ fn into_response(self) -> Response {
+ let status_code = match self {
+ GetMessageSendersError::LinkNotFound(_) => StatusCode::NOT_FOUND,
+ GetMessageSendersError::QueryError(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ if status_code.is_server_error() {
+ tracing::error!(
+ nested_error = ?self,
+ error_type = "GetMessageSendersError",
+ variant = self.as_ref(),
+ "Internal server error");
+ }
+
+ (status_code, self.to_string()).into_response()
+ }
+}
+
+/// Get message history information for search responses
+#[tracing::instrument(skip_all)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ Json(req_body): Json<MessageSendersRequest>,
+) -> Result<Response, GetMessageSendersError> {
+ let link = email_db_client::links::get::fetch_link_by_macro_id(&ctx.db, &req_body.user_id)
+ .await?
+ .ok_or(GetMessageSendersError::LinkNotFound(req_body.user_id))?;
+
+ let sender_map = email_db_client::messages::get::get_message_sender_and_pretty_sender(
+ &ctx.db,
+ link.id,
+ &req_body.message_ids,
+ )
+ .await?;
+
+ Ok((StatusCode::OK, Json(MessageSendersResponse { sender_map })).into_response())
+}
diff --git a/rust/cloud-storage/email_service/src/api/internal/mod.rs b/rust/cloud-storage/email_service/src/api/internal/mod.rs
index b5724c1261..ebb4b683a0 100644
--- a/rust/cloud-storage/email_service/src/api/internal/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/internal/mod.rs
@@ -6,6 +6,7 @@ use crate::api::ApiContext;
mod backfill;
mod delete_user;
mod get_message_by_id;
+mod get_message_senders;
mod get_messages_by_thread_id;
mod get_search_message_by_id;
mod get_search_messages_by_thread_id;
@@ -24,6 +25,7 @@ pub fn router() -> Router<ApiContext> {
"/messages/batch",
post(get_message_by_id::get_message_by_id_batch_handler),
)
+ .route("/messages/senders", post(get_message_senders::handler))
.route("/threads/histories", post(get_thread_histories::handler))
.route(
"/threads/:id/messages",
diff --git a/rust/cloud-storage/email_service_client/src/get_message_senders.rs b/rust/cloud-storage/email_service_client/src/get_message_senders.rs
new file mode 100644
index 0000000000..2b4538d306
--- /dev/null
+++ b/rust/cloud-storage/email_service_client/src/get_message_senders.rs
@@ -0,0 +1,20 @@
+use crate::EmailServiceClient;
+use models_email::service::message::{MessageSendersRequest, MessageSendersResponse};
+
+impl EmailServiceClient {
+ pub async fn get_message_senders(
+ &self,
+ request: MessageSendersRequest,
+ ) -> anyhow::Result<MessageSendersResponse> {
+ let res = self
+ .client
+ .post(format!("{}/internal/messages/senders", self.url))
+ .json(&request)
+ .send()
+ .await?
+ .error_for_status()?;
+
+ let result = res.json::<MessageSendersResponse>().await?;
+ Ok(result)
+ }
+}
diff --git a/rust/cloud-storage/email_service_client/src/lib.rs b/rust/cloud-storage/email_service_client/src/lib.rs
index 124759575c..fbf3e6f84d 100644
--- a/rust/cloud-storage/email_service_client/src/lib.rs
+++ b/rust/cloud-storage/email_service_client/src/lib.rs
@@ -5,6 +5,7 @@ pub(crate) mod constants;
mod external;
pub mod get_message_by_id;
+pub mod get_message_senders;
pub mod get_messages_by_thread_id;
pub mod get_thread_histories;
pub mod get_thread_owner;
diff --git a/rust/cloud-storage/models_email/src/email/service/message.rs b/rust/cloud-storage/models_email/src/email/service/message.rs
index 8ac0c532de..db2055fe66 100644
--- a/rust/cloud-storage/models_email/src/email/service/message.rs
+++ b/rust/cloud-storage/models_email/src/email/service/message.rs
@@ -310,6 +310,11 @@ pub struct ThreadHistoryInfo {
pub snippet: Option<String>,
pub user_id: String,
pub subject: Option<String>,
+ /// The sender of the latest email in the thread.
+ pub sender: String,
+ /// The pretty sender of the latest email in the thread.
+ /// This could be the sender's email if there is no contact name for the sender.
+ pub pretty_sender: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -323,6 +328,26 @@ pub struct ThreadHistoryResponse {
pub history_map: HashMap<Uuid, ThreadHistoryInfo>,
}
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct MessageSenderInfo {
+ /// The sender of the message.
+ pub sender: String,
+ /// The pretty sender of the message.
+ /// This could be the sender's email if there is no contact name for the sender.
+ pub pretty_sender: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct MessageSendersRequest {
+ pub user_id: String,
+ pub message_ids: Vec<Uuid>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct MessageSendersResponse {
+ pub sender_map: HashMap<Uuid, MessageSenderInfo>,
+}
+
pub trait HasContactInfo {
fn get_from(&self) -> Option<&ContactInfo>;
fn get_to(&self) -> &[ContactInfo];
diff --git a/rust/cloud-storage/models_search/Cargo.toml b/rust/cloud-storage/models_search/Cargo.toml
index c470c5d067..9542d2c222 100644
--- a/rust/cloud-storage/models_search/Cargo.toml
+++ b/rust/cloud-storage/models_search/Cargo.toml
@@ -15,3 +15,4 @@ serde_json = { workspace = true }
strum = { workspace = true }
utoipa = { workspace = true }
document_sub_type = { path = "../document_sub_type" }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/models_search/src/email.rs b/rust/cloud-storage/models_search/src/email.rs
index 7b63d249e8..b1a7f5cb50 100644
--- a/rust/cloud-storage/models_search/src/email.rs
+++ b/rust/cloud-storage/models_search/src/email.rs
@@ -9,10 +9,14 @@ use utoipa::ToSchema;
pub struct EmailSearchResult {
/// The email message id.
/// This is only present if the search result is on the message content
- pub message_id: Option<String>,
- /// The sender
- /// This is only present if the search result is on the message content
- pub sender: Option<String>,
+ pub message_id: Option<uuid::Uuid>,
+ /// The sender.
+ /// If the match is on the subject, the sender is the latest sender on the thread.
+ pub sender: String,
+ /// The pretty sender.
+ /// If the match is on the subject, the pretty sender is the latest sender on the thread.
+ /// This could be the sender's email if there is no contact name for the sender.
+ pub pretty_sender: String,
/// This is only present if the search result is on the message content
pub recipients: Vec<String>,
/// This is only present if the search result is on the message content
diff --git a/rust/cloud-storage/models_search/src/simple.rs b/rust/cloud-storage/models_search/src/simple.rs
index 2c80b9b112..c16be23a31 100644
--- a/rust/cloud-storage/models_search/src/simple.rs
+++ b/rust/cloud-storage/models_search/src/simple.rs
@@ -33,7 +33,7 @@ pub struct SearchGotoChat {
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct SearchGotoEmail {
/// The email message id
- pub email_message_id: String,
+ pub email_message_id: uuid::Uuid,
pub bcc: Vec<String>,
pub cc: Vec<String>,
pub labels: Vec<String>,
diff --git a/rust/cloud-storage/opensearch_client/Cargo.toml b/rust/cloud-storage/opensearch_client/Cargo.toml
index 022d95a270..4fea255899 100644
--- a/rust/cloud-storage/opensearch_client/Cargo.toml
+++ b/rust/cloud-storage/opensearch_client/Cargo.toml
@@ -23,3 +23,4 @@ tracing = { workspace = true }
unicode-segmentation = "1.9.0"
strum = { workspace = true }
models_opensearch = { path = "../models_opensearch" }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rs
index b881596413..fc3c195159 100644
--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs
@@ -163,7 +163,7 @@ pub(crate) struct EmailIndex {
/// The id of the email thread
pub entity_id: String,
/// The id of the email message
- pub message_id: String,
+ pub message_id: uuid::Uuid,
/// The sender of the email message
pub sender: String,
/// The recipients of the email message
diff --git a/rust/cloud-storage/opensearch_client/src/search/model.rs b/rust/cloud-storage/opensearch_client/src/search/model.rs
index 2dfce6b309..2c07bd2031 100644
--- a/rust/cloud-storage/opensearch_client/src/search/model.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/model.rs
@@ -125,7 +125,7 @@ pub struct SearchGotoChat {
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct SearchGotoEmail {
/// The email message id
- pub email_message_id: String,
+ pub email_message_id: uuid::Uuid,
/// The bcc of the email
pub bcc: Vec<String>,
/// The cc of the email
diff --git a/rust/cloud-storage/search_service/src/api/search/email.rs b/rust/cloud-storage/search_service/src/api/search/email.rs
index cd048c9e21..0b1940f548 100644
--- a/rust/cloud-storage/search_service/src/api/search/email.rs
+++ b/rust/cloud-storage/search_service/src/api/search/email.rs
@@ -9,14 +9,16 @@ use axum::{
};
use indexmap::IndexMap;
use model::{response::ErrorResponse, user::UserContext};
-use models_email::service::message::{ThreadHistoryInfo, ThreadHistoryRequest};
+use models_email::service::message::{
+ MessageSenderInfo, MessageSendersRequest, ThreadHistoryInfo, ThreadHistoryRequest,
+};
use models_search::email::{
EmailSearchRequest, EmailSearchResponse, EmailSearchResponseItem,
EmailSearchResponseItemWithMetadata, EmailSearchResult,
};
use opensearch_client::search::model::SearchGotoContent;
use sqlx::types::Uuid;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use super::SearchPaginationParams;
@@ -60,10 +62,38 @@ pub(in crate::api::search) async fn enrich_emails(
.await
.map_err(SearchError::InternalError)?;
- // Construct enriched results
- let enriched_results = construct_search_result(results, thread_histories.history_map)
+ let message_senders: HashSet<Uuid> = results
+ .iter()
+ .filter_map(|r| {
+ if let Some(goto) = &r.goto {
+ match goto {
+ // This should only ever be an email goto
+ SearchGotoContent::Emails(goto) => Some(goto.email_message_id),
+ _ => None,
+ }
+ } else {
+ None
+ }
+ })
+ .collect();
+
+ let message_senders_map = ctx
+ .email_service_client
+ .get_message_senders(MessageSendersRequest {
+ user_id: user_id.to_string(),
+ message_ids: message_senders.into_iter().collect(),
+ })
+ .await
.map_err(SearchError::InternalError)?;
+ // Construct enriched results
+ let enriched_results = construct_search_result(
+ results,
+ thread_histories.history_map,
+ message_senders_map.sender_map,
+ )
+ .map_err(SearchError::InternalError)?;
+
Ok(enriched_results)
}
@@ -117,38 +147,57 @@ pub async fn handler(
pub fn construct_search_result(
search_results: Vec<opensearch_client::search::model::SearchHit>,
thread_histories: HashMap<Uuid, ThreadHistoryInfo>,
+ message_senders: HashMap<Uuid, MessageSenderInfo>,
) -> anyhow::Result<Vec<EmailSearchResponseItemWithMetadata>> {
// construct entity hit map of id -> vec<hits> using IndexMap to preserve insertion order
let entity_id_hit_map: IndexMap<Uuid, Vec<EmailSearchResult>> = search_results
.into_iter()
- .map(|hit| {
+ .filter_map(|hit| {
let result = if let Some(SearchGotoContent::Emails(goto)) = hit.goto {
- EmailSearchResult {
+ let sender_info = message_senders.get(&goto.email_message_id);
+ let sender = sender_info
+ .map(|a| a.sender.clone())
+ .unwrap_or(goto.sender.clone());
+ let pretty_sender = sender_info
+ .map(|a| a.pretty_sender.clone())
+ .unwrap_or(goto.sender.clone());
+ Some(EmailSearchResult {
message_id: Some(goto.email_message_id),
bcc: goto.bcc,
cc: goto.cc,
labels: goto.labels,
sent_at: goto.sent_at,
- sender: Some(goto.sender),
+ sender,
+ pretty_sender,
recipients: goto.recipients,
highlight: hit.highlight.into(),
score: hit.score,
- }
+ })
} else {
- // name match
- EmailSearchResult {
- message_id: None,
- bcc: vec![],
- cc: vec![],
- labels: vec![],
- sent_at: None,
- sender: None,
- recipients: vec![],
- highlight: hit.highlight.into(),
- score: hit.score,
+ let thread_info = thread_histories.get(&hit.entity_id.parse().unwrap());
+ if let Some(thread_info) = thread_info {
+ let sender = thread_info.sender.clone();
+ let pretty_sender = thread_info.pretty_sender.clone();
+ // name match
+ Some(EmailSearchResult {
+ message_id: None,
+ bcc: vec![],
+ cc: vec![],
+ labels: vec![],
+ sent_at: None,
+ sender,
+ pretty_sender,
+ recipients: vec![],
+ highlight: hit.highlight.into(),
+ score: hit.score,
+ })
+ } else {
+ tracing::warn!("No thread info found for entity id {}", hit.entity_id);
+ None
}
};
- (hit.entity_id.parse().unwrap(), result)
+
+ result.map(|a| (hit.entity_id.parse().unwrap(), a))
})
.fold(IndexMap::new(), |mut map, (entity_id, result)| {
map.entry(entity_id).or_insert_with(Vec::new).push(result);
diff --git a/rust/cloud-storage/search_service/src/api/search/email/test.rs b/rust/cloud-storage/search_service/src/api/search/email/test.rs
index 4223cde8e4..665bfe83ee 100644
--- a/rust/cloud-storage/search_service/src/api/search/email/test.rs
+++ b/rust/cloud-storage/search_service/src/api/search/email/test.rs
@@ -14,12 +14,14 @@ fn create_email_history(thread_id: &str) -> models_email::service::message::Thre
snippet: None,
user_id: "user1".to_string(),
subject: Some("subject".to_string()),
+ sender: "[email protected]".to_string(),
+ pretty_sender: "Pretty Sender".to_string(),
}
}
#[test]
fn test_construct_search_result_empty_input() {
- let result = construct_search_result(vec![], HashMap::new());
+ let result = construct_search_result(vec![], HashMap::new(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap().len(), 0);
}
@@ -32,7 +34,7 @@ fn test_construct_search_result_single_thread() {
entity_type: SearchEntityType::Emails,
goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(
opensearch_client::search::model::SearchGotoEmail {
- email_message_id: "msg1".to_string(),
+ email_message_id: "11111111-1111-1111-1111-111111111111".parse().unwrap(),
sender: "[email protected]".to_string(),
recipients: vec!["[email protected]".to_string()],
cc: vec![],
@@ -54,7 +56,7 @@ fn test_construct_search_result_single_thread() {
create_email_history(thread_uuid),
);
- let result = construct_search_result(search_results, thread_histories).unwrap();
+ let result = construct_search_result(search_results, thread_histories, HashMap::new()).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].extra.thread_id, thread_uuid);
@@ -64,8 +66,9 @@ fn test_construct_search_result_single_thread() {
result[0].extra.email_message_search_results[0]
.message_id
.as_ref()
- .unwrap(),
- "msg1"
+ .unwrap()
+ .to_string(),
+ "11111111-1111-1111-1111-111111111111"
);
assert_eq!(result[0].extra.subject, Some("subject".to_string()));
}
@@ -86,7 +89,7 @@ fn test_sort_stability() {
entity_type: SearchEntityType::Emails,
goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(
opensearch_client::search::model::SearchGotoEmail {
- email_message_id: "msg3".to_string(),
+ email_message_id: "33333333-3333-3333-3333-333333333333".parse().unwrap(),
sender: "[email protected]".to_string(),
recipients: vec!["[email protected]".to_string()],
cc: vec![],
@@ -106,7 +109,7 @@ fn test_sort_stability() {
entity_type: SearchEntityType::Emails,
goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(
opensearch_client::search::model::SearchGotoEmail {
- email_message_id: "msg1".to_string(),
+ email_message_id: "11111111-1111-1111-1111-111111111111".parse().unwrap(),
sender: "[email protected]".to_string(),
recipients: vec!["[email protected]".to_string()],
cc: vec![],
@@ -126,7 +129,7 @@ fn test_sort_stability() {
entity_type: SearchEntityType::Emails,
goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(
opensearch_client::search::model::SearchGotoEmail {
- email_message_id: "msg5".to_string(),
+ email_message_id: "55555555-5555-5555-5555-555555555555".parse().unwrap(),
sender: "[email protected]".to_string(),
recipients: vec!["[email protected]".to_string()],
cc: vec![],
@@ -146,7 +149,7 @@ fn test_sort_stability() {
entity_type: SearchEntityType::Emails,
goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(
opensearch_client::search::model::SearchGotoEmail {
- email_message_id: "msg2".to_string(),
+ email_message_id: "22222222-2222-2222-2222-222222222222".parse().unwrap(),
sender: "[email protected]".to_string(),
recipients: vec!["[email protected]".to_string()],
cc: vec![],
@@ -166,7 +169,7 @@ fn test_sort_stability() {
entity_type: SearchEntityType::Emails,
goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(
opensearch_client::search::model::SearchGotoEmail {
- email_message_id: "msg4".to_string(),
+ email_message_id: "44444444-4444-4444-4444-444444444444".parse().unwrap(),
sender: "[email protected]".to_string(),
recipients: vec!["[email protected]".to_string()],
cc: vec![],
@@ -191,9 +194,12 @@ fn test_sort_stability() {
);
}
- let result1 = construct_search_result(input.clone(), thread_histories.clone()).unwrap();
- let result2 = construct_search_result(input.clone(), thread_histories.clone()).unwrap();
- let result3 = construct_search_result(input.clone(), thread_histories.clone()).unwrap();
+ let result1 =
+ construct_search_result(input.clone(), thread_histories.clone(), HashMap::new()).unwrap();
+ let result2 =
+ construct_search_result(input.clone(), thread_histories.clone(), HashMap::new()).unwrap();
+ let result3 =
+ construct_search_result(input.clone(), thread_histories.clone(), HashMap::new()).unwrap();
assert_eq!(result1.len(), 5);
assert_eq!(result2.len(), 5);