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(search): create new unified query (#215)
Will Hutchinsona861b974d88b
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex ab62e186dd..626f714b3f 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5746,6 +5746,7 @@ dependencies = ["opensearch_query_builder","serde","serde_json",+ "strum","thiserror 2.0.17","tokio","tracing",diff --git a/rust/cloud-storage/models_search/src/unified.rs b/rust/cloud-storage/models_search/src/unified.rsindex 7cd3c16749..b6a61acf6e 100644--- a/rust/cloud-storage/models_search/src/unified.rs+++ b/rust/cloud-storage/models_search/src/unified.rs@@ -1,3 +1,5 @@+use std::collections::HashSet;+use crate::channel::ChannelSearchResponseItemWithMetadata;use crate::chat::ChatSearchResponseItemWithMetadata;use crate::document::DocumentSearchResponseItemWithMetadata;@@ -56,6 +58,40 @@ pub struct UnifiedSearchRequest {pub include: Vec<UnifiedSearchIndex>,}+impl From<UnifiedSearchIndex> for opensearch_client::search::model::SearchIndex {+ fn from(index: UnifiedSearchIndex) -> Self {+ match index {+ UnifiedSearchIndex::Channels => Self::Channels,+ UnifiedSearchIndex::Chats => Self::Chats,+ UnifiedSearchIndex::Documents => Self::Documents,+ UnifiedSearchIndex::Emails => Self::Emails,+ UnifiedSearchIndex::Projects => Self::Projects,+ }+ }+}++/// Generates the search indices to search over for unified search+pub fn generate_unified_search_indices(+ include: Vec<UnifiedSearchIndex>,+) -> HashSet<opensearch_client::search::model::SearchIndex> {+ if include.is_empty() {+ let include: Vec<opensearch_client::search::model::SearchIndex> = [+ UnifiedSearchIndex::Channels,+ UnifiedSearchIndex::Chats,+ UnifiedSearchIndex::Documents,+ UnifiedSearchIndex::Emails,+ UnifiedSearchIndex::Projects,+ ]+ .into_iter()+ .map(|i| i.into())+ .collect();++ include.into_iter().collect()+ } else {+ include.into_iter().map(|i| i.into()).collect()+ }+}+// TODO: there's a data correlation between Filters and Response Item. Can this be consolidated?// None means do not search this entity, Some(_::default()) means search all for this entity#[derive(Debug, Serialize, Deserialize, ToSchema, Clone, JsonSchema)]@@ -112,6 +148,80 @@ pub enum SimpleUnifiedSearchResponseBaseItem<T> {pub type SimpleUnifiedSearchResponseItem =SimpleUnifiedSearchResponseBaseItem<crate::TimestampSeconds>;+impl From<opensearch_client::search::unified::UnifiedSearchResponse>+ for SimpleUnifiedSearchResponseItem+{+ fn from(response: opensearch_client::search::unified::UnifiedSearchResponse) -> Self {+ match response {+ opensearch_client::search::unified::UnifiedSearchResponse::Document(a) => {+ SimpleUnifiedSearchResponseItem::Document(SimpleDocumentSearchResponseBaseItem {+ document_id: a.document_id,+ document_name: a.document_name,+ node_id: a.node_id,+ owner_id: a.owner_id,+ file_type: a.file_type,+ updated_at: a.updated_at.into(),+ highlight: a.highlight.into(),+ raw_content: a.raw_content,+ })+ }+ opensearch_client::search::unified::UnifiedSearchResponse::Chat(a) => {+ SimpleUnifiedSearchResponseItem::Chat(SimpleChatSearchResponseBaseItem {+ chat_id: a.chat_id,+ chat_message_id: a.chat_message_id,+ user_id: a.user_id,+ role: a.role,+ title: a.title,+ highlight: a.highlight.into(),+ updated_at: a.updated_at.into(),+ })+ }+ opensearch_client::search::unified::UnifiedSearchResponse::Email(a) => {+ SimpleUnifiedSearchResponseItem::Email(SimpleEmailSearchResponseBaseItem {+ thread_id: a.thread_id,+ message_id: a.message_id,+ subject: a.subject,+ sender: a.sender,+ recipients: a.recipients,+ cc: a.cc,+ bcc: a.bcc,+ labels: a.labels,+ link_id: a.link_id,+ user_id: a.user_id,+ updated_at: a.updated_at.into(),+ sent_at: a.sent_at.map(|a| a.into()),+ highlight: a.highlight.into(),+ })+ }+ opensearch_client::search::unified::UnifiedSearchResponse::ChannelMessage(a) => {+ SimpleUnifiedSearchResponseItem::Channel(SimpleChannelSearchReponseBaseItem {+ channel_id: a.channel_id,+ channel_name: a.channel_name,+ channel_type: a.channel_type,+ org_id: a.org_id,+ message_id: a.message_id,+ thread_id: a.thread_id,+ sender_id: a.sender_id,+ mentions: a.mentions,+ created_at: a.created_at.into(),+ updated_at: a.updated_at.into(),+ highlight: a.highlight.into(),+ })+ }+ opensearch_client::search::unified::UnifiedSearchResponse::Project(a) => {+ SimpleUnifiedSearchResponseItem::Project(SimpleProjectSearchResponseBaseItem {+ project_id: a.project_id,+ project_name: a.project_name,+ user_id: a.user_id,+ created_at: a.created_at.into(),+ updated_at: a.updated_at.into(),+ highlight: a.highlight.into(),+ })+ }+ }+ }+}+#[derive(Debug, Serialize, Deserialize, ToSchema, Default)]pub struct SimpleUnifiedSearchBaseResponse<T> {pub results: Vec<SimpleUnifiedSearchResponseBaseItem<T>>,diff --git a/rust/cloud-storage/opensearch_client/Cargo.toml b/rust/cloud-storage/opensearch_client/Cargo.tomlindex 2faf8a1322..e1286b8788 100644--- a/rust/cloud-storage/opensearch_client/Cargo.toml+++ b/rust/cloud-storage/opensearch_client/Cargo.toml@@ -21,3 +21,4 @@ serde_json = { workspace = true }thiserror = { workspace = true }tracing = { workspace = true }unicode-segmentation = "1.9.0"+strum = { workspace = true }diff --git a/rust/cloud-storage/opensearch_client/examples/get_document_by_id.rs b/rust/cloud-storage/opensearch_client/examples/get_document_by_id.rsdeleted file mode 100644index 9fb0d13943..0000000000--- a/rust/cloud-storage/opensearch_client/examples/get_document_by_id.rs+++ /dev/null@@ -1,18 +0,0 @@-use anyhow::Context;--#[tokio::main]-async fn main() -> anyhow::Result<()> {- let url = std::env::var("OPENSEARCH_URL").context("OPENSEARCH_URL not set")?;- let username = std::env::var("OPENSEARCH_USERNAME")?;- let password = std::env::var("OPENSEARCH_PASSWORD")?;-- let client = opensearch_client::OpensearchClient::new(url, username, password)?;-- let result = client- .get_document_by_id("33591bbc-6a78-4748-93ca-8c9483201059")- .await?;-- println!("Found document: {:?}", result);-- Ok(())-}diff --git a/rust/cloud-storage/opensearch_client/src/error.rs b/rust/cloud-storage/opensearch_client/src/error.rsindex 45ca0cf073..d5a845b4bb 100644--- a/rust/cloud-storage/opensearch_client/src/error.rs+++ b/rust/cloud-storage/opensearch_client/src/error.rs@@ -28,6 +28,9 @@ pub enum OpensearchClientError {#[error("no terms provided")]NoTermsProvided,+ #[error("empty search indices provided")]+ EmptySearchIndices,+#[error("an unknown error occurred. method: {method:?} details: {details}")]Unknown {details: String,diff --git a/rust/cloud-storage/opensearch_client/src/lib.rs b/rust/cloud-storage/opensearch_client/src/lib.rsindex b2957bfe29..4b9948b7e7 100644--- a/rust/cloud-storage/opensearch_client/src/lib.rs+++ b/rust/cloud-storage/opensearch_client/src/lib.rs@@ -4,6 +4,7 @@ pub mod error;pub mod get_document;pub mod search;pub mod search_on;+pub mod unified;pub mod upsert;pub use search_on::SearchOn;diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rsindex 96f40761d3..d403a2e5f2 100644--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs@@ -10,7 +10,8 @@ use crate::{use crate::SearchOn;use opensearch_query_builder::{- FieldSort, QueryType, ScoreWithOrderSort, SearchRequest, SortOrder, SortType, ToOpenSearchJson,+ BoolQueryBuilder, FieldSort, QueryType, ScoreWithOrderSort, SearchRequest, SortOrder, SortType,+ ToOpenSearchJson,};use serde_json::Value;@@ -29,7 +30,7 @@ pub(crate) struct ChannelMessageIndex {pub updated_at_seconds: i64,}-#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]pub struct ChannelMessageSearchResponse {pub channel_id: String,pub channel_name: Option<String>,@@ -46,7 +47,7 @@ pub struct ChannelMessageSearchResponse {}#[derive(Default)]-struct ChannelMessageSearchConfig;+pub(crate) struct ChannelMessageSearchConfig;impl SearchQueryConfig for ChannelMessageSearchConfig {const INDEX: &'static str = CHANNEL_INDEX;@@ -63,7 +64,7 @@ impl SearchQueryConfig for ChannelMessageSearchConfig {}#[derive(Default)]-struct ChannelMessageQueryBuilder {+pub(crate) struct ChannelMessageQueryBuilder {inner: SearchQueryBuilder<ChannelMessageSearchConfig>,thread_ids: Vec<String>,mentions: Vec<String>,@@ -106,7 +107,8 @@ impl ChannelMessageQueryBuilder {fn disable_recency(disable_recency: bool) -> Self;}- fn build_search_request(self) -> Result<SearchRequest> {+ /// Builds the main bool query for the index+ pub fn build_bool_query(&self) -> Result<BoolQueryBuilder> {// Build the main bool query containing all terms and any other filterslet mut bool_query = self.inner.build_bool_query()?;@@ -114,21 +116,26 @@ impl ChannelMessageQueryBuilder {// Add thread_ids to must clause if providedif !self.thread_ids.is_empty() {- bool_query.must(QueryType::terms("thread_id", self.thread_ids));+ bool_query.must(QueryType::terms("thread_id", self.thread_ids.clone()));}// Add mentions to must clause if providedif !self.mentions.is_empty() {- bool_query.must(QueryType::terms("mentions", self.mentions));+ bool_query.must(QueryType::terms("mentions", self.mentions.clone()));}// Add sender_ids to must clause if providedif !self.sender_ids.is_empty() {- bool_query.must(QueryType::terms("sender_id", self.sender_ids));+ bool_query.must(QueryType::terms("sender_id", self.sender_ids.clone()));}-// END CUSTOM ATTRIBUTES SECTION+ Ok(bool_query)+ }++ fn build_search_request(&self) -> Result<SearchRequest> {+ let bool_query = self.build_bool_query()?;+// Build the search request with the bool query// This will automatically wrap the bool query in a function score if// SearchOn::NameContent is used@@ -155,23 +162,29 @@ pub struct ChannelMessageSearchArgs {pub disable_recency: bool,}+impl From<ChannelMessageSearchArgs> for ChannelMessageQueryBuilder {+ fn from(args: ChannelMessageSearchArgs) -> Self {+ ChannelMessageQueryBuilder::new(args.terms)+ .match_type(&args.match_type)+ .page_size(args.page_size)+ .page(args.page)+ .user_id(&args.user_id)+ .thread_ids(args.thread_ids)+ .mentions(args.mentions)+ .ids(args.channel_ids)+ .search_on(args.search_on)+ .collapse(args.collapse)+ .ids_only(args.ids_only)+ .sender_ids(args.sender_ids)+ .disable_recency(args.disable_recency)+ }+}+impl ChannelMessageSearchArgs {pub fn build(self) -> Result<Value> {- Ok(ChannelMessageQueryBuilder::new(self.terms)- .match_type(&self.match_type)- .page_size(self.page_size)- .page(self.page)- .user_id(&self.user_id)- .thread_ids(self.thread_ids)- .mentions(self.mentions)- .ids(self.channel_ids)- .search_on(self.search_on)- .collapse(self.collapse)- .ids_only(self.ids_only)- .sender_ids(self.sender_ids)- .disable_recency(self.disable_recency)- .build_search_request()?- .to_json())+ let builder: ChannelMessageQueryBuilder = self.into();++ Ok(builder.build_search_request()?.to_json())}}diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rsindex d831a17131..d1ed2d4270 100644--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs@@ -11,7 +11,8 @@ use crate::{use crate::SearchOn;use opensearch_query_builder::{- FieldSort, ScoreWithOrderSort, SearchRequest, SortOrder, SortType, ToOpenSearchJson,+ BoolQueryBuilder, FieldSort, ScoreWithOrderSort, SearchRequest, SortOrder, SortType,+ ToOpenSearchJson,};use serde_json::Value;@@ -26,7 +27,7 @@ pub(crate) struct ChatIndex {pub content: String,}-#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]pub struct ChatSearchResponse {pub chat_id: String,pub chat_message_id: String,@@ -37,7 +38,7 @@ pub struct ChatSearchResponse {pub highlight: Highlight,}-struct ChatSearchConfig;+pub(crate) struct ChatSearchConfig;impl SearchQueryConfig for ChatSearchConfig {const INDEX: &'static str = CHAT_INDEX;@@ -53,7 +54,7 @@ impl SearchQueryConfig for ChatSearchConfig {}}-struct ChatQueryBuilder {+pub(crate) struct ChatQueryBuilder {inner: SearchQueryBuilder<ChatSearchConfig>,/// The role of the chat messagerole: Vec<String>,@@ -85,8 +86,7 @@ impl ChatQueryBuilder {self}- fn build_search_request(self) -> Result<SearchRequest> {- // Build the main bool query containing all terms and any other filters+ pub fn build_bool_query(&self) -> Result<BoolQueryBuilder> {let mut bool_query = self.inner.build_bool_query()?;// CUSTOM ATTRIBUTES SECTION@@ -99,6 +99,12 @@ impl ChatQueryBuilder {// END CUSTOM ATTRIBUTES SECTION+ Ok(bool_query)+ }++ fn build_search_request(&self) -> Result<SearchRequest> {+ let bool_query = self.build_bool_query()?;+// Build the search request with the bool query// This will automatically wrap the bool query in a function score if// SearchOn::NameContent is used@@ -123,21 +129,26 @@ pub struct ChatSearchArgs {pub disable_recency: bool,}+impl From<ChatSearchArgs> for ChatQueryBuilder {+ fn from(args: ChatSearchArgs) -> Self {+ ChatQueryBuilder::new(args.terms)+ .match_type(&args.match_type)+ .page_size(args.page_size)+ .page(args.page)+ .user_id(&args.user_id)+ .ids(args.chat_ids)+ .role(args.role)+ .search_on(args.search_on)+ .collapse(args.collapse)+ .ids_only(args.ids_only)+ .disable_recency(args.disable_recency)+ }+}+impl ChatSearchArgs {pub fn build(self) -> Result<Value> {- Ok(ChatQueryBuilder::new(self.terms)- .match_type(&self.match_type)- .page_size(self.page_size)- .page(self.page)- .user_id(&self.user_id)- .ids(self.chat_ids)- .role(self.role)- .search_on(self.search_on)- .collapse(self.collapse)- .ids_only(self.ids_only)- .disable_recency(self.disable_recency)- .build_search_request()?- .to_json())+ let builder: ChatQueryBuilder = self.into();+ Ok(builder.build_search_request()?.to_json())}}diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rsindex 0f37a84a53..04a3413018 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs@@ -10,12 +10,13 @@ use crate::{use crate::SearchOn;use opensearch_query_builder::{- FieldSort, ScoreWithOrderSort, SearchRequest, SortOrder, SortType, ToOpenSearchJson,+ BoolQueryBuilder, FieldSort, ScoreWithOrderSort, SearchRequest, SortOrder, SortType,+ ToOpenSearchJson,};use serde_json::Value;#[derive(Clone)]-struct DocumentSearchConfig;+pub(crate) struct DocumentSearchConfig;impl SearchQueryConfig for DocumentSearchConfig {const INDEX: &'static str = DOCUMENTS_INDEX;@@ -31,7 +32,7 @@ impl SearchQueryConfig for DocumentSearchConfig {}}-struct DocumentQueryBuilder {+pub(crate) struct DocumentQueryBuilder {inner: SearchQueryBuilder<DocumentSearchConfig>,}@@ -55,20 +56,24 @@ impl DocumentQueryBuilder {fn disable_recency(disable_recency: bool) -> Self;}+ pub fn build_bool_query(&self) -> Result<BoolQueryBuilder> {+ self.inner.build_bool_query()+ }+fn build_search_request(self) -> Result<SearchRequest> {// Build the search request with the bool query// This will automatically wrap the bool query in a function score if// SearchOn::NameContent is usedlet search_request = self.inner- .build_search_request(self.inner.build_bool_query()?.build())?;+ .build_search_request(self.build_bool_query()?.build())?;Ok(search_request)}}#[derive(Debug, serde::Serialize, serde::Deserialize)]-pub struct DocumentIndex {+pub(crate) struct DocumentIndex {pub entity_id: String,pub document_name: String,pub node_id: String,@@ -79,7 +84,7 @@ pub struct DocumentIndex {pub updated_at_seconds: i64,}-#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]pub struct DocumentSearchResponse {pub document_id: String,pub document_name: String,@@ -106,20 +111,25 @@ pub struct DocumentSearchArgs {pub disable_recency: bool,}+impl From<DocumentSearchArgs> for DocumentQueryBuilder {+ fn from(args: DocumentSearchArgs) -> Self {+ DocumentQueryBuilder::new(args.terms)+ .match_type(&args.match_type)+ .page_size(args.page_size)+ .page(args.page)+ .user_id(&args.user_id)+ .ids(args.document_ids)+ .search_on(args.search_on)+ .collapse(args.collapse)+ .ids_only(args.ids_only)+ .disable_recency(args.disable_recency)+ }+}+impl DocumentSearchArgs {pub fn build(self) -> Result<Value> {- Ok(DocumentQueryBuilder::new(self.terms)- .match_type(&self.match_type)- .page_size(self.page_size)- .page(self.page)- .user_id(&self.user_id)- .ids(self.document_ids)- .search_on(self.search_on)- .collapse(self.collapse)- .ids_only(self.ids_only)- .disable_recency(self.disable_recency)- .build_search_request()?- .to_json())+ let builder: DocumentQueryBuilder = self.into();+ Ok(builder.build_search_request()?.to_json())}}diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex 9456bcfa54..0793d6f0c4 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -11,13 +11,14 @@ use crate::{use crate::SearchOn;use opensearch_query_builder::{- FieldSort, QueryType, ScoreWithOrderSort, SearchRequest, SortOrder, SortType, ToOpenSearchJson,+ BoolQueryBuilder, FieldSort, QueryType, ScoreWithOrderSort, SearchRequest, SortOrder, SortType,+ ToOpenSearchJson,};use crate::search::model::DefaultSearchResponse;use serde_json::Value;-struct EmailSearchConfig;+pub(crate) struct EmailSearchConfig;impl SearchQueryConfig for EmailSearchConfig {const INDEX: &'static str = EMAIL_INDEX;@@ -32,7 +33,7 @@ impl SearchQueryConfig for EmailSearchConfig {}}-struct EmailQueryBuilder {+pub(crate) struct EmailQueryBuilder {inner: SearchQueryBuilder<EmailSearchConfig>,/// link ids to query overlink_ids: Vec<String>,@@ -96,7 +97,7 @@ impl EmailQueryBuilder {self}- fn build_search_request(self) -> Result<SearchRequest> {+ pub fn build_bool_query(&self) -> Result<BoolQueryBuilder> {// Build the main bool query containing all terms and any other filterslet mut bool_query = self.inner.build_bool_query()?;@@ -104,7 +105,7 @@ impl EmailQueryBuilder {// If link_ids are provided, add them to the queryif !self.link_ids.is_empty() {- bool_query.must(QueryType::terms("link_id", self.link_ids));+ bool_query.must(QueryType::terms("link_id", self.link_ids.clone()));}if !self.sender.is_empty() {@@ -132,18 +133,23 @@ impl EmailQueryBuilder {}// END CUSTOM ATTRIBUTES SECTION+ Ok(bool_query)+ }+ fn build_search_request(&self) -> Result<SearchRequest> {// Build the search request with the bool query// This will automatically wrap the bool query in a function score if// SearchOn::NameContent is used- let search_request = self.inner.build_search_request(bool_query.build())?;+ let search_request = self+ .inner+ .build_search_request(self.build_bool_query()?.build())?;Ok(search_request)}}#[derive(Debug, serde::Serialize, serde::Deserialize)]-struct EmailIndex {+pub(crate) struct EmailIndex {/// The id of the email threadpub entity_id: String,/// The id of the email message@@ -172,7 +178,7 @@ struct EmailIndex {pub content: String,}-#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]pub struct EmailSearchResponse {pub thread_id: String,pub message_id: String,@@ -207,25 +213,30 @@ pub struct EmailSearchArgs {pub disable_recency: bool,}+impl From<EmailSearchArgs> for EmailQueryBuilder {+ fn from(args: EmailSearchArgs) -> Self {+ EmailQueryBuilder::new(args.terms)+ .match_type(&args.match_type)+ .page_size(args.page_size)+ .page(args.page)+ .user_id(&args.user_id)+ .ids(args.thread_ids)+ .link_ids(args.link_ids)+ .sender(args.sender)+ .cc(args.cc)+ .bcc(args.bcc)+ .search_on(args.search_on)+ .recipients(args.recipients)+ .collapse(args.collapse)+ .ids_only(args.ids_only)+ .disable_recency(args.disable_recency)+ }+}+impl EmailSearchArgs {pub fn build(self) -> Result<Value> {- Ok(EmailQueryBuilder::new(self.terms)- .match_type(&self.match_type)- .page_size(self.page_size)- .page(self.page)- .user_id(&self.user_id)- .ids(self.thread_ids)- .link_ids(self.link_ids)- .sender(self.sender)- .cc(self.cc)- .bcc(self.bcc)- .search_on(self.search_on)- .recipients(self.recipients)- .collapse(self.collapse)- .ids_only(self.ids_only)- .disable_recency(self.disable_recency)- .build_search_request()?- .to_json())+ let builder: EmailQueryBuilder = self.into();+ Ok(builder.build_search_request()?.to_json())}}diff --git a/rust/cloud-storage/opensearch_client/src/search/mod.rs b/rust/cloud-storage/opensearch_client/src/search/mod.rsindex 3f026de423..f8b184883a 100644--- a/rust/cloud-storage/opensearch_client/src/search/mod.rs+++ b/rust/cloud-storage/opensearch_client/src/search/mod.rs@@ -6,4 +6,5 @@ pub mod emails;pub mod model;pub mod projects;mod query;+pub mod unified;mod utils;diff --git a/rust/cloud-storage/opensearch_client/src/search/model.rs b/rust/cloud-storage/opensearch_client/src/search/model.rsindex c595965284..98c29ffda0 100644--- a/rust/cloud-storage/opensearch_client/src/search/model.rs+++ b/rust/cloud-storage/opensearch_client/src/search/model.rs@@ -2,6 +2,16 @@ use std::{collections::HashMap, fmt::Display};use crate::search::query::Keys;+#[derive(Debug, Clone, Hash, Eq, PartialEq, strum::Display, strum::EnumString, strum::AsRefStr)]+#[strum(serialize_all = "lowercase")]+pub enum SearchIndex {+ Channels,+ Chats,+ Documents,+ Emails,+ Projects,+}+/// macro open/close tags for highlight matches#[derive(Debug, PartialEq)]pub(crate) enum MacroEm {diff --git a/rust/cloud-storage/opensearch_client/src/search/projects.rs b/rust/cloud-storage/opensearch_client/src/search/projects.rsindex 6cf2f3d7ff..1fe3b250e3 100644--- a/rust/cloud-storage/opensearch_client/src/search/projects.rs+++ b/rust/cloud-storage/opensearch_client/src/search/projects.rs@@ -9,12 +9,12 @@ use crate::{};use crate::SearchOn;-use opensearch_query_builder::{HighlightField, SearchRequest, ToOpenSearchJson};+use opensearch_query_builder::{BoolQueryBuilder, HighlightField, SearchRequest, ToOpenSearchJson};use serde::{Deserialize, Serialize};use serde_json::Value;#[derive(Clone, Default)]-struct ProjectSearchConfig;+pub(crate) struct ProjectSearchConfig;impl SearchQueryConfig for ProjectSearchConfig {const INDEX: &'static str = PROJECT_INDEX;@@ -37,7 +37,7 @@ impl SearchQueryConfig for ProjectSearchConfig {}#[derive(Default)]-struct ProjectQueryBuilder {+pub(crate) struct ProjectQueryBuilder {inner: SearchQueryBuilder<ProjectSearchConfig>,}@@ -61,14 +61,17 @@ impl ProjectQueryBuilder {fn disable_recency(disable_recency: bool) -> Self;}- fn build_search_request(self) -> Result<SearchRequest> {- // Build the main bool query containing all terms and any other filters- let bool_query = self.inner.build_bool_query()?;+ pub fn build_bool_query(&self) -> Result<BoolQueryBuilder> {+ self.inner.build_bool_query()+ }+ fn build_search_request(&self) -> Result<SearchRequest> {// Build the search request with the bool query// This will automatically wrap the bool query in a function score if// SearchOn::NameContent is used- let search_request = self.inner.build_search_request(bool_query.build())?;+ let search_request = self+ .inner+ .build_search_request(self.build_bool_query()?.build())?;Ok(search_request)}@@ -98,24 +101,29 @@ pub struct ProjectSearchArgs {pub disable_recency: bool,}+impl From<ProjectSearchArgs> for ProjectQueryBuilder {+ fn from(args: ProjectSearchArgs) -> Self {+ ProjectQueryBuilder::new(args.terms)+ .match_type(&args.match_type)+ .page_size(args.page_size)+ .page(args.page)+ .user_id(&args.user_id)+ .search_on(args.search_on)+ .collapse(args.collapse)+ .ids(args.project_ids)+ .ids_only(args.ids_only)+ .disable_recency(args.disable_recency)+ }+}+impl ProjectSearchArgs {pub fn build(self) -> Result<Value> {- Ok(ProjectQueryBuilder::new(self.terms)- .match_type(&self.match_type)- .page_size(self.page_size)- .page(self.page)- .user_id(&self.user_id)- .search_on(self.search_on)- .collapse(self.collapse)- .ids(self.project_ids)- .ids_only(self.ids_only)- .disable_recency(self.disable_recency)- .build_search_request()?- .to_json())+ let builder: ProjectQueryBuilder = self.into();+ Ok(builder.build_search_request()?.to_json())}}-#[derive(Debug, Serialize, Deserialize)]+#[derive(Debug, Serialize, Deserialize, Clone)]pub struct ProjectSearchResponse {pub project_id: String,pub user_id: String,diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsnew file mode 100644index 0000000000..d267e1d84b--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -0,0 +1,597 @@+use std::collections::HashSet;++use crate::{+ CHANNEL_INDEX, CHAT_INDEX, DOCUMENTS_INDEX, EMAIL_INDEX, PROJECT_INDEX, Result,+ error::{OpensearchClientError, ResponseExt},+ search::{+ builder::SearchQueryConfig,+ channels::{+ ChannelMessageIndex, ChannelMessageQueryBuilder, ChannelMessageSearchArgs,+ ChannelMessageSearchConfig, ChannelMessageSearchResponse,+ },+ chats::{+ ChatIndex, ChatQueryBuilder, ChatSearchArgs, ChatSearchConfig, ChatSearchResponse,+ },+ documents::{+ DocumentIndex, DocumentQueryBuilder, DocumentSearchArgs, DocumentSearchConfig,+ DocumentSearchResponse,+ },+ emails::{+ EmailIndex, EmailQueryBuilder, EmailSearchArgs, EmailSearchConfig, EmailSearchResponse,+ },+ model::{DefaultSearchResponse, Hit, MacroEm, SearchIndex, parse_highlight_hit},+ projects::{+ ProjectIndex, ProjectQueryBuilder, ProjectSearchArgs, ProjectSearchConfig,+ ProjectSearchResponse,+ },+ query::Keys,+ },+};++use crate::SearchOn;+use opensearch_query_builder::*;++#[derive(Debug, Default, Clone)]+pub struct UnifiedSearchArgs {+ pub terms: Vec<String>,+ pub user_id: String,+ pub page: u32,+ pub page_size: u32,+ pub match_type: String,+ pub search_on: SearchOn,+ pub collapse: bool,+ pub disable_recency: bool,+ /// The indices to search over+ pub search_indices: HashSet<SearchIndex>,+ /// The document search args+ pub document_search_args: UnifiedDocumentSearchArgs,+ /// The email search args. If None, we do not search emails+ pub email_search_args: UnifiedEmailSearchArgs,+ /// The channel message search args. If None, we do not search channel messages+ pub channel_message_search_args: UnifiedChannelMessageSearchArgs,+ /// The chat search args. If None, we do not search chats+ pub chat_search_args: UnifiedChatSearchArgs,+ /// The project search args. If None, we do not search projects+ pub project_search_args: UnifiedProjectSearchArgs,+}++impl From<UnifiedSearchArgs> for DocumentSearchArgs {+ fn from(args: UnifiedSearchArgs) -> Self {+ DocumentSearchArgs {+ terms: args.terms,+ user_id: args.user_id,+ page: args.page,+ page_size: args.page_size,+ match_type: args.match_type,+ search_on: args.search_on,+ collapse: args.collapse,+ disable_recency: args.disable_recency,+ ids_only: args.document_search_args.ids_only,+ document_ids: args.document_search_args.document_ids,+ }+ }+}++impl From<UnifiedSearchArgs> for EmailSearchArgs {+ fn from(args: UnifiedSearchArgs) -> Self {+ EmailSearchArgs {+ terms: args.terms,+ user_id: args.user_id,+ page: args.page,+ page_size: args.page_size,+ match_type: args.match_type,+ search_on: args.search_on,+ collapse: args.collapse,+ ids_only: false, // Email is never ids only at the moment+ disable_recency: args.disable_recency,+ thread_ids: args.email_search_args.thread_ids,+ link_ids: args.email_search_args.link_ids,+ sender: args.email_search_args.sender,+ cc: args.email_search_args.cc,+ bcc: args.email_search_args.bcc,+ recipients: args.email_search_args.recipients,+ }+ }+}++impl From<UnifiedSearchArgs> for ChannelMessageSearchArgs {+ fn from(args: UnifiedSearchArgs) -> Self {+ ChannelMessageSearchArgs {+ terms: args.terms,+ user_id: args.user_id,+ page: args.page,+ page_size: args.page_size,+ match_type: args.match_type,+ search_on: args.search_on,+ collapse: args.collapse,+ ids_only: true, // channel messages are always ids only+ disable_recency: args.disable_recency,+ channel_ids: args.channel_message_search_args.channel_ids,+ thread_ids: args.channel_message_search_args.thread_ids,+ mentions: args.channel_message_search_args.mentions,+ sender_ids: args.channel_message_search_args.sender_ids,+ }+ }+}++impl From<UnifiedSearchArgs> for ChatSearchArgs {+ fn from(args: UnifiedSearchArgs) -> Self {+ ChatSearchArgs {+ terms: args.terms,+ user_id: args.user_id,+ page: args.page,+ page_size: args.page_size,+ match_type: args.match_type,+ search_on: args.search_on,+ collapse: args.collapse,+ disable_recency: args.disable_recency,+ ids_only: args.chat_search_args.ids_only,+ chat_ids: args.chat_search_args.chat_ids,+ role: args.chat_search_args.role,+ }+ }+}++impl From<UnifiedSearchArgs> for ProjectSearchArgs {+ fn from(args: UnifiedSearchArgs) -> Self {+ ProjectSearchArgs {+ terms: args.terms,+ user_id: args.user_id,+ page: args.page,+ page_size: args.page_size,+ match_type: args.match_type,+ search_on: args.search_on,+ collapse: args.collapse,+ disable_recency: args.disable_recency,+ ids_only: args.project_search_args.ids_only,+ project_ids: args.project_search_args.project_ids,+ }+ }+}++#[derive(Debug, Default, Clone)]+pub struct UnifiedChatSearchArgs {+ pub chat_ids: Vec<String>,+ pub role: Vec<String>,+ pub ids_only: bool,+}++#[derive(Debug, Default, Clone)]+pub struct UnifiedDocumentSearchArgs {+ pub document_ids: Vec<String>,+ pub ids_only: bool,+}++#[derive(Debug, Default, Clone)]+pub struct UnifiedEmailSearchArgs {+ pub thread_ids: Vec<String>,+ pub link_ids: Vec<String>,+ pub sender: Vec<String>,+ pub cc: Vec<String>,+ pub bcc: Vec<String>,+ pub recipients: Vec<String>,+}++#[derive(Debug, Default, Clone)]+pub struct UnifiedProjectSearchArgs {+ pub project_ids: Vec<String>,+ pub ids_only: bool,+}++#[derive(Debug, Default, Clone)]+pub struct UnifiedChannelMessageSearchArgs {+ pub channel_ids: Vec<String>,+ pub thread_ids: Vec<String>,+ pub mentions: Vec<String>,+ pub sender_ids: Vec<String>,+}++/// Possible search result indices for unified search+#[derive(Debug, serde::Serialize, serde::Deserialize)]+#[serde(untagged)]+pub(crate) enum UnifiedSearchIndex {+ ChannelMessage(ChannelMessageIndex),+ Document(DocumentIndex),+ Chat(ChatIndex),+ Email(EmailIndex),+ Project(ProjectIndex),+}++#[derive(Debug)]+pub enum UnifiedSearchResponse {+ ChannelMessage(ChannelMessageSearchResponse),+ Chat(ChatSearchResponse),+ Document(DocumentSearchResponse),+ Email(EmailSearchResponse),+ Project(ProjectSearchResponse),+}++pub struct SplitUnifiedSearchResponseValues {+ pub channel_message: Vec<ChannelMessageSearchResponse>,+ pub chat: Vec<ChatSearchResponse>,+ pub document: Vec<DocumentSearchResponse>,+ pub email: Vec<EmailSearchResponse>,+ pub project: Vec<ProjectSearchResponse>,+}++pub trait SplitUnifiedSearchResponse: Iterator<Item = UnifiedSearchResponse> {+ fn split_search_response(self) -> SplitUnifiedSearchResponseValues;+}++impl<T> SplitUnifiedSearchResponse for T+where+ T: Iterator<Item = UnifiedSearchResponse>,+{+ fn split_search_response(self) -> SplitUnifiedSearchResponseValues {+ let (channel_message, chat, document, email, project) = self.into_iter().fold(+ (vec![], vec![], vec![], vec![], vec![]),+ |(mut channel_message, mut chat, mut document, mut email, mut project), item| {+ match item {+ UnifiedSearchResponse::ChannelMessage(a) => {+ channel_message.push(a);+ }+ UnifiedSearchResponse::Chat(a) => {+ chat.push(a);+ }+ UnifiedSearchResponse::Document(a) => {+ document.push(a);+ }+ UnifiedSearchResponse::Email(a) => {+ email.push(a);+ }+ UnifiedSearchResponse::Project(a) => {+ project.push(a);+ }+ }+ (channel_message, chat, document, email, project)+ },+ );++ SplitUnifiedSearchResponseValues {+ channel_message,+ chat,+ document,+ email,+ project,+ }+ }+}++impl From<Hit<UnifiedSearchIndex>> for UnifiedSearchResponse {+ fn from(index: Hit<UnifiedSearchIndex>) -> Self {+ match index._source {+ UnifiedSearchIndex::ChannelMessage(a) => {+ UnifiedSearchResponse::ChannelMessage(ChannelMessageSearchResponse {+ channel_id: a.entity_id,+ channel_name: a.channel_name,+ channel_type: a.channel_type,+ org_id: a.org_id,+ message_id: a.message_id,+ thread_id: a.thread_id,+ sender_id: a.sender_id,+ mentions: a.mentions,+ created_at: a.created_at_seconds,+ updated_at: a.updated_at_seconds,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: ChannelMessageSearchConfig::TITLE_KEY,+ content_key: ChannelMessageSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default(),+ })+ }+ UnifiedSearchIndex::Document(a) => {+ UnifiedSearchResponse::Document(DocumentSearchResponse {+ document_id: a.entity_id,+ document_name: a.document_name,+ node_id: a.node_id,+ raw_content: a.raw_content,+ owner_id: a.owner_id,+ file_type: a.file_type,+ updated_at: a.updated_at_seconds,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: DocumentSearchConfig::TITLE_KEY,+ content_key: DocumentSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default(),+ })+ }+ UnifiedSearchIndex::Email(a) => UnifiedSearchResponse::Email(EmailSearchResponse {+ thread_id: a.entity_id,+ message_id: a.message_id,+ subject: a.subject,+ sender: a.sender,+ recipients: a.recipients,+ cc: a.cc,+ bcc: a.bcc,+ labels: a.labels,+ link_id: a.link_id,+ user_id: a.user_id,+ updated_at: a.updated_at_seconds,+ sent_at: a.sent_at_seconds,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: EmailSearchConfig::TITLE_KEY,+ content_key: EmailSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default(),+ }),+ UnifiedSearchIndex::Project(a) => {+ UnifiedSearchResponse::Project(ProjectSearchResponse {+ project_id: a.entity_id,+ user_id: a.user_id,+ project_name: a.project_name,+ created_at: a.created_at_seconds,+ updated_at: a.updated_at_seconds,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: ProjectSearchConfig::TITLE_KEY,+ content_key: ProjectSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default(),+ })+ }+ UnifiedSearchIndex::Chat(a) => UnifiedSearchResponse::Chat(ChatSearchResponse {+ chat_id: a.entity_id,+ chat_message_id: a.chat_message_id,+ user_id: a.user_id,+ role: a.role,+ title: a.title,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: ChatSearchConfig::TITLE_KEY,+ content_key: ChatSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default(),+ updated_at: a.updated_at_seconds,+ }),+ }+ }+}++#[tracing::instrument(skip(args), err)]+fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequest> {+ if args.search_indices.is_empty() {+ return Err(OpensearchClientError::EmptySearchIndices);+ }+ // Build out the title keys that we could need for highlighting+ let mut title_keys = vec![];+ for index in &args.search_indices {+ match index {+ SearchIndex::Channels => title_keys.push(ChannelMessageSearchConfig::TITLE_KEY),+ SearchIndex::Chats => title_keys.push(ChatSearchConfig::TITLE_KEY),+ SearchIndex::Documents => title_keys.push(DocumentSearchConfig::TITLE_KEY),+ SearchIndex::Emails => title_keys.push(EmailSearchConfig::TITLE_KEY),+ SearchIndex::Projects => title_keys.push(ProjectSearchConfig::TITLE_KEY),+ }+ }++ let mut bool_query = BoolQueryBuilder::new();+ bool_query.minimum_should_match(1);++ if args.search_indices.contains(&SearchIndex::Documents) {+ let document_search_args: DocumentSearchArgs = args.clone().into();+ let document_query_builder: DocumentQueryBuilder = document_search_args.into();+ let mut document_bool_query = document_query_builder.build_bool_query()?;+ document_bool_query.must(QueryType::term("_index", DOCUMENTS_INDEX));+ bool_query.should(document_bool_query.build().into());+ }++ if args.search_indices.contains(&SearchIndex::Emails) {+ let email_search_args: EmailSearchArgs = args.clone().into();+ let email_query_builder: EmailQueryBuilder = email_search_args.into();+ let mut email_bool_query = email_query_builder.build_bool_query()?;+ email_bool_query.must(QueryType::term("_index", EMAIL_INDEX));+ bool_query.should(email_bool_query.build().into());+ }++ if args.search_indices.contains(&SearchIndex::Channels) {+ let channel_message_search_args: ChannelMessageSearchArgs = args.clone().into();+ let channel_message_query_builder: ChannelMessageQueryBuilder =+ channel_message_search_args.into();+ let mut channel_message_bool_query = channel_message_query_builder.build_bool_query()?;+ channel_message_bool_query.must(QueryType::term("_index", CHANNEL_INDEX));+ bool_query.should(channel_message_bool_query.build().into());+ }++ if args.search_indices.contains(&SearchIndex::Chats) {+ let chat_search_args: ChatSearchArgs = args.clone().into();+ let chat_query_builder: ChatQueryBuilder = chat_search_args.into();+ let mut chat_bool_query = chat_query_builder.build_bool_query()?;+ chat_bool_query.must(QueryType::term("_index", CHAT_INDEX));+ bool_query.should(chat_bool_query.build().into());+ }++ if args.search_indices.contains(&SearchIndex::Projects) {+ let project_search_args: ProjectSearchArgs = args.clone().into();+ let project_query_builder: ProjectQueryBuilder = project_search_args.into();+ let mut project_bool_query = project_query_builder.build_bool_query()?;+ project_bool_query.must(QueryType::term("_index", PROJECT_INDEX));+ bool_query.should(project_bool_query.build().into());+ }++ // create the search request+ let mut search_request_builder = SearchRequestBuilder::new();++ search_request_builder.from(args.page * args.page_size);+ search_request_builder.size(args.page_size);++ if args.collapse || args.search_on == SearchOn::NameContent || args.search_on == SearchOn::Name+ {+ search_request_builder.collapse(Collapse::new("entity_id"));+ }++ if args.search_on == SearchOn::NameContent {+ search_request_builder.track_total_hits(true);+ search_request_builder.add_agg(+ "total_uniques".to_string(),+ AggregationType::Cardinality(CardinalityAggregation::new("entity_id")),+ );+ }++ // Build sort+ let sort = vec![+ SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),+ SortType::Field(FieldSort::new("entity_id", SortOrder::Asc)),+ ];++ for sort in sort {+ search_request_builder.add_sort(sort);+ }++ // Build highlight+ let highlight = match args.search_on {+ SearchOn::Content => Highlight::new().require_field_match(true).field(+ "content",+ HighlightField::new()+ .highlight_type("plain")+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()])+ .number_of_fragments(500),+ ),+ SearchOn::Name => {+ let mut highlight = Highlight::new();++ highlight = highlight.require_field_match(true);++ for field in title_keys {+ highlight = highlight.field(+ field,+ HighlightField::new()+ .highlight_type("plain")+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()])+ .number_of_fragments(1),+ );+ }+ highlight+ }+ SearchOn::NameContent => {+ let mut highlight = Highlight::new();++ highlight = highlight.require_field_match(false);++ for field in title_keys {+ highlight = highlight.field(+ field,+ HighlightField::new()+ .highlight_type("plain")+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()])+ .number_of_fragments(1),+ );+ }++ highlight = highlight.field(+ "content",+ HighlightField::new()+ .highlight_type("plain")+ .pre_tags(vec![MacroEm::Open.to_string()])+ .post_tags(vec![MacroEm::Close.to_string()])+ .number_of_fragments(1),+ );++ highlight+ }+ };++ search_request_builder.highlight(highlight);++ let query_object = bool_query.build();++ let built_query: QueryType = match args.search_on {+ SearchOn::Name | SearchOn::Content => query_object.into(),+ SearchOn::NameContent => {+ if args.disable_recency {+ query_object.into()+ } else {+ let mut function_score_query = FunctionScoreQueryBuilder::new();++ function_score_query.query(query_object.into());++ function_score_query.function(ScoreFunction {+ function: ScoreFunctionType::Gauss(DecayFunction {+ field: "updated_at_seconds".to_string(),+ origin: Some("now".into()),+ scale: "21d".to_string(),+ offset: Some("3d".to_string()),+ decay: Some(0.5),+ }),+ filter: None,+ weight: Some(1.3),+ });++ function_score_query.boost_mode(BoostMode::Multiply);+ function_score_query.score_mode(ScoreMode::Multiply);++ function_score_query.build().into()+ }+ }+ };++ search_request_builder.query(built_query);++ Ok(search_request_builder.build())+}++#[tracing::instrument(skip(client, args), err)]+pub(crate) async fn search_unified(+ client: &opensearch::OpenSearch,+ args: UnifiedSearchArgs,+) -> Result<Vec<UnifiedSearchResponse>> {+ let search_request = build_unified_search_request(&args)?.to_json();++ let search_indices: Vec<&str> = args.search_indices.iter().map(|i| i.as_ref()).collect();++ let response = client+ .search(opensearch::SearchParts::Index(&search_indices))+ .body(search_request)+ .send()+ .await+ .map_client_error()+ .await?;++ let result = response+ .json::<DefaultSearchResponse<UnifiedSearchIndex>>()+ .await+ .map_err(|e| OpensearchClientError::DeserializationFailed {+ details: e.to_string(),+ method: Some("search_unified".to_string()),+ })?;++ Ok(result.hits.hits.into_iter().map(|h| h.into()).collect())+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rsnew file mode 100644index 0000000000..9d69bedbb1--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs@@ -0,0 +1,1994 @@+use super::*;++use opensearch_query_builder::ToOpenSearchJson;++#[test]+fn test_deserialization() -> anyhow::Result<()> {+ let json = serde_json::json!({+ "took": 20,+ "timed_out": false,+ "_shards": {+ "total": 15,+ "successful": 15,+ "skipped": 0,+ "failed": 0+ },+ "hits": {+ "total": {+ "value": 739,+ "relation": "eq"+ },+ "max_score": 27.399992,+ "hits": [+ {+ "_index": "emails",+ "_id": "019a5a07-a1ed-7342-93a7-861582b59a55:019a5a07-b09d-7af9-b6ce-98bced9353d2",+ "_score": 27.399992,+ "_source": {+ "cc": [+ "[email protected]",+ ],+ "bcc": [],+ "subject": "[macro-inc/macro-api] chore: improve ws api gateway authorizer lambda (PR #2520)",+ "message_id": "019a5a07-b09d-7af9-b6ce-98bced9353d2",+ "entity_id": "019a5a07-a1ed-7342-93a7-861582b59a55",+ "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",+ "content": "## Summary\ntype safety + better deny policy\n## Screenshots, GIFs, and Videos\n## Checklist\n* Included (`MACRO-N`) in the PR title.\n* QA'd\nTests for PR (pick one):\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2520\n#### Commit Summary\n* 20b26f7 update\n* f39426a make it TS\n#### File Changes\n(6 files)\n* **A** websocket/handlers/authorization-handler/.gitignore (5)\n* **D** websocket/handlers/authorization-handler/index.js (105)\n* **A** websocket/handlers/authorization-handler/index.ts (159)\n* **M** websocket/handlers/authorization-handler/package.json (10)\n* **A** websocket/handlers/authorization-handler/tsconfig.json (18)\n* **M** websocket/infra/index.ts (65)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2520.patch\n* https://github.com/macro-inc/macro-api/pull/2520.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",+ "labels": [+ "github",+ "CATEGORY_PERSONAL",+ "UNREAD",+ "IMPORTANT"+ ],+ "thread_id": "019a5a07-a1ed-7342-93a7-861582b59a55",+ "sent_at_seconds": 1762447040,+ "sender": "[email protected]",+ "user_id": "macro|[email protected]",+ "updated_at_seconds": 1762447044,+ "recipients": [+ ]+ },+ "highlight": {+ "content": [+ ":\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>",+ "* f39426a make it TS\n#### File Changes\n(6 files)\n* **A** websocket/handlers/authorization-handler/.<macro_em>gitignore</macro_em>",+ "authorization-handler/tsconfig.json (18)\n* **M** websocket/infra/index.ts (65)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",+ "/macro-inc/macro-api/pull/2520.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2520.diff\n—\nReply",+ "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",+ "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2520@<macro_em>github.com</macro_em>"+ ]+ }+ },+ {+ "_index": "emails",+ "_id": "01999c74-fb30-7c8a-b334-16035ee46783:01999c75-1c32-7cf4-a168-7741881ceec3",+ "_score": 22.173065,+ "_source": {+ "cc": [],+ "bcc": [],+ "subject": "From IaC to AI Platform Engineering: Insights You Can’t Afford to Miss",+ "message_id": "01999c75-1c32-7cf4-a168-7741881ceec3",+ "entity_id": "01999c74-fb30-7c8a-b334-16035ee46783",+ "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",+ "content": "Learn, connect, and explore the future of IaC, platform engineering, DevOps, and AI.\n pulumi email banner \nHi Will,\nPulumi is on the move, bringing together communities of builders who are pushing the boundaries of Platform Engineering and DevOps with AI.\nThis is where new ideas surface, best practices are shared first, and the conversations shaping tomorrow’s infrastructure are happening now. Don't miss your chance to be part of it!\n### Pulumi User Groups (PUG) Meetups\nOct 1 São Paulo, BR Sao Paulo PUG: Evento de Lançamento - Do IaC ao Platform Engineering \nOct 9 Copenhagen, DK PUG In-Person Meetup Nº 1: Discover AI in a DevOps World\nOct 22 London, UK PUG In-Person Meetup Nº 3: Building Better Platforms with Pulumi IDP\nOct 29 Tel Aviv, IL In-Person Meetup Nº 2: Platform Engineering and DevOps in the Age of AI \n### Events & Conferences\nOct 8 Copenhagen, DK Join Engin Diri, Senior Solutions Architect at Pulumi, for his talk on GitOps Promotion Tools to add to your GitOps Toolkit in 2025. \nOct 17 Santa Monica, CA AWS MCP Hackathon\nOct 27–29 San Francisco, CA TechCrunch Disrupt\nOct 29 Bellevue, WA MCP Academy\nWe hope to see you soon!\nHappy building,\nThe Pulumi Team\n ai-workshop-series-banner \n cloud-red \nTry Pulumi\n docs \nView Docs\ntwitter GitHub-Mark-120px-plus linkedin youtube-play slack-2 \n© 2025 Pulumi. All rights reserved.\nPulumi Corporation, Two Union Square, 601 Union St, Pulumi Suite 1415, Seattle, WA 98101\nUnsubscribe Manage preferences",+ "labels": [+ "INBOX",+ "CATEGORY_PROMOTIONS"+ ],+ "sent_at": 1759241406,+ "thread_id": "01999c74-fb30-7c8a-b334-16035ee46783",+ "updated_at": 1759266586,+ "sent_at_seconds": 1759241406,+ "sender": "[email protected]",+ "user_id": "macro|[email protected]",+ "updated_at_seconds": 1759266586,+ "recipients": [+ ]+ },+ "highlight": {+ "content": [+ "Oct 8 Copenhagen, DK Join Engin Diri, Senior Solutions Architect at Pulumi, for his talk on <macro_em>GitOps</macro_em>",+ "Promotion Tools to add to your <macro_em>GitOps</macro_em> Toolkit in 2025.",+ "The Pulumi Team\n ai-workshop-series-banner \n cloud-red \nTry Pulumi\n docs \nView Docs\ntwitter <macro_em>GitHub</macro_em>-Mark"+ ]+ }+ },+ {+ "_index": "documents",+ "_id": "013021c7-5e14-4aab-855e-01413fff85dc:77",+ "_score": 18.047625,+ "_source": {+ "document_name": "Rust for Rustaceans Idiomatic Programming for Experienced Developers (1)",+ "updated_at": 1752523635,+ "updated_at_seconds": 1752523635,+ "file_type": "pdf",+ "owner_id": "macro|[email protected]",+ "document_id": "013021c7-5e14-4aab-855e-01413fff85dc",+ "document_version_id": 10091,+ "entity_id": "013021c7-5e14-4aab-855e-01413fff85dc",+ "content": "74 Chapter 6\r\n[patch.crates-io]\r\n# use a local (presumably modified) source\r\nregex = { path = \"/home/jon/regex\" }\r\n# use a modification on a git branch\r\nserde = { git = \"https://github.com/serde-rs/serde.git\", branch = \"faster\" }\r\n# patch a git dependency\r\n[patch.'https://github.com/jonhoo/project.git']\r\nproject = { path = \"/home/jon/project\" }\r\nListing 6-6: Overriding dependency sources in Cargo.toml using [patch]\r\nEven if you patch a dependency, Cargo takes care to check the crate \r\nversions so that you don’t accidentally end up patching the wrong major version of a crate. If you for some reason transitively depend on multiple major \r\nversions of the same crate, you can patch each one by giving them distinct \r\nidentifiers, as shown in Listing 6-7.\r\n[patch.crates-io]\r\nnom4 = { path = \"/home/jon/nom4\", package = \"nom\" }\r\nnom5 = { path = \"/home/jon/nom5\", package = \"nom\" }\r\nListing 6-7: Overriding multiple versions of the same crate in Cargo.toml using [patch]\r\nCargo will look at the Cargo.toml inside each path, realize that /nom4\r\ncontains major version 4 and that /nom5 contains major version 5, and patch \r\nthe two versions appropriately. The package keyword tells Cargo to look for a \r\ncrate by the name nom in both cases instead of using the dependency identifiers (the part on the left) as it does by default. You can use package this way \r\nin your regular dependencies as well to rename a dependency!\r\nKeep in mind that patches are not taken into account in the package \r\nthat’s uploaded when you publish a crate. A crate that depends on your \r\ncrate will use only its own [patch] section (which may be empty), not that of \r\nyour crate!\r\nCR ATES VS. PACKAGES\r\nYou may wonder what the difference between a package and a crate is. \r\nThese two terms are often used interchangeably in informal contexts, but they \r\nalso have specific definitions that vary depending on whether you’re talking \r\nabout the Rust compiler, Cargo, crates.io, or something else. I personally think \r\nof a crate as a Rust module hierarchy starting at a root .rs file (one where you \r\ncan use crate-level attributes like #![feature])—usually something like lib.rs or \r\nmain.rs. In contrast, a package is a collection of crates and metadata, so essentially all that’s described by a Cargo.toml file. That may include a library crate, \r\nmultiple binary crates, some integration test crates, and maybe even multiple \r\nworkspace members that themselves have Cargo.toml files.\r\nIntermediate Rust (Early Access) © 2022 by Jon Gjengset ",+ "node_id": "77"+ },+ "highlight": {+ "content": [+ "local (presumably modified) source\r\nregex = { path = \"/home/jon/regex\" }\r\n# use a modification on a <macro_em>git</macro_em>",+ "branch\r\nserde = { <macro_em>git</macro_em> = \"https://<macro_em>github.com</macro_em>/serde-rs/serde.git\", branch = \"faster\" }\r\n# patch a <macro_em>git</macro_em>",+ "https://<macro_em>github.com</macro_em>/jonhoo/project.git']\r\nproject = { path = \"/home/jon/project\" }\r\nListing 6-6: Overriding"+ ]+ }+ },+ {+ "_index": "emails",+ "_id": "019a3002-d9ff-79ad-9a5f-c3116b5b229a:019a3002-da01-71aa-aed0-3d699723ba58",+ "_score": 17.734608,+ "_source": {+ "cc": [],+ "bcc": [],+ "subject": "[GitHub] A personal access token (classic) has been regenerated for your account",+ "message_id": "019a3002-da01-71aa-aed0-3d699723ba58",+ "entity_id": "019a3002-d9ff-79ad-9a5f-c3116b5b229a",+ "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",+ "content": "Hey whutchinson98!\r\n\r\nA personal access token (classic) \"zephyr\" with notifications scopes was recently regenerated for your account. Visit https://github.com/settings/tokens for more information.\r\n\r\nTo see this and other security events for your account, visit https://github.com/settings/security-log\r\n\r\nIf you run into problems, please contact support by visiting https://github.com/contact\r\n\r\nThanks,\r\nThe GitHub Team",+ "labels": [+ "INBOX",+ "CATEGORY_UPDATES",+ "UNREAD"+ ],+ "sent_at": 1761742081,+ "thread_id": "019a3002-d9ff-79ad-9a5f-c3116b5b229a",+ "updated_at": 1761742084,+ "sent_at_seconds": 1761742081,+ "sender": "[email protected]",+ "user_id": "macro|[email protected]",+ "updated_at_seconds": 1761742084,+ "recipients": [+ ]+ },+ "highlight": {+ "content": [+ "Visit https://<macro_em>github.com</macro_em>/settings/tokens for more information.",+ "To see this and other security events for your account, visit https://<macro_em>github.com</macro_em>/settings/security-log",+ "If you run into problems, please contact support by visiting https://<macro_em>github.com</macro_em>/contact\r\n\r\nThanks",+ ",\r\nThe <macro_em>GitHub</macro_em> Team"+ ]+ }+ },+ {+ "_index": "documents",+ "_id": "71ff8822-b421-4cab-b23e-f65355bf90d4:77",+ "_score": 17.689163,+ "_source": {+ "document_name": "Rust for Rustaceans Idiomatic Programming for Experienced Developers (1)",+ "updated_at": 1752522588,+ "updated_at_seconds": 1752522588,+ "file_type": "pdf",+ "owner_id": "macro|[email protected]",+ "document_id": "71ff8822-b421-4cab-b23e-f65355bf90d4",+ "document_version_id": 511386,+ "entity_id": "71ff8822-b421-4cab-b23e-f65355bf90d4",+ "content": "74 Chapter 6\r\n[patch.crates-io]\r\n# use a local (presumably modified) source\r\nregex = { path = \"/home/jon/regex\" }\r\n# use a modification on a git branch\r\nserde = { git = \"https://github.com/serde-rs/serde.git\", branch = \"faster\" }\r\n# patch a git dependency\r\n[patch.'https://github.com/jonhoo/project.git']\r\nproject = { path = \"/home/jon/project\" }\r\nListing 6-6: Overriding dependency sources in Cargo.toml using [patch]\r\nEven if you patch a dependency, Cargo takes care to check the crate \r\nversions so that you don’t accidentally end up patching the wrong major version of a crate. If you for some reason transitively depend on multiple major \r\nversions of the same crate, you can patch each one by giving them distinct \r\nidentifiers, as shown in Listing 6-7.\r\n[patch.crates-io]\r\nnom4 = { path = \"/home/jon/nom4\", package = \"nom\" }\r\nnom5 = { path = \"/home/jon/nom5\", package = \"nom\" }\r\nListing 6-7: Overriding multiple versions of the same crate in Cargo.toml using [patch]\r\nCargo will look at the Cargo.toml inside each path, realize that /nom4\r\ncontains major version 4 and that /nom5 contains major version 5, and patch \r\nthe two versions appropriately. The package keyword tells Cargo to look for a \r\ncrate by the name nom in both cases instead of using the dependency identifiers (the part on the left) as it does by default. You can use package this way \r\nin your regular dependencies as well to rename a dependency!\r\nKeep in mind that patches are not taken into account in the package \r\nthat’s uploaded when you publish a crate. A crate that depends on your \r\ncrate will use only its own [patch] section (which may be empty), not that of \r\nyour crate!\r\nCR ATES VS. PACKAGES\r\nYou may wonder what the difference between a package and a crate is. \r\nThese two terms are often used interchangeably in informal contexts, but they \r\nalso have specific definitions that vary depending on whether you’re talking \r\nabout the Rust compiler, Cargo, crates.io, or something else. I personally think \r\nof a crate as a Rust module hierarchy starting at a root .rs file (one where you \r\ncan use crate-level attributes like #![feature])—usually something like lib.rs or \r\nmain.rs. In contrast, a package is a collection of crates and metadata, so essentially all that’s described by a Cargo.toml file. That may include a library crate, \r\nmultiple binary crates, some integration test crates, and maybe even multiple \r\nworkspace members that themselves have Cargo.toml files.\r\nIntermediate Rust (Early Access) © 2022 by Jon Gjengset ",+ "node_id": "77"+ },+ "highlight": {+ "content": [+ "local (presumably modified) source\r\nregex = { path = \"/home/jon/regex\" }\r\n# use a modification on a <macro_em>git</macro_em>",+ "branch\r\nserde = { <macro_em>git</macro_em> = \"https://<macro_em>github.com</macro_em>/serde-rs/serde.git\", branch = \"faster\" }\r\n# patch a <macro_em>git</macro_em>",+ "https://<macro_em>github.com</macro_em>/jonhoo/project.git']\r\nproject = { path = \"/home/jon/project\" }\r\nListing 6-6: Overriding"+ ]+ }+ },+ {+ "_index": "emails",+ "_id": "019a1675-844c-7dcc-bd45-109c25b94fa0:019a1675-8467-7cb3-b57d-8c5c45d5b50c",+ "_score": 17.500538,+ "_source": {+ "cc": [+ "[email protected]",+ ],+ "bcc": [],+ "subject": "[macro-inc/macro-api] fix table name in policy (PR #2425)",+ "message_id": "019a1675-8467-7cb3-b57d-8c5c45d5b50c",+ "entity_id": "019a1675-844c-7dcc-bd45-109c25b94fa0",+ "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",+ "content": "#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2425\n#### Commit Summary\n* 624dc3f fix table name in policy\n#### File Changes\n(1 file)\n* **M** cloud-storage/infra/packages/resources/src/resources/frecency.ts (4)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2425.patch\n* https://github.com/macro-inc/macro-api/pull/2425.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",+ "labels": [+ "github",+ "CATEGORY_UPDATES",+ "UNREAD",+ "IMPORTANT"+ ],+ "sent_at": 1761313387,+ "thread_id": "019a1675-844c-7dcc-bd45-109c25b94fa0",+ "updated_at": 1761313391,+ "sent_at_seconds": 1761313387,+ "sender": "[email protected]",+ "user_id": "macro|[email protected]",+ "updated_at_seconds": 1761313391,+ "recipients": [+ ]+ },+ "highlight": {+ "content": [+ "#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>/macro-inc/macro-api",+ "** cloud-storage/infra/packages/resources/src/resources/frecency.ts (4)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",+ "/macro-inc/macro-api/pull/2425.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2425.diff\n—\nReply",+ "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",+ "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2425@<macro_em>github.com</macro_em>"+ ]+ }+ },+ {+ "_index": "emails",+ "_id": "019a3653-c914-769b-9454-3b70dc2ad966:019a3653-cd3b-7b24-9dd7-9090e7d30f65",+ "_score": 17.168581,+ "_source": {+ "cc": [+ "[email protected]",+ ],+ "bcc": [],+ "subject": "[macro-inc/macro-api] Fix conn gateway var name (PR #2471)",+ "message_id": "019a3653-cd3b-7b24-9dd7-9090e7d30f65",+ "entity_id": "019a3653-c914-769b-9454-3b70dc2ad966",+ "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",+ "content": "just rename the thing\n#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2471\n#### Commit Summary\n* f3e3ab1 rename env var\n#### File Changes\n(1 file)\n* **M** cloud-storage/infra/stacks/connection-gateway/index.ts (2)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2471.patch\n* https://github.com/macro-inc/macro-api/pull/2471.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",+ "labels": [+ "github",+ "CATEGORY_PERSONAL",+ "UNREAD",+ "IMPORTANT"+ ],+ "sent_at": 1761848050,+ "thread_id": "019a3653-c914-769b-9454-3b70dc2ad966",+ "updated_at": 1761848053,+ "sent_at_seconds": 1761848050,+ "sender": "[email protected]",+ "user_id": "macro|[email protected]",+ "updated_at_seconds": 1761848053,+ "recipients": [+ ]+ },+ "highlight": {+ "content": [+ "just rename the thing\n#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>",+ "file)\n* **M** cloud-storage/infra/stacks/connection-gateway/index.ts (2)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",+ "/macro-inc/macro-api/pull/2471.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2471.diff\n—\nReply",+ "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",+ "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2471@<macro_em>github.com</macro_em>"+ ]+ }+ },+ {+ "_index": "emails",+ "_id": "019a12cf-ed6d-7cbc-b705-a78bbbe1bba0:019a12d7-9a39-7ce4-a407-a737db30bdfd",+ "_score": 17.127216,+ "_source": {+ "cc": [+ "[email protected]",+ ],+ "bcc": [],+ "subject": "Re: [macro-inc/macro-api] Update macrodb to use sqlx (PR #2423)",+ "message_id": "019a12d7-9a39-7ce4-a407-a737db30bdfd",+ "entity_id": "019a12cf-ed6d-7cbc-b705-a78bbbe1bba0",+ "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",+ "content": "@evanhutnik commented on this pull request.\nIn .github/workflows/db-client-check.yml:\n> @@ -1,12 +1,12 @@\nname: db client check\non:\npull_request:\n- branches: 'never'\n- # branches: 'dev', 'prod'\n- # paths:\n+ branches: 'never' \nimage.png (view on web)\nsometimes it be your own self\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because you commented.Message ID: <macro-inc/macro-api/pull/2423/review/[email protected]>",+ "labels": [+ "github",+ "CATEGORY_PERSONAL",+ "UNREAD",+ "IMPORTANT"+ ],+ "sent_at": 1761252648,+ "thread_id": "019a12cf-ed6d-7cbc-b705-a78bbbe1bba0",+ "updated_at": 1761252711,+ "sent_at_seconds": 1761252648,+ "sender": "[email protected]",+ "user_id": "macro|[email protected]",+ "updated_at_seconds": 1761252711,+ "recipients": [+ ]+ },+ "highlight": {+ "content": [+ "In .<macro_em>github</macro_em>/workflows/db-client-check.yml:\n> @@ -1,12 +1,12 @@\nname: db client check\non:\npull_request:",+ "' \nimage.png (view on web)\nsometimes it be your own self\n—\nReply to this email directly, view it on <macro_em>GitHub</macro_em>",+ "are receiving this because you commented.Message ID: <macro-inc/macro-api/pull/2423/review/3372627995@<macro_em>github.com</macro_em>"+ ]+ }+ },+ {+ "_index": "emails",+ "_id": "019a3575-3540-7231-8b83-51279a1bf623:019a3575-3541-7c31-9857-5dfea488c4c6",+ "_score": 17.092716,+ "_source": {+ "cc": [+ "[email protected]",+ ],+ "bcc": [],+ "subject": "[macro-inc/macro-api] Upgrade db version (PR #2466)",+ "message_id": "019a3575-3541-7c31-9857-5dfea488c4c6",+ "entity_id": "019a3575-3540-7231-8b83-51279a1bf623",+ "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",+ "content": "## Summary\nAWS auto updated our dbs from 16.3 to 16.8. Updating pulumi to reflect this.\n## Screenshots, GIFs, and Videos\n## Checklist\n* Included (`MACRO-N`) in the PR title.\n* QA'd\nTests for PR (pick one):\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2466\n#### Commit Summary\n* 452175c Upgrade db version\n#### File Changes\n(1 file)\n* **M** cloud-storage/infra/packages/resources/src/resources/rds.ts (2)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2466.patch\n* https://github.com/macro-inc/macro-api/pull/2466.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",+ "labels": [+ "github",+ "CATEGORY_UPDATES",+ "UNREAD"+ ],+ "sent_at": 1761833460,+ "thread_id": "019a3575-3540-7231-8b83-51279a1bf623",+ "updated_at": 1761833465,+ "sent_at_seconds": 1761833460,+ "sender": "[email protected]",+ "user_id": "macro|[email protected]",+ "updated_at_seconds": 1761833465,+ "recipients": [+ ]+ },+ "highlight": {+ "content": [+ ":\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>",+ "* **M** cloud-storage/infra/packages/resources/src/resources/rds.ts (2)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",+ "/macro-inc/macro-api/pull/2466.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2466.diff\n—\nReply",+ "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",+ "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2466@<macro_em>github.com</macro_em>"+ ]+ }+ },+ {+ "_index": "emails",+ "_id": "019a30ae-2a24-78b3-9eef-e3aa7594a1e4:019a30b1-c647-7949-8be2-1ef3f2195790",+ "_score": 17.033447,+ "_source": {+ "cc": [+ "[email protected]",+ ],+ "bcc": [],+ "subject": "[macro-inc/macro-api] seanaye/add/conn gateway pg frecency (PR #2457)",+ "message_id": "019a30b1-c647-7949-8be2-1ef3f2195790",+ "entity_id": "019a30ae-2a24-78b3-9eef-e3aa7594a1e4",+ "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",+ "content": "## Summary\nThis PR swaps the backing storage layer for frecency in connection gateway from dynamo -> pg\n* **add inbound poller worker**\n* **switch connection gateway to pg frecency**\n* **use secret macro_db connection string**\n## Screenshots, GIFs, and Videos\n## Checklist\n* Included (`MACRO-N`) in the PR title.\n* QA'd\nTests for PR (pick one):\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2457\n#### Commit Summary\n* 1575c1b add inbound poller worker\n* b51c9a4 switch connection gateway to pg frecency\n* 3c44249 use secret macro_db connection string\n#### File Changes\n(14 files)\n* **M** .github/CODEOWNERS (2)\n* **M** cloud-storage/Cargo.lock (1)\n* **M** cloud-storage/connection_gateway/Cargo.toml (3)\n* **M** cloud-storage/connection_gateway/src/context.rs (9)\n* **M** cloud-storage/connection_gateway/src/main.rs (33)\n* **M** cloud-storage/frecency/Cargo.toml (11)\n* **M** cloud-storage/frecency/src/domain/models.rs (20)\n* **M** cloud-storage/frecency/src/domain/ports.rs (6)\n* **M** cloud-storage/frecency/src/domain/services.rs (39)\n* **M** cloud-storage/frecency/src/inbound.rs (2)\n* **M** cloud-storage/frecency/src/inbound/polling_aggregator.rs (91)\n* **M** cloud-storage/frecency/src/outbound/postgres.rs (3)\n* **M** cloud-storage/infra/stacks/connection-gateway/index.ts (12)\n* **M** cloud-storage/remote_env_var/src/lib.rs (16)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2457.patch\n* https://github.com/macro-inc/macro-api/pull/2457.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",+ "labels": [+ "github",+ "CATEGORY_PERSONAL",+ "UNREAD",+ "IMPORTANT"+ ],+ "sent_at": 1761753544,+ "thread_id": "019a30ae-2a24-78b3-9eef-e3aa7594a1e4",+ "updated_at": 1761753548,+ "sent_at_seconds": 1761753544,+ "sender": "[email protected]",+ "user_id": "macro|[email protected]",+ "updated_at_seconds": 1761753548,+ "recipients": [+ ]+ },+ "highlight": {+ "content": [+ ":\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>",+ "to pg frecency\n* 3c44249 use secret macro_db connection string\n#### File Changes\n(14 files)\n* **M** .<macro_em>github</macro_em>",+ "connection-gateway/index.ts (12)\n* **M** cloud-storage/remote_env_var/src/lib.rs (16)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",+ "/macro-inc/macro-api/pull/2457.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2457.diff\n—\nReply",+ "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",+ "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2457@<macro_em>github.com</macro_em>"+ ]+ }+ }+ ]+ }+ });++ let _: DefaultSearchResponse<UnifiedSearchIndex> = serde_json::from_value(json)?;++ Ok(())+}++#[test]+fn test_build_unified_search_request_content() -> anyhow::Result<()> {+ let unified_search_args = UnifiedSearchArgs {+ search_indices: vec![+ SearchIndex::Documents,+ SearchIndex::Emails,+ SearchIndex::Projects,+ SearchIndex::Channels,+ SearchIndex::Chats,+ ]+ .into_iter()+ .collect(),+ terms: vec!["test".to_string()],+ user_id: "user".to_string(),+ page: 1,+ page_size: 20,+ match_type: "exact".to_string(),+ search_on: SearchOn::Content,+ collapse: true,+ disable_recency: false,+ document_search_args: UnifiedDocumentSearchArgs {+ document_ids: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ email_search_args: UnifiedEmailSearchArgs {+ thread_ids: vec!["id1".to_string(), "id2".to_string()],+ link_ids: vec!["id1".to_string(), "id2".to_string()],+ sender: vec!["id1".to_string(), "id2".to_string()],+ cc: vec!["id1".to_string(), "id2".to_string()],+ bcc: vec!["id1".to_string(), "id2".to_string()],+ recipients: vec!["id1".to_string(), "id2".to_string()],+ },+ channel_message_search_args: UnifiedChannelMessageSearchArgs {+ channel_ids: vec!["id1".to_string(), "id2".to_string()],+ thread_ids: vec!["id1".to_string(), "id2".to_string()],+ mentions: vec!["id1".to_string(), "id2".to_string()],+ sender_ids: vec!["id1".to_string(), "id2".to_string()],+ },+ chat_search_args: UnifiedChatSearchArgs {+ chat_ids: vec!["id1".to_string(), "id2".to_string()],+ role: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ project_search_args: UnifiedProjectSearchArgs {+ project_ids: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ };++ let result = build_unified_search_request(&unified_search_args)?;++ let expected = serde_json::json!({+ "collapse": {+ "field": "entity_id"+ },+ "from": 20,+ "highlight": {+ "fields": {+ "content": {+ "number_of_fragments": 500,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ }+ },+ "require_field_match": true+ },+ "query": {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "term": {+ "_index": "documents"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "owner_id": "user"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "terms": {+ "link_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "sender": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "sender": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "cc": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "cc": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "bcc": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "bcc": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "recipients": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "recipients": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "emails"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "terms": {+ "thread_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "terms": {+ "mentions": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "terms": {+ "sender_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "_index": "channels"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "chats"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "term": {+ "_index": "projects"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ }+ ]+ }+ },+ "size": 20,+ "sort": [+ {+ "_score": "desc"+ },+ {+ "entity_id": "asc"+ }+ ]+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}++#[test]+fn test_build_unified_search_request_name() -> anyhow::Result<()> {+ let unified_search_args = UnifiedSearchArgs {+ search_indices: vec![+ SearchIndex::Documents,+ SearchIndex::Emails,+ SearchIndex::Projects,+ SearchIndex::Channels,+ SearchIndex::Chats,+ ]+ .into_iter()+ .collect(),+ terms: vec!["test".to_string()],+ user_id: "user".to_string(),+ page: 1,+ page_size: 20,+ match_type: "exact".to_string(),+ search_on: SearchOn::Name,+ collapse: true,+ disable_recency: false,+ document_search_args: UnifiedDocumentSearchArgs {+ document_ids: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ email_search_args: UnifiedEmailSearchArgs {+ thread_ids: vec!["id1".to_string(), "id2".to_string()],+ link_ids: vec!["id1".to_string(), "id2".to_string()],+ sender: vec!["id1".to_string(), "id2".to_string()],+ cc: vec!["id1".to_string(), "id2".to_string()],+ bcc: vec!["id1".to_string(), "id2".to_string()],+ recipients: vec!["id1".to_string(), "id2".to_string()],+ },+ channel_message_search_args: UnifiedChannelMessageSearchArgs {+ channel_ids: vec!["id1".to_string(), "id2".to_string()],+ thread_ids: vec!["id1".to_string(), "id2".to_string()],+ mentions: vec!["id1".to_string(), "id2".to_string()],+ sender_ids: vec!["id1".to_string(), "id2".to_string()],+ },+ chat_search_args: UnifiedChatSearchArgs {+ chat_ids: vec!["id1".to_string(), "id2".to_string()],+ role: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ project_search_args: UnifiedProjectSearchArgs {+ project_ids: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ };++ let result = build_unified_search_request(&unified_search_args)?;++ let expected = serde_json::json!({+ "collapse": {+ "field": "entity_id"+ },+ "from": 20,+ "highlight": {+ "fields": {+ "document_name": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "subject": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "title": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "channel_name": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "project_name": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ }+ },+ "require_field_match": true+ },+ "query": {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "document_name": "test"+ }+ },+ {+ "term": {+ "_index": "documents"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "owner_id": "user"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "subject": "test"+ }+ },+ {+ "terms": {+ "link_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "sender": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "sender": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "cc": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "cc": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "bcc": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "bcc": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "recipients": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "recipients": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "emails"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "channel_name": "test"+ }+ },+ {+ "terms": {+ "thread_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "terms": {+ "mentions": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "terms": {+ "sender_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "_index": "channels"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "title": "test"+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "chats"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "project_name": "test"+ }+ },+ {+ "term": {+ "_index": "projects"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ }+ ]+ }+ },+ "size": 20,+ "sort": [+ {+ "_score": "desc"+ },+ {+ "entity_id": "asc"+ }+ ]+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}++#[test]+fn test_build_unified_search_request_name_content() -> anyhow::Result<()> {+ let unified_search_args = UnifiedSearchArgs {+ search_indices: vec![+ SearchIndex::Documents,+ SearchIndex::Emails,+ SearchIndex::Projects,+ SearchIndex::Channels,+ SearchIndex::Chats,+ ]+ .into_iter()+ .collect(),+ terms: vec!["test".to_string()],+ user_id: "user".to_string(),+ page: 1,+ page_size: 20,+ match_type: "exact".to_string(),+ search_on: SearchOn::NameContent,+ collapse: true,+ disable_recency: false,+ document_search_args: UnifiedDocumentSearchArgs {+ document_ids: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ email_search_args: UnifiedEmailSearchArgs {+ thread_ids: vec!["id1".to_string(), "id2".to_string()],+ link_ids: vec!["id1".to_string(), "id2".to_string()],+ sender: vec!["id1".to_string(), "id2".to_string()],+ cc: vec!["id1".to_string(), "id2".to_string()],+ bcc: vec!["id1".to_string(), "id2".to_string()],+ recipients: vec!["id1".to_string(), "id2".to_string()],+ },+ channel_message_search_args: UnifiedChannelMessageSearchArgs {+ channel_ids: vec!["id1".to_string(), "id2".to_string()],+ thread_ids: vec!["id1".to_string(), "id2".to_string()],+ mentions: vec!["id1".to_string(), "id2".to_string()],+ sender_ids: vec!["id1".to_string(), "id2".to_string()],+ },+ chat_search_args: UnifiedChatSearchArgs {+ chat_ids: vec!["id1".to_string(), "id2".to_string()],+ role: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ project_search_args: UnifiedProjectSearchArgs {+ project_ids: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ };++ let result = build_unified_search_request(&unified_search_args)?;++ let expected = serde_json::json!(+ {+ "aggs": {+ "total_uniques": {+ "cardinality": {+ "field": "entity_id"+ }+ }+ },+ "collapse": {+ "field": "entity_id"+ },+ "from": 20,+ "highlight": {+ "fields": {+ "channel_name": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "content": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "document_name": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "project_name": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "subject": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ },+ "title": {+ "number_of_fragments": 1,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ }+ },+ "require_field_match": false+ },+ "query": {+ "function_score": {+ "boost_mode": "multiply",+ "functions": [+ {+ "gauss": {+ "updated_at_seconds": {+ "decay": 0.5,+ "offset": "3d",+ "origin": "now",+ "scale": "21d"+ }+ },+ "weight": 1.3+ }+ ],+ "query": {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase_prefix": {+ "document_name": {+ "boost": 1000.0,+ "query": "test"+ }+ }+ },+ {+ "match_phrase_prefix": {+ "content": {+ "boost": 900.0,+ "query": "test"+ }+ }+ },+ {+ "match": {+ "document_name": {+ "boost": 0.1,+ "minimum_should_match": "80%",+ "query": "test"+ }+ }+ },+ {+ "match": {+ "content": {+ "boost": 0.09,+ "minimum_should_match": "1",+ "query": "test"+ }+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "documents"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "owner_id": "user"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase_prefix": {+ "subject": {+ "boost": 1000.0,+ "query": "test"+ }+ }+ },+ {+ "match_phrase_prefix": {+ "content": {+ "boost": 900.0,+ "query": "test"+ }+ }+ },+ {+ "match": {+ "subject": {+ "boost": 0.1,+ "minimum_should_match": "80%",+ "query": "test"+ }+ }+ },+ {+ "match": {+ "content": {+ "boost": 0.09,+ "minimum_should_match": "1",+ "query": "test"+ }+ }+ }+ ]+ }+ },+ {+ "terms": {+ "link_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "sender": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "sender": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "cc": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "cc": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "bcc": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "bcc": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "recipients": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "recipients": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "emails"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase_prefix": {+ "channel_name": {+ "boost": 1000.0,+ "query": "test"+ }+ }+ },+ {+ "match_phrase_prefix": {+ "content": {+ "boost": 900.0,+ "query": "test"+ }+ }+ },+ {+ "match": {+ "channel_name": {+ "boost": 0.1,+ "minimum_should_match": "80%",+ "query": "test"+ }+ }+ },+ {+ "match": {+ "content": {+ "boost": 0.09,+ "minimum_should_match": "1",+ "query": "test"+ }+ }+ }+ ]+ }+ },+ {+ "terms": {+ "thread_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "terms": {+ "mentions": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "terms": {+ "sender_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "_index": "channels"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase_prefix": {+ "title": {+ "boost": 1000.0,+ "query": "test"+ }+ }+ },+ {+ "match_phrase_prefix": {+ "content": {+ "boost": 900.0,+ "query": "test"+ }+ }+ },+ {+ "match": {+ "title": {+ "boost": 0.1,+ "minimum_should_match": "80%",+ "query": "test"+ }+ }+ },+ {+ "match": {+ "content": {+ "boost": 0.09,+ "minimum_should_match": "1",+ "query": "test"+ }+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "chats"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase_prefix": {+ "project_name": {+ "boost": 1000.0,+ "query": "test"+ }+ }+ },+ {+ "match_phrase_prefix": {+ "content": {+ "boost": 900.0,+ "query": "test"+ }+ }+ },+ {+ "match": {+ "project_name": {+ "boost": 0.1,+ "minimum_should_match": "80%",+ "query": "test"+ }+ }+ },+ {+ "match": {+ "content": {+ "boost": 0.09,+ "minimum_should_match": "1",+ "query": "test"+ }+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "projects"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ }+ ]+ }+ },+ "score_mode": "multiply"+ }+ },+ "size": 20,+ "sort": [+ {+ "_score": "desc"+ },+ {+ "entity_id": "asc"+ }+ ],+ "track_total_hits": true+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}++#[test]+fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {+ let unified_search_args = UnifiedSearchArgs {+ search_indices: vec![SearchIndex::Documents].into_iter().collect(),+ terms: vec!["test".to_string()],+ user_id: "user".to_string(),+ page: 1,+ page_size: 20,+ match_type: "exact".to_string(),+ search_on: SearchOn::Content,+ collapse: true,+ disable_recency: false,+ document_search_args: UnifiedDocumentSearchArgs {+ document_ids: vec!["id1".to_string(), "id2".to_string()],+ ids_only: false,+ },+ ..Default::default()+ };++ let result = build_unified_search_request(&unified_search_args)?;+ let expected = serde_json::json!({+ "collapse": {+ "field": "entity_id"+ },+ "from": 20,+ "highlight": {+ "fields": {+ "content": {+ "number_of_fragments": 500,+ "post_tags": [+ "</macro_em>"+ ],+ "pre_tags": [+ "<macro_em>"+ ],+ "type": "plain"+ }+ },+ "require_field_match": true+ },+ "query": {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "bool": {+ "minimum_should_match": 1,+ "must": [+ {+ "match_phrase": {+ "content": "test"+ }+ },+ {+ "term": {+ "_index": "documents"+ }+ }+ ],+ "should": [+ {+ "terms": {+ "entity_id": [+ "id1",+ "id2"+ ]+ }+ },+ {+ "term": {+ "owner_id": "user"+ }+ }+ ]+ }+ },+ ]+ }+ },+ "size": 20,+ "sort": [+ {+ "_score": "desc"+ },+ {+ "entity_id": "asc"+ }+ ]+ });++ assert_eq!(result.to_json(), expected);++ Ok(())+}++#[test]+fn test_build_unified_search_request_empty_indices() -> anyhow::Result<()> {+ let unified_search_args = UnifiedSearchArgs {+ search_indices: vec![].into_iter().collect(),+ ..Default::default()+ };++ let err = build_unified_search_request(&unified_search_args).unwrap_err();++ assert_eq!(err, OpensearchClientError::EmptySearchIndices);++ Ok(())+}diff --git a/rust/cloud-storage/opensearch_client/src/unified.rs b/rust/cloud-storage/opensearch_client/src/unified.rsnew file mode 100644index 0000000000..8bfff0c14a--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/unified.rs@@ -0,0 +1,18 @@+use crate::{+ OpensearchClient, Result,+ search::{+ self,+ unified::{UnifiedSearchArgs, UnifiedSearchResponse},+ },+};++impl OpensearchClient {+ /// Performs a unified search+ #[tracing::instrument(skip(self, args))]+ pub async fn search_unified(+ &self,+ args: UnifiedSearchArgs,+ ) -> Result<Vec<UnifiedSearchResponse>> {+ search::unified::search_unified(&self.inner, args).await+ }+}diff --git a/rust/cloud-storage/search_service/src/api/search/channel.rs b/rust/cloud-storage/search_service/src/api/search/channel.rsindex 1dc0d0072c..44e642430a 100644--- a/rust/cloud-storage/search_service/src/api/search/channel.rs+++ b/rust/cloud-storage/search_service/src/api/search/channel.rs@@ -20,30 +20,20 @@ use models_search::channel::{};use sqlx::types::Uuid;-/// Performs a search through channels and enriches the results with metadata-pub async fn search_channels_enriched(+/// Enriches channel message search results with metadata+#[tracing::instrument(skip(ctx, results), err)]+pub(in crate::api::search) async fn enrich_channels(ctx: &ApiContext,user_id: &str,- user_organization_id: Option<i32>,- query_params: &SearchPaginationParams,- req: ChannelSearchRequest,+ results: Vec<opensearch_client::search::channels::ChannelMessageSearchResponse>,) -> Result<Vec<ChannelSearchResponseItemWithMetadata>, SearchError> {- // Use the simple search to get raw OpenSearch results- let opensearch_results =- search_channels(ctx, user_id, user_organization_id, query_params, req).await?;-+ if results.is_empty() {+ return Ok(vec![]);+ }// Extract channel IDs from results- let channel_ids: Vec<Uuid> = opensearch_results+ let channel_ids: Vec<Uuid> = results.iter()- .filter_map(|r| {- match Uuid::parse_str(&r.channel_id) {- Ok(uuid) => Some(uuid),- Err(e) => {- tracing::warn!(error=?e, channel_id=?r.channel_id, "Failed to parse channel ID as UUID");- None- }- }- })+ .map(|r| r.channel_id.parse().unwrap()).collect();// Fetch channel metadata from comms service@@ -57,13 +47,28 @@ pub async fn search_channels_enriched(.map_err(|e| SearchError::InternalError(e.into()))?;// Construct enriched results- let enriched_results =- construct_search_result(opensearch_results, channel_histories.channels_history)- .map_err(SearchError::InternalError)?;+ let enriched_results = construct_search_result(results, channel_histories.channels_history)+ .map_err(SearchError::InternalError)?;Ok(enriched_results)}+/// Performs a search through channels and enriches the results with metadata+#[tracing::instrument(skip(ctx, req, query_params, user_organization_id), err)]+pub async fn search_channels_enriched(+ ctx: &ApiContext,+ user_id: &str,+ user_organization_id: Option<i32>,+ query_params: &SearchPaginationParams,+ req: ChannelSearchRequest,+) -> Result<Vec<ChannelSearchResponseItemWithMetadata>, SearchError> {+ // Use the simple search to get raw OpenSearch results+ let opensearch_results =+ search_channels(ctx, user_id, user_organization_id, query_params, req).await?;++ enrich_channels(ctx, user_id, opensearch_results).await+}+/// Perform a search through your emails#[utoipa::path(post,diff --git a/rust/cloud-storage/search_service/src/api/search/chat.rs b/rust/cloud-storage/search_service/src/api/search/chat.rsindex 7c9485bf83..ebe092638b 100644--- a/rust/cloud-storage/search_service/src/api/search/chat.rs+++ b/rust/cloud-storage/search_service/src/api/search/chat.rs@@ -16,21 +16,18 @@ use std::collections::HashMap;use super::SearchPaginationParams;-/// Performs a search through chats and enriches the results with metadata-pub async fn search_chats_enriched(+/// Enriches chat search results with metadata+#[tracing::instrument(skip(ctx, results), err)]+pub(in crate::api::search) async fn enrich_chats(ctx: &ApiContext,user_id: &str,- query_params: &SearchPaginationParams,- req: ChatSearchRequest,+ results: Vec<opensearch_client::search::chats::ChatSearchResponse>,) -> Result<Vec<ChatSearchResponseItemWithMetadata>, SearchError> {- // Use the simple search to get raw OpenSearch results- let opensearch_results = search_chats(ctx, user_id, query_params, req).await?;-+ if results.is_empty() {+ return Ok(vec![]);+ }// Extract chat IDs from results- let chat_ids: Vec<String> = opensearch_results- .iter()- .map(|r| r.chat_id.clone())- .collect();+ let chat_ids: Vec<String> = results.iter().map(|r| r.chat_id.clone()).collect();// Fetch chat metadata from databaselet chat_histories =@@ -39,12 +36,25 @@ pub async fn search_chats_enriched(.map_err(SearchError::InternalError)?;// Construct enriched results- let enriched_results = construct_search_result(opensearch_results, chat_histories)- .map_err(SearchError::InternalError)?;+ let enriched_results =+ construct_search_result(results, chat_histories).map_err(SearchError::InternalError)?;Ok(enriched_results)}+/// Performs a search through chats and enriches the results with metadata+pub async fn search_chats_enriched(+ ctx: &ApiContext,+ user_id: &str,+ query_params: &SearchPaginationParams,+ req: ChatSearchRequest,+) -> Result<Vec<ChatSearchResponseItemWithMetadata>, SearchError> {+ // Use the simple search to get raw OpenSearch results+ let opensearch_results = search_chats(ctx, user_id, query_params, req).await?;++ enrich_chats(ctx, user_id, opensearch_results).await+}+/// Perform a search through your chats#[utoipa::path(post,diff --git a/rust/cloud-storage/search_service/src/api/search/document.rs b/rust/cloud-storage/search_service/src/api/search/document.rsindex 5b97fd7179..c19cc96150 100644--- a/rust/cloud-storage/search_service/src/api/search/document.rs+++ b/rust/cloud-storage/search_service/src/api/search/document.rs@@ -19,21 +19,18 @@ use crate::{api::ApiContext, util};use super::SearchPaginationParams;-/// Performs a search through documents and enriches the results with metadata-pub async fn search_documents_enriched(+/// Enriches document search results with metadata+#[tracing::instrument(skip(ctx, results), err)]+pub(in crate::api::search) async fn enrich_documents(ctx: &ApiContext,user_id: &str,- query_params: &SearchPaginationParams,- req: DocumentSearchRequest,+ results: Vec<opensearch_client::search::documents::DocumentSearchResponse>,) -> Result<Vec<DocumentSearchResponseItemWithMetadata>, SearchError> {- // Use the simple search to get raw OpenSearch results- let opensearch_results = search_documents(ctx, user_id, query_params, req).await?;-+ if results.is_empty() {+ return Ok(vec![]);+ }// Extract document IDs from results- let document_ids: Vec<String> = opensearch_results- .iter()- .map(|r| r.document_id.clone())- .collect();+ let document_ids: Vec<String> = results.iter().map(|r| r.document_id.clone()).collect();// Fetch document metadata from databaselet document_histories =@@ -46,12 +43,25 @@ pub async fn search_documents_enriched(.map_err(SearchError::InternalError)?;// Construct enriched results- let enriched_results = construct_search_result(opensearch_results, document_histories)- .map_err(SearchError::InternalError)?;+ let enriched_results =+ construct_search_result(results, document_histories).map_err(SearchError::InternalError)?;Ok(enriched_results)}+/// Performs a search through documents and enriches the results with metadata+pub async fn search_documents_enriched(+ ctx: &ApiContext,+ user_id: &str,+ query_params: &SearchPaginationParams,+ req: DocumentSearchRequest,+) -> Result<Vec<DocumentSearchResponseItemWithMetadata>, SearchError> {+ // Use the simple search to get raw OpenSearch results+ let opensearch_results = search_documents(ctx, user_id, query_params, req).await?;++ enrich_documents(ctx, user_id, opensearch_results).await+}+/// Perform a search through your documents#[utoipa::path(post,diff --git a/rust/cloud-storage/search_service/src/api/search/email.rs b/rust/cloud-storage/search_service/src/api/search/email.rsindex 6399bbc4a0..2cc58a78ba 100644--- a/rust/cloud-storage/search_service/src/api/search/email.rs+++ b/rust/cloud-storage/search_service/src/api/search/email.rs@@ -18,18 +18,18 @@ use std::collections::HashMap;use super::SearchPaginationParams;-/// Performs a search through emails and enriches the results with metadata-pub async fn search_emails_enriched(+/// Enriches email search results with metadata+#[tracing::instrument(skip(ctx, results), err)]+pub(in crate::api::search) async fn enrich_emails(ctx: &ApiContext,user_id: &str,- query_params: &SearchPaginationParams,- req: EmailSearchRequest,+ results: Vec<opensearch_client::search::emails::EmailSearchResponse>,) -> Result<Vec<EmailSearchResponseItemWithMetadata>, SearchError> {- // Use the simple search to get raw OpenSearch results- let opensearch_results = search_emails(ctx, user_id, query_params, req).await?;-+ if results.is_empty() {+ return Ok(vec![]);+ }// Extract thread IDs from results- let thread_ids: Vec<Uuid> = opensearch_results+ let thread_ids: Vec<Uuid> = results.iter().filter_map(|r| {match Uuid::parse_str(&r.thread_id) {@@ -53,13 +53,26 @@ pub async fn search_emails_enriched(.map_err(SearchError::InternalError)?;// Construct enriched results- let enriched_results =- construct_search_result(opensearch_results, thread_histories.history_map)- .map_err(SearchError::InternalError)?;+ let enriched_results = construct_search_result(results, thread_histories.history_map)+ .map_err(SearchError::InternalError)?;Ok(enriched_results)}+/// Performs a search through emails and enriches the results with metadata+#[tracing::instrument(skip(ctx, query_params, req), err)]+pub async fn search_emails_enriched(+ ctx: &ApiContext,+ user_id: &str,+ query_params: &SearchPaginationParams,+ req: EmailSearchRequest,+) -> Result<Vec<EmailSearchResponseItemWithMetadata>, SearchError> {+ // Use the simple search to get raw OpenSearch results+ let opensearch_results = search_emails(ctx, user_id, query_params, req).await?;++ enrich_emails(ctx, user_id, opensearch_results).await+}+/// Perform a search through your emails#[utoipa::path(post,diff --git a/rust/cloud-storage/search_service/src/api/search/enrich.rs b/rust/cloud-storage/search_service/src/api/search/enrich.rsnew file mode 100644index 0000000000..dce8463643--- /dev/null+++ b/rust/cloud-storage/search_service/src/api/search/enrich.rs@@ -0,0 +1,110 @@+//! This module is responsible for enriching search results with metadata++use models_search::unified::UnifiedSearchResponseItem;+use opensearch_client::search::{+ channels::ChannelMessageSearchResponse, chats::ChatSearchResponse,+ documents::DocumentSearchResponse, emails::EmailSearchResponse,+ projects::ProjectSearchResponse,+};++use crate::api::{+ context::ApiContext,+ search::{+ channel::enrich_channels, chat::enrich_chats, document::enrich_documents,+ email::enrich_emails, project::enrich_projects, simple::SearchError,+ },+};++/// Trait to enrich the search results from opensearch with extra data+pub(super) trait EnrichSearchResponse<T>: Iterator<Item = T> {+ fn enrich_search_response(+ self,+ ctx: &ApiContext,+ user_id: &str,+ ) -> impl Future<Output = Result<Vec<UnifiedSearchResponseItem>, SearchError>> + Send;+}++impl<T> EnrichSearchResponse<DocumentSearchResponse> for T+where+ T: Iterator<Item = DocumentSearchResponse> + Send,+{+ async fn enrich_search_response(+ self,+ ctx: &ApiContext,+ user_id: &str,+ ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {+ let response = enrich_documents(ctx, user_id, self.collect()).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Document)+ .collect())+ }+}++impl<T> EnrichSearchResponse<EmailSearchResponse> for T+where+ T: Iterator<Item = EmailSearchResponse> + Send,+{+ async fn enrich_search_response(+ self,+ ctx: &ApiContext,+ user_id: &str,+ ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {+ let response = enrich_emails(ctx, user_id, self.collect()).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Email)+ .collect())+ }+}++impl<T> EnrichSearchResponse<ChannelMessageSearchResponse> for T+where+ T: Iterator<Item = ChannelMessageSearchResponse> + Send,+{+ async fn enrich_search_response(+ self,+ ctx: &ApiContext,+ user_id: &str,+ ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {+ let response = enrich_channels(ctx, user_id, self.collect()).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Channel)+ .collect())+ }+}++impl<T> EnrichSearchResponse<ChatSearchResponse> for T+where+ T: Iterator<Item = ChatSearchResponse> + Send,+{+ async fn enrich_search_response(+ self,+ ctx: &ApiContext,+ user_id: &str,+ ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {+ let response = enrich_chats(ctx, user_id, self.collect()).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Chat)+ .collect())+ }+}++impl<T> EnrichSearchResponse<ProjectSearchResponse> for T+where+ T: Iterator<Item = ProjectSearchResponse> + Send,+{+ async fn enrich_search_response(+ self,+ ctx: &ApiContext,+ user_id: &str,+ ) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {+ let response = enrich_projects(ctx, user_id, self.collect()).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::Project)+ .collect())+ }+}diff --git a/rust/cloud-storage/search_service/src/api/search/mod.rs b/rust/cloud-storage/search_service/src/api/search/mod.rsindex b8cb8f39c6..76bbe36416 100644--- a/rust/cloud-storage/search_service/src/api/search/mod.rs+++ b/rust/cloud-storage/search_service/src/api/search/mod.rs@@ -6,6 +6,7 @@ pub(in crate::api) mod channel;pub(in crate::api) mod chat;pub(in crate::api) mod document;pub(in crate::api) mod email;+pub(in crate::api::search) mod enrich;pub(in crate::api) mod project;pub(in crate::api) mod simple;pub(in crate::api) mod unified;diff --git a/rust/cloud-storage/search_service/src/api/search/project.rs b/rust/cloud-storage/search_service/src/api/search/project.rsindex 8d6f312a61..0043903fdb 100644--- a/rust/cloud-storage/search_service/src/api/search/project.rs+++ b/rust/cloud-storage/search_service/src/api/search/project.rs@@ -19,21 +19,18 @@ use crate::{api::ApiContext, util};use super::SearchPaginationParams;-/// Performs a search through projects and enriches the results with metadata-pub async fn search_projects_enriched(+/// Enriches project search results with metadata+#[tracing::instrument(skip(ctx, results), err)]+pub(in crate::api::search) async fn enrich_projects(ctx: &ApiContext,user_id: &str,- query_params: &SearchPaginationParams,- req: ProjectSearchRequest,+ results: Vec<opensearch_client::search::projects::ProjectSearchResponse>,) -> Result<Vec<ProjectSearchResponseItemWithMetadata>, SearchError> {- // Use the simple search to get raw OpenSearch results- let opensearch_results = search_projects(ctx, user_id, query_params, req).await?;-+ if results.is_empty() {+ return Ok(vec![]);+ }// Extract project IDs from results- let project_ids: Vec<String> = opensearch_results- .iter()- .map(|r| r.project_id.clone())- .collect();+ let project_ids: Vec<String> = results.iter().map(|r| r.project_id.clone()).collect();// Fetch project metadata from databaselet project_histories =@@ -46,12 +43,26 @@ pub async fn search_projects_enriched(.map_err(SearchError::InternalError)?;// Construct enriched results- let enriched_results = construct_search_result(opensearch_results, project_histories)- .map_err(SearchError::InternalError)?;+ let enriched_results =+ construct_search_result(results, project_histories).map_err(SearchError::InternalError)?;Ok(enriched_results)}+/// Performs a search through projects and enriches the results with metadata+#[tracing::instrument(skip(ctx, query_params, req), err)]+pub async fn search_projects_enriched(+ ctx: &ApiContext,+ user_id: &str,+ query_params: &SearchPaginationParams,+ req: ProjectSearchRequest,+) -> Result<Vec<ProjectSearchResponseItemWithMetadata>, SearchError> {+ // Use the simple search to get raw OpenSearch results+ let opensearch_results = search_projects(ctx, user_id, query_params, req).await?;++ enrich_projects(ctx, user_id, opensearch_results).await+}+/// Perform a search through your projects#[utoipa::path(post,diff --git a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs b/rust/cloud-storage/search_service/src/api/search/simple/filter.rsnew file mode 100644index 0000000000..58b77985c2--- /dev/null+++ b/rust/cloud-storage/search_service/src/api/search/simple/filter.rs@@ -0,0 +1,166 @@+//! This module is responsible for defining a trait to convert item_filters into a UnifiedSearchArgsVariant+//! This is used in simple_unified.rs++use opensearch_client::search::unified::{+ UnifiedChannelMessageSearchArgs, UnifiedChatSearchArgs, UnifiedDocumentSearchArgs,+ UnifiedEmailSearchArgs, UnifiedProjectSearchArgs,+};++use crate::api::{+ context::ApiContext,+ search::simple::{+ SearchError, simple_channel::filter_channels, simple_chat::filter_chats,+ simple_document::filter_documents, simple_project::filter_projects,+ },+};++#[derive(Debug)]+pub(super) enum UnifiedSearchArgsVariant {+ Document(UnifiedDocumentSearchArgs),+ Channel(UnifiedChannelMessageSearchArgs),+ Chat(UnifiedChatSearchArgs),+ Project(UnifiedProjectSearchArgs),+ Email(UnifiedEmailSearchArgs),+}++/// Trait to convert item_filters into a UnifiedSearchArgsVariant+pub(super) trait FilterVariantToSearchArgs {+ fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ user_organization_id: Option<i32>,+ should_include: bool,+ ) -> impl Future<Output = Result<UnifiedSearchArgsVariant, SearchError>> + Send;+}++impl FilterVariantToSearchArgs for item_filters::DocumentFilters {+ async fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ _user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<UnifiedSearchArgsVariant, SearchError> {+ if !should_include {+ Ok(UnifiedSearchArgsVariant::Document(+ UnifiedDocumentSearchArgs::default(),+ ))+ } else {+ let filter_document_response = filter_documents(ctx, user_id, self).await?;++ Ok(UnifiedSearchArgsVariant::Document(+ UnifiedDocumentSearchArgs {+ document_ids: filter_document_response.document_ids,+ ids_only: filter_document_response.ids_only,+ },+ ))+ }+ }+}++impl FilterVariantToSearchArgs for item_filters::ChannelFilters {+ async fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<UnifiedSearchArgsVariant, SearchError> {+ if !should_include {+ Ok(UnifiedSearchArgsVariant::Channel(+ UnifiedChannelMessageSearchArgs::default(),+ ))+ } else {+ let filter_channel_response =+ filter_channels(ctx, user_id, user_organization_id, self).await?;++ Ok(UnifiedSearchArgsVariant::Channel(+ UnifiedChannelMessageSearchArgs {+ channel_ids: filter_channel_response+ .channel_ids+ .iter()+ .map(|c| c.to_string())+ .collect(),+ thread_ids: self.thread_ids.clone(),+ mentions: self.mentions.clone(),+ sender_ids: self.sender_ids.clone(),+ },+ ))+ }+ }+}++impl FilterVariantToSearchArgs for item_filters::ChatFilters {+ async fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ _user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<UnifiedSearchArgsVariant, SearchError> {+ if !should_include {+ Ok(UnifiedSearchArgsVariant::Chat(+ UnifiedChatSearchArgs::default(),+ ))+ } else {+ let filter_chat_response = filter_chats(ctx, user_id, self).await?;++ Ok(UnifiedSearchArgsVariant::Chat(UnifiedChatSearchArgs {+ chat_ids: filter_chat_response.chat_ids,+ ids_only: filter_chat_response.ids_only,+ role: self.role.clone(),+ }))+ }+ }+}++impl FilterVariantToSearchArgs for item_filters::ProjectFilters {+ async fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ _user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<UnifiedSearchArgsVariant, SearchError> {+ if !should_include {+ Ok(UnifiedSearchArgsVariant::Project(+ UnifiedProjectSearchArgs::default(),+ ))+ } else {+ let filter_project_response = filter_projects(ctx, user_id, self).await?;++ Ok(UnifiedSearchArgsVariant::Project(+ UnifiedProjectSearchArgs {+ project_ids: filter_project_response.project_ids,+ ids_only: filter_project_response.ids_only,+ },+ ))+ }+ }+}++impl FilterVariantToSearchArgs for item_filters::EmailFilters {+ async fn filter_to_search_args(+ &self,+ _ctx: &ApiContext,+ _user_id: &str,+ _user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<UnifiedSearchArgsVariant, SearchError> {+ if !should_include {+ Ok(UnifiedSearchArgsVariant::Email(+ UnifiedEmailSearchArgs::default(),+ ))+ } else {+ Ok(UnifiedSearchArgsVariant::Email(UnifiedEmailSearchArgs {+ thread_ids: vec![],+ link_ids: vec![],+ sender: self.senders.clone(),+ cc: self.cc.clone(),+ bcc: self.bcc.clone(),+ recipients: self.recipients.clone(),+ }))+ }+ }+}diff --git a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs b/rust/cloud-storage/search_service/src/api/search/simple/mod.rsindex 0324d11461..dc2feace0c 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/mod.rs@@ -8,6 +8,7 @@ use axum::{use model::response::ErrorResponse;use opensearch_client::error::OpensearchClientError;+pub(in crate::api::search::simple) mod filter;pub(in crate::api) mod simple_channel;pub(in crate::api) mod simple_chat;pub(in crate::api) mod simple_document;diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rsindex 2d4142e70f..49309925dd 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs@@ -1,4 +1,5 @@use crate::api::search::{SearchPaginationParams, simple::SearchError};+use item_filters::ChannelFilters;use std::collections::HashSet;use axum::{@@ -57,6 +58,57 @@ pub async fn handler(.into_response())}+pub(in crate::api::search) struct FilterChannelResponse {+ pub channel_ids: Vec<sqlx::types::Uuid>,+}++pub(in crate::api::search) async fn filter_channels(+ ctx: &ApiContext,+ user_id: &str,+ organization_id: Option<i32>,+ filters: &ChannelFilters,+) -> Result<FilterChannelResponse, SearchError> {+ // Get all channel ids for the user+ let channel_ids = ctx+ .comms_service_client+ .get_user_channel_ids(user_id, organization_id)+ .await+ .map_err(|e| SearchError::InternalError(e.into()))?;++ // If the user has no channels, return an empty response+ if channel_ids.is_empty() {+ return Ok(FilterChannelResponse {+ channel_ids: vec![],+ });+ }++ // filter through specific channel ids if provided+ let channel_ids = if !filters.channel_ids.is_empty() {+ let available_ids: HashSet<String> = filters+ .channel_ids+ .iter()+ .map(|id| id.to_string())+ .collect();++ channel_ids+ .into_iter()+ .filter(|id| available_ids.contains(&id.to_string()))+ .collect()+ } else {+ channel_ids+ };++ // filter through org_id if provided+ let channel_ids = if let Some(org_id) = filters.org_id {+ macro_db_client::items::filter::filter_channels_by_org_id(&ctx.db, &channel_ids, org_id)+ .await?+ } else {+ channel_ids+ };++ Ok(FilterChannelResponse { channel_ids })+}+pub(in crate::api::search) async fn search_channels(ctx: &ApiContext,user_id: &str,@@ -94,46 +146,24 @@ pub(in crate::api::search) async fn search_channels(return Err(SearchError::NoQueryOrTermsProvided);};- // Get all channel ids for the user- let channel_ids = ctx- .comms_service_client- .get_user_channel_ids(user_id, organization_id)- .await- .map_err(|e| SearchError::InternalError(e.into()))?;-- // If the user has no channels, return an empty response- if channel_ids.is_empty() {- return Ok(vec![]);- }-let filters = req.filters.unwrap_or_default();- // filter through specific channel ids if provided- let channel_ids = if !filters.channel_ids.is_empty() {- let available_ids: HashSet<String> = filters.channel_ids.into_iter().collect();-- channel_ids- .into_iter()- .filter(|id| available_ids.contains(&id.to_string()))- .collect()- } else {- channel_ids- };+ let filter_channel_response = filter_channels(ctx, user_id, organization_id, &filters).await?;- // filter through org_id if provided- let channel_ids = if let Some(org_id) = filters.org_id {- macro_db_client::items::filter::filter_channels_by_org_id(&ctx.db, &channel_ids, org_id)- .await?- } else {- channel_ids- };+ if filter_channel_response.channel_ids.is_empty() {+ return Ok(vec![]);+ }let results = ctx.opensearch_client.search_channel_messages(ChannelMessageSearchArgs {terms,user_id: user_id.to_string(),- channel_ids: channel_ids.iter().map(|c| c.to_string()).collect(),+ channel_ids: filter_channel_response+ .channel_ids+ .iter()+ .map(|c| c.to_string())+ .collect(),thread_ids: filters.thread_ids,mentions: filters.mentions,page,diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rsindex 5063cc515a..94e5c47814 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs@@ -5,6 +5,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};+use item_filters::ChatFilters;use model::{item::{ShareableItem, ShareableItemType},response::ErrorResponse,@@ -52,44 +53,16 @@ pub async fn handler(.into_response())}-pub(in crate::api::search) async fn search_chats(+pub(in crate::api::search) struct FilterChatResponse {+ pub chat_ids: Vec<String>,+ pub ids_only: bool,+}++pub(in crate::api::search) async fn filter_chats(ctx: &ApiContext,user_id: &str,- query_params: &SearchPaginationParams,- req: ChatSearchRequest,-) -> Result<Vec<opensearch_client::search::chats::ChatSearchResponse>, SearchError> {- if user_id.is_empty() {- return Err(SearchError::NoUserId);- }-- let page = query_params.page.unwrap_or(0);-- let page_size = if let Some(page_size) = query_params.page_size {- if !(0..=100).contains(&page_size) {- return Err(SearchError::InvalidPageSize);- }- page_size- } else {- 10- };-- let terms: Vec<String> = if let Some(terms) = req.terms {- terms- .into_iter()- .filter_map(|t| if t.len() < 3 { None } else { Some(t) })- .collect()- } else if let Some(query) = req.query {- if query.len() < 3 {- return Err(SearchError::InvalidQuerySize);- }-- vec![query]- } else {- return Err(SearchError::NoQueryOrTermsProvided);- };-- let filters = req.filters.unwrap_or_default();-+ filters: &ChatFilters,+) -> Result<FilterChatResponse, SearchError> {let chat_ids_response = if !filters.chat_ids.is_empty() {// Item ids are provided, we want to get the list of those that are accessible to the userctx.dss_client@@ -148,7 +121,10 @@ pub(in crate::api::search) async fn search_chats(};if chat_ids.is_empty() && ids_only {- return Ok(Vec::new());+ return Ok(FilterChatResponse {+ chat_ids: vec![],+ ids_only,+ });}let chat_ids = if !filters.owners.is_empty() {@@ -164,7 +140,50 @@ pub(in crate::api::search) async fn search_chats(chat_ids};- if chat_ids.is_empty() && ids_only {+ Ok(FilterChatResponse { chat_ids, ids_only })+}++pub(in crate::api::search) async fn search_chats(+ ctx: &ApiContext,+ user_id: &str,+ query_params: &SearchPaginationParams,+ req: ChatSearchRequest,+) -> Result<Vec<opensearch_client::search::chats::ChatSearchResponse>, SearchError> {+ if user_id.is_empty() {+ return Err(SearchError::NoUserId);+ }++ let page = query_params.page.unwrap_or(0);++ let page_size = if let Some(page_size) = query_params.page_size {+ if !(0..=100).contains(&page_size) {+ return Err(SearchError::InvalidPageSize);+ }+ page_size+ } else {+ 10+ };++ let terms: Vec<String> = if let Some(terms) = req.terms {+ terms+ .into_iter()+ .filter_map(|t| if t.len() < 3 { None } else { Some(t) })+ .collect()+ } else if let Some(query) = req.query {+ if query.len() < 3 {+ return Err(SearchError::InvalidQuerySize);+ }++ vec![query]+ } else {+ return Err(SearchError::NoQueryOrTermsProvided);+ };++ let filters = req.filters.unwrap_or_default();++ let filter_chat_response = filter_chats(ctx, user_id, &filters).await?;++ if filter_chat_response.chat_ids.is_empty() && filter_chat_response.ids_only {return Ok(Vec::new());}@@ -173,14 +192,14 @@ pub(in crate::api::search) async fn search_chats(.search_chats(ChatSearchArgs {terms,user_id: user_id.to_string(),- chat_ids,+ chat_ids: filter_chat_response.chat_ids,page,page_size,match_type: req.match_type.to_string(),role: filters.role,search_on: req.search_on.into(),collapse: req.collapse.unwrap_or(false),- ids_only,+ ids_only: filter_chat_response.ids_only,disable_recency: req.disable_recency,}).awaitdiff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rsindex 552b199ae6..73590f2286 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs@@ -5,6 +5,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};+use item_filters::DocumentFilters;use model::{item::{ShareableItem, ShareableItemType},response::ErrorResponse,@@ -52,45 +53,16 @@ pub async fn handler(.into_response())}-/// Performs a search through your documents and returns the raw opensearch results-pub(in crate::api::search) async fn search_documents(+pub(in crate::api::search) struct FilterDocumentResponse {+ pub document_ids: Vec<String>,+ pub ids_only: bool,+}++pub(in crate::api::search) async fn filter_documents(ctx: &ApiContext,user_id: &str,- query_params: &SearchPaginationParams,- req: DocumentSearchRequest,-) -> Result<Vec<opensearch_client::search::documents::DocumentSearchResponse>, SearchError> {- if user_id.is_empty() {- return Err(SearchError::NoUserId);- }-- let page = query_params.page.unwrap_or(0);-- let page_size = if let Some(page_size) = query_params.page_size {- if !(0..=100).contains(&page_size) {- return Err(SearchError::InvalidPageSize);- }- page_size- } else {- 10- };-- let terms: Vec<String> = if let Some(terms) = req.terms.as_ref() {- terms- .iter()- .filter_map(|t| if t.len() < 3 { None } else { Some(t.clone()) })- .collect()- } else if let Some(query) = req.query.as_ref() {- if query.len() < 3 {- return Err(SearchError::InvalidQuerySize);- }-- vec![query.clone()]- } else {- return Err(SearchError::NoQueryOrTermsProvided);- };-- let filters = req.filters.unwrap_or_default();-+ filters: &DocumentFilters,+) -> Result<FilterDocumentResponse, SearchError> {let document_ids_response = if !filters.document_ids.is_empty() {// Item ids are provided, we want to get the list of those that are accessible to the userctx.dss_client@@ -154,7 +126,10 @@ pub(in crate::api::search) async fn search_documents(};if document_ids.is_empty() && ids_only {- return Ok(Vec::new());+ return Ok(FilterDocumentResponse {+ document_ids: vec![],+ ids_only,+ });}let document_ids = if !filters.owners.is_empty() {@@ -171,7 +146,10 @@ pub(in crate::api::search) async fn search_documents(};if document_ids.is_empty() && ids_only {- return Ok(Vec::new());+ return Ok(FilterDocumentResponse {+ document_ids: vec![],+ ids_only,+ });}let document_ids = if !filters.file_types.is_empty() {@@ -186,7 +164,53 @@ pub(in crate::api::search) async fn search_documents(document_ids};- if document_ids.is_empty() && ids_only {+ Ok(FilterDocumentResponse {+ document_ids,+ ids_only,+ })+}++/// Performs a search through your documents and returns the raw opensearch results+pub(in crate::api::search) async fn search_documents(+ ctx: &ApiContext,+ user_id: &str,+ query_params: &SearchPaginationParams,+ req: DocumentSearchRequest,+) -> Result<Vec<opensearch_client::search::documents::DocumentSearchResponse>, SearchError> {+ if user_id.is_empty() {+ return Err(SearchError::NoUserId);+ }++ let page = query_params.page.unwrap_or(0);++ let page_size = if let Some(page_size) = query_params.page_size {+ if !(0..=100).contains(&page_size) {+ return Err(SearchError::InvalidPageSize);+ }+ page_size+ } else {+ 10+ };++ let terms: Vec<String> = if let Some(terms) = req.terms.as_ref() {+ terms+ .iter()+ .filter_map(|t| if t.len() < 3 { None } else { Some(t.clone()) })+ .collect()+ } else if let Some(query) = req.query.as_ref() {+ if query.len() < 3 {+ return Err(SearchError::InvalidQuerySize);+ }++ vec![query.clone()]+ } else {+ return Err(SearchError::NoQueryOrTermsProvided);+ };++ let filter_document_response =+ filter_documents(ctx, user_id, &req.filters.unwrap_or_default()).await?;++ if filter_document_response.document_ids.is_empty() && filter_document_response.ids_only {return Ok(Vec::new());}@@ -195,13 +219,13 @@ pub(in crate::api::search) async fn search_documents(.search_documents(DocumentSearchArgs {terms,user_id: user_id.to_string(),- document_ids,+ document_ids: filter_document_response.document_ids,page,page_size,match_type: req.match_type.to_string(),search_on: req.search_on.into(),collapse: req.collapse.unwrap_or(false),- ids_only,+ ids_only: filter_document_response.ids_only,disable_recency: req.disable_recency,}).awaitdiff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rsindex 6e51a57705..80f864c875 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs@@ -5,6 +5,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};+use item_filters::ProjectFilters;use model::{item::{ShareableItem, ShareableItemType},response::ErrorResponse,@@ -53,49 +54,16 @@ pub async fn handler(.into_response())}-pub(in crate::api::search) async fn search_projects(+pub(in crate::api::search) struct FilterProjectResponse {+ pub project_ids: Vec<String>,+ pub ids_only: bool,+}++pub(in crate::api::search) async fn filter_projects(ctx: &ApiContext,user_id: &str,- query_params: &SearchPaginationParams,- req: ProjectSearchRequest,-) -> Result<Vec<opensearch_client::search::projects::ProjectSearchResponse>, SearchError> {- // content search is not applicable for projects- if req.search_on == SearchOn::Content {- return Ok(Vec::new());- }-- if user_id.is_empty() {- return Err(SearchError::NoUserId);- }-- let page = query_params.page.unwrap_or(0);-- let page_size = if let Some(page_size) = query_params.page_size {- if !(0..=100).contains(&page_size) {- return Err(SearchError::InvalidPageSize);- }- page_size- } else {- 10- };-- let terms: Vec<String> = if let Some(terms) = req.terms {- terms- .into_iter()- .filter_map(|t| if t.len() < 3 { None } else { Some(t) })- .collect()- } else if let Some(query) = req.query {- if query.len() < 3 {- return Err(SearchError::InvalidQuerySize);- }-- vec![query]- } else {- return Err(SearchError::NoQueryOrTermsProvided);- };-- let filters = req.filters.unwrap_or_default();-+ filters: &ProjectFilters,+) -> Result<FilterProjectResponse, SearchError> {let project_ids: Vec<String> = if !filters.project_ids.is_empty() {// Item ids are provided, we want to get the list of those that are accessible to the userctx.dss_client@@ -149,7 +117,10 @@ pub(in crate::api::search) async fn search_projects(};if project_ids.is_empty() && ids_only {- return Ok(Vec::new());+ return Ok(FilterProjectResponse {+ project_ids: vec![],+ ids_only,+ });}let project_ids = if !filters.owners.is_empty() {@@ -165,7 +136,58 @@ pub(in crate::api::search) async fn search_projects(project_ids};- if project_ids.is_empty() && ids_only {+ Ok(FilterProjectResponse {+ project_ids,+ ids_only,+ })+}++pub(in crate::api::search) async fn search_projects(+ ctx: &ApiContext,+ user_id: &str,+ query_params: &SearchPaginationParams,+ req: ProjectSearchRequest,+) -> Result<Vec<opensearch_client::search::projects::ProjectSearchResponse>, SearchError> {+ // content search is not applicable for projects+ if req.search_on == SearchOn::Content {+ return Ok(Vec::new());+ }++ if user_id.is_empty() {+ return Err(SearchError::NoUserId);+ }++ let page = query_params.page.unwrap_or(0);++ let page_size = if let Some(page_size) = query_params.page_size {+ if !(0..=100).contains(&page_size) {+ return Err(SearchError::InvalidPageSize);+ }+ page_size+ } else {+ 10+ };++ let terms: Vec<String> = if let Some(terms) = req.terms {+ terms+ .into_iter()+ .filter_map(|t| if t.len() < 3 { None } else { Some(t) })+ .collect()+ } else if let Some(query) = req.query {+ if query.len() < 3 {+ return Err(SearchError::InvalidQuerySize);+ }++ vec![query]+ } else {+ return Err(SearchError::NoQueryOrTermsProvided);+ };++ let filters = req.filters.unwrap_or_default();++ let filter_project_response = filter_projects(ctx, user_id, &filters).await?;++ if filter_project_response.project_ids.is_empty() && filter_project_response.ids_only {return Ok(Vec::new());}@@ -177,10 +199,10 @@ pub(in crate::api::search) async fn search_projects(page,page_size,match_type: req.match_type.to_string(),- project_ids,+ project_ids: filter_project_response.project_ids,search_on: req.search_on.into(),collapse: req.collapse.unwrap_or(false),- ids_only,+ ids_only: filter_project_response.ids_only,disable_recency: req.disable_recency,}).awaitdiff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rsindex 889800e0ed..fb5916b011 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs@@ -1,93 +1,34 @@-use super::{simple_channel, simple_chat, simple_document, simple_email, simple_project};use crate::api::{ApiContext,- search::{SearchPaginationParams, simple::SearchError},+ search::{+ SearchPaginationParams,+ simple::{+ SearchError,+ filter::{FilterVariantToSearchArgs, UnifiedSearchArgsVariant},+ },+ },};use axum::{Extension,extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},+ response::Json,};-use futures::{FutureExt, StreamExt, stream::FuturesUnordered};use model::{response::ErrorResponse, user::UserContext};-use models_search::{- channel::ChannelSearchRequest,- chat::ChatSearchRequest,- document::DocumentSearchRequest,- email::EmailSearchRequest,- project::ProjectSearchRequest,- unified::{- SimpleUnifiedSearchResponse, SimpleUnifiedSearchResponseItem, UnifiedSearchIndex,- UnifiedSearchRequest,- },+use models_search::unified::{+ SimpleUnifiedSearchResponse, UnifiedSearchIndex, UnifiedSearchRequest,+ generate_unified_search_indices,};--/// This utility function provides a unified approach for processing search futures across different content types-/// (documents, chats, emails, etc.). It handles the complete flow from raw search execution through metadata-/// enrichment to final result formatting.-///-/// # Type Parameters-/// - `Fut`: Future that executes the OpenSearch query and fetches associated metadata, yielding `(T, U)`-/// - `T`: Raw search results returned from the OpenSearch operation-/// - `U`: Metadata retrieved from external sources to enrich the search results-/// - `S`: Intermediate search result type after combining raw results with metadata-/// - `V`: Structured search result type for the unified response format-///-/// # Parameters-/// - `search_future`: Async operation performing the search and metadata retrieval-/// - `variant_mapper`: Converts structured results into the unified response format-///-/// # Returns-/// A boxed future resolving to either unified search response items or a SearchError-pub(crate) fn boxed_search_future<Fut, T, S, V>(- search_future: Fut,- variant_mapper: fn(S) -> V,-) -> futures::future::BoxFuture<'static, Result<Vec<V>, SearchError>>-where- Fut: futures::Future<Output = Result<Vec<T>, SearchError>> + Send + 'static,- T: 'static + std::convert::Into<S>,- S: 'static,- V: 'static,-{- search_future- .map(move |res| {- res.map(|items| {- items- .into_iter()- .map(|item| variant_mapper(item.into()))- .collect::<Vec<V>>()- })- })- .boxed()-}--/// Perform a search through all items.-/// This is a simple search where we do not group your results by entity id.-#[utoipa::path(- post,- path = "/search/simple",- operation_id = "simple_unified_search",- params(- ("page" = i64, Query, description = "The page. Defaults to 0."),- ("page_size" = i64, Query, description = "The page size. Defaults to 10."),- ),- responses(- (status = 200, body=SimpleUnifiedSearchResponse),- (status = 400, body=ErrorResponse),- (status = 401, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )-)]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id), err)]-pub async fn handler(- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- extract::Query(query_params): extract::Query<SearchPaginationParams>,- extract::Json(req): extract::Json<UnifiedSearchRequest>,-) -> Result<Response, SearchError> {- tracing::info!("simple_unified_search");-+use opensearch_client::search::unified::UnifiedSearchArgs;++/// Creates a unified search request and performs the search+/// Returning the opensearch results+#[tracing::instrument(skip(ctx, user_context, query_params, req), err)]+pub(in crate::api::search) async fn perform_unified_search(+ ctx: &ApiContext,+ user_context: &UserContext,+ query_params: SearchPaginationParams,+ req: UnifiedSearchRequest,+) -> Result<Vec<opensearch_client::search::unified::UnifiedSearchResponse>, SearchError> {let user_id = &user_context.user_id;let user_organization_id = user_context.organization_id;let search_on = req.search_on;@@ -97,8 +38,6 @@ pub async fn handler(return Err(SearchError::NoUserId);}- // TODO: deduplicate logic for getting page and page size-let page = query_params.page.unwrap_or(0);let page_size = query_params.page_size.unwrap_or(10);@@ -106,7 +45,6 @@ pub async fn handler(return Err(SearchError::InvalidPageSize);}- // TODO: deduplicate logic for extracting termslet terms: Vec<String> = match (req.terms, req.query) {(Some(terms), _) => terms.into_iter().filter(|t| t.len() >= 3).collect(),(None, Some(query)) if query.len() >= 3 => vec![query],@@ -116,171 +54,146 @@ pub async fn handler(_ => vec![],};- // no filters means search all- let filters = req.filters.unwrap_or_default();let match_type = req.match_type;let disable_recency = req.disable_recency;- let include_all_items = req.include.is_empty();-- let mut tasks = FuturesUnordered::new();-- if include_all_items || req.include.contains(&UnifiedSearchIndex::Documents) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };-- let request = DocumentSearchRequest {- query: None,- terms: Some(terms.clone()),- match_type,- filters: filters.document,- search_on,- collapse: Some(collapse),- disable_recency,- };-- let ctx = ctx.clone();- let user_id = user_id.clone();-- tasks.push(boxed_search_future(- async move {- simple_document::search_documents(&ctx, &user_id, &query_params, request).await- },- SimpleUnifiedSearchResponseItem::Document,- ));- }-- if include_all_items || req.include.contains(&UnifiedSearchIndex::Chats) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };-- let request = ChatSearchRequest {- query: None,- terms: Some(terms.clone()),- match_type,- filters: filters.chat,- search_on,- collapse: Some(collapse),- disable_recency,- };-- let ctx = ctx.clone();- let user_id = user_id.clone();-- tasks.push(boxed_search_future(- async move { simple_chat::search_chats(&ctx, &user_id, &query_params, request).await },- SimpleUnifiedSearchResponseItem::Chat,- ));- }-- if include_all_items || req.include.contains(&UnifiedSearchIndex::Emails) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };-- let request = EmailSearchRequest {- query: None,- terms: Some(terms.clone()),- match_type,- filters: filters.email,- search_on,- collapse: Some(collapse),- disable_recency,- };+ let include = req.include;- let ctx = ctx.clone();- let user_id = user_id.clone();+ // Create default filters+ let filters = req.filters.unwrap_or_default();+ let channel_filters = filters.channel.unwrap_or_default();+ let email_filters = filters.email.unwrap_or_default();+ let chat_filters = filters.chat.unwrap_or_default();+ let project_filters = filters.project.unwrap_or_default();+ let doc_filters = filters.document.unwrap_or_default();++ let should_include_documents =+ include.is_empty() || include.contains(&UnifiedSearchIndex::Documents);++ let should_include_channels =+ include.is_empty() || include.contains(&UnifiedSearchIndex::Channels);++ let should_include_chats = include.is_empty() || include.contains(&UnifiedSearchIndex::Chats);++ let should_include_projects =+ include.is_empty() || include.contains(&UnifiedSearchIndex::Projects);++ let should_include_emails = include.is_empty() || include.contains(&UnifiedSearchIndex::Emails);++ // Await all tasks in parallel+ let (doc_result, channel_result, chat_result, project_result, email_result) = tokio::try_join!(+ doc_filters.filter_to_search_args(+ ctx,+ user_id,+ user_organization_id,+ should_include_documents,+ ),+ channel_filters.filter_to_search_args(+ ctx,+ user_id,+ user_organization_id,+ should_include_channels,+ ),+ chat_filters.filter_to_search_args(+ ctx,+ user_id,+ user_organization_id,+ should_include_chats,+ ),+ project_filters.filter_to_search_args(+ ctx,+ user_id,+ user_organization_id,+ should_include_projects,+ ),+ email_filters.filter_to_search_args(+ ctx,+ user_id,+ user_organization_id,+ should_include_emails,+ ),+ )+ .map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;- tasks.push(- boxed_search_future(- async move {- simple_email::search_emails(&ctx, &user_id, &query_params, request).await- },- SimpleUnifiedSearchResponseItem::Email,- ),- );- }+ let filter_document_response = match doc_result {+ UnifiedSearchArgsVariant::Document(response) => response,+ _ => unreachable!(),+ };- if include_all_items || req.include.contains(&UnifiedSearchIndex::Channels) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };+ let filter_channel_response = match channel_result {+ UnifiedSearchArgsVariant::Channel(response) => response,+ _ => unreachable!(),+ };- let request = ChannelSearchRequest {- query: None,- terms: Some(terms.clone()),- match_type,- filters: filters.channel,- search_on,- collapse: Some(collapse),- disable_recency,- };+ let filter_chat_response = match chat_result {+ UnifiedSearchArgsVariant::Chat(response) => response,+ _ => unreachable!(),+ };- let ctx = ctx.clone();- let user_id = user_id.clone();+ let filter_project_response = match project_result {+ UnifiedSearchArgsVariant::Project(response) => response,+ _ => unreachable!(),+ };- tasks.push(boxed_search_future(- async move {- simple_channel::search_channels(- &ctx,- &user_id,- user_organization_id,- &query_params,- request,- )- .await- },- SimpleUnifiedSearchResponseItem::Channel,- ));- }+ let filter_email_response = match email_result {+ UnifiedSearchArgsVariant::Email(response) => response,+ _ => unreachable!(),+ };- if include_all_items || req.include.contains(&UnifiedSearchIndex::Projects) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };+ let unified_search_args = UnifiedSearchArgs {+ terms,+ user_id: user_id.to_string(),+ page,+ page_size,+ match_type: match_type.to_string(),+ search_on: search_on.into(),+ collapse,+ disable_recency,+ search_indices: generate_unified_search_indices(include),+ document_search_args: filter_document_response,+ email_search_args: filter_email_response,+ channel_message_search_args: filter_channel_response,+ chat_search_args: filter_chat_response,+ project_search_args: filter_project_response,+ };- let request = ProjectSearchRequest {- query: None,- terms: Some(terms),- match_type,- filters: filters.project,- search_on,- collapse: Some(collapse),- disable_recency,- };+ let results = ctx+ .opensearch_client+ .search_unified(unified_search_args)+ .await?;- let ctx = ctx.clone();- let user_id = user_id.clone();+ Ok(results)+}- tasks.push(- boxed_search_future(- async move {- simple_project::search_projects(&ctx, &user_id, &query_params, request).await- },- SimpleUnifiedSearchResponseItem::Project,- ),- );- }+/// Perform a search through all items.+/// This is a simple search where we do not group your results by entity id.+#[utoipa::path(+ post,+ path = "/search/simple",+ operation_id = "simple_unified_search",+ params(+ ("page" = i64, Query, description = "The page. Defaults to 0."),+ ("page_size" = i64, Query, description = "The page size. Defaults to 10."),+ ),+ responses(+ (status = 200, body=SimpleUnifiedSearchResponse),+ (status = 400, body=ErrorResponse),+ (status = 401, body=ErrorResponse),+ (status = 500, body=ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id), err)]+pub async fn handler(+ State(ctx): State<ApiContext>,+ user_context: Extension<UserContext>,+ extract::Query(query_params): extract::Query<SearchPaginationParams>,+ extract::Json(req): extract::Json<UnifiedSearchRequest>,+) -> Result<Json<SimpleUnifiedSearchResponse>, SearchError> {+ tracing::info!("simple_unified_search");- let mut results = Vec::new();+ let results = perform_unified_search(&ctx, &user_context, query_params, req).await?;- while let Some(result) = tasks.next().await {- match result {- Ok(items) => results.extend(items),- Err(err_response) => return Err(err_response),- }- }+ let results = results.into_iter().map(|a| a.into()).collect();- Ok((- StatusCode::OK,- Json(SimpleUnifiedSearchResponse { results }),- )- .into_response())+ Ok(Json(SimpleUnifiedSearchResponse { results }))}diff --git a/rust/cloud-storage/search_service/src/api/search/unified.rs b/rust/cloud-storage/search_service/src/api/search/unified.rsindex 9ee74ac4fc..52bc0efac2 100644--- a/rust/cloud-storage/search_service/src/api/search/unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/unified.rs@@ -2,12 +2,8 @@ use super::SearchPaginationParams;use crate::api::{ApiContext,search::{- channel::search_channels_enriched,- chat::search_chats_enriched,- document::search_documents_enriched,- email::search_emails_enriched,- project::search_projects_enriched,- simple::{SearchError, simple_unified::boxed_search_future},+ enrich::EnrichSearchResponse,+ simple::{SearchError, simple_unified::perform_unified_search},},};use axum::{@@ -16,17 +12,10 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};-use futures::{StreamExt, stream::FuturesUnordered};use model::{response::ErrorResponse, user::UserContext};-use models_search::{- channel::ChannelSearchRequest,- chat::ChatSearchRequest,- document::DocumentSearchRequest,- email::EmailSearchRequest,- project::ProjectSearchRequest,- unified::{- UnifiedSearchIndex, UnifiedSearchRequest, UnifiedSearchResponse, UnifiedSearchResponseItem,- },+use models_search::unified::{UnifiedSearchRequest, UnifiedSearchResponse};+use opensearch_client::search::unified::{+ SplitUnifiedSearchResponse, SplitUnifiedSearchResponseValues,};/// Perform a search through all items@@ -54,185 +43,50 @@ pub async fn handler() -> Result<Response, SearchError> {tracing::info!("unified_search");- let user_id = &user_context.user_id;- let user_organization_id = user_context.organization_id;- let search_on = req.search_on;- let collapse = req.collapse.unwrap_or(false);-- if user_id.is_empty() {- return Err(SearchError::NoUserId);- }-- // TODO: deduplicate logic for getting page and page size-- let page = query_params.page.unwrap_or(0);-- let page_size = query_params.page_size.unwrap_or(10);- if !(0..=100).contains(&page_size) {- return Err(SearchError::InvalidPageSize);- }-- // TODO: deduplicate logic for extracting terms- let terms: Vec<String> = match (req.terms, req.query) {- (Some(terms), _) => terms.into_iter().filter(|t| t.len() >= 3).collect(),- (None, Some(query)) if query.len() >= 3 => vec![query],- (None, Some(_)) => {- return Err(SearchError::InvalidQuerySize);- }- _ => vec![],- };-- // no filters means search all- let filters = req.filters.unwrap_or_default();- let match_type = req.match_type;- let disable_recency = req.disable_recency;-- let mut tasks = FuturesUnordered::new();-- let include_all_items = req.include.is_empty();-- if include_all_items || req.include.contains(&UnifiedSearchIndex::Documents) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };-- let request = DocumentSearchRequest {- query: None,- terms: Some(terms.clone()),- match_type,- filters: filters.document,- search_on,- collapse: Some(collapse),- disable_recency,- };-- let ctx = ctx.clone();- let user_id = user_id.clone();-- tasks.push(boxed_search_future(- async move { search_documents_enriched(&ctx, &user_id, &query_params, request).await },- UnifiedSearchResponseItem::Document,- ));- }-- if include_all_items || req.include.contains(&UnifiedSearchIndex::Chats) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };-- let request = ChatSearchRequest {- query: None,- terms: Some(terms.clone()),- match_type,- filters: filters.chat,- search_on,- collapse: Some(collapse),- disable_recency,- };-- let ctx = ctx.clone();- let user_id = user_id.clone();-- tasks.push(boxed_search_future(- async move { search_chats_enriched(&ctx, &user_id, &query_params, request).await },- UnifiedSearchResponseItem::Chat,- ));- }-- if include_all_items || req.include.contains(&UnifiedSearchIndex::Emails) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };-- let request = EmailSearchRequest {- query: None,- terms: Some(terms.clone()),- match_type,- filters: filters.email,- search_on,- collapse: Some(collapse),- disable_recency,- };-- let ctx = ctx.clone();- let user_id = user_id.clone();-- tasks.push(boxed_search_future(- async move { search_emails_enriched(&ctx, &user_id, &query_params, request).await },- UnifiedSearchResponseItem::Email,- ));- }-- if include_all_items || req.include.contains(&UnifiedSearchIndex::Channels) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };-- let request = ChannelSearchRequest {- query: None,- terms: Some(terms.clone()),- match_type,- filters: filters.channel,- search_on,- collapse: Some(collapse),- disable_recency,- };-- let ctx = ctx.clone();- let user_id = user_id.clone();-- tasks.push(boxed_search_future(- async move {- search_channels_enriched(- &ctx,- &user_id,- user_organization_id,- &query_params,- request,- )- .await- },- UnifiedSearchResponseItem::Channel,- ));- }-- if include_all_items || req.include.contains(&UnifiedSearchIndex::Projects) {- let query_params = SearchPaginationParams {- page: Some(page),- page_size: Some(page_size),- };-- let request = ProjectSearchRequest {- query: None,- terms: Some(terms),- match_type,- filters: filters.project,- search_on,- collapse: Some(collapse),- disable_recency,- };-- let ctx = ctx.clone();- let user_id = user_id.clone();+ let results = perform_unified_search(&ctx, &user_context, query_params, req).await?;++ let SplitUnifiedSearchResponseValues {+ channel_message,+ chat,+ document,+ email,+ project,+ } = results.into_iter().split_search_response();++ let (+ enriched_document_results,+ enriched_chat_results,+ enriched_channel_results,+ enriched_project_results,+ enriched_email_results,+ ) = tokio::try_join!(+ document+ .into_iter()+ .enrich_search_response(&ctx, &user_context.user_id),+ chat.into_iter()+ .enrich_search_response(&ctx, &user_context.user_id),+ channel_message+ .into_iter()+ .enrich_search_response(&ctx, &user_context.user_id),+ project+ .into_iter()+ .enrich_search_response(&ctx, &user_context.user_id),+ .into_iter()+ .enrich_search_response(&ctx, &user_context.user_id)+ )+ .map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;- tasks.push(boxed_search_future(- async move { search_projects_enriched(&ctx, &user_id, &query_params, request).await },- UnifiedSearchResponseItem::Project,- ));- }+ let mut results = vec![];- let mut results = Vec::new();+ results.extend(enriched_document_results);+ results.extend(enriched_chat_results);+ results.extend(enriched_channel_results);+ results.extend(enriched_project_results);+ results.extend(enriched_email_results);- while let Some(result) = tasks.next().await {- match result {- Ok(items) => results.extend(items),- Err(err_response) => return Err(err_response),- }- }+ // TODO: sort at the end. need to expose hit score first+ // https://linear.app/macro-eng/issue/M-5244/sort-by-hit-score-after-combining-enriched-resultsOk((StatusCode::OK, Json(UnifiedSearchResponse { results })).into_response())}