Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(search): channel content thread-mode sort (#3150)

gbirman0adaa64a3d6b
diff --git a/js/app/packages/service-clients/service-search/generated/models/channelSearchRequestAllOfTwo.ts b/js/app/packages/service-clients/service-search/generated/models/channelSearchRequestAllOfTwo.ts
index 6a810763d2..3d146404c7 100644
--- a/js/app/packages/service-clients/service-search/generated/models/channelSearchRequestAllOfTwo.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/channelSearchRequestAllOfTwo.ts
@@ -7,6 +7,7 @@
import type { ChannelSearchRequestAllOfTwoCollapse } from './channelSearchRequestAllOfTwoCollapse';
import type { ChannelSearchRequestAllOfTwoQuery } from './channelSearchRequestAllOfTwoQuery';
import type { ChannelSearchRequestAllOfTwoTerms } from './channelSearchRequestAllOfTwoTerms';
+import type { ChannelSortTimestamp } from './channelSortTimestamp';
import type { MatchType } from './matchType';
import type { SearchOn } from './searchOn';
@@ -19,6 +20,8 @@ export type ChannelSearchRequestAllOfTwo = {
query?: ChannelSearchRequestAllOfTwoQuery;
/** Fields to search on (Name, Content, NameContent). Defaults to Content */
search_on?: SearchOn;
+ /** Sort key for results. Defaults to `message`. */
+ sort?: ChannelSortTimestamp;
/** Multiple terms to search over */
terms?: ChannelSearchRequestAllOfTwoTerms;
};
diff --git a/js/app/packages/service-clients/service-search/generated/models/channelSearchResponse.ts b/js/app/packages/service-clients/service-search/generated/models/channelSearchResponse.ts
index 6a1eb9d64b..3e3a074f06 100644
--- a/js/app/packages/service-clients/service-search/generated/models/channelSearchResponse.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/channelSearchResponse.ts
@@ -4,12 +4,16 @@
* search_service
* OpenAPI spec version: 0.1.0
*/
+
import type { ChannelSearchResponseItemWithMetadata } from './channelSearchResponseItemWithMetadata';
+import type { ChannelSearchResponseNextCursor } from './channelSearchResponseNextCursor';
/**
* The document search response object
*/
export interface ChannelSearchResponse {
+ /** Base64-encoded cursor for the next page; `None` when exhausted. */
+ next_cursor?: ChannelSearchResponseNextCursor;
/** List containing results from email threads */
results: ChannelSearchResponseItemWithMetadata[];
}
diff --git a/js/app/packages/service-clients/service-search/generated/models/channelSearchResponseNextCursor.ts b/js/app/packages/service-clients/service-search/generated/models/channelSearchResponseNextCursor.ts
new file mode 100644
index 0000000000..6e7ed500d9
--- /dev/null
+++ b/js/app/packages/service-clients/service-search/generated/models/channelSearchResponseNextCursor.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Base64-encoded cursor for the next page; `None` when exhausted.
+ */
+export type ChannelSearchResponseNextCursor = string | null;
diff --git a/js/app/packages/service-clients/service-search/generated/models/channelSortTimestamp.ts b/js/app/packages/service-clients/service-search/generated/models/channelSortTimestamp.ts
new file mode 100644
index 0000000000..0998a4f8f7
--- /dev/null
+++ b/js/app/packages/service-clients/service-search/generated/models/channelSortTimestamp.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Sort key for channel content search results.
+ */
+export type ChannelSortTimestamp =
+ (typeof ChannelSortTimestamp)[keyof typeof ChannelSortTimestamp];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ChannelSortTimestamp = {
+ message: 'message',
+ thread: 'thread',
+} as const;
diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.ts
index db3b850a94..2cb13f4274 100644
--- a/js/app/packages/service-clients/service-search/generated/models/index.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts
@@ -40,6 +40,7 @@ export * from './channelSearchResponseItemOwnerId';
export * from './channelSearchResponseItemWithMetadata';
export * from './channelSearchResponseItemWithMetadataAllOf';
export * from './channelSearchResponseItemWithMetadataAllOfMetadata';
+export * from './channelSearchResponseNextCursor';
export * from './channelSearchResult';
export * from './channelSearchResultCreatedAt';
export * from './channelSearchResultDeletedAt';
@@ -48,6 +49,7 @@ export * from './channelSearchResultScore';
export * from './channelSearchResultSenderId';
export * from './channelSearchResultThreadId';
export * from './channelSearchResultUpdatedAt';
+export * from './channelSortTimestamp';
export * from './chatFilters';
export * from './chatFiltersImportance';
export * from './chatMessageSearchResult';
diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.json
index e3c7c28a37..c39b2dcd71 100644
--- a/js/app/packages/service-clients/service-search/openapi.json
+++ b/js/app/packages/service-clients/service-search/openapi.json
@@ -454,6 +454,10 @@
"$ref": "#/components/schemas/SearchOn",
"description": "Fields to search on (Name, Content, NameContent). Defaults to Content"
},
+ "sort": {
+ "$ref": "#/components/schemas/ChannelSortTimestamp",
+ "description": "Sort key for results. Defaults to `message`."
+ },
"terms": {
"type": ["array", "null"],
"items": {
@@ -470,6 +474,10 @@
"description": "The document search response object",
"required": ["results"],
"properties": {
+ "next_cursor": {
+ "type": ["string", "null"],
+ "description": "Base64-encoded cursor for the next page; `None` when exhausted."
+ },
"results": {
"type": "array",
"items": {
@@ -585,6 +593,11 @@
}
}
},
+ "ChannelSortTimestamp": {
+ "type": "string",
+ "description": "Sort key for channel content search results.",
+ "enum": ["message", "thread"]
+ },
"ChatFilters": {
"type": "object",
"description": "The chat filters used to filter down what chats you search over.",
diff --git a/rust/cloud-storage/models_search/src/channel.rs b/rust/cloud-storage/models_search/src/channel.rs
index 2f3fa52ffa..bd4b0ca29e 100644
--- a/rust/cloud-storage/models_search/src/channel.rs
+++ b/rust/cloud-storage/models_search/src/channel.rs
@@ -5,6 +5,19 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
+/// Sort key for channel content search results.
+#[derive(
+ Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq, ToSchema, JsonSchema,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum ChannelSortTimestamp {
+ /// Sort by message created_at DESC, message_id DESC tiebreaker.
+ #[default]
+ Message,
+ /// Sort by thread_id DESC, message_id DESC tiebreaker.
+ Thread,
+}
+
/// A channel message match for a given channel id
#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct ChannelSearchResult {
@@ -99,6 +112,9 @@ impl From<SearchResponseItem<ChannelSearchResult, ChannelSearchMetadata>>
pub struct ChannelSearchResponse {
/// List containing results from email threads
pub results: Vec<ChannelSearchResponseItemWithMetadata>,
+ /// Base64-encoded cursor for the next page; `None` when exhausted.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub next_cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, ToSchema, JsonSchema)]
@@ -118,6 +134,9 @@ pub struct ChannelSearchRequest {
/// If true, returns only 1 result per entity. False by default.
#[serde(skip_serializing_if = "Option::is_none")]
pub collapse: Option<bool>,
+ /// Sort key for results. Defaults to `message`.
+ #[serde(default)]
+ pub sort: ChannelSortTimestamp,
}
#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]
diff --git a/rust/cloud-storage/models_search/src/channel/test.rs b/rust/cloud-storage/models_search/src/channel/test.rs
index 8ee94174ee..64417b2557 100644
--- a/rust/cloud-storage/models_search/src/channel/test.rs
+++ b/rust/cloud-storage/models_search/src/channel/test.rs
@@ -15,10 +15,11 @@ fn test_channel_search_request_json_serialization() {
}),
search_on: SearchOn::Content,
collapse: None,
+ sort: ChannelSortTimestamp::Message,
};
let json = serde_json::to_string(&request).expect("Failed to serialize to JSON");
- let expected = r#"{"query":"test query","terms":["term1","term2"],"match_type":"exact","thread_ids":["thread1","thread2"],"mentions":["@user1","@user2"],"org_id":12345,"search_on":"content"}"#;
+ let expected = r#"{"query":"test query","terms":["term1","term2"],"match_type":"exact","thread_ids":["thread1","thread2"],"mentions":["@user1","@user2"],"org_id":12345,"search_on":"content","sort":"message"}"#;
assert_eq!(json, expected);
}
@@ -92,6 +93,7 @@ fn test_channel_search_request_round_trip() {
}),
search_on: SearchOn::Content,
collapse: None,
+ sort: ChannelSortTimestamp::Message,
};
let json = serde_json::to_string(&original).expect("Failed to serialize");
diff --git a/rust/cloud-storage/models_search_cursor/src/lib.rs b/rust/cloud-storage/models_search_cursor/src/lib.rs
index e81bc9ac0a..bc2f6565c2 100644
--- a/rust/cloud-storage/models_search_cursor/src/lib.rs
+++ b/rust/cloud-storage/models_search_cursor/src/lib.rs
@@ -21,14 +21,77 @@ pub struct PaginatedResult<T> {
pub cursor: SearchCursorOption,
}
-/// Used to store individual cursor information for a given search method.
-/// This could be document names, email subject, content etc.
+/// Cursor for a single search method. Each variant matches the sort fields
+/// of the search it paginates, so the values can be passed straight to
+/// OpenSearch's `search_after` without re-purposing.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct SearchMethodCursor {
- /// The id of the entity, used in tie breakers
- pub entity_id: uuid::Uuid,
- /// The updated at time of the entity
- pub updated_at: chrono::DateTime<chrono::Utc>,
+pub enum SearchMethodCursor {
+ /// Sort: `[updated_at_ms desc, entity_id asc]`. Used by name searches and
+ /// the default channel content sort.
+ UpdatedAt {
+ /// Tiebreaker entity id.
+ entity_id: uuid::Uuid,
+ /// Primary sort timestamp.
+ updated_at: chrono::DateTime<chrono::Utc>,
+ },
+ /// Sort: `[thread_id desc, message_id desc]`. Used by channel content
+ /// search in thread-grouped mode.
+ Thread {
+ /// Primary sort key.
+ thread_id: uuid::Uuid,
+ /// Tiebreaker for replies within the same thread.
+ message_id: uuid::Uuid,
+ },
+}
+
+impl SearchMethodCursor {
+ /// Produces the values to pass as OpenSearch `search_after`.
+ pub fn search_after(&self) -> Vec<serde_json::Value> {
+ match self {
+ Self::UpdatedAt {
+ entity_id,
+ updated_at,
+ } => vec![
+ serde_json::json!(updated_at.timestamp_millis()),
+ serde_json::json!(entity_id.to_string()),
+ ],
+ Self::Thread {
+ thread_id,
+ message_id,
+ } => vec![
+ serde_json::json!(thread_id.to_string()),
+ serde_json::json!(message_id.to_string()),
+ ],
+ }
+ }
+
+ /// Returns `(entity_id, updated_at)` for the `UpdatedAt` variant.
+ /// Callers that only paginate by `(updated_at, entity_id)` use this to
+ /// avoid exhaustive matching; `Thread` cursors yield `None`.
+ pub fn as_updated_at(&self) -> Option<(uuid::Uuid, chrono::DateTime<chrono::Utc>)> {
+ match self {
+ Self::UpdatedAt {
+ entity_id,
+ updated_at,
+ } => Some((*entity_id, *updated_at)),
+ Self::Thread { .. } => None,
+ }
+ }
+
+ /// Encodes the cursor as a base64 string for client transport.
+ pub fn encode(&self) -> Option<String> {
+ serde_json::to_vec(self)
+ .ok()
+ .map(|bytes| BASE64.encode(bytes))
+ }
+
+ /// Decodes a base64-encoded cursor string.
+ pub fn decode(encoded: &str) -> Option<Self> {
+ BASE64
+ .decode(encoded)
+ .ok()
+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())
+ }
}
/// Represents the state of a search cursor
@@ -72,7 +135,7 @@ impl SearchCursorOption {
let cursor = if has_more {
match items.last() {
- Some(last) => SearchCursorOption::NotDone(Some(SearchMethodCursor {
+ Some(last) => SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
entity_id: last.entity_id(),
updated_at: last.updated_at(),
})),
diff --git a/rust/cloud-storage/name_search/src/chat.rs b/rust/cloud-storage/name_search/src/chat.rs
index 5b940f4bba..d489293367 100644
--- a/rust/cloud-storage/name_search/src/chat.rs
+++ b/rust/cloud-storage/name_search/src/chat.rs
@@ -25,7 +25,8 @@ async fn ids_search(
let (cursor_updated_at, cursor_entity_id) = cursor
.as_ref()
- .map(|c| (Some(c.updated_at), Some(c.entity_id.to_string())))
+ .and_then(|c| c.as_updated_at())
+ .map(|(id, ts)| (Some(ts), Some(id.to_string())))
.unwrap_or((None, None));
// Fetch limit + 1 to determine if there are more results
@@ -93,7 +94,8 @@ async fn owner_search<'a>(
) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {
let (cursor_updated_at, cursor_entity_id) = cursor
.as_ref()
- .map(|c| (Some(c.updated_at), Some(c.entity_id.to_string())))
+ .and_then(|c| c.as_updated_at())
+ .map(|(id, ts)| (Some(ts), Some(id.to_string())))
.unwrap_or((None, None));
// Fetch limit + 1 to determine if there are more results
@@ -158,7 +160,7 @@ async fn owner_search<'a>(
time = 30,
result = true,
key = "String",
- convert = r#"{ format!("{}-{:?}-{}-{}-{}-{}", macro_user_id.as_ref(), chat_ids, term, ids_only, limit, cursor.as_ref().map(|c| format!("{}-{}", c.entity_id, c.updated_at)).unwrap_or_default()) }"#
+ convert = r#"{ format!("{}-{:?}-{}-{}-{}-{}", macro_user_id.as_ref(), chat_ids, term, ids_only, limit, cursor.as_ref().and_then(|c| c.as_updated_at()).map(|(id, ts)| format!("{}-{}", id, ts)).unwrap_or_default()) }"#
)
)]
pub async fn search_chat_names<'a>(
@@ -173,6 +175,9 @@ pub async fn search_chat_names<'a>(
if term.is_empty() {
return Err(NameSearchError::EmptySearchTerm);
}
+ if cursor.as_ref().is_some_and(|c| c.as_updated_at().is_none()) {
+ return Err(NameSearchError::IncompatibleCursor);
+ }
let search_pattern = format!("%{term}%");
let highlight_pattern = format!("({})", escape_regex(&term));
diff --git a/rust/cloud-storage/name_search/src/chat/test.rs b/rust/cloud-storage/name_search/src/chat/test.rs
index f7c3594bec..7b8f6b94ff 100644
--- a/rust/cloud-storage/name_search/src/chat/test.rs
+++ b/rust/cloud-storage/name_search/src/chat/test.rs
@@ -1,7 +1,7 @@
//! Tests for chat module
use macro_db_migrator::MACRO_DB_MIGRATIONS;
-use models_search_cursor::SearchCursorOption;
+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -423,3 +423,36 @@ async fn test_search_chat_names_excludes_soft_deleted(pool: Pool<Postgres>) -> a
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_rejects_thread_cursor(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let cursor = SearchMethodCursor::Thread {
+ thread_id: Uuid::new_v4(),
+ message_id: Uuid::new_v4(),
+ };
+
+ let result = search_chat_names(
+ &pool,
+ &user_id,
+ &[],
+ "test".to_string(),
+ false,
+ 10,
+ Some(cursor),
+ )
+ .await;
+
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::IncompatibleCursor
+ ));
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/name_search/src/document.rs b/rust/cloud-storage/name_search/src/document.rs
index 6dd5ef587f..878a5930f3 100644
--- a/rust/cloud-storage/name_search/src/document.rs
+++ b/rust/cloud-storage/name_search/src/document.rs
@@ -25,7 +25,8 @@ async fn ids_search(
let (cursor_updated_at, cursor_entity_id) = cursor
.as_ref()
- .map(|c| (Some(c.updated_at), Some(c.entity_id.to_string())))
+ .and_then(|c| c.as_updated_at())
+ .map(|(id, ts)| (Some(ts), Some(id.to_string())))
.unwrap_or((None, None));
// Fetch limit + 1 to determine if there are more results
@@ -93,7 +94,8 @@ async fn owner_search<'a>(
) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {
let (cursor_updated_at, cursor_entity_id) = cursor
.as_ref()
- .map(|c| (Some(c.updated_at), Some(c.entity_id.to_string())))
+ .and_then(|c| c.as_updated_at())
+ .map(|(id, ts)| (Some(ts), Some(id.to_string())))
.unwrap_or((None, None));
// Fetch limit + 1 to determine if there are more results
@@ -158,7 +160,7 @@ async fn owner_search<'a>(
time = 30,
result = true,
key = "String",
- convert = r#"{ format!("{}-{:?}-{}-{}-{}-{}", macro_user_id.as_ref(), document_ids, term, ids_only, limit, cursor.as_ref().map(|c| format!("{}-{}", c.entity_id, c.updated_at)).unwrap_or_default()) }"#
+ convert = r#"{ format!("{}-{:?}-{}-{}-{}-{}", macro_user_id.as_ref(), document_ids, term, ids_only, limit, cursor.as_ref().and_then(|c| c.as_updated_at()).map(|(id, ts)| format!("{}-{}", id, ts)).unwrap_or_default()) }"#
)
)]
pub async fn search_document_names<'a>(
@@ -173,6 +175,9 @@ pub async fn search_document_names<'a>(
if term.is_empty() {
return Err(NameSearchError::EmptySearchTerm);
}
+ if cursor.as_ref().is_some_and(|c| c.as_updated_at().is_none()) {
+ return Err(NameSearchError::IncompatibleCursor);
+ }
let search_pattern = format!("%{term}%");
let highlight_pattern = format!("({})", escape_regex(&term));
diff --git a/rust/cloud-storage/name_search/src/document/test.rs b/rust/cloud-storage/name_search/src/document/test.rs
index a9b6519fb3..3c5dd35573 100644
--- a/rust/cloud-storage/name_search/src/document/test.rs
+++ b/rust/cloud-storage/name_search/src/document/test.rs
@@ -1,7 +1,7 @@
//! Tests for document module
use macro_db_migrator::MACRO_DB_MIGRATIONS;
-use models_search_cursor::SearchCursorOption;
+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -391,3 +391,38 @@ async fn test_search_document_names_user_isolation(pool: Pool<Postgres>) -> anyh
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_rejects_thread_cursor(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let cursor = SearchMethodCursor::Thread {
+ thread_id: Uuid::new_v4(),
+ message_id: Uuid::new_v4(),
+ };
+
+ let result = search_document_names(
+ &pool,
+ &user_id,
+ &[],
+ "test".to_string(),
+ false,
+ 10,
+ Some(cursor),
+ )
+ .await;
+
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::IncompatibleCursor
+ ));
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/name_search/src/lib.rs b/rust/cloud-storage/name_search/src/lib.rs
index d03e612e66..e6174d9546 100644
--- a/rust/cloud-storage/name_search/src/lib.rs
+++ b/rust/cloud-storage/name_search/src/lib.rs
@@ -40,6 +40,9 @@ pub enum NameSearchError {
/// Empty ids provided with ids only set to true
#[error("empty ids provided with ids only set to true")]
EmptyIdsWithIdsOnly,
+ /// Cursor variant doesn't match this search method.
+ #[error("incompatible cursor variant for name search")]
+ IncompatibleCursor,
}
/// Name search result match
diff --git a/rust/cloud-storage/name_search/src/project.rs b/rust/cloud-storage/name_search/src/project.rs
index 8b86696856..d8d75ad774 100644
--- a/rust/cloud-storage/name_search/src/project.rs
+++ b/rust/cloud-storage/name_search/src/project.rs
@@ -25,7 +25,8 @@ async fn ids_search(
let (cursor_updated_at, cursor_entity_id) = cursor
.as_ref()
- .map(|c| (Some(c.updated_at), Some(c.entity_id.to_string())))
+ .and_then(|c| c.as_updated_at())
+ .map(|(id, ts)| (Some(ts), Some(id.to_string())))
.unwrap_or((None, None));
// Fetch limit + 1 to determine if there are more results
@@ -93,7 +94,8 @@ async fn owner_search<'a>(
) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {
let (cursor_updated_at, cursor_entity_id) = cursor
.as_ref()
- .map(|c| (Some(c.updated_at), Some(c.entity_id.to_string())))
+ .and_then(|c| c.as_updated_at())
+ .map(|(id, ts)| (Some(ts), Some(id.to_string())))
.unwrap_or((None, None));
// Fetch limit + 1 to determine if there are more results
@@ -158,7 +160,7 @@ async fn owner_search<'a>(
time = 30,
result = true,
key = "String",
- convert = r#"{ format!("{}-{:?}-{}-{}-{}-{}", macro_user_id.as_ref(), project_ids, term, ids_only, limit, cursor.as_ref().map(|c| format!("{}-{}", c.entity_id, c.updated_at)).unwrap_or_default()) }"#
+ convert = r#"{ format!("{}-{:?}-{}-{}-{}-{}", macro_user_id.as_ref(), project_ids, term, ids_only, limit, cursor.as_ref().and_then(|c| c.as_updated_at()).map(|(id, ts)| format!("{}-{}", id, ts)).unwrap_or_default()) }"#
)
)]
pub async fn search_project_names<'a>(
@@ -173,6 +175,9 @@ pub async fn search_project_names<'a>(
if term.is_empty() {
return Err(NameSearchError::EmptySearchTerm);
}
+ if cursor.as_ref().is_some_and(|c| c.as_updated_at().is_none()) {
+ return Err(NameSearchError::IncompatibleCursor);
+ }
let search_pattern = format!("%{term}%");
let highlight_pattern = format!("({})", escape_regex(&term));
diff --git a/rust/cloud-storage/name_search/src/project/test.rs b/rust/cloud-storage/name_search/src/project/test.rs
index 3c3384cc8c..844caa6de8 100644
--- a/rust/cloud-storage/name_search/src/project/test.rs
+++ b/rust/cloud-storage/name_search/src/project/test.rs
@@ -1,7 +1,7 @@
//! Tests for project module
use macro_db_migrator::MACRO_DB_MIGRATIONS;
-use models_search_cursor::SearchCursorOption;
+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -419,3 +419,38 @@ async fn test_search_project_names_excludes_soft_deleted(
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_rejects_thread_cursor(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let cursor = SearchMethodCursor::Thread {
+ thread_id: Uuid::new_v4(),
+ message_id: Uuid::new_v4(),
+ };
+
+ let result = search_project_names(
+ &pool,
+ &user_id,
+ &[],
+ "test".to_string(),
+ false,
+ 10,
+ Some(cursor),
+ )
+ .await;
+
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::IncompatibleCursor
+ ));
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/opensearch_client/src/channel_message.rs b/rust/cloud-storage/opensearch_client/src/channel_message.rs
index 351cb2520f..efbd10e782 100644
--- a/rust/cloud-storage/opensearch_client/src/channel_message.rs
+++ b/rust/cloud-storage/opensearch_client/src/channel_message.rs
@@ -1,8 +1,22 @@
+use models_search_cursor::SearchCursorOption;
+
use crate::{
OpensearchClient, Result, delete,
+ search::{self, channels::ChannelSearchArgs, model::SearchHit},
upsert::{self, channel_message::UpsertChannelMessageArgs},
};
+impl OpensearchClient {
+ /// Performs a channel content search.
+ #[tracing::instrument(skip(self, args))]
+ pub async fn search_channel(
+ &self,
+ args: ChannelSearchArgs,
+ ) -> Result<(Vec<SearchHit>, SearchCursorOption)> {
+ search::channels::search_channel(&self.inner, args).await
+ }
+}
+
impl OpensearchClient {
/// Upserts a channel message into the opensearch index
#[tracing::instrument(skip(self))]
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rs
index c50b016039..ae9b34444b 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs
@@ -5,7 +5,6 @@ use crate::error::OpensearchClientError;
use crate::search::query::QueryKey;
use crate::search::query::generate_terms_must_query;
use models_opensearch::OpenSearchEntityType;
-use models_search_cursor::SearchMethodCursor;
use opensearch_query_builder::{
BoolQueryBuilder, FieldSort, QueryType, Script, ScriptSort, ScriptSortType, SortOrder, SortType,
};
@@ -45,6 +44,16 @@ macro_rules! delegate_methods {
};
}
+/// Sort mode for the channel content endpoint.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub enum ChannelSortMode {
+ /// Sort by sent_at_seconds/updated_at_seconds, entity_id as tiebreaker.
+ #[default]
+ Message,
+ /// Sort by thread_id, message_id as tiebreaker.
+ Thread,
+}
+
/// Creates sort vec to sort by sent_at_seconds (preferred) or updated_at_seconds (fallback)
/// with entity_id as a tiebreaker. Items without a timestamp are pushed to the end.
pub(crate) fn updated_at_sort<'a>() -> Vec<SortType<'a>> {
@@ -66,10 +75,13 @@ pub(crate) fn updated_at_sort<'a>() -> Vec<SortType<'a>> {
]
}
-pub(crate) fn search_after(cursor: SearchMethodCursor) -> Vec<serde_json::Value> {
+/// Sort vec for channel content with thread-grouped ordering.
+/// `unmapped_type` lets the same sort apply to non-channel indices in mixed
+/// unified search.
+pub(crate) fn thread_sort<'a>() -> Vec<SortType<'a>> {
vec![
- serde_json::json!(cursor.updated_at.timestamp_millis()),
- serde_json::json!(cursor.entity_id.to_string()),
+ SortType::Field(FieldSort::new("thread_id", SortOrder::Desc).unmapped_type("keyword")),
+ SortType::Field(FieldSort::new("message_id", SortOrder::Desc).unmapped_type("keyword")),
]
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rs
index b2397192c1..128d11aa67 100644
--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs
@@ -1,10 +1,23 @@
+pub use crate::search::builder::ChannelSortMode;
+
use crate::{
Result, delegate_methods,
- search::builder::{SearchQueryBuilder, SearchQueryConfig},
+ error::{OpensearchClientError, ResponseExt},
+ search::{
+ builder::{SearchQueryBuilder, SearchQueryConfig, thread_sort, updated_at_sort},
+ model::{
+ DefaultSearchResponse, Hit, MacroEm, SearchGotoChannel, SearchGotoContent, SearchHit,
+ exclude_source_content, inject_fragment_size, parse_highlight_hit,
+ },
+ query::Keys,
+ },
};
-use models_opensearch::OpenSearchEntityType;
-use opensearch_query_builder::{BoolQueryBuilder, QueryType};
+use chrono::{DateTime, Utc};
+use models_opensearch::{OpenSearchEntityType, SearchEntityType, SearchIndex};
+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};
+use opensearch_query_builder::*;
+use tracing::Instrument;
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct ChannelMessageIndex {
@@ -12,7 +25,8 @@ pub(crate) struct ChannelMessageIndex {
pub channel_type: String,
pub org_id: Option<i64>,
pub message_id: uuid::Uuid,
- pub thread_id: Option<uuid::Uuid>,
+ /// Threadless messages are indexed with `thread_id == message_id`.
+ pub thread_id: uuid::Uuid,
pub sender_id: String,
pub mentions: Vec<String>,
pub created_at_seconds: i64,
@@ -126,5 +140,181 @@ impl From<ChannelMessageSearchArgs> for ChannelMessageQueryBuilder {
}
}
+/// Args for the dedicated channel content search endpoint.
+#[derive(Debug, Default, Clone)]
+pub struct ChannelSearchArgs {
+ pub user_id: String,
+ pub page_size: u32,
+ pub match_type: String,
+ pub cursor: SearchCursorOption,
+ pub terms: Vec<String>,
+ pub channel_ids: Vec<String>,
+ pub thread_ids: Vec<String>,
+ pub mentions: Vec<String>,
+ pub sender_ids: Vec<String>,
+ pub sort_mode: ChannelSortMode,
+}
+
+fn build_channel_search_request(
+ args: &ChannelSearchArgs,
+) -> Result<opensearch_query_builder::SearchRequest<'static>> {
+ let channel_search_args = ChannelMessageSearchArgs {
+ terms: args.terms.clone(),
+ user_id: args.user_id.clone(),
+ page: 0,
+ page_size: args.page_size,
+ match_type: args.match_type.clone(),
+ collapse: false,
+ ids_only: true,
+ channel_ids: args.channel_ids.clone(),
+ thread_ids: args.thread_ids.clone(),
+ mentions: args.mentions.clone(),
+ sender_ids: args.sender_ids.clone(),
+ };
+
+ let query_builder: ChannelMessageQueryBuilder = channel_search_args.into();
+ let bool_query = query_builder.build_bool_query()?;
+ let query: QueryType = bool_query.build().into();
+ let query = query.to_owned();
+
+ let mut request_builder = SearchRequestBuilder::new();
+ request_builder.size(args.page_size + 1);
+ request_builder.query(query);
+
+ if let SearchCursorOption::NotDone(Some(cursor)) = &args.cursor {
+ request_builder.set_search_after(cursor.search_after());
+ }
+
+ let sort = match args.sort_mode {
+ ChannelSortMode::Message => updated_at_sort(),
+ ChannelSortMode::Thread => thread_sort(),
+ };
+ for s in sort {
+ request_builder.add_sort(s);
+ }
+
+ let em_field = || {
+ HighlightField::new()
+ .highlight_type("plain")
+ .pre_tags(vec![MacroEm::Open.to_string()])
+ .post_tags(vec![MacroEm::Close.to_string()])
+ };
+ let highlight = Highlight::new()
+ .require_field_match(true)
+ .field("content", em_field().number_of_fragments(1));
+ request_builder.highlight(highlight);
+
+ Ok(request_builder.build())
+}
+
+#[tracing::instrument(skip(client, args), err)]
+pub(crate) async fn search_channel(
+ client: &opensearch::OpenSearch,
+ args: ChannelSearchArgs,
+) -> Result<(Vec<SearchHit>, SearchCursorOption)> {
+ let mut search_request = build_channel_search_request(&args)?.to_json();
+ inject_fragment_size(&mut search_request, 1000);
+ exclude_source_content(&mut search_request);
+
+ let index = SearchIndex::Channels.as_ref();
+ let response = async {
+ client
+ .search(opensearch::SearchParts::Index(&[index]))
+ .body(search_request)
+ .send()
+ .await
+ .map_client_error()
+ .await
+ }
+ .instrument(tracing::info_span!("opensearch_http_request"))
+ .await?;
+
+ let bytes = async {
+ response
+ .bytes()
+ .await
+ .map_err(|e| OpensearchClientError::HttpBytesError {
+ details: e.to_string(),
+ })
+ }
+ .instrument(tracing::info_span!("opensearch_read_response_body"))
+ .await?;
+
+ let result: DefaultSearchResponse<ChannelMessageIndex> = serde_json::from_slice(&bytes)
+ .map_err(|e| OpensearchClientError::SearchDeserializationFailed {
+ details: e.to_string(),
+ raw_body: String::from_utf8_lossy(&bytes).to_string(),
+ })?;
+
+ let mut results: Vec<SearchHit> = result
+ .hits
+ .hits
+ .into_iter()
+ .map(channel_hit_to_search_hit)
+ .collect();
+
+ let has_more = results.len() > args.page_size as usize;
+ if has_more {
+ results.pop();
+ }
+
+ let cursor = if has_more {
+ let last_cursor = results
+ .last()
+ .and_then(|last| build_channel_cursor(last, args.sort_mode));
+ SearchCursorOption::NotDone(last_cursor)
+ } else {
+ SearchCursorOption::Done
+ };
+
+ Ok((results, cursor))
+}
+
+fn channel_hit_to_search_hit(hit: Hit<ChannelMessageIndex>) -> SearchHit {
+ let a = hit.source;
+ let highlight = hit
+ .highlight
+ .map(|h| {
+ parse_highlight_hit(
+ h,
+ Keys {
+ title_key: ChannelMessageSearchConfig::TITLE_KEY,
+ content_key: ChannelMessageSearchConfig::CONTENT_KEY,
+ },
+ )
+ })
+ .unwrap_or_default();
+ SearchHit {
+ entity_id: a.entity_id,
+ entity_type: SearchEntityType::Channels,
+ score: hit.score,
+ highlight,
+ goto: Some(SearchGotoContent::Channels(SearchGotoChannel {
+ channel_message_id: a.message_id,
+ thread_id: (a.thread_id != a.message_id).then_some(a.thread_id),
+ sender_id: a.sender_id,
+ created_at: DateTime::from_timestamp(a.created_at_seconds, 0).unwrap_or_default(),
+ updated_at: DateTime::from_timestamp(a.updated_at_seconds, 0).unwrap_or_default(),
+ })),
+ updated_at: DateTime::from_timestamp(a.updated_at_seconds, 0),
+ }
+}
+
+fn build_channel_cursor(last: &SearchHit, mode: ChannelSortMode) -> Option<SearchMethodCursor> {
+ match mode {
+ ChannelSortMode::Message => Some(SearchMethodCursor::UpdatedAt {
+ entity_id: last.entity_id,
+ updated_at: last.updated_at.unwrap_or_else(Utc::now),
+ }),
+ ChannelSortMode::Thread => match &last.goto {
+ Some(SearchGotoContent::Channels(ch)) => Some(SearchMethodCursor::Thread {
+ thread_id: ch.thread_id.unwrap_or(ch.channel_message_id),
+ message_id: ch.channel_message_id,
+ }),
+ _ => None,
+ },
+ }
+}
+
#[cfg(test)]
mod test;
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index 60c424d953..c082945f88 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -4,7 +4,7 @@ use crate::{
Result,
error::{OpensearchClientError, ResponseExt},
search::{
- builder::{SearchQueryConfig, search_after, updated_at_sort},
+ builder::{SearchQueryConfig, updated_at_sort},
call_records::{
CallRecordIndex, CallRecordQueryBuilder, CallRecordSearchArgs, CallRecordSearchConfig,
},
@@ -212,7 +212,7 @@ pub(crate) enum UnifiedSearchIndex {
ChannelMessage(ChannelMessageIndex),
Document(DocumentIndex),
Chat(ChatIndex),
- Email(EmailIndex),
+ Email(Box<EmailIndex>),
CallRecord(CallRecordIndex),
}
@@ -301,7 +301,7 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
.unwrap_or_default(),
goto: Some(SearchGotoContent::Channels(SearchGotoChannel {
channel_message_id: a.message_id,
- thread_id: a.thread_id,
+ thread_id: (a.thread_id != a.message_id).then_some(a.thread_id),
sender_id: a.sender_id,
created_at: DateTime::from_timestamp(a.created_at_seconds, 0)
.unwrap_or_default(),
@@ -334,37 +334,40 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
.updated_at_seconds
.and_then(|s| DateTime::from_timestamp(s, 0)),
},
- UnifiedSearchIndex::Email(a) => SearchHit {
- entity_id: a.entity_id,
- entity_type: SearchEntityType::Emails,
- score: index.score,
- highlight: index
- .highlight
- .map(|h| {
- parse_highlight_hit(
- h,
- Keys {
- title_key: EmailSearchConfig::TITLE_KEY,
- content_key: EmailSearchConfig::CONTENT_KEY,
- },
- )
- })
- .unwrap_or_default(),
- goto: Some(SearchGotoContent::Emails(SearchGotoEmail {
- email_message_id: a.message_id,
- bcc: a.bcc,
- cc: a.cc,
- labels: a.labels,
- sent_at: a
+ UnifiedSearchIndex::Email(a) => {
+ let a = *a;
+ SearchHit {
+ entity_id: a.entity_id,
+ entity_type: SearchEntityType::Emails,
+ score: index.score,
+ highlight: index
+ .highlight
+ .map(|h| {
+ parse_highlight_hit(
+ h,
+ Keys {
+ title_key: EmailSearchConfig::TITLE_KEY,
+ content_key: EmailSearchConfig::CONTENT_KEY,
+ },
+ )
+ })
+ .unwrap_or_default(),
+ goto: Some(SearchGotoContent::Emails(SearchGotoEmail {
+ email_message_id: a.message_id,
+ bcc: a.bcc,
+ cc: a.cc,
+ labels: a.labels,
+ sent_at: a
+ .sent_at_seconds
+ .and_then(|ts| DateTime::from_timestamp(ts, 0)),
+ sender: a.sender,
+ recipients: a.recipients,
+ })),
+ updated_at: a
.sent_at_seconds
- .and_then(|ts| DateTime::from_timestamp(ts, 0)),
- sender: a.sender,
- recipients: a.recipients,
- })),
- updated_at: a
- .sent_at_seconds
- .and_then(|s| DateTime::from_timestamp(s, 0)),
- },
+ .and_then(|s| DateTime::from_timestamp(s, 0)),
+ }
+ }
UnifiedSearchIndex::Chat(a) => SearchHit {
entity_id: a.entity_id,
entity_type: SearchEntityType::Chats,
@@ -494,7 +497,7 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchReques
let mut search_request_builder = SearchRequestBuilder::new();
if let Some(cursor) = cursor {
- search_request_builder.set_search_after(search_after(cursor));
+ search_request_builder.set_search_after(cursor.search_after());
}
search_request_builder.size(args.page_size + 1);
@@ -503,10 +506,7 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchReques
search_request_builder.collapse(Collapse::new("entity_id"));
}
- // Build sort
- let sort = updated_at_sort();
-
- for sort in sort {
+ for sort in updated_at_sort() {
search_request_builder.add_sort(sort);
}
@@ -603,9 +603,9 @@ pub(crate) async fn search_unified(
}
let cursor = if has_more {
- SearchCursorOption::NotDone(results.last().map(|last| SearchMethodCursor {
+ SearchCursorOption::NotDone(results.last().map(|last| SearchMethodCursor::UpdatedAt {
entity_id: last.entity_id,
- updated_at: last.updated_at.unwrap_or(Utc::now()),
+ updated_at: last.updated_at.unwrap_or_else(Utc::now),
}))
} else {
SearchCursorOption::Done
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
index 7f1100efea..a114c11816 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
@@ -1,5 +1,6 @@
use super::*;
+use crate::search::builder::updated_at_sort;
use chrono::Utc;
use models_search_cursor::SearchMethodCursor;
use opensearch_query_builder::ToOpenSearchJson;
@@ -450,7 +451,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
ids_only: false,
},
call_record_search_args: UnifiedCallRecordSearchArgs::default(),
- cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor {
+ cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
entity_id,
updated_at: time,
})),
@@ -836,7 +837,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
ids_only: false,
},
call_record_search_args: UnifiedCallRecordSearchArgs::default(),
- cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor {
+ cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
entity_id,
updated_at: time,
})),
@@ -960,3 +961,15 @@ fn test_build_unified_search_request_empty_indices() -> anyhow::Result<()> {
Ok(())
}
+
+#[test]
+fn test_thread_sort_is_thread_id_then_message_id_field_sorts() {
+ use crate::search::builder::thread_sort;
+ let json: Vec<serde_json::Value> = thread_sort().iter().map(|s| s.to_json()).collect();
+
+ assert_eq!(json.len(), 2);
+ assert_eq!(json[0]["thread_id"]["order"], "desc");
+ assert_eq!(json[0]["thread_id"]["unmapped_type"], "keyword");
+ assert_eq!(json[1]["message_id"]["order"], "desc");
+ assert_eq!(json[1]["message_id"]["unmapped_type"], "keyword");
+}
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/channel_message.rs b/rust/cloud-storage/opensearch_client/src/upsert/channel_message.rs
index 096690ef6e..9f9ce1641e 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/channel_message.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/channel_message.rs
@@ -3,8 +3,7 @@ use models_opensearch::SearchIndex;
use crate::{Result, date_format::EpochSeconds, error::OpensearchClientError};
/// The arguments for upserting a channel message into the opensearch index.
-/// Threadless messages are indexed with `thread_id == message_id` so the
-/// index is uniformly sortable on `[thread_id, message_id]`.
+/// Threadless messages are indexed with `thread_id == message_id`.
#[derive(Debug, serde::Serialize)]
pub struct UpsertChannelMessageArgs {
#[serde(rename = "entity_id")]
diff --git a/rust/cloud-storage/search_service/src/api/search/channel.rs b/rust/cloud-storage/search_service/src/api/search/channel.rs
index e0a6bee56e..774583c101 100644
--- a/rust/cloud-storage/search_service/src/api/search/channel.rs
+++ b/rust/cloud-storage/search_service/src/api/search/channel.rs
@@ -4,10 +4,22 @@ use indexmap::IndexMap;
use std::collections::HashMap;
use crate::api::context::SearchHandlerState;
+use crate::api::search::SearchPaginationParams;
+use axum::{
+ Extension, Router,
+ extract::{self, State},
+ response::Json,
+ routing::post,
+};
+use macro_user_id::user_id::MacroUserId;
use model::comms::ChannelHistoryInfo;
+use model::user::UserContext;
use models_search::channel::{
- ChannelSearchResponseItem, ChannelSearchResponseItemWithMetadata, ChannelSearchResult,
+ ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem,
+ ChannelSearchResponseItemWithMetadata, ChannelSearchResult, ChannelSortTimestamp,
};
+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};
+use opensearch_client::search::channels::{ChannelSearchArgs, ChannelSortMode};
use opensearch_client::search::model::SearchGotoContent;
use sqlx::types::Uuid;
@@ -17,6 +29,7 @@ pub(in crate::api::search) async fn enrich_channels(
ctx: &SearchHandlerState,
user_id: &str,
results: Vec<opensearch_client::search::model::SearchHit>,
+ sort_timestamp: ChannelSortTimestamp,
) -> Result<Vec<ChannelSearchResponseItemWithMetadata>, SearchError> {
let results: Vec<opensearch_client::search::model::SearchHit> = results
.into_iter()
@@ -60,8 +73,9 @@ pub(in crate::api::search) async fn enrich_channels(
.map_err(SearchError::InternalError)?;
// Construct enriched results
- let enriched_results = construct_search_result(results, channel_histories, message_states)
- .map_err(SearchError::InternalError)?;
+ let enriched_results =
+ construct_search_result(results, channel_histories, message_states, sort_timestamp)
+ .map_err(SearchError::InternalError)?;
Ok(enriched_results)
}
@@ -70,6 +84,7 @@ pub fn construct_search_result(
search_results: Vec<opensearch_client::search::model::SearchHit>,
channel_histories: HashMap<Uuid, ChannelHistoryInfo>,
message_states: HashMap<Uuid, Option<DateTime<Utc>>>,
+ sort_timestamp: ChannelSortTimestamp,
) -> anyhow::Result<Vec<ChannelSearchResponseItemWithMetadata>> {
// construct entity hit map of id -> vec<hits> using IndexMap to preserve insertion order
let entity_id_hit_map: IndexMap<sqlx::types::Uuid, Vec<ChannelSearchResult>> = search_results
@@ -114,15 +129,16 @@ pub fn construct_search_result(
let result: Vec<ChannelSearchResponseItemWithMetadata> = entity_id_hit_map
.into_iter()
.filter_map(|(entity_id, mut hits)| {
- // OpenSearch sorts content matches by created_at DESC, but ties on the
- // second resolution are non-deterministic. message_id is uuidv7
- // (time-ordered), so it can be used as a tiebreaker. Sort DESC to keep newer
- // messages first, matching the primary sort.
- hits.sort_by(|a, b| {
- b.created_at
- .cmp(&a.created_at)
- .then_with(|| b.message_id.cmp(&a.message_id))
- });
+ match sort_timestamp {
+ ChannelSortTimestamp::Message => {
+ hits.sort_by(|a, b| {
+ b.created_at
+ .cmp(&a.created_at)
+ .then_with(|| b.message_id.cmp(&a.message_id))
+ });
+ }
+ ChannelSortTimestamp::Thread => {}
+ }
if let Some(info) = channel_histories.get(&entity_id) {
let info = info.clone();
@@ -151,5 +167,102 @@ pub fn construct_search_result(
Ok(result)
}
+pub fn router() -> Router<SearchHandlerState> {
+ Router::new().route("/", post(handler))
+}
+
+/// Channel content search.
+#[utoipa::path(
+ post,
+ path = "/search/channel",
+ operation_id = "channel_search",
+ params(
+ ("page_size" = i64, Query, description = "Page size, defaults to 10."),
+ ("cursor" = Option<String>, Query, description = "Base64-encoded cursor."),
+ ),
+ responses(
+ (status = 200, body=ChannelSearchResponse),
+ (status = 400, body=model::response::ErrorResponse),
+ (status = 401, body=model::response::ErrorResponse),
+ (status = 500, body=model::response::ErrorResponse),
+ )
+)]
+pub async fn handler(
+ State(ctx): State<SearchHandlerState>,
+ user_context: Extension<UserContext>,
+ extract::Query(query_params): extract::Query<SearchPaginationParams>,
+ extract::Json(req): extract::Json<ChannelSearchRequest>,
+) -> Result<Json<ChannelSearchResponse>, SearchError> {
+ let user_id = user_context.user_id.clone();
+ if user_id.is_empty() {
+ return Err(SearchError::NoUserId);
+ }
+ let user_id = MacroUserId::parse_from_str(&user_id)
+ .map_err(|_| SearchError::InvalidUserId(user_id.to_string()))?
+ .lowercase();
+
+ let page_size = query_params.page_size.unwrap_or(10);
+ if !(0..=100).contains(&page_size) {
+ return Err(SearchError::InvalidPageSize);
+ }
+
+ let terms = match (req.query, req.terms) {
+ (Some(q), _) if !q.trim().is_empty() => vec![q.trim().to_string()],
+ (_, Some(t)) if !t.is_empty() => t,
+ _ => return Err(SearchError::NoQueryOrTermsProvided),
+ };
+ if terms.iter().any(|t| t.len() < 3) {
+ return Err(SearchError::InvalidQuerySize);
+ }
+
+ let cursor = query_params
+ .cursor
+ .as_ref()
+ .and_then(|c| SearchMethodCursor::decode(c));
+ let cursor_option = cursor
+ .map(|c| SearchCursorOption::NotDone(Some(c)))
+ .unwrap_or_default();
+
+ let filters = req.filters.unwrap_or_default();
+ if filters.channel_ids.is_empty() {
+ return Err(SearchError::NoChannelIds);
+ }
+ let sort_mode = match req.sort {
+ ChannelSortTimestamp::Message => ChannelSortMode::Message,
+ ChannelSortTimestamp::Thread => ChannelSortMode::Thread,
+ };
+
+ let args = ChannelSearchArgs {
+ user_id: user_id.as_ref().to_string(),
+ page_size,
+ match_type: req.match_type.to_string(),
+ cursor: cursor_option,
+ terms,
+ channel_ids: filters.channel_ids,
+ thread_ids: filters.thread_ids,
+ mentions: filters.mentions,
+ sender_ids: filters.sender_ids,
+ sort_mode,
+ };
+
+ let (hits, next_cursor) = ctx
+ .opensearch_client
+ .search_channel(args)
+ .await
+ .map_err(SearchError::Search)?;
+
+ let results = enrich_channels(&ctx, user_id.as_ref(), hits, req.sort).await?;
+
+ let next_cursor = match next_cursor {
+ SearchCursorOption::NotDone(Some(c)) => c.encode(),
+ _ => None,
+ };
+
+ Ok(Json(ChannelSearchResponse {
+ results,
+ next_cursor,
+ }))
+}
+
#[cfg(test)]
mod test;
diff --git a/rust/cloud-storage/search_service/src/api/search/channel/test.rs b/rust/cloud-storage/search_service/src/api/search/channel/test.rs
index 1ce167b504..1d56d19e42 100644
--- a/rust/cloud-storage/search_service/src/api/search/channel/test.rs
+++ b/rust/cloud-storage/search_service/src/api/search/channel/test.rs
@@ -22,7 +22,12 @@ fn active_states_for(
#[test]
fn test_construct_search_result_empty_input() {
- let result = construct_search_result(vec![], HashMap::new(), HashMap::new());
+ let result = construct_search_result(
+ vec![],
+ HashMap::new(),
+ HashMap::new(),
+ ChannelSortTimestamp::Message,
+ );
assert!(result.is_ok());
assert_eq!(result.unwrap().len(), 0);
}
@@ -60,7 +65,13 @@ fn test_construct_search_result_single_channel() {
);
let states = active_states_for(&search_results);
- let result = construct_search_result(search_results, channel_histories, states).unwrap();
+ let result = construct_search_result(
+ search_results,
+ channel_histories,
+ states,
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].extra.channel_id, channel_uuid);
@@ -143,7 +154,13 @@ fn test_construct_search_result_multiple_messages_same_channel() {
);
let states = active_states_for(&search_results);
- let result = construct_search_result(search_results, channel_histories, states).unwrap();
+ let result = construct_search_result(
+ search_results,
+ channel_histories,
+ states,
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].extra.channel_id, channel_uuid);
@@ -226,7 +243,13 @@ fn test_construct_search_result_filters_messages_without_content() {
);
let states = active_states_for(&search_results);
- let result = construct_search_result(search_results, channel_histories, states).unwrap();
+ let result = construct_search_result(
+ search_results,
+ channel_histories,
+ states,
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].extra.channel_message_search_results.len(), 2);
@@ -281,7 +304,13 @@ fn test_construct_search_result_filters_orphans_and_propagates_deleted_at() {
states.insert(deleted_message_id, Some(deleted_at));
// orphan_message_id intentionally omitted to simulate a hard-deleted row.
- let result = construct_search_result(search_results, channel_histories, states).unwrap();
+ let result = construct_search_result(
+ search_results,
+ channel_histories,
+ states,
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
assert_eq!(result.len(), 1);
let hits = &result[0].extra.channel_message_search_results;
@@ -368,7 +397,13 @@ fn test_channel_history_timestamps() {
// Call the function under test
let states = active_states_for(&input);
- let result = construct_search_result(input, channel_histories, states).unwrap();
+ let result = construct_search_result(
+ input,
+ channel_histories,
+ states,
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
// Verify that timestamps were copied from the channel history
assert_eq!(result.len(), 1);
@@ -410,7 +445,13 @@ fn test_channel_history_missing_entry() {
// Call the function under test
let states = active_states_for(&input);
- let result = construct_search_result(input, channel_histories, states).unwrap();
+ let result = construct_search_result(
+ input,
+ channel_histories,
+ states,
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
// Channels without history info should not be returned
assert_eq!(result.len(), 0);
@@ -445,7 +486,13 @@ fn test_channel_history_null_viewed_at() {
// Call the function under test
let states = active_states_for(&input);
- let result = construct_search_result(input, channel_histories, states).unwrap();
+ let result = construct_search_result(
+ input,
+ channel_histories,
+ states,
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
// Verify that timestamps were copied correctly and viewed_at is None
assert_eq!(result.len(), 1);
@@ -592,12 +639,27 @@ fn test_sort_stability() {
}
let states = active_states_for(&input);
- let result1 =
- construct_search_result(input.clone(), channel_histories.clone(), states.clone()).unwrap();
- let result2 =
- construct_search_result(input.clone(), channel_histories.clone(), states.clone()).unwrap();
- let result3 =
- construct_search_result(input.clone(), channel_histories.clone(), states).unwrap();
+ let result1 = construct_search_result(
+ input.clone(),
+ channel_histories.clone(),
+ states.clone(),
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
+ let result2 = construct_search_result(
+ input.clone(),
+ channel_histories.clone(),
+ states.clone(),
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
+ let result3 = construct_search_result(
+ input.clone(),
+ channel_histories.clone(),
+ states,
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
assert_eq!(result1.len(), 5);
assert_eq!(result2.len(), 5);
@@ -665,7 +727,13 @@ fn test_construct_search_result_breaks_created_at_ties_by_message_id() {
);
let states = active_states_for(&search_results);
- let result = construct_search_result(search_results, channel_histories, states).unwrap();
+ let result = construct_search_result(
+ search_results,
+ channel_histories,
+ states,
+ ChannelSortTimestamp::Message,
+ )
+ .unwrap();
let hits = &result[0].extra.channel_message_search_results;
assert_eq!(hits.len(), 3);
diff --git a/rust/cloud-storage/search_service/src/api/search/enrich.rs b/rust/cloud-storage/search_service/src/api/search/enrich.rs
index f7b49faaec..eadb308739 100644
--- a/rust/cloud-storage/search_service/src/api/search/enrich.rs
+++ b/rust/cloud-storage/search_service/src/api/search/enrich.rs
@@ -1,9 +1,13 @@
//! This module is responsible for enriching search results with metadata
use models_opensearch::SearchEntityType;
+use models_search::channel::ChannelSortTimestamp;
use models_search::unified::UnifiedSearchResponseItem;
use opensearch_client::search::model::SearchHit;
+// Unified search always re-sorts channel results by created_at app-side (Message mode).
+const UNIFIED_CHANNEL_SORT: ChannelSortTimestamp = ChannelSortTimestamp::Message;
+
use crate::api::{
context::SearchHandlerState,
search::{
@@ -13,7 +17,7 @@ use crate::api::{
},
};
-/// Enriches search results with metadat and converts to UnifiedSearchResponseItem
+/// Enriches search results with metadata and converts to UnifiedSearchResponseItem
#[tracing::instrument(skip(ctx, results), fields(result_count = results.len()), err)]
pub async fn enrich_search_response(
ctx: &SearchHandlerState,
@@ -38,7 +42,7 @@ pub async fn enrich_search_response(
.collect())
}
SearchEntityType::Channels => {
- let response = enrich_channels(ctx, user_id, results).await?;
+ let response = enrich_channels(ctx, user_id, results, UNIFIED_CHANNEL_SORT).await?;
Ok(response
.into_iter()
.map(UnifiedSearchResponseItem::Channel)
diff --git a/rust/cloud-storage/search_service/src/api/search/mod.rs b/rust/cloud-storage/search_service/src/api/search/mod.rs
index 475a08713c..13d48ed675 100644
--- a/rust/cloud-storage/search_service/src/api/search/mod.rs
+++ b/rust/cloud-storage/search_service/src/api/search/mod.rs
@@ -16,6 +16,7 @@ pub fn router() -> Router<SearchHandlerState> {
Router::new()
.route("/", post(unified::handler))
.nest("/simple", simple::router())
+ .nest("/channel", channel::router())
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
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.rs
index 7b6aec929e..9adde747d9 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
@@ -38,6 +38,9 @@ pub enum SearchError {
/// No query or terms provided
#[error("query or terms must be provided and at least 3 characters")]
NoQueryOrTermsProvided,
+ /// No channel IDs provided
+ #[error("at least one channel_id must be provided")]
+ NoChannelIds,
#[error("searching with an invalid cursor")]
/// Searching with an invalid cursor
InvalidCursor,
@@ -59,7 +62,9 @@ impl IntoResponse for SearchError {
SearchError::InvalidPageSize
| SearchError::InvalidQuerySize
| SearchError::InvalidCursor
- | SearchError::NoQueryOrTermsProvided => StatusCode::BAD_REQUEST,
+ | SearchError::NoQueryOrTermsProvided
+ | SearchError::NoChannelIds => StatusCode::BAD_REQUEST,
+ SearchError::NameSearch(NameSearchError::IncompatibleCursor) => StatusCode::BAD_REQUEST,
SearchError::Search(_) | SearchError::NameSearch(_) | SearchError::InternalError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
}
diff --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.rs
index ea2447bf18..d37dca690c 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
@@ -44,22 +44,18 @@ fn find_last_of_source(
results.iter().rev().find(|h| h.source == source)
}
-/// Generate a cursor from a TaggedSearchHit
+/// Generate a cursor from a TaggedSearchHit.
fn cursor_from_tagged(tagged: &TaggedSearchHit) -> Option<SearchMethodCursor> {
- tagged.hit.updated_at.map(|ts| SearchMethodCursor {
- entity_id: tagged.hit.entity_id,
- updated_at: ts,
- })
+ tagged
+ .hit
+ .updated_at
+ .map(|ts| SearchMethodCursor::UpdatedAt {
+ entity_id: tagged.hit.entity_id,
+ updated_at: ts,
+ })
}
-/// Computes the next cursor for a search source based on pagination state
-///
-/// # Arguments
-/// * `next_cursor_from_search` - The cursor returned by the search operation
-/// * `included_count` - Number of results from this source included in final page
-/// * `original_count` - Total number of results returned by search for this source
-/// * `last_included_hit` - The last result of this source type included in final page
-/// * `original_cursor` - The cursor passed into the search (to carry forward if no results included)
+/// Computes the next cursor for a search source based on pagination state.
fn compute_next_cursor(
next_cursor_from_search: &SearchCursorOption,
included_count: usize,
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs
index 58eead8291..4e9c1e9af6 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs
@@ -127,8 +127,9 @@ fn test_compute_next_cursor_excluded_results_with_included_generates_cursor() {
match result {
SearchCursorOption::NotDone(Some(cursor)) => {
- assert_eq!(cursor.entity_id, entity_id);
- assert_eq!(cursor.updated_at, timestamp);
+ let (id, ts) = cursor.as_updated_at().expect("expected UpdatedAt cursor");
+ assert_eq!(id, entity_id);
+ assert_eq!(ts, timestamp);
}
_ => panic!("Expected NotDone with cursor, got {:?}", result),
}
@@ -143,7 +144,7 @@ fn test_compute_next_cursor_search_has_more_with_included_generates_cursor() {
let last_hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::ChatName);
let result = compute_next_cursor(
- &SearchCursorOption::NotDone(Some(SearchMethodCursor {
+ &SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
entity_id: Uuid::new_v4(),
updated_at: ts(500),
})), // search has more
@@ -155,8 +156,9 @@ fn test_compute_next_cursor_search_has_more_with_included_generates_cursor() {
match result {
SearchCursorOption::NotDone(Some(cursor)) => {
- assert_eq!(cursor.entity_id, entity_id);
- assert_eq!(cursor.updated_at, timestamp);
+ let (id, ts) = cursor.as_updated_at().expect("expected UpdatedAt cursor");
+ assert_eq!(id, entity_id);
+ assert_eq!(ts, timestamp);
}
_ => panic!("Expected NotDone with cursor, got {:?}", result),
}
@@ -168,7 +170,7 @@ fn test_compute_next_cursor_excluded_results_no_included_carries_forward() {
// carry forward the original cursor
let original_entity_id = Uuid::new_v4();
let original_timestamp = ts(500);
- let original_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor {
+ let original_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
entity_id: original_entity_id,
updated_at: original_timestamp,
}));
@@ -183,8 +185,9 @@ fn test_compute_next_cursor_excluded_results_no_included_carries_forward() {
match result {
SearchCursorOption::NotDone(Some(cursor)) => {
- assert_eq!(cursor.entity_id, original_entity_id);
- assert_eq!(cursor.updated_at, original_timestamp);
+ let (id, ts) = cursor.as_updated_at().expect("expected UpdatedAt cursor");
+ assert_eq!(id, original_entity_id);
+ assert_eq!(ts, original_timestamp);
}
_ => panic!("Expected original cursor carried forward, got {:?}", result),
}
@@ -228,8 +231,9 @@ fn test_compute_next_cursor_all_included_but_search_not_done_continues() {
// Since search says not done, we should continue pagination
match result {
SearchCursorOption::NotDone(Some(cursor)) => {
- assert_eq!(cursor.entity_id, entity_id);
- assert_eq!(cursor.updated_at, timestamp);
+ let (id, ts) = cursor.as_updated_at().expect("expected UpdatedAt cursor");
+ assert_eq!(id, entity_id);
+ assert_eq!(ts, timestamp);
}
_ => panic!("Expected NotDone with cursor, got {:?}", result),
}
@@ -306,9 +310,12 @@ fn test_cursor_from_tagged_with_timestamp() {
let cursor = cursor_from_tagged(&hit);
assert!(cursor.is_some());
- let cursor = cursor.unwrap();
- assert_eq!(cursor.entity_id, entity_id);
- assert_eq!(cursor.updated_at, timestamp);
+ let (id, ts) = cursor
+ .unwrap()
+ .as_updated_at()
+ .expect("expected UpdatedAt cursor");
+ assert_eq!(id, entity_id);
+ assert_eq!(ts, timestamp);
}
#[test]
@@ -341,7 +348,7 @@ fn test_cursor_logic_pagination_scenario() {
make_tagged_hit(doc_ids[7], Some(timestamps[7]), SearchSource::DocumentName),
];
- let doc_next_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor {
+ let doc_next_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
entity_id: doc_ids[6],
updated_at: timestamps[6],
}));
@@ -363,8 +370,9 @@ fn test_cursor_logic_pagination_scenario() {
// Should generate cursor from last included doc (doc_ids[7])
match new_doc_cursor {
SearchCursorOption::NotDone(Some(cursor)) => {
- assert_eq!(cursor.entity_id, doc_ids[7]);
- assert_eq!(cursor.updated_at, timestamps[7]);
+ let (id, ts) = cursor.as_updated_at().expect("expected UpdatedAt cursor");
+ assert_eq!(id, doc_ids[7]);
+ assert_eq!(ts, timestamps[7]);
}
_ => panic!(
"Expected cursor from last included doc, got {:?}",