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) support cursor for unified search (#892)
Will Hutchinsond86a7fc0d602
diff --git a/js/app/justfile b/js/app/justfileindex 85348e7c70..f78bb80ad5 100644--- a/js/app/justfile+++ b/js/app/justfile@@ -53,8 +53,8 @@ csharp-build:bun scripts/publish-docx-server.js# Codegen-gen-api:- bun scripts/generate-api-schema.ts+gen-api *SERVICES:+ bun scripts/generate-api-schema.ts {{SERVICES}}gen-dcs-types:bun scripts/generate-dcs-types.tsdiff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsxindex b8e4fe0ed0..6c83df3b78 100644--- a/js/app/packages/app/component/UnifiedListView.tsx+++ b/js/app/packages/app/component/UnifiedListView.tsx@@ -75,7 +75,7 @@ import {type UnifiedNotification,useNotificationsForEntity,} from '@notifications';-import type { PaginatedSearchArgs } from '@service-search/client';+import type { SearchArgs } from '@service-search/client';import type {ChannelFilters,ChatFilters,@@ -160,7 +160,7 @@ import {type ViewData,} from './ViewConfig';-const SEARCH_SERVICE_DEBOUNCE_MS = 200;+const SEARCH_SERVICE_DEBOUNCE_MS = 300;const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 20;const NIL_UUID = '00000000-0000-0000-0000-000000000000';@@ -939,9 +939,9 @@ export function UnifiedListView(props: UnifiedListViewProps) {}));const searchUnifiedNameContentQueryParams = createMemo(- (): PaginatedSearchArgs => ({+ (): SearchArgs => ({params: {- page: 0,+ cursor: null,page_size: 100,},request: {@@ -2111,6 +2111,7 @@ function SearchBar(props: {icon={SearchIcon}theme="clear"tooltip={{ label: 'Search' }}+ tabIndex={-1}onClick={() => {inputRef?.focus();}}@@ -2122,6 +2123,7 @@ function SearchBar(props: {icon={XIcon}theme="clear"tooltip={{ label: 'Clear search' }}+ tabIndex={-1}onClick={() => {setSearchText('');inputRef?.focus();@@ -2136,6 +2138,7 @@ function SearchBar(props: {theme="clear"tooltip={{ label: 'Cancel search' }}class="[&_svg]:animate-spin"+ tabIndex={-1}onClick={() => {setSearchText('');inputRef?.focus();diff --git a/js/app/packages/app/component/command/useSearchItems.ts b/js/app/packages/app/component/command/useSearchItems.tsindex ded5d9f9ef..eba7e9fdd2 100644--- a/js/app/packages/app/component/command/useSearchItems.ts+++ b/js/app/packages/app/component/command/useSearchItems.ts@@ -252,7 +252,7 @@ export function useSearchItems(searchTerm: () => string) {export function usePaginatedSearchItems(searchTerm: () => string) {const [allItems, setAllItems] = createSignal<CommandItemCard[]>([]);- const [currentPage, setCurrentPage] = createSignal(0);+ const [nextCursor, setNextCursor] = createSignal<string | null>(null);const [hasMore, setHasMore] = createSignal(true);const [isLoading, setIsLoading] = createSignal(false);let loadMoreAbortController: AbortController | null = null;@@ -265,7 +265,7 @@ export function usePaginatedSearchItems(searchTerm: () => string) {loadMoreAbortController = null;}setAllItems([]);- setCurrentPage(0);+ setNextCursor(null);setHasMore(true);}));@@ -274,16 +274,16 @@ export function usePaginatedSearchItems(searchTerm: () => string) {const searchResults = useSearch(searchTerm);createEffect(() => {const results = searchResults();- if (results && currentPage() === 0) {+ if (results && nextCursor() === null) {const items = convertSearchResultsToItems(results);setAllItems(items);- // Hardcode hasMore to always be true for now- setHasMore(true);+ setNextCursor(results.next_cursor ?? null);+ setHasMore(!!results.next_cursor);}});const loadMore = async () => {- if (isLoading()) return;+ if (isLoading() || !hasMore()) return;if (loadMoreAbortController) {loadMoreAbortController.abort();@@ -292,8 +292,8 @@ export function usePaginatedSearchItems(searchTerm: () => string) {setIsLoading(true);try {- const nextPage = currentPage() + 1;const term = searchTerm();+ const cursor = nextCursor();if (!ENABLE_SEARCH_SERVICE || term.length < 3) {return;@@ -305,7 +305,7 @@ export function usePaginatedSearchItems(searchTerm: () => string) {match_type: 'partial',query: term,},- params: { page: nextPage, page_size: 10 },+ params: { cursor, page_size: 10 },},{ signal: loadMoreAbortController.signal });@@ -319,8 +319,8 @@ export function usePaginatedSearchItems(searchTerm: () => string) {if (data) {const newItems = convertSearchResultsToItems(data);setAllItems((prev) => [...prev, ...newItems]);- setCurrentPage(nextPage);- if (newItems.length === 0) setHasMore(false);+ setNextCursor(data.next_cursor ?? null);+ setHasMore(!!data.next_cursor);}} catch (error) {if (loadMoreAbortController.signal.aborted) return;diff --git a/js/app/packages/app/component/split-layout/components/SplitHeader.tsx b/js/app/packages/app/component/split-layout/components/SplitHeader.tsxindex 904bc13b4b..6e5dd99521 100644--- a/js/app/packages/app/component/split-layout/components/SplitHeader.tsx+++ b/js/app/packages/app/component/split-layout/components/SplitHeader.tsx@@ -133,6 +133,7 @@ function SplitPreviewToggle() {hotkeyToken={TOKENS.unifiedList.togglePreview}/>}+ tabIndex={-1}onClick={() => setPreview((prev) => !prev)}><SplitIcon />diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsxindex 7ea82c3253..5a5a105637 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx@@ -28,7 +28,7 @@ import {useEmails,} from '@macro-entity';import { useHistoryQuery } from '@queries/history/history';-import type { PaginatedSearchArgs } from '@service-search/client';+import type { SearchArgs } from '@service-search/client';import type { Item } from '@service-storage/generated/schemas/item';import { debounce } from '@solid-primitives/scheduled';import { globalSplitManager } from 'app/signal/splitLayout';@@ -476,11 +476,10 @@ function MentionsMenuInner(props: {});}- const args = createMemo((): PaginatedSearchArgs => {+ const args = createMemo((): SearchArgs => {return {params: {- page: 0,- // small -> fast!+ cursor: null,page_size: 10,},request: {diff --git a/js/app/packages/core/signal/search.ts b/js/app/packages/core/signal/search.tsindex de146f9118..0b2fc3c1b2 100644--- a/js/app/packages/core/signal/search.ts+++ b/js/app/packages/core/signal/search.ts@@ -1,186 +1,19 @@import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';-import { isErr, type MaybeResult } from '@core/util/maybeResult';-import { logger } from '@observability';+import { isErr } from '@core/util/maybeResult';import { searchClient } from '@service-search/client';-import type { ChatSearchResponse } from '@service-search/generated/models/chatSearchResponse';-import type { DocumentSearchResponse } from '@service-search/generated/models/documentSearchResponse';-import type { EmailSearchResponseItem } from '@service-search/generated/models/emailSearchResponseItem';import type { UnifiedSearchResponse } from '@service-search/generated/models/unifiedSearchResponse';import { makeAbortable } from '@solid-primitives/resource';import { createMemo, createResource } from 'solid-js';-function createSearchResource<T>(- searchTerm: () => string,- searchFn: (- term: string,- signal: AbortSignal- ) => Promise<MaybeResult<string, T>>-) {- const [signal, , filterError] = makeAbortable();- return createResource(searchTerm, async (term) => {- if (!ENABLE_SEARCH_SERVICE) return null;- if (term.length < 3) {- // HACK: returning null instead of undefined makes the command bar not crash- return null;- }- try {- const result = await searchFn(term, signal());- if (isErr(result)) {- console.error('Failed to get search query');- // HACK: returning null instead of undefined makes the command bar not crash- return null;- }- const [, data] = result;- return data as T;- } catch (err) {- filterError(err);- return null;- }- });-}--export function createSearchDocumentsResource(searchTerm: () => string) {- return createSearchResource<DocumentSearchResponse>(- searchTerm,- (term, signal) =>- searchClient.searchDocuments(- {- match_type: 'partial',- terms: [term],- },- { signal }- )- );-}--export function useSearchDocuments(searchTerm: () => string) {- const [resource] = createSearchDocumentsResource(searchTerm);- return createMemo((): DocumentSearchResponse | undefined => {- const latest = resource?.latest;- if (!latest) return undefined;- return latest;- });-}--// Note from Peter: I've experimentally altered this to create a paginated resource. If we think this is successful, we should refactor the other createSearch*Resource and useSearch* functions to use this pattern. Note that I've removed useSearchEmails, because I don't think we need to memoize the resource? Whatever is consuming this resource can handle that, I think?-// This method of pagination is naive, in that it only allows for "loading more". If we thought the search results were likely to change, this would be a problem, as it could return duplicate data. But I think search results are fairly stable, and we can live with this for now.-export function createPaginatedEmailSearchResource(- searchTerm: () => string,- pageSize: number = 25-) {- type fetchSearchEmailsResult = {- results: EmailSearchResponseItem[];- nextPage: number;- hasMore: boolean;- };-- const [signal, , filterError] = makeAbortable();-- const fetchSearchEmails = async (- term: string,- info: {- value?: fetchSearchEmailsResult;- refetching?: boolean | { page?: number };- }- ) => {- const { value, refetching } = info;- const nullResult = {- results: [],- nextPage: 0,- hasMore: false,- };- if (!ENABLE_SEARCH_SERVICE) return nullResult;- if (term.length < 3) return nullResult;-- try {- const pageNumber =- refetching && typeof refetching === 'object' && refetching.page- ? refetching.page- : 0;- const result = await searchClient.searchEmails(- {- request: {- match_type: 'partial',- terms: [term],- },- params: { page: pageNumber, page_size: pageSize },- },- { signal: signal() }- );- if (isErr(result)) {- logger.error(`Failed to get search query: ${result[0]}`);- return nullResult;- }- const [, data] = result;- const newResults = data.results ?? [];-- const existingResults = pageNumber > 0 && value ? value.results : [];- const allResults = [...existingResults, ...newResults];-- const hasMore = newResults.length === pageSize;-- return {- results: allResults,- nextPage: pageNumber + 1,- hasMore,- };- } catch (err) {- filterError(err);- return nullResult;- }- };-- const [data, { refetch }] = createResource(searchTerm, fetchSearchEmails);-- const loadMore = () => {- const currentData = data();- if (currentData && currentData.hasMore && !data.loading) {- const nextPage = currentData.nextPage;- refetch({ page: nextPage });- }- };-- const refresh = () => {- refetch({ page: 0 });- };-- return {- data,- loadMore,- refresh,- };-}--export function createSearchChatsResource(searchTerm: () => string) {- return createSearchResource<ChatSearchResponse>(searchTerm, (term, signal) =>- searchClient.searchChats(- {- match_type: 'partial',- terms: [term],- },- { signal }- )- );-}--export function useSearchChats(searchTerm: () => string) {- const [resource] = createSearchChatsResource(searchTerm);- return createMemo((): ChatSearchResponse | undefined => {- const latest = resource?.latest;- if (!latest) return undefined;- return latest;- });-}-// TODO: would be nice to rework things to all use createSearchResource again... sighexport function createUnifiedSearchResource(searchTerm: () => string,- pageNumber: () => number+ cursor: () => string | null = () => null) {- const combined = () => [searchTerm(), pageNumber()] as const;+ const combined = () => [searchTerm(), cursor()] as const;const [signal, , filterError] = makeAbortable();- return createResource(combined, async ([term, page]) => {+ return createResource(combined, async ([term, cursorValue]) => {if (!ENABLE_SEARCH_SERVICE) return null;if (term.length < 3) return null;@@ -191,7 +24,6 @@ export function createUnifiedSearchResource(search_on: 'content',match_type: 'partial',terms: [term],- // in order for an index to be searched on, the key needs to exist in "filters"filters: {channel: {},chat: {},@@ -200,7 +32,7 @@ export function createUnifiedSearchResource(project: {},},},- params: { page, page_size: 10 },+ params: { cursor: cursorValue, page_size: 10 },},{ signal: signal() });@@ -219,9 +51,9 @@ export function createUnifiedSearchResource(export function useSearch(searchTerm: () => string,- pageNumber: () => number = () => 0+ cursor: () => string | null = () => null) {- const [resource] = createUnifiedSearchResource(searchTerm, pageNumber);+ const [resource] = createUnifiedSearchResource(searchTerm, cursor);return createMemo((): UnifiedSearchResponse | undefined => {const latest = resource?.latest;if (!latest) return undefined;diff --git a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx b/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsxindex 0860fc8155..e3fabbb5ae 100644--- a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx+++ b/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx@@ -259,9 +259,7 @@ export function createUnifiedInfiniteList<T extends EntityData>({entityQueries?.map((query) => {const operations = getOperations(query.operations);const data =- query.query.isSuccess && query.query.isEnabled- ? query.query.data- : [];+ query.query.isEnabled && query.query.data ? query.query.data : [];return {data,operations,@@ -418,9 +416,19 @@ export function createUnifiedInfiniteList<T extends EntityData>({};createEffect(() => {- entityInfiniteQueries.map((query) => {- if (!query.query.isEnabled || !query.query.isError) return;+ const enabledQueries = entityInfiniteQueries.filter(+ (q) => q.query.isEnabled+ );+ const errorQueries = enabledQueries.filter((q) => q.query.isError);++ // Only show error if all enabled queries failed+ if (+ errorQueries.length === 0 ||+ errorQueries.length < enabledQueries.length+ )+ return;+ errorQueries.forEach((query) => {if (query.query.isFetchNextPageError) {console.error('failed to fetch next page', query.query.failureReason);toast.failure('Failed to fetch more data');diff --git a/js/app/packages/macro-entity/src/queries/key.ts b/js/app/packages/macro-entity/src/queries/key.tsindex b2fd310f5d..8b7af949ed 100644--- a/js/app/packages/macro-entity/src/queries/key.ts+++ b/js/app/packages/macro-entity/src/queries/key.ts@@ -1,5 +1,5 @@import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';-import type { PaginatedSearchArgs } from '@service-search/client';+import type { SearchArgs } from '@service-search/client';import { hashKey } from '@tanstack/solid-query';const BASE_AUTH = ['auth'];@@ -29,7 +29,7 @@ type EmailKeyOptions = InfiniteKeyOptions & {};type SearchKeyOptions = {infinite: true;-} & PaginatedSearchArgs;+} & SearchArgs;export const queryKeys = {all: {diff --git a/js/app/packages/macro-entity/src/queries/search.ts b/js/app/packages/macro-entity/src/queries/search.tsindex 64717db618..eb6f7113b4 100644--- a/js/app/packages/macro-entity/src/queries/search.ts+++ b/js/app/packages/macro-entity/src/queries/search.ts@@ -10,7 +10,7 @@ import {truncateSearchMatch,} from '@core/util/searchHighlight';import type { ChannelType } from '@service-comms/generated/models';-import { type PaginatedSearchArgs, searchClient } from '@service-search/client';+import { type SearchArgs, searchClient } from '@service-search/client';import type {ChannelSearchResult,ChatMessageSearchResult,@@ -326,10 +326,7 @@ const useMapSearchResponseItem = () => {};};-const fetchPaginatedSearchResults = async (- args: PaginatedSearchArgs,- signal?: AbortSignal-) => {+const fetchSearchResults = async (args: SearchArgs, signal?: AbortSignal) => {const res = await searchClient.search(args, { signal });if (isErr(res)) throw res[0];const [, data] = res;@@ -337,13 +334,13 @@ const fetchPaginatedSearchResults = async (};export function createUnifiedSearchInfiniteQuery(- args: Accessor<PaginatedSearchArgs>,+ args: Accessor<SearchArgs>,options?: {disabled?: Accessor<boolean>;}): EntityInfiniteQuery<WithSearch<EntityData>> {const params = createMemo(() => args());- const pageParams = createMemo(() => params().params);+ const pageSize = createMemo(() => params().params.page_size);const request = createMemo(() => params().request);const terms = createMemo(() => {const query = request().query;@@ -385,19 +382,22 @@ export function createUnifiedSearchInfiniteQuery(...params(),}),queryFn: (ctx) =>- fetchPaginatedSearchResults(+ fetchSearchResults({params: ctx.pageParam,request: request(),},ctx.signal),- initialPageParam: pageParams(),- getNextPageParam: (lastPage, _allPages, lastPageParam, _allPageParams) => {- if (lastPage.results.length === 0) return;+ initialPageParam: {+ cursor: null as string | null,+ page_size: pageSize(),+ },+ getNextPageParam: (lastPage) => {+ if (!lastPage.next_cursor) return;return {- ...pageParams(),- page: lastPageParam.page + 1,+ cursor: lastPage.next_cursor as string | null,+ page_size: pageSize(),};},select: (data) => {diff --git a/js/app/packages/service-clients/service-search/client.ts b/js/app/packages/service-clients/service-search/client.tsindex 885115e724..a6fdab1cea 100644--- a/js/app/packages/service-clients/service-search/client.ts+++ b/js/app/packages/service-clients/service-search/client.ts@@ -14,13 +14,6 @@ import type { SafeFetchInit } from '@core/util/safeFetch';const searchServiceHost = `${SERVER_HOSTS['search-service']}`;-import type { ChatSearchRequest } from './generated/models/chatSearchRequest';-import type { ChatSearchResponse } from './generated/models/chatSearchResponse';-import type { DocumentSearchRequest } from './generated/models/documentSearchRequest';-import type { DocumentSearchResponse } from './generated/models/documentSearchResponse';-import type { EmailSearchParams } from './generated/models/emailSearchParams';-import type { EmailSearchRequest } from './generated/models/emailSearchRequest';-import type { EmailSearchResponse } from './generated/models/emailSearchResponse';import type { UnifiedSearchRequest } from './generated/models/unifiedSearchRequest';import type { UnifiedSearchResponse } from './generated/models/unifiedSearchResponse';@@ -41,67 +34,37 @@ export function searchServiceFetch<T extends ObjectLike = never>(return fetchWithToken<T>(`${searchServiceHost}${url}`, init);}-type WithPagination = {- page: number;- page_size: number;+export type SearchParams = {+ cursor?: string | null;+ page_size?: number;};-export type PaginatedSearchArgs = {- params: WithPagination;+export type SearchArgs = {+ params: SearchParams;request: UnifiedSearchRequest;};export const searchClient = {- async searchDocuments(args: DocumentSearchRequest, init?: SafeFetchInit) {- return mapOk(- await searchServiceFetch<DocumentSearchResponse>(`/search/document`, {- method: 'POST',- body: JSON.stringify(args),- ...init,- }),- (result) => result- );- },- async searchEmails(- args: {- request: EmailSearchRequest;- params: EmailSearchParams;- },- init?: SafeFetchInit- ) {- return mapOk(- await searchServiceFetch<EmailSearchResponse>(- `/search/email?page=${args.params.page ?? 0}&page_size=${args.params.page_size ?? 10}`,- {- method: 'POST',- body: JSON.stringify(args.request),- ...init,- }- ),- (result) => result- );- },- async searchChats(args: ChatSearchRequest, init?: SafeFetchInit) {+ async search(args: SearchArgs, init?: SafeFetchInit) {+ const params = new URLSearchParams();++ if (args.params.page_size !== undefined) {+ params.append('page_size', args.params.page_size.toString());+ }+ if (args.params.cursor) {+ params.append('cursor', args.params.cursor);+ }++ const queryString = params.toString();+ const url = queryString ? `/search?${queryString}` : '/search';+return mapOk(- await searchServiceFetch<ChatSearchResponse>(`/search/chat`, {+ await searchServiceFetch<UnifiedSearchResponse>(url, {method: 'POST',- body: JSON.stringify(args),+ body: JSON.stringify(args.request),...init,}),(result) => result);},- async search(args: PaginatedSearchArgs, init?: SafeFetchInit) {- return mapOk(- await searchServiceFetch<UnifiedSearchResponse>(- `/search?page=${args.params.page}&page_size=${args.params.page_size}`,- {- method: 'POST',- body: JSON.stringify(args.request),- ...init,- }- ),- (result) => result- );- },};diff --git a/js/app/packages/service-clients/service-search/generated/client.ts b/js/app/packages/service-clients/service-search/generated/client.tsindex c5720b4e5b..c301595846 100644--- a/js/app/packages/service-clients/service-search/generated/client.ts+++ b/js/app/packages/service-clients/service-search/generated/client.ts@@ -5,33 +5,8 @@* OpenAPI spec version: 0.1.0*/import type {- ChannelSearchParams,- ChannelSearchRequest,- ChannelSearchResponse,- ChatSearchParams,- ChatSearchRequest,- ChatSearchResponse,- DocumentSearchParams,- DocumentSearchRequest,- DocumentSearchResponse,- EmailSearchParams,- EmailSearchRequest,- EmailSearchResponse,EmptyResponse,ErrorResponse,- ProjectSearchParams,- ProjectSearchRequest,- SearchResponse,- SimpleChannelSearchParams,- SimpleChannelSearchResponse,- SimpleChatSearchParams,- SimpleChatSearchResponse,- SimpleDocumentSearchParams,- SimpleDocumentSearchResponse,- SimpleEmailSearchParams,- SimpleEmailSearchResponse,- SimpleProjectSearchParams,- SimpleProjectSearchResponse,SimpleUnifiedSearchBaseResponse,SimpleUnifiedSearchParams,UnifiedSearchParams,@@ -149,346 +124,6 @@ export const unifiedSearch = async (unifiedSearchRequest: UnifiedSearchRequest,-/**- * @summary Perform a search through your emails- */-export type channelSearchResponse200 = {- data: ChannelSearchResponse- status: 200-}--export type channelSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type channelSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type channelSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type channelSearchResponseSuccess = (channelSearchResponse200) & {- headers: Headers;-};-export type channelSearchResponseError = (channelSearchResponse400 | channelSearchResponse401 | channelSearchResponse500) & {- headers: Headers;-};--export type channelSearchResponse = (channelSearchResponseSuccess | channelSearchResponseError)--export const getChannelSearchUrl = (params: ChannelSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/channel?${stringifiedParams}` : `/search/channel`-}--export const channelSearch = async (channelSearchRequest: ChannelSearchRequest,- params: ChannelSearchParams, options?: RequestInit): Promise<channelSearchResponse> => {-- const res = await fetch(getChannelSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- channelSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: channelSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as channelSearchResponse-}----/**- * @summary Perform a search through your chats- */-export type chatSearchResponse200 = {- data: ChatSearchResponse- status: 200-}--export type chatSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type chatSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type chatSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type chatSearchResponseSuccess = (chatSearchResponse200) & {- headers: Headers;-};-export type chatSearchResponseError = (chatSearchResponse400 | chatSearchResponse401 | chatSearchResponse500) & {- headers: Headers;-};--export type chatSearchResponse = (chatSearchResponseSuccess | chatSearchResponseError)--export const getChatSearchUrl = (params: ChatSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/chat?${stringifiedParams}` : `/search/chat`-}--export const chatSearch = async (chatSearchRequest: ChatSearchRequest,- params: ChatSearchParams, options?: RequestInit): Promise<chatSearchResponse> => {-- const res = await fetch(getChatSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- chatSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: chatSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as chatSearchResponse-}----/**- * @summary Perform a search through your documents- */-export type documentSearchResponse200 = {- data: DocumentSearchResponse- status: 200-}--export type documentSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type documentSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type documentSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type documentSearchResponseSuccess = (documentSearchResponse200) & {- headers: Headers;-};-export type documentSearchResponseError = (documentSearchResponse400 | documentSearchResponse401 | documentSearchResponse500) & {- headers: Headers;-};--export type documentSearchResponse = (documentSearchResponseSuccess | documentSearchResponseError)--export const getDocumentSearchUrl = (params: DocumentSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/document?${stringifiedParams}` : `/search/document`-}--export const documentSearch = async (documentSearchRequest: DocumentSearchRequest,- params: DocumentSearchParams, options?: RequestInit): Promise<documentSearchResponse> => {-- const res = await fetch(getDocumentSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- documentSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: documentSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as documentSearchResponse-}----/**- * @summary Perform a search through your emails- */-export type emailSearchResponse200 = {- data: EmailSearchResponse- status: 200-}--export type emailSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type emailSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type emailSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type emailSearchResponseSuccess = (emailSearchResponse200) & {- headers: Headers;-};-export type emailSearchResponseError = (emailSearchResponse400 | emailSearchResponse401 | emailSearchResponse500) & {- headers: Headers;-};--export type emailSearchResponse = (emailSearchResponseSuccess | emailSearchResponseError)--export const getEmailSearchUrl = (params: EmailSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/email?${stringifiedParams}` : `/search/email`-}--export const emailSearch = async (emailSearchRequest: EmailSearchRequest,- params: EmailSearchParams, options?: RequestInit): Promise<emailSearchResponse> => {-- const res = await fetch(getEmailSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- emailSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: emailSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as emailSearchResponse-}----/**- * @summary Perform a search through your projects- */-export type projectSearchResponse200 = {- data: SearchResponse- status: 200-}--export type projectSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type projectSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type projectSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type projectSearchResponseSuccess = (projectSearchResponse200) & {- headers: Headers;-};-export type projectSearchResponseError = (projectSearchResponse400 | projectSearchResponse401 | projectSearchResponse500) & {- headers: Headers;-};--export type projectSearchResponse = (projectSearchResponseSuccess | projectSearchResponseError)--export const getProjectSearchUrl = (params?: ProjectSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/project?${stringifiedParams}` : `/search/project`-}--export const projectSearch = async (projectSearchRequest: ProjectSearchRequest,- params?: ProjectSearchParams, options?: RequestInit): Promise<projectSearchResponse> => {-- const res = await fetch(getProjectSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- projectSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: projectSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as projectSearchResponse-}---/*** @summary Perform a search through all items.This is a simple search where we do not group your results by entity id.@@ -555,348 +190,3 @@ export const simpleUnifiedSearch = async (unifiedSearchRequest: UnifiedSearchReqconst data: simpleUnifiedSearchResponse['data'] = body ? JSON.parse(body) : {}return { data, status: res.status, headers: res.headers } as simpleUnifiedSearchResponse}----/**- * @summary Perform a search through your channels-This is a simple search where we do not group your results by channel id.- */-export type simpleChannelSearchResponse200 = {- data: SimpleChannelSearchResponse- status: 200-}--export type simpleChannelSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type simpleChannelSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type simpleChannelSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type simpleChannelSearchResponseSuccess = (simpleChannelSearchResponse200) & {- headers: Headers;-};-export type simpleChannelSearchResponseError = (simpleChannelSearchResponse400 | simpleChannelSearchResponse401 | simpleChannelSearchResponse500) & {- headers: Headers;-};--export type simpleChannelSearchResponse = (simpleChannelSearchResponseSuccess | simpleChannelSearchResponseError)--export const getSimpleChannelSearchUrl = (params: SimpleChannelSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/simple/channel?${stringifiedParams}` : `/search/simple/channel`-}--export const simpleChannelSearch = async (channelSearchRequest: ChannelSearchRequest,- params: SimpleChannelSearchParams, options?: RequestInit): Promise<simpleChannelSearchResponse> => {-- const res = await fetch(getSimpleChannelSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- channelSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: simpleChannelSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as simpleChannelSearchResponse-}----/**- * @summary Perform a search through your chats-This is a simple search where we do not group your results by chat id.- */-export type simpleChatSearchResponse200 = {- data: SimpleChatSearchResponse- status: 200-}--export type simpleChatSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type simpleChatSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type simpleChatSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type simpleChatSearchResponseSuccess = (simpleChatSearchResponse200) & {- headers: Headers;-};-export type simpleChatSearchResponseError = (simpleChatSearchResponse400 | simpleChatSearchResponse401 | simpleChatSearchResponse500) & {- headers: Headers;-};--export type simpleChatSearchResponse = (simpleChatSearchResponseSuccess | simpleChatSearchResponseError)--export const getSimpleChatSearchUrl = (params: SimpleChatSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/simple/chat?${stringifiedParams}` : `/search/simple/chat`-}--export const simpleChatSearch = async (chatSearchRequest: ChatSearchRequest,- params: SimpleChatSearchParams, options?: RequestInit): Promise<simpleChatSearchResponse> => {-- const res = await fetch(getSimpleChatSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- chatSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: simpleChatSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as simpleChatSearchResponse-}----/**- * @summary Perform a search through your documents-This is a simple search where we do not group yor results by document id.- */-export type simpleDocumentSearchResponse200 = {- data: SimpleDocumentSearchResponse- status: 200-}--export type simpleDocumentSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type simpleDocumentSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type simpleDocumentSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type simpleDocumentSearchResponseSuccess = (simpleDocumentSearchResponse200) & {- headers: Headers;-};-export type simpleDocumentSearchResponseError = (simpleDocumentSearchResponse400 | simpleDocumentSearchResponse401 | simpleDocumentSearchResponse500) & {- headers: Headers;-};--export type simpleDocumentSearchResponse = (simpleDocumentSearchResponseSuccess | simpleDocumentSearchResponseError)--export const getSimpleDocumentSearchUrl = (params: SimpleDocumentSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/simple/document?${stringifiedParams}` : `/search/simple/document`-}--export const simpleDocumentSearch = async (documentSearchRequest: DocumentSearchRequest,- params: SimpleDocumentSearchParams, options?: RequestInit): Promise<simpleDocumentSearchResponse> => {-- const res = await fetch(getSimpleDocumentSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- documentSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: simpleDocumentSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as simpleDocumentSearchResponse-}----/**- * @summary Perform a search through your emails-This is a simple search where we do not group your results by thread id.- */-export type simpleEmailSearchResponse200 = {- data: SimpleEmailSearchResponse- status: 200-}--export type simpleEmailSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type simpleEmailSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type simpleEmailSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type simpleEmailSearchResponseSuccess = (simpleEmailSearchResponse200) & {- headers: Headers;-};-export type simpleEmailSearchResponseError = (simpleEmailSearchResponse400 | simpleEmailSearchResponse401 | simpleEmailSearchResponse500) & {- headers: Headers;-};--export type simpleEmailSearchResponse = (simpleEmailSearchResponseSuccess | simpleEmailSearchResponseError)--export const getSimpleEmailSearchUrl = (params: SimpleEmailSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/simple/email?${stringifiedParams}` : `/search/simple/email`-}--export const simpleEmailSearch = async (emailSearchRequest: EmailSearchRequest,- params: SimpleEmailSearchParams, options?: RequestInit): Promise<simpleEmailSearchResponse> => {-- const res = await fetch(getSimpleEmailSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- emailSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: simpleEmailSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as simpleEmailSearchResponse-}----/**- * @summary Perform a search through your projects-This is a simple search where we do not group your results by project id.- */-export type simpleProjectSearchResponse200 = {- data: SimpleProjectSearchResponse- status: 200-}--export type simpleProjectSearchResponse400 = {- data: ErrorResponse- status: 400-}--export type simpleProjectSearchResponse401 = {- data: ErrorResponse- status: 401-}--export type simpleProjectSearchResponse500 = {- data: ErrorResponse- status: 500-}--export type simpleProjectSearchResponseSuccess = (simpleProjectSearchResponse200) & {- headers: Headers;-};-export type simpleProjectSearchResponseError = (simpleProjectSearchResponse400 | simpleProjectSearchResponse401 | simpleProjectSearchResponse500) & {- headers: Headers;-};--export type simpleProjectSearchResponse = (simpleProjectSearchResponseSuccess | simpleProjectSearchResponseError)--export const getSimpleProjectSearchUrl = (params?: SimpleProjectSearchParams,) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {-- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- });-- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0 ? `/search/simple/project?${stringifiedParams}` : `/search/simple/project`-}--export const simpleProjectSearch = async (projectSearchRequest: ProjectSearchRequest,- params?: SimpleProjectSearchParams, options?: RequestInit): Promise<simpleProjectSearchResponse> => {-- const res = await fetch(getSimpleProjectSearchUrl(params),- {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(- projectSearchRequest,)- }-)-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: simpleProjectSearchResponse['data'] = body ? JSON.parse(body) : {}- return { data, status: res.status, headers: res.headers } as simpleProjectSearchResponse-}diff --git a/js/app/packages/service-clients/service-search/generated/models/channelSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/channelSearchParams.tsdeleted file mode 100644index 7ffcd70f9f..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/channelSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type ChannelSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;-/**- * The page size. Defaults to 10.- */-page_size: number;-};diff --git a/js/app/packages/service-clients/service-search/generated/models/chatSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/chatSearchParams.tsdeleted file mode 100644index c8ce42be52..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/chatSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type ChatSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;-/**- * The page size. Defaults to 10.- */-page_size: number;-};diff --git a/js/app/packages/service-clients/service-search/generated/models/documentSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/documentSearchParams.tsdeleted file mode 100644index 665029337a..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/documentSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type DocumentSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;-/**- * The page size. Defaults to 10.- */-page_size: number;-};diff --git a/js/app/packages/service-clients/service-search/generated/models/emailSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/emailSearchParams.tsdeleted file mode 100644index abff48573b..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/emailSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type EmailSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;-/**- * The page size. Defaults to 10.- */-page_size: number;-};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.tsindex b5ed1154a0..e430824d2e 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@@ -10,7 +10,6 @@ export * from './channelFiltersOrgId';export * from './channelMetadata';export * from './channelMetadataInteractedAt';export * from './channelMetadataViewedAt';-export * from './channelSearchParams';export * from './channelSearchRequest';export * from './channelSearchRequestAllOf';export * from './channelSearchRequestAllOfTwo';@@ -39,7 +38,6 @@ export * from './chatMetadata';export * from './chatMetadataDeletedAt';export * from './chatMetadataProjectId';export * from './chatMetadataViewedAt';-export * from './chatSearchParams';export * from './chatSearchRequest';export * from './chatSearchRequestAllOf';export * from './chatSearchRequestAllOfTwo';@@ -56,7 +54,6 @@ export * from './documentMetadata';export * from './documentMetadataDeletedAt';export * from './documentMetadataProjectId';export * from './documentMetadataViewedAt';-export * from './documentSearchParams';export * from './documentSearchRequest';export * from './documentSearchRequestAllOf';export * from './documentSearchRequestAllOfTwo';@@ -76,7 +73,6 @@ export * from './documentSearchResultRawContent';export * from './documentSearchResultScore';export * from './documentSubType';export * from './emailFilters';-export * from './emailSearchParams';export * from './emailSearchRequest';export * from './emailSearchRequestAllOf';export * from './emailSearchRequestAllOfTwo';@@ -105,7 +101,6 @@ export * from './projectMetadataDeletedAt';export * from './projectMetadataParentProjectId';export * from './projectMetadataViewedAt';export * from './projectSearchMetadata';-export * from './projectSearchParams';export * from './projectSearchRequest';export * from './projectSearchRequestAllOf';export * from './projectSearchRequestAllOfTwo';@@ -124,7 +119,6 @@ export * from './searchHighlightSender';export * from './searchHighlightUserId';export * from './searchOn';export * from './searchResponse';-export * from './simpleChannelSearchParams';export * from './simpleChannelSearchReponseBaseItem';export * from './simpleChannelSearchReponseBaseItemOrgId';export * from './simpleChannelSearchReponseBaseItemThreadId';@@ -132,17 +126,14 @@ export * from './simpleChannelSearchReponseBaseItemTimestampSeconds';export * from './simpleChannelSearchReponseBaseItemTimestampSecondsOrgId';export * from './simpleChannelSearchReponseBaseItemTimestampSecondsThreadId';export * from './simpleChannelSearchResponse';-export * from './simpleChatSearchParams';export * from './simpleChatSearchResponse';export * from './simpleChatSearchResponseBaseItem';export * from './simpleChatSearchResponseBaseItemTimestampSeconds';-export * from './simpleDocumentSearchParams';export * from './simpleDocumentSearchResponse';export * from './simpleDocumentSearchResponseBaseItem';export * from './simpleDocumentSearchResponseBaseItemRawContent';export * from './simpleDocumentSearchResponseBaseItemTimestampSeconds';export * from './simpleDocumentSearchResponseBaseItemTimestampSecondsRawContent';-export * from './simpleEmailSearchParams';export * from './simpleEmailSearchResponse';export * from './simpleEmailSearchResponseBaseItem';export * from './simpleEmailSearchResponseBaseItemSentAt';@@ -150,7 +141,6 @@ export * from './simpleEmailSearchResponseBaseItemSubject';export * from './simpleEmailSearchResponseBaseItemTimestampSeconds';export * from './simpleEmailSearchResponseBaseItemTimestampSecondsSentAt';export * from './simpleEmailSearchResponseBaseItemTimestampSecondsSubject';-export * from './simpleProjectSearchParams';export * from './simpleProjectSearchResponse';export * from './simpleProjectSearchResponseBaseItem';export * from './simpleProjectSearchResponseBaseItemTimestampSeconds';@@ -217,4 +207,5 @@ export * from './unifiedSearchResponseItemOneOfOnezeroAllOf';export * from './unifiedSearchResponseItemOneOfOnezeroAllOfType';export * from './unifiedSearchResponseItemOneOfSeven';export * from './unifiedSearchResponseItemOneOfSevenAllOf';-export * from './unifiedSearchResponseItemOneOfSevenAllOfType';\ No newline at end of file+export * from './unifiedSearchResponseItemOneOfSevenAllOfType';+export * from './unifiedSearchResponseNextCursor';\ No newline at end of filediff --git a/js/app/packages/service-clients/service-search/generated/models/projectSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/projectSearchParams.tsdeleted file mode 100644index cab250d6cb..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/projectSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type ProjectSearchParams = {-/**- * The page. Defaults to 0.- */-page?: number;-/**- * The page size. Defaults to 10.- */-page_size?: number;-};diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleChannelSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/simpleChannelSearchParams.tsdeleted file mode 100644index 91e8d90924..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/simpleChannelSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type SimpleChannelSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;-/**- * The page size. Defaults to 10.- */-page_size: number;-};diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleChatSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/simpleChatSearchParams.tsdeleted file mode 100644index 3d7e5fd16f..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/simpleChatSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type SimpleChatSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;-/**- * The page size. Defaults to 10.- */-page_size: number;-};diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleDocumentSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/simpleDocumentSearchParams.tsdeleted file mode 100644index 89dd4fc2dd..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/simpleDocumentSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type SimpleDocumentSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;-/**- * The page size. Defaults to 10.- */-page_size: number;-};diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleEmailSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/simpleEmailSearchParams.tsdeleted file mode 100644index 84859360df..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/simpleEmailSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type SimpleEmailSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;-/**- * The page size. Defaults to 10.- */-page_size: number;-};diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleProjectSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/simpleProjectSearchParams.tsdeleted file mode 100644index 58663cf2c7..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/simpleProjectSearchParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type SimpleProjectSearchParams = {-/**- * The page. Defaults to 0.- */-page?: number;-/**- * The page size. Defaults to 10.- */-page_size?: number;-};diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchParams.tsindex fba69a7e45..02302cdbed 100644--- a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchParams.ts+++ b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchParams.ts@@ -6,12 +6,12 @@*/export type SimpleUnifiedSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;/*** The page size. Defaults to 10.*/page_size: number;+/**+ * Base64 encoded cursor for pagination.+ */+cursor?: string;};diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchParams.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchParams.tsindex f02b29fb29..e36cedfaae 100644--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchParams.ts+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchParams.ts@@ -6,12 +6,12 @@*/export type UnifiedSearchParams = {-/**- * The page. Defaults to 0.- */-page: number;/*** The page size. Defaults to 10.*/page_size: number;+/**+ * Base64 encoded cursor value.+ */+cursor?: string;};diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponse.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponse.tsindex 4b07ab4c4d..828fc312f9 100644--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponse.ts+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponse.ts@@ -4,8 +4,12 @@* search_service* OpenAPI spec version: 0.1.0*/+import type { UnifiedSearchResponseNextCursor } from './unifiedSearchResponseNextCursor';import type { UnifiedSearchResponseItem } from './unifiedSearchResponseItem';export interface UnifiedSearchResponse {+ /** The next cursor to use for paginating results */+ next_cursor?: UnifiedSearchResponseNextCursor;+ /** The search results */results: UnifiedSearchResponseItem[];}diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseNextCursor.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseNextCursor.tsnew file mode 100644index 0000000000..0566fcf74e--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseNextCursor.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The next cursor to use for paginating results+ */+export type UnifiedSearchResponseNextCursor = string | null;diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex 72c59dec57..6e384d213f 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -31,622 +31,25 @@"summary": "Perform a search through all items","operationId": "unified_search","parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- },- {- "name": "page_size",- "in": "query",- "description": "The page size. Defaults to 10.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/UnifiedSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/UnifiedSearchResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/channel": {- "post": {- "tags": ["search::channel"],- "summary": "Perform a search through your emails",- "operationId": "channel_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- },- {- "name": "page_size",- "in": "query",- "description": "The page size. Defaults to 10.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ChannelSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ChannelSearchResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/chat": {- "post": {- "tags": ["search::chat"],- "summary": "Perform a search through your chats",- "operationId": "chat_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- },- {- "name": "page_size",- "in": "query",- "description": "The page size. Defaults to 10.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ChatSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ChatSearchResponse" }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/document": {- "post": {- "tags": ["search::document"],- "summary": "Perform a search through your documents",- "operationId": "document_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- },- {- "name": "page_size",- "in": "query",- "description": "The page size. Defaults to 10.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/DocumentSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/DocumentSearchResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/email": {- "post": {- "tags": ["search::email"],- "summary": "Perform a search through your emails",- "operationId": "email_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- },- {- "name": "page_size",- "in": "query",- "description": "The page size. Defaults to 10.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/EmailSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/EmailSearchResponse" }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/project": {- "post": {- "tags": ["search::project"],- "summary": "Perform a search through your projects",- "operationId": "project_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": false,- "schema": { "type": "integer", "format": "int64" }- },- {- "name": "page_size",- "in": "query",- "description": "The page size. Defaults to 10.",- "required": false,- "schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ProjectSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/SearchResponse" }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/simple": {- "post": {- "tags": ["search::simple::simple_unified"],- "summary": "Perform a search through all items.\nThis is a simple search where we do not group your results by entity id.",- "operationId": "simple_unified_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- },- {- "name": "page_size",- "in": "query",- "description": "The page size. Defaults to 10.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/UnifiedSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/SimpleUnifiedSearchBaseResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/simple/channel": {- "post": {- "tags": ["search::simple::simple_channel"],- "summary": "Perform a search through your channels\nThis is a simple search where we do not group your results by channel id.",- "operationId": "simple_channel_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- },- {- "name": "page_size",- "in": "query",- "description": "The page size. Defaults to 10.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ChannelSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/SimpleChannelSearchResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/simple/chat": {- "post": {- "tags": ["search::simple::simple_chat"],- "summary": "Perform a search through your chats\nThis is a simple search where we do not group your results by chat id.",- "operationId": "simple_chat_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- },{"name": "page_size","in": "query","description": "The page size. Defaults to 10.","required": true,"schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ChatSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/SimpleChatSearchResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/simple/document": {- "post": {- "tags": ["search::simple::simple_document"],- "summary": "Perform a search through your documents\nThis is a simple search where we do not group yor results by document id.",- "operationId": "simple_document_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }},{- "name": "page_size",+ "name": "cursor","in": "query",- "description": "The page size. Defaults to 10.",- "required": true,- "schema": { "type": "integer", "format": "int64" }+ "description": "Base64 encoded cursor value.",+ "required": false,+ "schema": { "type": "string" }}],"requestBody": {"content": {"application/json": {- "schema": { "$ref": "#/components/schemas/DocumentSearchRequest" }+ "schema": { "$ref": "#/components/schemas/UnifiedSearchRequest" }}},"required": true@@ -657,7 +60,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/SimpleDocumentSearchResponse"+ "$ref": "#/components/schemas/UnifiedSearchResponse"}}}@@ -689,98 +92,31 @@}}},- "/search/simple/email": {+ "/search/simple": {"post": {- "tags": ["search::simple::simple_email"],- "summary": "Perform a search through your emails\nThis is a simple search where we do not group your results by thread id.",- "operationId": "simple_email_search",+ "tags": ["search::simple::simple_unified"],+ "summary": "Perform a search through all items.\nThis is a simple search where we do not group your results by entity id.",+ "operationId": "simple_unified_search","parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": true,- "schema": { "type": "integer", "format": "int64" }- },{"name": "page_size","in": "query","description": "The page size. Defaults to 10.","required": true,"schema": { "type": "integer", "format": "int64" }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/EmailSearchRequest" }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/SimpleEmailSearchResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": { "$ref": "#/components/schemas/ErrorResponse" }- }- }- }- }- }- },- "/search/simple/project": {- "post": {- "tags": ["search::simple::simple_project"],- "summary": "Perform a search through your projects\nThis is a simple search where we do not group your results by project id.",- "operationId": "simple_project_search",- "parameters": [- {- "name": "page",- "in": "query",- "description": "The page. Defaults to 0.",- "required": false,- "schema": { "type": "integer", "format": "int64" }},{- "name": "page_size",+ "name": "cursor","in": "query",- "description": "The page size. Defaults to 10.",+ "description": "Base64 encoded cursor for pagination.","required": false,- "schema": { "type": "integer", "format": "int64" }+ "schema": { "type": "string" }}],"requestBody": {"content": {"application/json": {- "schema": { "$ref": "#/components/schemas/ProjectSearchRequest" }+ "schema": { "$ref": "#/components/schemas/UnifiedSearchRequest" }}},"required": true@@ -791,7 +127,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/SimpleProjectSearchResponse"+ "$ref": "#/components/schemas/SimpleUnifiedSearchBaseResponse"}}}@@ -2977,11 +2313,16 @@"type": "object","required": ["results"],"properties": {+ "next_cursor": {+ "type": ["string", "null"],+ "description": "The next cursor to use for paginating results"+ },"results": {"type": "array","items": {"$ref": "#/components/schemas/UnifiedSearchResponseItem"- }+ },+ "description": "The search results"}}},diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 14336b6d26..a7a1abfefa 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3054,6 +3054,24 @@ dependencies = ["uuid",]+[[package]]+name = "email_contact_search"+version = "0.1.0"+dependencies = [+ "anyhow",+ "cached",+ "chrono",+ "macro_db_migrator",+ "macro_user_id",+ "models_search_cursor",+ "serde",+ "sqlx",+ "thiserror 2.0.17",+ "tokio",+ "tracing",+ "uuid",+]+[[package]]name = "email_db_client"version = "0.1.0"@@ -5619,6 +5637,17 @@ dependencies = ["uuid",]+[[package]]+name = "models_search_cursor"+version = "0.1.0"+dependencies = [+ "base64 0.22.1",+ "chrono",+ "serde",+ "serde_json",+ "uuid",+]+[[package]]name = "models_sfs"version = "0.1.0"@@ -5698,9 +5727,12 @@ name = "name_search"version = "0.1.0"dependencies = ["anyhow",+ "cached",+ "chrono","macro_db_migrator","macro_user_id","models_opensearch",+ "models_search_cursor","non_empty","serde","sqlx",@@ -6005,6 +6037,7 @@ dependencies = ["chrono","macro_entrypoint","models_opensearch",+ "models_search_cursor","opensearch","opensearch_query_builder","serde",@@ -7581,6 +7614,7 @@ dependencies = ["comms_service_client","document_storage_service_client","document_sub_type",+ "email_contact_search","email_service_client","futures","http-body-util",@@ -7597,6 +7631,7 @@ dependencies = ["models_email","models_opensearch","models_search",+ "models_search_cursor","name_search","opensearch_client","secretsmanager_client",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 4872757e97..00b43911b2 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -27,6 +27,7 @@ members = ["document_text_extractor","docx_unzip_handler","dynamodb_client",+ "email_contact_search","email_db_client","email_refresh_handler","email_scheduled_handler",@@ -67,6 +68,7 @@ members = ["models_permissions","models_properties","models_search",+ "models_search_cursor","models_sfs","models_soup","models_team",diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rsindex 8762c08424..767b742549 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs@@ -60,7 +60,7 @@ impl AsyncTool<ToolServiceContext, RequestContext> for ContentSearch {let response = context.search_service_client- .search_unified(&request_context.user_id, search_request, 0, PAGE_SIZE)+ .search_unified(&request_context.user_id, search_request, None, PAGE_SIZE).await.map_err(|e| ToolCallError {description: format!("failed to perform content search: {}", e),diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/mod.rs b/rust/cloud-storage/ai_tools/src/search/search_service/mod.rsindex 7566f6eb67..2f1548a588 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/mod.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/mod.rs@@ -1,5 +1,3 @@pub mod content;pub mod name;pub mod types;-#[allow(unused)]-pub mod unified;diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rsindex c14ebf384b..e7654fdd2f 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs@@ -60,7 +60,7 @@ impl AsyncTool<ToolServiceContext, RequestContext> for NameSearch {let response = context.search_service_client- .search_unified(&request_context.user_id, search_request, 0, PAGE_SIZE)+ .search_unified(&request_context.user_id, search_request, None, PAGE_SIZE).await.map_err(|e| ToolCallError {description: format!("failed to perform name search: {}", e),diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/unified.rs b/rust/cloud-storage/ai_tools/src/search/search_service/unified.rsdeleted file mode 100644index a91dd848a4..0000000000--- a/rust/cloud-storage/ai_tools/src/search/search_service/unified.rs+++ /dev/null@@ -1,359 +0,0 @@-use std::cmp::min;--use crate::tool_context::{RequestContext, ToolServiceContext};-use ai::tool::{AsyncTool, ToolCallError, ToolResult};-use async_trait::async_trait;-use models_search::unified::{UnifiedSearchRequest, UnifiedSearchResponseItem};-use schemars::{JsonSchema, Schema};-use serde::{Deserialize, Serialize};--/// maximum number of results to return to the ai client-const TRUNCATED_RESULTS_LIMIT: usize = 150;--/// when exhaustive search is disabled, fetch this many results-/// note that a result includes a content match for the same document id so this is not the same as-/// unique document matches-const DEFAULT_SEARCH_LIMIT: usize = 10;--const MAX_PAGE_SIZE: i64 = 100;-const MAX_PAGE_COUNT: i64 = 100; // this times max page size will exceed open search max result window--fn default_exhaustive_search() -> bool {- true-}--fn default_page_size() -> i64 {- DEFAULT_SEARCH_LIMIT as i64-}--// optionally truncate the results to a maximum of TRUNCATED_RESULTS_LIMIT-#[derive(Debug, JsonSchema, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct TruncatedUnifiedSearchResponse {- /// The search results (truncated to `results_returned` limit if applicable)- pub results: Vec<UnifiedSearchResponseItem>,- /// total number of results from search- pub total_results: usize,- /// the number of results returned- pub results_returned: usize,-}--#[derive(Debug, JsonSchema, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct UnifiedSearchResponseOutput {- /// The search results- pub response: TruncatedUnifiedSearchResponse,- /// The JSON schema for the response so the LLM can understand it- pub response_schema: serde_json::Value,-}--lazy_static::lazy_static! {- static ref RESPONSE_SCHEMA: Schema = response_schema();-}--fn response_schema() -> Schema {- let generator = ai::tool::minimized_output_schema_generator();- generator.into_root_schema_for::<UnifiedSearchResponseOutput>()-}--#[derive(Debug, JsonSchema, Deserialize, Clone)]-#[serde(rename_all = "camelCase")]-#[schemars(- description = "Universal search across all content types (documents, emails, AI conversations, chat/slack threads/channels, projects aka folders). This tool will return broad metadata from successful results and/or content matches. Use the Read tool next to read the results from those matches. Only ever refer to documents by name or with a document mention. Never state the id of the document in plaintext. User's are presented with the results of this tool as a UI element so there is no need to enumerate the information found from this tool.",- title = "UnifiedSearch"-)]-pub struct UnifiedSearch {- #[schemars(- description = "Exhaustive search across all results matching the query. Defaults to true. Use false when the user only requires a limitied subset of results to answer the question"- )]- #[serde(default = "default_exhaustive_search")]- pub exhaustive_search: bool,-- #[schemars(- description = "Page offset. Default is 0. Use a higher offset to page through results intelligently. Set exhaustive_search to true to get all results."- )]- #[serde(default)]- pub page_offset: i64,-- #[schemars(- description = "Search count per search type (i.e. applies separately to each of documents, emails, ai_conversations, chats, projects). Max is 100. Default is 10. Does not apply when exhaustive_search is set to true."- )]- #[serde(default = "default_page_size")]- pub page_size: i64,-- #[schemars(description = "Aggregated search request, see individual fields for details")]- pub request: UnifiedSearchRequest,-}--async fn fetch_all_pages_simple(- context: &ToolServiceContext,- request_context: &RequestContext,- search_request: &UnifiedSearchRequest,-) -> Result<Vec<UnifiedSearchResponseItem>, ToolCallError> {- const BATCH_SIZE: usize = 4;- let mut page = 0;- let mut all_results = vec![];-- loop {- // Create concurrent requests for the batch- let mut tasks = Vec::with_capacity(BATCH_SIZE);- let mut hit_pagination_limit = false;-- for i in 0..BATCH_SIZE {- let current_page = page + i as i64;-- if current_page >= MAX_PAGE_COUNT {- tracing::warn!(- page = current_page,- "exhaustive search exceeded max page count, stopping"- );- hit_pagination_limit = true;- break;- }-- let context = context.clone();- let request_context = request_context.clone();- let search_request = search_request.clone();-- let task = tokio::spawn(async move {- let result = context- .search_service_client- .search_unified(- &request_context.user_id,- search_request,- current_page,- MAX_PAGE_SIZE,- )- .await;-- (current_page, result)- });-- tasks.push(task);- }-- // Wait for all requests to complete- let mut batch_has_results = false;-- for task in tasks {- let (current_page, response) = task.await.map_err(|e| ToolCallError {- description: format!("task join error: {}", e),- internal_error: e.into(),- })?;-- match response {- Ok(response) => {- let result_count = response.results.len();-- tracing::debug!(- page = current_page,- result_count,- "exhaustive search: fetched page in batch"- );-- if result_count > 0 {- batch_has_results = true;- all_results.extend(response.results);- } else {- tracing::debug!(- page = current_page,- "exhaustive search: found empty page, stopping"- );- }- }- Err(e) => {- return Err(ToolCallError {- description: format!(- "failed to perform exhaustive unified search on page {}: {}",- current_page, e- ),- internal_error: e,- });- }- }- }-- if hit_pagination_limit {- tracing::info!(- total_results = all_results.len(),- last_successful_page = page,- "exhaustive search stopped due to OpenSearch pagination limit"- );- break;- }-- if !batch_has_results {- break;- }-- page += BATCH_SIZE as i64;- }-- Ok(all_results)-}--#[async_trait]-impl AsyncTool<ToolServiceContext, RequestContext> for UnifiedSearch {- type Output = UnifiedSearchResponseOutput;-- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]- async fn call(- &self,- context: ToolServiceContext,- request_context: RequestContext,- ) -> ToolResult<Self::Output> {- tracing::info!(self=?self, "Unified search params");-- let search_request = UnifiedSearchRequest {- query: self.request.query.clone(),- terms: self.request.terms.clone(),- match_type: self.request.match_type,- filters: self.request.filters.clone(),- search_on: self.request.search_on,- collapse: Some(false), // collapse=true will return one result per opensearch document- include: self.request.include.clone(),- disable_recency: self.request.disable_recency,- };- tracing::info!(search_request=?search_request, "Unified search request");-- if self.exhaustive_search {- // Use exhaustive search with batched pagination- return match fetch_all_pages_simple(&context, &request_context, &search_request).await {- Ok(all_results) => {- let total_results = all_results.len();- let results_returned = min(total_results, TRUNCATED_RESULTS_LIMIT);- let results = if results_returned < total_results {- all_results.into_iter().take(results_returned).collect()- } else {- all_results- };-- let response_schema = RESPONSE_SCHEMA.as_value().clone();- let tool_response = UnifiedSearchResponseOutput {- response: TruncatedUnifiedSearchResponse {- results,- total_results,- results_returned,- },- response_schema,- };- tracing::debug!(- "exhaustive search returned {results_returned} results of {total_results}"- );- ToolResult::Ok(tool_response)- }- Err(e) => ToolResult::Err(e),- };- }-- // Non-exhaustive search - single page- let page = self.page_offset;- let page_size = self.page_size;-- // Validate parameters- if page < 0 {- return Err(ToolCallError {- description: "page_offset must be greater than or equal to 0".to_string(),- internal_error: anyhow::anyhow!("page_offset must be greater than or equal to 0"),- });- } else if page > MAX_PAGE_COUNT {- return Err(ToolCallError {- description: format!(- "page_offset must be less than or equal to {}",- MAX_PAGE_COUNT- ),- internal_error: anyhow::anyhow!(format!(- "page_offset must be less than or equal to {}",- MAX_PAGE_COUNT- )),- });- }-- if page_size <= 0 {- return Err(ToolCallError {- description: format!(- "page_size must be greater than 0. default is {DEFAULT_SEARCH_LIMIT}"- ),- internal_error: anyhow::anyhow!("page_size must be greater than 0"),- });- } else if page_size > MAX_PAGE_SIZE {- return Err(ToolCallError {- description: format!("page_size must be less than or equal to {}", MAX_PAGE_SIZE),- internal_error: anyhow::anyhow!(format!(- "page_size must be less than or equal to {}",- MAX_PAGE_SIZE- )),- });- }-- match context- .search_service_client- .search_unified(&request_context.user_id, search_request, page, page_size)- .await- {- Ok(response) => {- let result_count = response.results.len();- let response_schema = RESPONSE_SCHEMA.as_value().clone();- let tool_response = UnifiedSearchResponseOutput {- response: TruncatedUnifiedSearchResponse {- results: response.results,- total_results: result_count,- results_returned: result_count,- },- response_schema,- };- tracing::debug!("search tool returned {result_count} results");- ToolResult::Ok(tool_response)- }- Err(e) => {- tracing::warn!("Search failed with error: {}", e);- Err(ToolCallError {- description: format!("failed to perform unified search: {}", e),- internal_error: e,- })- }- }- }-}--#[cfg(test)]-mod tests {- use super::*;- use ai::generate_tool_input_schema;- use ai::tool::types::tool_object::validate_tool_schema;-- // run `cargo test -p ai_tools unified::tests::print_output_schema -- --nocapture --include-ignored`- #[test]- #[ignore = "prints the output schema"]- fn print_output_schema() {- let schema = RESPONSE_SCHEMA.as_value().clone();- println!("{}", serde_json::to_string_pretty(&schema).unwrap());- }-- // run `cargo test -p ai_tools unified::tests::print_input_schema -- --nocapture --include-ignored`- #[test]- #[ignore = "prints the input schema"]- fn print_input_schema() {- let schema = generate_tool_input_schema!(UnifiedSearch);- println!("{}", serde_json::to_string_pretty(&schema).unwrap());- }-- #[test]- fn test_unified_search_schema_validation() {- let schema = generate_tool_input_schema!(UnifiedSearch);-- // Test using the actual validate_tool_schema function- let result = validate_tool_schema(&schema);- assert!(result.is_ok(), "{:?}", result);-- let (name, description) = result.unwrap();- assert_eq!(- name, "UnifiedSearch",- "Tool name should match the schemars title"- );- assert!(- description.contains("Universal search across all content types"),- "Description should contain expected text"- );- }-}diff --git a/rust/cloud-storage/email_contact_search/.sqlx/query-e57d9f9da7bf3d99431ca7a4d074674f46d21e94aa1dd747a6095b7b369faff1.json b/rust/cloud-storage/email_contact_search/.sqlx/query-e57d9f9da7bf3d99431ca7a4d074674f46d21e94aa1dd747a6095b7b369faff1.jsonnew file mode 100644index 0000000000..6acada9fae--- /dev/null+++ b/rust/cloud-storage/email_contact_search/.sqlx/query-e57d9f9da7bf3d99431ca7a4d074674f46d21e94aa1dd747a6095b7b369faff1.json@@ -0,0 +1,56 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH paginated_threads AS (\n SELECT t.id, t.latest_non_spam_message_ts\n FROM email_threads t\n WHERE t.link_id = (SELECT id FROM email_links WHERE macro_id = $1)\n AND t.latest_non_spam_message_ts IS NOT NULL\n AND (\n $4::timestamptz IS NULL\n OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)\n )\n AND EXISTS (\n -- Check for sender matches\n SELECT 1\n FROM email_messages m\n JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.thread_id = t.id\n AND (c.name ILIKE $2 OR c.email_address ILIKE $2 OR m.from_name ILIKE $2)\n\n UNION ALL\n\n -- Check for recipient matches\n SELECT 1\n FROM email_messages m\n JOIN email_message_recipients mr ON mr.message_id = m.id\n JOIN email_contacts c ON c.id = mr.contact_id\n WHERE m.thread_id = t.id\n AND (c.name ILIKE $2 OR c.email_address ILIKE $2 OR mr.name ILIKE $2)\n )\n ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC\n LIMIT $3\n )\n SELECT\n pt.id as \"thread_id!\",\n pt.latest_non_spam_message_ts as \"updated_at!\",\n matches.message_id as \"message_id!\",\n matches.contact_name as \"contact_name?\",\n matches.contact_email as \"contact_email!\",\n matches.contact_type as \"contact_type!\"\n FROM paginated_threads pt\n CROSS JOIN LATERAL (\n -- Sender matches: check contact.name, contact.email_address, and message.from_name\n SELECT DISTINCT\n m.id as message_id,\n COALESCE(m.from_name, c.name) as contact_name,\n c.email_address as contact_email,\n 'FROM'::text as contact_type\n FROM email_messages m\n JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.thread_id = pt.id\n AND (c.name ILIKE $2 OR c.email_address ILIKE $2 OR m.from_name ILIKE $2)\n\n UNION\n\n -- Recipient matches: check contact.name, contact.email_address, and recipient.name\n SELECT DISTINCT\n m.id as message_id,\n COALESCE(mr.name, c.name) as contact_name,\n c.email_address as contact_email,\n mr.recipient_type::text as contact_type\n FROM email_messages m\n JOIN email_message_recipients mr ON mr.message_id = m.id\n JOIN email_contacts c ON c.id = mr.contact_id\n WHERE m.thread_id = pt.id\n AND (c.name ILIKE $2 OR c.email_address ILIKE $2 OR mr.name ILIKE $2)\n ) matches(message_id, contact_name, contact_email, contact_type)\n ORDER BY pt.latest_non_spam_message_ts DESC, pt.id DESC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "updated_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 2,+ "name": "message_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "contact_name?",+ "type_info": "Varchar"+ },+ {+ "ordinal": 4,+ "name": "contact_email!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 5,+ "name": "contact_type!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Int8",+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true,+ null,+ null,+ null,+ null+ ]+ },+ "hash": "e57d9f9da7bf3d99431ca7a4d074674f46d21e94aa1dd747a6095b7b369faff1"+}diff --git a/rust/cloud-storage/email_contact_search/Cargo.toml b/rust/cloud-storage/email_contact_search/Cargo.tomlnew file mode 100644index 0000000000..a88155a0c9--- /dev/null+++ b/rust/cloud-storage/email_contact_search/Cargo.toml@@ -0,0 +1,21 @@+[package]+edition = "2024"+name = "email_contact_search"+publish = false+version = "0.1.0"++[dependencies]+anyhow = { workspace = true }+cached = { workspace = true }+chrono = { workspace = true }+macro_user_id = { path = "../macro_user_id" }+models_search_cursor = { path = "../models_search_cursor" }+serde = { workspace = true }+sqlx = { workspace = true }+thiserror = { workspace = true }+tracing = { workspace = true }+uuid = { workspace = true }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+tokio = { workspace = true }diff --git a/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sql b/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sqlnew file mode 100644index 0000000000..549da76311--- /dev/null+++ b/rust/cloud-storage/email_contact_search/fixtures/email_contacts.sql@@ -0,0 +1,112 @@+-- Test users+INSERT INTO "User" (id, email, name)+VALUES+ ('macro|[email protected]', '[email protected]', 'Test User 1'),+ ('macro|[email protected]', '[email protected]', 'Test User 2');++-- Email links (email account connections for each user)+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES+ ('00000000-0000-0001-0000-000000000001', 'macro|[email protected]', 'fa_user1', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+ ('00000000-0000-0002-0000-000000000002', 'macro|[email protected]', 'fa_user2', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');++-- Email contacts with various names for testing+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)+VALUES+ -- Contacts for user1's link+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Alice Smith', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Bob Johnson', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Charlie Brown', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', '00000000-0000-0001-0000-000000000001', '[email protected]', 'David Miller', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+ -- Contact with NULL name (should use message-level override)+ ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', '00000000-0000-0001-0000-000000000001', '[email protected]', NULL, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),++ -- Contacts for user2's link (for isolation testing)+ ('ffffffff-ffff-ffff-ffff-ffffffffffff', '00000000-0000-0002-0000-000000000002', '[email protected]', 'Frank Wilson', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');++-- Email threads for user1+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)+VALUES+ -- Thread 1: Most recent (latest_non_spam_message_ts: 2024-12-06)+ ('11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-06 10:00:00+00', '2024-01-01 10:00:00+00', '2024-12-06 10:00:00+00'),++ -- Thread 2: Second most recent (latest_non_spam_message_ts: 2024-12-05)+ ('22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-05 10:00:00+00', '2024-02-01 10:00:00+00', '2024-12-05 10:00:00+00'),++ -- Thread 3: Third most recent (latest_non_spam_message_ts: 2024-12-04)+ ('33333333-3333-3333-3333-333333333333', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-04 10:00:00+00', '2024-03-01 10:00:00+00', '2024-12-04 10:00:00+00'),++ -- Thread 4: Fourth most recent (latest_non_spam_message_ts: 2024-12-03)+ ('44444444-4444-4444-4444-444444444444', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-03 10:00:00+00', '2024-04-01 10:00:00+00', '2024-12-03 10:00:00+00'),++ -- Thread 5: Thread with NULL latest_non_spam_message_ts+ ('55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', true, false, NULL, '2024-05-01 10:00:00+00', '2024-05-01 10:00:00+00');++-- Email threads for user2 (for isolation testing)+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)+VALUES+ ('99999999-9999-9999-9999-999999999999', '00000000-0000-0002-0000-000000000002', true, false, '2024-12-09 10:00:00+00', '2024-09-01 10:00:00+00', '2024-12-09 10:00:00+00');++-- Email messages for user1's threads+-- Thread 1: Alice is the sender+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)+VALUES+ ('10000000-0001-0000-0000-000000000001', '11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'Subject 1', '2024-01-01 10:00:00+00', false, false, '2024-01-01 10:00:00+00', '2024-01-01 10:00:00+00');++-- Thread 2: Bob is the sender, Alice and Charlie are recipients+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)+VALUES+ ('10000000-0002-0000-0000-000000000001', '22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NULL, 'Subject 2', '2024-02-01 10:00:00+00', false, false, '2024-02-01 10:00:00+00', '2024-02-01 10:00:00+00');++-- Thread 3: Charlie is the sender with message-level name override+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)+VALUES+ ('10000000-0003-0000-0000-000000000001', '33333333-3333-3333-3333-333333333333', '00000000-0000-0001-0000-000000000001', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'Charles B. Brown', 'Subject 3', '2024-03-01 10:00:00+00', false, false, '2024-03-01 10:00:00+00', '2024-03-01 10:00:00+00');++-- Thread 4: Emily is the sender (has NULL name in contact, uses from_name override)+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)+VALUES+ ('10000000-0004-0000-0000-000000000001', '44444444-4444-4444-4444-444444444444', '00000000-0000-0001-0000-000000000001', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'Emily Davis', 'Subject 4', '2024-04-01 10:00:00+00', false, false, '2024-04-01 10:00:00+00', '2024-04-01 10:00:00+00');++-- Thread 5: David is sender+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)+VALUES+ ('10000000-0005-0000-0000-000000000001', '55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', 'dddddddd-dddd-dddd-dddd-dddddddddddd', NULL, 'Subject 5', '2024-05-01 10:00:00+00', false, false, '2024-05-01 10:00:00+00', '2024-05-01 10:00:00+00');++-- Email messages for user2's threads (for isolation testing)+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, from_name, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)+VALUES+ ('10000000-0009-0000-0000-000000000001', '99999999-9999-9999-9999-999999999999', '00000000-0000-0002-0000-000000000002', 'ffffffff-ffff-ffff-ffff-ffffffffffff', NULL, 'User2 Subject', '2024-09-01 10:00:00+00', false, false, '2024-09-01 10:00:00+00', '2024-09-01 10:00:00+00');++-- Message recipients for Thread 1: Alice TO, Bob CC+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)+VALUES+ ('10000000-0001-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'TO', NULL),+ ('10000000-0001-0000-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'CC', NULL);++-- Message recipients for Thread 2: Alice TO, Charlie CC, David BCC+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)+VALUES+ ('10000000-0002-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'TO', NULL),+ ('10000000-0002-0000-0000-000000000001', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'CC', NULL),+ ('10000000-0002-0000-0000-000000000001', 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'BCC', NULL);++-- Message recipients for Thread 3: Bob TO with name override+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)+VALUES+ ('10000000-0003-0000-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'TO', 'Robert J.');++-- Message recipients for Thread 4: David TO+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)+VALUES+ ('10000000-0004-0000-0000-000000000001', 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'TO', NULL);++-- Message recipients for Thread 5: Emily TO+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)+VALUES+ ('10000000-0005-0000-0000-000000000001', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'TO', NULL);++-- Message recipients for user2's thread+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)+VALUES+ ('10000000-0009-0000-0000-000000000001', 'ffffffff-ffff-ffff-ffff-ffffffffffff', 'TO', NULL);diff --git a/rust/cloud-storage/email_contact_search/src/lib.rs b/rust/cloud-storage/email_contact_search/src/lib.rsnew file mode 100644index 0000000000..05505ead0a--- /dev/null+++ b/rust/cloud-storage/email_contact_search/src/lib.rs@@ -0,0 +1,241 @@+#![deny(missing_docs)]++//! This crate contains the queries to search over macrodb for your email contacts++#[cfg(not(test))]+use cached::proc_macro::cached;+use chrono::{DateTime, Utc};+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use models_search_cursor::{+ PaginatedResult, SearchCursorAttributes, SearchCursorOption, SearchMethodCursor,+};+use sqlx::{Pool, Postgres};++/// Errors for email contact search crate+#[derive(Debug, thiserror::Error)]+pub enum EmailContactSearchError {+ /// Database error+ #[error("database error occurred {0}")]+ DatabaseError(#[from] sqlx::Error),+ /// Empty search term+ #[error("empty search term provided")]+ EmptySearchTerm,+}++/// The contact type for the match+#[derive(Debug, Clone, serde::Serialize)]+pub enum ContactType {+ /// To+ To,+ /// From+ From,+ /// Cc+ Cc,+ /// Bcc+ Bcc,+}++/// Email thread contact match result+#[derive(Debug, Clone, serde::Serialize)]+pub struct EmailContactMatchThreadResult {+ /// The id of the thread+ pub thread_id: uuid::Uuid,+ /// The id of the message where the match was found+ pub message_id: uuid::Uuid,+ /// The contact name that was matched on+ pub contact_name: Option<String>,+ /// The contact email address+ pub contact_email: String,+ /// The contact type of the match+ pub contact_type: ContactType,+ /// The timestamp used for cursor-based pagination+ pub updated_at: DateTime<Utc>,+}++impl SearchCursorAttributes for EmailContactMatchThreadResult {+ fn entity_id(&self) -> uuid::Uuid {+ self.thread_id+ }++ fn updated_at(&self) -> DateTime<Utc> {+ self.updated_at+ }+}++/// Helper struct for paginating by unique threads+struct ThreadPaginationEntry {+ thread_id: uuid::Uuid,+ updated_at: DateTime<Utc>,+}++impl SearchCursorAttributes for ThreadPaginationEntry {+ fn entity_id(&self) -> uuid::Uuid {+ self.thread_id+ }++ fn updated_at(&self) -> DateTime<Utc> {+ self.updated_at+ }+}++/// Search over your email contacts to find potential contact name matches+#[tracing::instrument(skip(db), err)]+#[cfg_attr(+ not(test),+ cached(+ time = 30,+ result = true,+ key = "String",+ convert = r#"{ format!("{}-{}-{}-{}", macro_user_id.as_ref(), term, limit, cursor.as_ref().map(|c| format!("{}-{}", c.entity_id, c.updated_at)).unwrap_or_default()) }"#+ )+)]+pub async fn search_email_contacts<'a>(+ db: &Pool<Postgres>,+ macro_user_id: MacroUserId<Lowercase<'a>>,+ term: String,+ limit: u32,+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<EmailContactMatchThreadResult>, EmailContactSearchError> {+ if term.is_empty() {+ return Err(EmailContactSearchError::EmptySearchTerm);+ }++ let search_pattern = format!("%{term}%");++ let (cursor_updated_at, cursor_entity_id) = cursor+ .as_ref()+ .map(|c| (Some(c.updated_at), Some(c.entity_id)))+ .unwrap_or((None, None));++ // Fetch limit + 1 to determine if there are more results+ let fetch_limit = limit as i64 + 1;++ let rows = sqlx::query!(+ r#"+ WITH paginated_threads AS (+ SELECT t.id, t.latest_non_spam_message_ts+ FROM email_threads t+ WHERE t.link_id = (SELECT id FROM email_links WHERE macro_id = $1)+ AND t.latest_non_spam_message_ts IS NOT NULL+ AND (+ $4::timestamptz IS NULL+ OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)+ )+ AND EXISTS (+ -- Check for sender matches+ SELECT 1+ FROM email_messages m+ JOIN email_contacts c ON c.id = m.from_contact_id+ WHERE m.thread_id = t.id+ AND (c.name ILIKE $2 OR c.email_address ILIKE $2 OR m.from_name ILIKE $2)++ UNION ALL++ -- Check for recipient matches+ SELECT 1+ FROM email_messages m+ JOIN email_message_recipients mr ON mr.message_id = m.id+ JOIN email_contacts c ON c.id = mr.contact_id+ WHERE m.thread_id = t.id+ AND (c.name ILIKE $2 OR c.email_address ILIKE $2 OR mr.name ILIKE $2)+ )+ ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC+ LIMIT $3+ )+ SELECT+ pt.id as "thread_id!",+ pt.latest_non_spam_message_ts as "updated_at!",+ matches.message_id as "message_id!",+ matches.contact_name as "contact_name?",+ matches.contact_email as "contact_email!",+ matches.contact_type as "contact_type!"+ FROM paginated_threads pt+ CROSS JOIN LATERAL (+ -- Sender matches: check contact.name, contact.email_address, and message.from_name+ SELECT DISTINCT+ m.id as message_id,+ COALESCE(m.from_name, c.name) as contact_name,+ c.email_address as contact_email,+ 'FROM'::text as contact_type+ FROM email_messages m+ JOIN email_contacts c ON c.id = m.from_contact_id+ WHERE m.thread_id = pt.id+ AND (c.name ILIKE $2 OR c.email_address ILIKE $2 OR m.from_name ILIKE $2)++ UNION++ -- Recipient matches: check contact.name, contact.email_address, and recipient.name+ SELECT DISTINCT+ m.id as message_id,+ COALESCE(mr.name, c.name) as contact_name,+ c.email_address as contact_email,+ mr.recipient_type::text as contact_type+ FROM email_messages m+ JOIN email_message_recipients mr ON mr.message_id = m.id+ JOIN email_contacts c ON c.id = mr.contact_id+ WHERE m.thread_id = pt.id+ AND (c.name ILIKE $2 OR c.email_address ILIKE $2 OR mr.name ILIKE $2)+ ) matches(message_id, contact_name, contact_email, contact_type)+ ORDER BY pt.latest_non_spam_message_ts DESC, pt.id DESC+ "#,+ macro_user_id.as_ref(),+ search_pattern,+ fetch_limit,+ cursor_updated_at,+ cursor_entity_id,+ )+ .fetch_all(db)+ .await?;++ let results: Vec<EmailContactMatchThreadResult> = rows+ .into_iter()+ .map(|row| EmailContactMatchThreadResult {+ thread_id: row.thread_id,+ message_id: row.message_id,+ contact_name: row.contact_name,+ contact_email: row.contact_email,+ contact_type: match row.contact_type.as_str() {+ "TO" => ContactType::To,+ "CC" => ContactType::Cc,+ "BCC" => ContactType::Bcc,+ _ => ContactType::From,+ },+ updated_at: row.updated_at,+ })+ .collect();++ // Collect unique threads for pagination (preserving order)+ let mut seen_threads = std::collections::HashSet::new();+ let thread_entries: Vec<ThreadPaginationEntry> = results+ .iter()+ .filter(|r| seen_threads.insert(r.thread_id))+ .map(|r| ThreadPaginationEntry {+ thread_id: r.thread_id,+ updated_at: r.updated_at,+ })+ .collect();++ // Use paginate helper to determine cursor+ let paginated_threads = SearchCursorOption::paginate(thread_entries, limit as usize);++ // Get the thread IDs we want to keep+ let threads_to_keep: std::collections::HashSet<_> = paginated_threads+ .items+ .iter()+ .map(|t| t.thread_id)+ .collect();++ // Filter results to only include matches from kept threads+ let filtered_results: Vec<_> = results+ .into_iter()+ .filter(|r| threads_to_keep.contains(&r.thread_id))+ .collect();++ Ok(PaginatedResult {+ items: filtered_results,+ cursor: paginated_threads.cursor,+ })+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/email_contact_search/src/test.rs b/rust/cloud-storage/email_contact_search/src/test.rsnew file mode 100644index 0000000000..fbc384cbef--- /dev/null+++ b/rust/cloud-storage/email_contact_search/src/test.rs@@ -0,0 +1,486 @@+//! Tests for email contact search module++use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserId;+use models_search_cursor::SearchCursorOption;+use sqlx::{Pool, Postgres};++use super::*;++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_empty_term(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ let result = search_email_contacts(&pool, user_id, "".to_string(), 10, None).await;++ assert!(result.is_err());+ assert!(matches!(+ result.unwrap_err(),+ EmailContactSearchError::EmptySearchTerm+ ));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_finds_sender_by_name(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "Alice" - should find Thread 1 where Alice is the sender+ let response = search_email_contacts(&pool, user_id, "Alice".to_string(), 10, None).await?;++ // Should find matches (Alice is sender in thread 1, recipient in threads 1 and 2)+ assert!(!response.items.is_empty());++ // Check that we have a From match for Alice+ let from_match = response.items.iter().find(|r| {+ matches!(r.contact_type, ContactType::From)+ && r.contact_name.as_deref() == Some("Alice Smith")+ });+ assert!(from_match.is_some());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_finds_recipients(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "Bob" - should find threads where Bob is a recipient+ let response = search_email_contacts(&pool, user_id, "Bob".to_string(), 10, None).await?;++ assert!(!response.items.is_empty());++ // Check for CC match (Bob is CC in thread 1)+ let cc_match = response.items.iter().find(|r| {+ matches!(r.contact_type, ContactType::Cc)+ && r.contact_name.as_deref() == Some("Bob Johnson")+ && r.thread_id.to_string() == "11111111-1111-1111-1111-111111111111"+ });+ assert!(cc_match.is_some());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_finds_bcc_recipients(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "David" - should find thread 2 where David is BCC+ let response = search_email_contacts(&pool, user_id, "David".to_string(), 10, None).await?;++ assert!(!response.items.is_empty());++ // Check for BCC match+ let bcc_match = response.items.iter().find(|r| {+ matches!(r.contact_type, ContactType::Bcc)+ && r.contact_name.as_deref() == Some("David Miller")+ && r.thread_id.to_string() == "22222222-2222-2222-2222-222222222222"+ });+ assert!(bcc_match.is_some());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_sorted_by_latest_message(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "Smith" - Alice Smith appears in multiple threads+ let response = search_email_contacts(&pool, user_id, "Smith".to_string(), 10, None).await?;++ assert!(!response.items.is_empty());++ // Thread 11111111 has latest_non_spam_message_ts: 2024-12-06 (most recent)+ // Thread 22222222 has latest_non_spam_message_ts: 2024-12-05 (second most recent)+ // Results should be sorted by latest_non_spam_message_ts DESC+ if response.items.len() >= 2 {+ assert_eq!(+ response.items[0].thread_id.to_string(),+ "11111111-1111-1111-1111-111111111111"+ );+ }++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search with different cases+ let response_lower =+ search_email_contacts(&pool, user_id.clone(), "alice".to_string(), 10, None).await?;+ let response_upper =+ search_email_contacts(&pool, user_id.clone(), "ALICE".to_string(), 10, None).await?;+ let response_mixed =+ search_email_contacts(&pool, user_id, "AlIcE".to_string(), 10, None).await?;++ // All should return the same number of results+ assert_eq!(response_lower.items.len(), response_upper.items.len());+ assert_eq!(response_lower.items.len(), response_mixed.items.len());+ assert!(!response_lower.items.is_empty());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_partial_match(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for partial term "John" should match "Bob Johnson"+ let response = search_email_contacts(&pool, user_id, "John".to_string(), 10, None).await?;++ assert!(!response.items.is_empty());+ assert!(response.items.iter().any(|r| {+ r.contact_name+ .as_ref()+ .map_or(false, |n| n.contains("Johnson"))+ }));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_pagination_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search with limit of 2 threads - may return multiple rows per thread (one per contact match)+ let response = search_email_contacts(&pool, user_id, "a".to_string(), 2, None).await?;++ // Limit applies to threads, not rows - verify we get at most 2 unique threads+ let unique_threads: std::collections::HashSet<_> =+ response.items.iter().map(|r| r.thread_id).collect();+ assert!(unique_threads.len() <= 2);++ // Should have more results available+ assert!(response.cursor.has_more());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_pagination_cursor(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // First page with limit of 2+ let first_response =+ search_email_contacts(&pool, user_id.clone(), "a".to_string(), 2, None).await?;++ // Count unique threads in first page+ let first_threads: std::collections::HashSet<_> =+ first_response.items.iter().map(|r| r.thread_id).collect();+ assert!(first_threads.len() <= 2);+ assert!(first_response.cursor.has_more());++ // Extract cursor for second page+ let cursor = match first_response.cursor {+ SearchCursorOption::NotDone(c) => c,+ SearchCursorOption::Done => panic!("Expected more results"),+ };++ // Second page using cursor+ let second_response =+ search_email_contacts(&pool, user_id.clone(), "a".to_string(), 2, cursor).await?;++ // Count unique threads in second page+ let second_threads: std::collections::HashSet<_> =+ second_response.items.iter().map(|r| r.thread_id).collect();++ // Verify no overlap between pages+ assert!(first_threads.is_disjoint(&second_threads));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_user_isolation(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "Frank" - Frank belongs to user2, not user1+ let response = search_email_contacts(&pool, user_id, "Frank".to_string(), 10, None).await?;++ // Should return 0 results (Frank is not accessible to user1)+ assert_eq!(response.items.len(), 0);+ assert!(response.cursor.is_done());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_no_results(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for a name that doesn't exist+ let response =+ search_email_contacts(&pool, user_id, "NonexistentPerson".to_string(), 10, None).await?;++ assert_eq!(response.items.len(), 0);+ assert!(response.cursor.is_done());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_includes_email_address(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "Alice"+ let response = search_email_contacts(&pool, user_id, "Alice".to_string(), 10, None).await?;++ assert!(!response.items.is_empty());++ // Check that email address is included+ let alice_result = response+ .items+ .iter()+ .find(|r| r.contact_name.as_deref() == Some("Alice Smith"))+ .unwrap();+ assert_eq!(alice_result.contact_email, "[email protected]");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_uses_message_level_name_override(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "Charles" - Thread 3 has from_name = "Charles B. Brown" which overrides contact name "Charlie Brown"+ let response =+ search_email_contacts(&pool, user_id.clone(), "Charles".to_string(), 10, None).await?;++ // Should find the message with from_name override+ let charles_match = response+ .items+ .iter()+ .find(|r| r.contact_name.as_deref() == Some("Charles B. Brown"));+ assert!(charles_match.is_some());++ // The returned name should be the from_name (override), not the contact name+ assert_eq!(+ charles_match.unwrap().contact_name.as_deref(),+ Some("Charles B. Brown")+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_searches_both_from_name_and_contact_name(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "Charlie" - should find thread 3 because the contact name is "Charlie Brown"+ // even though the from_name is "Charles B. Brown"+ let response = search_email_contacts(&pool, user_id, "Charlie".to_string(), 10, None).await?;++ // Should find thread 3's sender by searching the contact name+ let charlie_from_match = response.items.iter().find(|r| {+ matches!(r.contact_type, ContactType::From)+ && r.thread_id.to_string() == "33333333-3333-3333-3333-333333333333"+ });+ assert!(charlie_from_match.is_some());++ // But the displayed name should still be the from_name override+ assert_eq!(+ charlie_from_match.unwrap().contact_name.as_deref(),+ Some("Charles B. Brown")+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_recipient_name_override(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "Robert" - Thread 3 has recipient with name override "Robert J." for Bob Johnson+ let response = search_email_contacts(&pool, user_id, "Robert".to_string(), 10, None).await?;++ // Should find the recipient with name override+ let robert_match = response+ .items+ .iter()+ .find(|r| r.contact_name.as_deref() == Some("Robert J."));+ assert!(robert_match.is_some());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_pagination_by_thread(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "Smith" - matches Alice Smith who appears in:+ // - Thread 1 (Dec 6) as sender and TO recipient+ // - Thread 2 (Dec 5) as TO recipient+ // This ensures we have 2 threads to paginate over++ // Get first thread (limit=1, cursor=None) - should be Thread 1 (most recent)+ let page1 = search_email_contacts(&pool, user_id.clone(), "Smith".to_string(), 1, None).await?;++ // All results on page 1 should be from Thread 1 (the most recent)+ assert!(!page1.items.is_empty());+ let page1_thread_ids: std::collections::HashSet<_> =+ page1.items.iter().map(|r| r.thread_id).collect();+ assert_eq!(page1_thread_ids.len(), 1);+ assert!(+ page1_thread_ids+ .contains(&uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap())+ );+ assert!(page1.cursor.has_more());++ // Extract cursor for page 2+ let cursor1 = match page1.cursor {+ SearchCursorOption::NotDone(c) => c,+ SearchCursorOption::Done => panic!("Expected more results"),+ };++ // Get second thread using cursor - should be Thread 2 (second most recent)+ let page2 =+ search_email_contacts(&pool, user_id.clone(), "Smith".to_string(), 1, cursor1).await?;++ // All results on page 2 should be from Thread 2+ assert!(!page2.items.is_empty());+ let page2_thread_ids: std::collections::HashSet<_> =+ page2.items.iter().map(|r| r.thread_id).collect();+ assert_eq!(page2_thread_ids.len(), 1);+ assert!(+ page2_thread_ids+ .contains(&uuid::Uuid::parse_str("22222222-2222-2222-2222-222222222222").unwrap())+ );++ // Verify the two pages return different threads+ assert!(page1_thread_ids.is_disjoint(&page2_thread_ids));++ // Page 2 should indicate no more results since there are only 2 threads matching "Smith"+ assert!(page2.cursor.is_done());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("email_contacts"))+)]+async fn test_search_email_contacts_by_email_address(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .map(|l| l.lowercase())+ .unwrap();++ // Search for "bob.johnson" - should match [email protected]+ let response =+ search_email_contacts(&pool, user_id.clone(), "bob.johnson".to_string(), 10, None).await?;++ assert!(!response.items.is_empty());++ // Should find Bob Johnson by email address+ let bob_match = response+ .items+ .iter()+ .find(|r| r.contact_email == "[email protected]");+ assert!(bob_match.is_some());++ // Search for partial email domain - should match all @example.com contacts+ let domain_response =+ search_email_contacts(&pool, user_id, "@example.com".to_string(), 10, None).await?;++ assert!(!domain_response.items.is_empty());++ Ok(())+}diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 231481ce8f..db87da5aad 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -1,9 +1,16 @@MACRODB := "postgres://user:password@localhost:5432/macrodb"DATABASE_URL := "postgres://user:password@localhost:5432"+mod sqlx './sqlx.just'+check:RUSTFLAGS=-Dwarnings RUSTDOCFLAGS=-Dwarnings CARGO_TERM_COLOR=always SQLX_OFFLINE=true cargo check+# This can be used in any crate that uses macrodb under the hood+[no-cd]+prepare_db:+ just sqlx::prepare_db {{ MACRODB }}+format:SQLX_OFFLINE=true cargo fmt@@ -58,6 +65,7 @@ setup_test_envs:echo "DATABASE_URL={{ MACRODB }}" >> ./system_properties/.envecho "DATABASE_URL={{ MACRODB }}" >> ./properties/.envecho "DATABASE_URL={{ MACRODB }}" >> ./name_search/.env+ echo "DATABASE_URL={{ MACRODB }}" >> ./email_contact_search/.envsetup_macrodb:just macro_db_client/migrate_dbdiff --git a/rust/cloud-storage/macro_db_client/migrations/20260107190314_email_contacts_name_trgm.sql b/rust/cloud-storage/macro_db_client/migrations/20260107190314_email_contacts_name_trgm.sqlnew file mode 100644index 0000000000..fdd2814b2e--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260107190314_email_contacts_name_trgm.sql@@ -0,0 +1,5 @@+-- no-transaction++CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_contacts_name_trgm+ ON email_contacts USING gin (name gin_trgm_ops)+ WHERE name IS NOT NULL;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260107190315_email_messages_from_name_trgm.sql b/rust/cloud-storage/macro_db_client/migrations/20260107190315_email_messages_from_name_trgm.sqlnew file mode 100644index 0000000000..ac7ea10312--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260107190315_email_messages_from_name_trgm.sql@@ -0,0 +1,5 @@+-- no-transaction++CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_messages_from_name_trgm+ ON email_messages USING gin (from_name gin_trgm_ops)+ WHERE from_name IS NOT NULL;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260107190316_email_message_recipients_name_trgm.sql b/rust/cloud-storage/macro_db_client/migrations/20260107190316_email_message_recipients_name_trgm.sqlnew file mode 100644index 0000000000..486cc8aa41--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260107190316_email_message_recipients_name_trgm.sql@@ -0,0 +1,5 @@+-- no-transaction++CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_message_recipients_name_trgm+ ON email_message_recipients USING gin (name gin_trgm_ops)+ WHERE name IS NOT NULL;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260107190317_email_contacts_link_id_name.sql b/rust/cloud-storage/macro_db_client/migrations/20260107190317_email_contacts_link_id_name.sqlnew file mode 100644index 0000000000..6d9ed755d4--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260107190317_email_contacts_link_id_name.sql@@ -0,0 +1,5 @@+-- no-transaction++CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_contacts_link_id_name+ ON email_contacts (link_id, name)+ WHERE name IS NOT NULL;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260107190318_email_contact_address_index.sql b/rust/cloud-storage/macro_db_client/migrations/20260107190318_email_contact_address_index.sqlnew file mode 100644index 0000000000..339331ab75--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260107190318_email_contact_address_index.sql@@ -0,0 +1,4 @@+-- no-transaction++CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_contacts_email_address_trgm+ ON email_contacts USING gin (email_address gin_trgm_ops);diff --git a/rust/cloud-storage/models_search/src/unified.rs b/rust/cloud-storage/models_search/src/unified.rsindex 8111231460..f8319ea3f7 100644--- a/rust/cloud-storage/models_search/src/unified.rs+++ b/rust/cloud-storage/models_search/src/unified.rs@@ -171,7 +171,10 @@ impl UnifiedSearchResponseItem {#[derive(Debug, Serialize, Deserialize, ToSchema, Default)]pub struct UnifiedSearchResponse {+ /// The search resultspub results: Vec<UnifiedSearchResponseItem>,+ /// The next cursor to use for paginating results+ pub next_cursor: Option<String>,}#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]diff --git a/rust/cloud-storage/models_search_cursor/Cargo.toml b/rust/cloud-storage/models_search_cursor/Cargo.tomlnew file mode 100644index 0000000000..9ed05b28c8--- /dev/null+++ b/rust/cloud-storage/models_search_cursor/Cargo.toml@@ -0,0 +1,12 @@+[package]+edition = "2024"+name = "models_search_cursor"+publish = false+version = "0.1.0"++[dependencies]+base64 = { workspace = true }+chrono = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+uuid = { workspace = true }diff --git a/rust/cloud-storage/models_search_cursor/src/lib.rs b/rust/cloud-storage/models_search_cursor/src/lib.rsnew file mode 100644index 0000000000..b5ff404e4a--- /dev/null+++ b/rust/cloud-storage/models_search_cursor/src/lib.rs@@ -0,0 +1,131 @@+#![deny(missing_docs)]++//! This crate contains models for the search cursor.++use base64::{Engine, engine::general_purpose::STANDARD as BASE64};++/// Required trait to be able to create a cursor from a Sortable list of items+pub trait SearchCursorAttributes {+ /// Gets the entity id+ fn entity_id(&self) -> uuid::Uuid;+ /// Gets the updated_at+ fn updated_at(&self) -> chrono::DateTime<chrono::Utc>;+}++/// Result of processing sorted results for pagination+#[derive(Debug, Clone)]+pub struct PaginatedResult<T> {+ /// The items to return (with extra item removed if present)+ pub items: Vec<T>,+ /// The cursor for fetching the next page+ pub cursor: SearchCursorOption,+}++/// Used to store individual cursor information for a given search method.+/// This could be document names, email subject, content etc.+#[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>,+}++/// Represents the state of a search cursor+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub enum SearchCursorOption {+ /// The cursor has either not been started or is not exhausted+ NotDone(Option<SearchMethodCursor>),+ /// The cursor is exhausted+ Done,+}++impl Default for SearchCursorOption {+ fn default() -> Self {+ SearchCursorOption::NotDone(None)+ }+}++impl SearchCursorOption {+ /// Returns true if there are more results to fetch+ pub fn has_more(&self) -> bool {+ matches!(self, SearchCursorOption::NotDone(_))+ }++ /// Returns true if the cursor is exhausted (no more results)+ pub fn is_done(&self) -> bool {+ matches!(self, SearchCursorOption::Done)+ }++ /// Processes sorted results for pagination.+ ///+ /// Expects the query to have fetched `limit + 1` items. Returns the trimmed+ /// items (at most `limit`) and the appropriate cursor.+ pub fn paginate<T: SearchCursorAttributes>(+ mut items: Vec<T>,+ limit: usize,+ ) -> PaginatedResult<T> {+ let has_more = items.len() > limit;+ if has_more {+ items.pop();+ }++ let cursor = if has_more {+ match items.last() {+ Some(last) => SearchCursorOption::NotDone(Some(SearchMethodCursor {+ entity_id: last.entity_id(),+ updated_at: last.updated_at(),+ })),+ None => SearchCursorOption::Done,+ }+ } else {+ SearchCursorOption::Done+ };++ PaginatedResult { items, cursor }+ }+}++/// The search cursor contains all the individual `SearchCursorOption` for each search method.+#[derive(Debug, serde::Serialize, serde::Deserialize, Default)]+pub struct SearchCursor {+ /// The document name cursor+ pub document_name_cursor: SearchCursorOption,+ /// The chat name cursor+ pub chat_name_cursor: SearchCursorOption,+ /// The content cursor+ pub content_cursor: SearchCursorOption,+ /// The email subject cursor+ pub email_subject_cursor: SearchCursorOption,+ /// The email contact cursor+ pub email_contact_cursor: SearchCursorOption,+ /// The project cursor+ pub project_name_cursor: SearchCursorOption,+}++impl SearchCursor {+ /// Decodes a base64-encoded cursor string into a SearchCursor+ pub fn decode(encoded: &str) -> Option<Self> {+ BASE64+ .decode(encoded)+ .ok()+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())+ }++ /// Encodes the SearchCursor into a base64 string+ pub fn encode(&self) -> Option<String> {+ serde_json::to_vec(self)+ .ok()+ .map(|bytes| BASE64.encode(bytes))+ }++ /// Returns if the cursor is fully exhausted+ pub fn is_exhausted(&self) -> bool {+ self.document_name_cursor.is_done()+ && self.chat_name_cursor.is_done()+ && self.content_cursor.is_done()+ && self.email_subject_cursor.is_done()+ && self.email_contact_cursor.is_done()+ && self.project_name_cursor.is_done()+ }+}diff --git a/rust/cloud-storage/name_search/.sqlx/query-33b53a9416b38ba5801627767061f440b4755192af39a0b38ab75482324e32c7.json b/rust/cloud-storage/name_search/.sqlx/query-33b53a9416b38ba5801627767061f440b4755192af39a0b38ab75482324e32c7.jsondeleted file mode 100644index 9467ec9a25..0000000000--- a/rust/cloud-storage/name_search/.sqlx/query-33b53a9416b38ba5801627767061f440b4755192af39a0b38ab75482324e32c7.json+++ /dev/null@@ -1,32 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n d.id as entity_id,\n d.name\n FROM \"Document\" d\n WHERE (d.owner = $1 OR d.id = ANY($2))\n AND d.\"deletedAt\" IS NULL\n AND d.name ILIKE $3\n ORDER BY d.\"updatedAt\" DESC\n LIMIT $4\n OFFSET $5\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray",- "Text",- "Int8",- "Int8"- ]- },- "nullable": [- false,- false- ]- },- "hash": "33b53a9416b38ba5801627767061f440b4755192af39a0b38ab75482324e32c7"-}diff --git a/rust/cloud-storage/name_search/.sqlx/query-345333b49aa634cf527c0d5c10f6064359b93f5cadb52da18c5e12a50cf50ae1.json b/rust/cloud-storage/name_search/.sqlx/query-345333b49aa634cf527c0d5c10f6064359b93f5cadb52da18c5e12a50cf50ae1.jsonnew file mode 100644index 0000000000..e4348b6a7f--- /dev/null+++ b/rust/cloud-storage/name_search/.sqlx/query-345333b49aa634cf527c0d5c10f6064359b93f5cadb52da18c5e12a50cf50ae1.json@@ -0,0 +1,45 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n c.id as entity_id,\n c.name,\n regexp_replace(\n c.name,\n $6,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n c.\"updatedAt\" as updated_at\n FROM \"Chat\" c\n WHERE c.id = ANY($1)\n AND c.\"deletedAt\" IS NULL\n AND c.name ILIKE $2\n AND (\n $4::timestamptz IS NULL\n OR (c.\"updatedAt\", c.id) < ($4, $5)\n )\n ORDER BY c.\"updatedAt\" DESC, c.id DESC\n LIMIT $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name_highlighted",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "updated_at",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "Text",+ "Int8",+ "Timestamptz",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ false+ ]+ },+ "hash": "345333b49aa634cf527c0d5c10f6064359b93f5cadb52da18c5e12a50cf50ae1"+}diff --git a/rust/cloud-storage/name_search/.sqlx/query-37557ab1a0fd8180269c401b89c5cc9ae1526f2b7126f21cee6c9ac17b5c51c3.json b/rust/cloud-storage/name_search/.sqlx/query-37557ab1a0fd8180269c401b89c5cc9ae1526f2b7126f21cee6c9ac17b5c51c3.jsondeleted file mode 100644index d64ce700e8..0000000000--- a/rust/cloud-storage/name_search/.sqlx/query-37557ab1a0fd8180269c401b89c5cc9ae1526f2b7126f21cee6c9ac17b5c51c3.json+++ /dev/null@@ -1,32 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n p.id as entity_id,\n p.name\n FROM \"Project\" p\n WHERE (p.\"userId\" = $1 OR p.id = ANY($2))\n AND p.\"deletedAt\" IS NULL\n AND p.name ILIKE $3\n ORDER BY p.\"updatedAt\" DESC\n LIMIT $4\n OFFSET $5\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray",- "Text",- "Int8",- "Int8"- ]- },- "nullable": [- false,- false- ]- },- "hash": "37557ab1a0fd8180269c401b89c5cc9ae1526f2b7126f21cee6c9ac17b5c51c3"-}diff --git a/rust/cloud-storage/name_search/.sqlx/query-3f0ed2175e561447f2ece9e875428a9052496b4e6b6d60e35e0b6e50b7d61a85.json b/rust/cloud-storage/name_search/.sqlx/query-3f0ed2175e561447f2ece9e875428a9052496b4e6b6d60e35e0b6e50b7d61a85.jsondeleted file mode 100644index 854ea4b349..0000000000--- a/rust/cloud-storage/name_search/.sqlx/query-3f0ed2175e561447f2ece9e875428a9052496b4e6b6d60e35e0b6e50b7d61a85.json+++ /dev/null@@ -1,31 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH oldest_messages AS (\n SELECT DISTINCT ON (thread_id)\n thread_id,\n subject\n FROM email_messages\n WHERE thread_id = ANY($1)\n ORDER BY thread_id, internal_date_ts ASC\n )\n SELECT\n t.id as entity_id,\n om.subject as \"name!\"\n FROM email_threads t\n INNER JOIN oldest_messages om ON om.thread_id = t.id\n WHERE om.subject ILIKE $2\n ORDER BY t.latest_non_spam_message_ts DESC\n LIMIT $3\n OFFSET $4\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "name!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "UuidArray",- "Text",- "Int8",- "Int8"- ]- },- "nullable": [- false,- true- ]- },- "hash": "3f0ed2175e561447f2ece9e875428a9052496b4e6b6d60e35e0b6e50b7d61a85"-}diff --git a/rust/cloud-storage/name_search/.sqlx/query-4666b1f3cddd519e0a461257e9aa91c26eb255c7a4a2eaf9143f03c3a1600fce.json b/rust/cloud-storage/name_search/.sqlx/query-4666b1f3cddd519e0a461257e9aa91c26eb255c7a4a2eaf9143f03c3a1600fce.jsondeleted file mode 100644index 970c0fb35e..0000000000--- a/rust/cloud-storage/name_search/.sqlx/query-4666b1f3cddd519e0a461257e9aa91c26eb255c7a4a2eaf9143f03c3a1600fce.json+++ /dev/null@@ -1,32 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n c.id as entity_id,\n c.name\n FROM \"Chat\" c\n WHERE (c.\"userId\" = $1 OR c.id = ANY($2))\n AND c.\"deletedAt\" IS NULL\n AND c.name ILIKE $3\n ORDER BY c.\"updatedAt\" DESC\n LIMIT $4\n OFFSET $5\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray",- "Text",- "Int8",- "Int8"- ]- },- "nullable": [- false,- false- ]- },- "hash": "4666b1f3cddd519e0a461257e9aa91c26eb255c7a4a2eaf9143f03c3a1600fce"-}diff --git a/rust/cloud-storage/name_search/.sqlx/query-4e188b522b313eaf51caac616fe177abfe97c6ce6291ba8f83148ba02eaead73.json b/rust/cloud-storage/name_search/.sqlx/query-4e188b522b313eaf51caac616fe177abfe97c6ce6291ba8f83148ba02eaead73.jsonnew file mode 100644index 0000000000..6908ba7727--- /dev/null+++ b/rust/cloud-storage/name_search/.sqlx/query-4e188b522b313eaf51caac616fe177abfe97c6ce6291ba8f83148ba02eaead73.json@@ -0,0 +1,45 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n d.id as entity_id,\n d.name,\n regexp_replace(\n d.name,\n $6,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n d.\"updatedAt\" as updated_at\n FROM \"Document\" d\n WHERE d.id = ANY($1)\n AND d.\"deletedAt\" IS NULL\n AND d.name ILIKE $2\n AND (\n $4::timestamptz IS NULL\n OR (d.\"updatedAt\", d.id) < ($4, $5)\n )\n ORDER BY d.\"updatedAt\" DESC, d.id DESC\n LIMIT $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name_highlighted",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "updated_at",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "Text",+ "Int8",+ "Timestamptz",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ false+ ]+ },+ "hash": "4e188b522b313eaf51caac616fe177abfe97c6ce6291ba8f83148ba02eaead73"+}diff --git a/rust/cloud-storage/name_search/.sqlx/query-85423841a8e715417d2e6c4c210b096a1aedea8c4bb63029e0024bce1e5029f9.json b/rust/cloud-storage/name_search/.sqlx/query-85423841a8e715417d2e6c4c210b096a1aedea8c4bb63029e0024bce1e5029f9.jsonnew file mode 100644index 0000000000..ee245078e2--- /dev/null+++ b/rust/cloud-storage/name_search/.sqlx/query-85423841a8e715417d2e6c4c210b096a1aedea8c4bb63029e0024bce1e5029f9.json@@ -0,0 +1,45 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n p.id as entity_id,\n p.name,\n regexp_replace(\n p.name,\n $6,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n p.\"updatedAt\" as updated_at\n FROM \"Project\" p\n WHERE p.id = ANY($1)\n AND p.\"deletedAt\" IS NULL\n AND p.name ILIKE $2\n AND (\n $4::timestamptz IS NULL\n OR (p.\"updatedAt\", p.id) < ($4, $5)\n )\n ORDER BY p.\"updatedAt\" DESC, p.id DESC\n LIMIT $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name_highlighted",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "updated_at",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "Text",+ "Int8",+ "Timestamptz",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ false+ ]+ },+ "hash": "85423841a8e715417d2e6c4c210b096a1aedea8c4bb63029e0024bce1e5029f9"+}diff --git a/rust/cloud-storage/name_search/.sqlx/query-9460f97a5fe2c0ddb08e81f8ded812694d0f7408053c49c3e58ecca561d67c64.json b/rust/cloud-storage/name_search/.sqlx/query-9460f97a5fe2c0ddb08e81f8ded812694d0f7408053c49c3e58ecca561d67c64.jsonnew file mode 100644index 0000000000..b26f50c7f4--- /dev/null+++ b/rust/cloud-storage/name_search/.sqlx/query-9460f97a5fe2c0ddb08e81f8ded812694d0f7408053c49c3e58ecca561d67c64.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n c.id as entity_id,\n c.name,\n regexp_replace(\n c.name,\n $7,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n c.\"updatedAt\" as updated_at\n FROM \"Chat\" c\n WHERE (c.\"userId\" = $1 OR c.id = ANY($2))\n AND c.\"deletedAt\" IS NULL\n AND c.name ILIKE $3\n AND (\n $5::timestamptz IS NULL\n OR (c.\"updatedAt\", c.id) < ($5, $6)\n )\n ORDER BY c.\"updatedAt\" DESC, c.id DESC\n LIMIT $4\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name_highlighted",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "updated_at",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "Text",+ "Int8",+ "Timestamptz",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ false+ ]+ },+ "hash": "9460f97a5fe2c0ddb08e81f8ded812694d0f7408053c49c3e58ecca561d67c64"+}diff --git a/rust/cloud-storage/name_search/.sqlx/query-9fea14ffa4f42968dc58e1da081ca87e317d7bf3e54708e3c1425c910b2640b5.json b/rust/cloud-storage/name_search/.sqlx/query-9fea14ffa4f42968dc58e1da081ca87e317d7bf3e54708e3c1425c910b2640b5.jsondeleted file mode 100644index a8e9bf6272..0000000000--- a/rust/cloud-storage/name_search/.sqlx/query-9fea14ffa4f42968dc58e1da081ca87e317d7bf3e54708e3c1425c910b2640b5.json+++ /dev/null@@ -1,31 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n d.id as entity_id,\n d.name -- If there is a name match name obviously name exists\n FROM \"Document\" d\n WHERE d.id = ANY($1)\n AND d.\"deletedAt\" IS NULL\n AND d.name ILIKE $2\n ORDER BY d.\"updatedAt\" DESC\n LIMIT $3\n OFFSET $4\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "TextArray",- "Text",- "Int8",- "Int8"- ]- },- "nullable": [- false,- false- ]- },- "hash": "9fea14ffa4f42968dc58e1da081ca87e317d7bf3e54708e3c1425c910b2640b5"-}diff --git a/rust/cloud-storage/name_search/.sqlx/query-a321d44c7093eba7f5af8adf30827efead8bb987ad26e89f2e12f875ff38e0be.json b/rust/cloud-storage/name_search/.sqlx/query-a321d44c7093eba7f5af8adf30827efead8bb987ad26e89f2e12f875ff38e0be.jsonnew file mode 100644index 0000000000..9642d18561--- /dev/null+++ b/rust/cloud-storage/name_search/.sqlx/query-a321d44c7093eba7f5af8adf30827efead8bb987ad26e89f2e12f875ff38e0be.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n d.id as entity_id,\n d.name,\n regexp_replace(\n d.name,\n $7,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n d.\"updatedAt\" as updated_at\n FROM \"Document\" d\n WHERE (d.owner = $1 OR d.id = ANY($2))\n AND d.\"deletedAt\" IS NULL\n AND d.name ILIKE $3\n AND (\n $5::timestamptz IS NULL\n OR (d.\"updatedAt\", d.id) < ($5, $6)\n )\n ORDER BY d.\"updatedAt\" DESC, d.id DESC\n LIMIT $4\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name_highlighted",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "updated_at",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "Text",+ "Int8",+ "Timestamptz",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ false+ ]+ },+ "hash": "a321d44c7093eba7f5af8adf30827efead8bb987ad26e89f2e12f875ff38e0be"+}diff --git a/rust/cloud-storage/name_search/.sqlx/query-a5773b5116e356b3c148e80c2fcb99799a074deeab9f9446359897536cfc772f.json b/rust/cloud-storage/name_search/.sqlx/query-a5773b5116e356b3c148e80c2fcb99799a074deeab9f9446359897536cfc772f.jsondeleted file mode 100644index 431e732bac..0000000000--- a/rust/cloud-storage/name_search/.sqlx/query-a5773b5116e356b3c148e80c2fcb99799a074deeab9f9446359897536cfc772f.json+++ /dev/null@@ -1,33 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH oldest_messages AS (\n SELECT DISTINCT ON (thread_id)\n thread_id,\n subject\n FROM email_messages\n WHERE link_id IN (\n SELECT id FROM email_links WHERE macro_id = $1\n )\n AND (thread_id = ANY($2) OR $3)\n ORDER BY thread_id, internal_date_ts ASC\n )\n SELECT\n t.id as entity_id,\n om.subject as \"name!\"\n FROM email_threads t\n INNER JOIN oldest_messages om ON om.thread_id = t.id\n WHERE t.link_id IN (\n SELECT id FROM email_links WHERE macro_id = $1\n )\n AND om.subject ILIKE $4\n ORDER BY t.latest_non_spam_message_ts DESC\n LIMIT $5\n OFFSET $6\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "name!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "UuidArray",- "Bool",- "Text",- "Int8",- "Int8"- ]- },- "nullable": [- false,- true- ]- },- "hash": "a5773b5116e356b3c148e80c2fcb99799a074deeab9f9446359897536cfc772f"-}diff --git a/rust/cloud-storage/name_search/.sqlx/query-b6ffefe0291e41a22f8e4c383f26a37ce7478a83aed3110bd2b2999085ac3882.json b/rust/cloud-storage/name_search/.sqlx/query-b6ffefe0291e41a22f8e4c383f26a37ce7478a83aed3110bd2b2999085ac3882.jsondeleted file mode 100644index 3c7558deec..0000000000--- a/rust/cloud-storage/name_search/.sqlx/query-b6ffefe0291e41a22f8e4c383f26a37ce7478a83aed3110bd2b2999085ac3882.json+++ /dev/null@@ -1,31 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n c.id as entity_id,\n c.name\n FROM \"Chat\" c\n WHERE c.id = ANY($1)\n AND c.\"deletedAt\" IS NULL\n AND c.name ILIKE $2\n ORDER BY c.\"updatedAt\" DESC\n LIMIT $3\n OFFSET $4\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "TextArray",- "Text",- "Int8",- "Int8"- ]- },- "nullable": [- false,- false- ]- },- "hash": "b6ffefe0291e41a22f8e4c383f26a37ce7478a83aed3110bd2b2999085ac3882"-}diff --git a/rust/cloud-storage/name_search/.sqlx/query-c7561d429d5838d4af4740208dc0453028c8cb196e76544ceeddb0c8a4c7bbea.json b/rust/cloud-storage/name_search/.sqlx/query-c7561d429d5838d4af4740208dc0453028c8cb196e76544ceeddb0c8a4c7bbea.jsonnew file mode 100644index 0000000000..62a5665c93--- /dev/null+++ b/rust/cloud-storage/name_search/.sqlx/query-c7561d429d5838d4af4740208dc0453028c8cb196e76544ceeddb0c8a4c7bbea.json@@ -0,0 +1,45 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH oldest_messages AS (\n SELECT DISTINCT ON (thread_id)\n thread_id,\n subject\n FROM email_messages\n WHERE thread_id = ANY($1)\n ORDER BY thread_id, internal_date_ts ASC\n )\n SELECT\n t.id as entity_id,\n om.subject as \"name!\",\n regexp_replace(\n om.subject,\n $6,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n t.latest_non_spam_message_ts as updated_at\n FROM email_threads t\n INNER JOIN oldest_messages om ON om.thread_id = t.id\n WHERE om.subject ILIKE $2\n AND (\n $4::timestamptz IS NULL\n OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)\n )\n ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC\n LIMIT $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name_highlighted",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "Text",+ "Int8",+ "Timestamptz",+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ null,+ true+ ]+ },+ "hash": "c7561d429d5838d4af4740208dc0453028c8cb196e76544ceeddb0c8a4c7bbea"+}diff --git a/rust/cloud-storage/name_search/.sqlx/query-c9cb7e2eedc56971de5831b85df4ad182b902afb511bce1b5ea1c94d90632dee.json b/rust/cloud-storage/name_search/.sqlx/query-c9cb7e2eedc56971de5831b85df4ad182b902afb511bce1b5ea1c94d90632dee.jsondeleted file mode 100644index c5a7a422be..0000000000--- a/rust/cloud-storage/name_search/.sqlx/query-c9cb7e2eedc56971de5831b85df4ad182b902afb511bce1b5ea1c94d90632dee.json+++ /dev/null@@ -1,31 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n p.id as entity_id,\n p.name\n FROM \"Project\" p\n WHERE p.id = ANY($1)\n AND p.\"deletedAt\" IS NULL\n AND p.name ILIKE $2\n ORDER BY p.\"updatedAt\" DESC\n LIMIT $3\n OFFSET $4\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "TextArray",- "Text",- "Int8",- "Int8"- ]- },- "nullable": [- false,- false- ]- },- "hash": "c9cb7e2eedc56971de5831b85df4ad182b902afb511bce1b5ea1c94d90632dee"-}diff --git a/rust/cloud-storage/name_search/.sqlx/query-cebafd0d72b44d2f63bce484750fcab2a26f543e5a6ca992e38bdb662dc7c2f4.json b/rust/cloud-storage/name_search/.sqlx/query-cebafd0d72b44d2f63bce484750fcab2a26f543e5a6ca992e38bdb662dc7c2f4.jsonnew file mode 100644index 0000000000..75361e6ea2--- /dev/null+++ b/rust/cloud-storage/name_search/.sqlx/query-cebafd0d72b44d2f63bce484750fcab2a26f543e5a6ca992e38bdb662dc7c2f4.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n p.id as entity_id,\n p.name,\n regexp_replace(\n p.name,\n $7,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n p.\"updatedAt\" as updated_at\n FROM \"Project\" p\n WHERE (p.\"userId\" = $1 OR p.id = ANY($2))\n AND p.\"deletedAt\" IS NULL\n AND p.name ILIKE $3\n AND (\n $5::timestamptz IS NULL\n OR (p.\"updatedAt\", p.id) < ($5, $6)\n )\n ORDER BY p.\"updatedAt\" DESC, p.id DESC\n LIMIT $4\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name_highlighted",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "updated_at",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "Text",+ "Int8",+ "Timestamptz",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ false+ ]+ },+ "hash": "cebafd0d72b44d2f63bce484750fcab2a26f543e5a6ca992e38bdb662dc7c2f4"+}diff --git a/rust/cloud-storage/name_search/.sqlx/query-f0754932b58807334f28d76f583f743662b7195d0c14a8e425acee712d510542.json b/rust/cloud-storage/name_search/.sqlx/query-f0754932b58807334f28d76f583f743662b7195d0c14a8e425acee712d510542.jsonnew file mode 100644index 0000000000..3a32075c4d--- /dev/null+++ b/rust/cloud-storage/name_search/.sqlx/query-f0754932b58807334f28d76f583f743662b7195d0c14a8e425acee712d510542.json@@ -0,0 +1,47 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH oldest_messages AS (\n SELECT DISTINCT ON (thread_id)\n thread_id,\n subject\n FROM email_messages\n WHERE link_id IN (\n SELECT id FROM email_links WHERE macro_id = $1\n )\n AND (thread_id = ANY($2) OR $3)\n ORDER BY thread_id, internal_date_ts ASC\n )\n SELECT\n t.id as entity_id,\n om.subject as \"name!\",\n regexp_replace(\n om.subject,\n $8,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n t.latest_non_spam_message_ts as updated_at\n FROM email_threads t\n INNER JOIN oldest_messages om ON om.thread_id = t.id\n WHERE t.link_id IN (\n SELECT id FROM email_links WHERE macro_id = $1\n )\n AND om.subject ILIKE $4\n AND (\n $6::timestamptz IS NULL\n OR (t.latest_non_spam_message_ts, t.id) < ($6, $7)\n )\n ORDER BY t.latest_non_spam_message_ts DESC, t.id DESC\n LIMIT $5\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name_highlighted",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray",+ "Bool",+ "Text",+ "Int8",+ "Timestamptz",+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ null,+ true+ ]+ },+ "hash": "f0754932b58807334f28d76f583f743662b7195d0c14a8e425acee712d510542"+}diff --git a/rust/cloud-storage/name_search/Cargo.toml b/rust/cloud-storage/name_search/Cargo.tomlindex fd7c38735f..77f854f666 100644--- a/rust/cloud-storage/name_search/Cargo.toml+++ b/rust/cloud-storage/name_search/Cargo.toml@@ -6,8 +6,11 @@ version = "0.1.0"[dependencies]anyhow = { workspace = true }+cached = { workspace = true }+chrono = { workspace = true }macro_user_id = { path = "../macro_user_id" }models_opensearch = { path = "../models_opensearch" }+models_search_cursor = { path = "../models_search_cursor" }non_empty = { path = "../non_empty" }serde = { workspace = true }sqlx = { workspace = true }diff --git a/rust/cloud-storage/name_search/src/chat.rs b/rust/cloud-storage/name_search/src/chat.rsindex 295c6c6b6d..5b940f4bba 100644--- a/rust/cloud-storage/name_search/src/chat.rs+++ b/rust/cloud-storage/name_search/src/chat.rs@@ -1,56 +1,84 @@//! This module contains logic for searching chats by name+#[cfg(not(test))]+use cached::proc_macro::cached;+use chrono::{DateTime, Utc};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};use sqlx::{Pool, Postgres};use uuid::Uuid;-use crate::{NameSearchError, NameSearchResult, SearchEntityType};+use crate::{NameSearchError, NameSearchResult, PaginatedResult, SearchEntityType, escape_regex};/// Searches chats by IDs onlyasync fn ids_search(db: &Pool<Postgres>,chat_ids: &[Uuid],search_pattern: String,+ highlight_pattern: String,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {if chat_ids.is_empty() {return Err(NameSearchError::EmptyIdsWithIdsOnly);}+ let (cursor_updated_at, cursor_entity_id) = cursor+ .as_ref()+ .map(|c| (Some(c.updated_at), Some(c.entity_id.to_string())))+ .unwrap_or((None, None));++ // Fetch limit + 1 to determine if there are more results+ let fetch_limit = limit as i64 + 1;+let rows = sqlx::query!(r#"SELECT- c.id as entity_id,- c.name+ c.id as entity_id,+ c.name,+ regexp_replace(+ c.name,+ $6,+ '<macro_em>\1</macro_em>',+ 'gi'+ ) as name_highlighted,+ c."updatedAt" as updated_atFROM "Chat" cWHERE c.id = ANY($1)AND c."deletedAt" IS NULLAND c.name ILIKE $2- ORDER BY c."updatedAt" DESC+ AND (+ $4::timestamptz IS NULL+ OR (c."updatedAt", c.id) < ($4, $5)+ )+ ORDER BY c."updatedAt" DESC, c.id DESCLIMIT $3- OFFSET $4"#,&chat_ids.iter().map(|id| id.to_string()).collect::<Vec<String>>(),search_pattern,- limit as i64,- offset as i64,+ fetch_limit,+ cursor_updated_at,+ cursor_entity_id,+ highlight_pattern,).fetch_all(db).await.map_err(NameSearchError::DatabaseError)?;- Ok(rows+ let results: Vec<NameSearchResult> = rows.into_iter().map(|row| NameSearchResult {entity_id: row.entity_id.parse().unwrap(),entity_type: SearchEntityType::Chats,- name: row.name,+ name: row.name_highlighted.unwrap_or(row.name),+ updated_at: DateTime::<Utc>::from_naive_utc_and_offset(row.updated_at, Utc),})- .collect())+ .collect();++ Ok(SearchCursorOption::paginate(results, limit as usize))}/// Searches chats by owner or IDs@@ -59,21 +87,40 @@ async fn owner_search<'a>(macro_user_id: &MacroUserId<Lowercase<'a>>,chat_ids: &[Uuid],search_pattern: String,+ highlight_pattern: String,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> 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())))+ .unwrap_or((None, None));++ // Fetch limit + 1 to determine if there are more results+ let fetch_limit = limit as i64 + 1;+let rows = sqlx::query!(r#"SELECTc.id as entity_id,- c.name+ c.name,+ regexp_replace(+ c.name,+ $7,+ '<macro_em>\1</macro_em>',+ 'gi'+ ) as name_highlighted,+ c."updatedAt" as updated_atFROM "Chat" cWHERE (c."userId" = $1 OR c.id = ANY($2))AND c."deletedAt" IS NULLAND c.name ILIKE $3- ORDER BY c."updatedAt" DESC+ AND (+ $5::timestamptz IS NULL+ OR (c."updatedAt", c.id) < ($5, $6)+ )+ ORDER BY c."updatedAt" DESC, c.id DESCLIMIT $4- OFFSET $5"#,macro_user_id.as_ref(),&chat_ids@@ -81,25 +128,39 @@ async fn owner_search<'a>(.map(|id| id.to_string()).collect::<Vec<String>>(),search_pattern,- limit as i64,- offset as i64,+ fetch_limit,+ cursor_updated_at,+ cursor_entity_id,+ highlight_pattern,).fetch_all(db).await.map_err(NameSearchError::DatabaseError)?;- Ok(rows+ let results: Vec<NameSearchResult> = rows.into_iter().map(|row| NameSearchResult {entity_id: row.entity_id.parse().unwrap(),entity_type: SearchEntityType::Chats,- name: row.name,+ name: row.name_highlighted.unwrap_or(row.name),+ updated_at: DateTime::<Utc>::from_naive_utc_and_offset(row.updated_at, Utc),})- .collect())+ .collect();++ Ok(SearchCursorOption::paginate(results, limit as usize))}/// Searches over the user's chats by name#[tracing::instrument(skip(db), err)]+#[cfg_attr(+ not(test),+ cached(+ 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()) }"#+ )+)]pub async fn search_chat_names<'a>(db: &Pool<Postgres>,macro_user_id: &MacroUserId<Lowercase<'a>>,@@ -107,18 +168,36 @@ pub async fn search_chat_names<'a>(term: String,ids_only: bool,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {if term.is_empty() {return Err(NameSearchError::EmptySearchTerm);}let search_pattern = format!("%{term}%");+ let highlight_pattern = format!("({})", escape_regex(&term));if ids_only {- ids_search(db, chat_ids, search_pattern, limit, offset).await+ ids_search(+ db,+ chat_ids,+ search_pattern,+ highlight_pattern,+ limit,+ cursor,+ )+ .await} else {- owner_search(db, macro_user_id, chat_ids, search_pattern, limit, offset).await+ owner_search(+ db,+ macro_user_id,+ chat_ids,+ search_pattern,+ highlight_pattern,+ limit,+ cursor,+ )+ .await}}diff --git a/rust/cloud-storage/name_search/src/chat/test.rs b/rust/cloud-storage/name_search/src/chat/test.rsindex c803bf30d5..f7c3594bec 100644--- a/rust/cloud-storage/name_search/src/chat/test.rs+++ b/rust/cloud-storage/name_search/src/chat/test.rs@@ -1,6 +1,7 @@//! Tests for chat moduleuse macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_search_cursor::SearchCursorOption;use sqlx::{Pool, Postgres};use uuid::Uuid;@@ -15,7 +16,7 @@ async fn test_search_chat_names_empty_term(pool: Pool<Postgres>) -> anyhow::Resu.map(|l| l.lowercase()).unwrap();- let result = search_chat_names(&pool, &user_id, &[], "".to_string(), false, 10, 0).await;+ let result = search_chat_names(&pool, &user_id, &[], "".to_string(), false, 10, None).await;assert!(result.is_err());assert!(matches!(@@ -37,7 +38,8 @@ async fn test_search_chat_names_ids_only_with_empty_ids(.map(|l| l.lowercase()).unwrap();- let result = search_chat_names(&pool, &user_id, &[], "project".to_string(), true, 10, 0).await;+ let result =+ search_chat_names(&pool, &user_id, &[], "project".to_string(), true, 10, None).await;assert!(result.is_err());assert!(matches!(@@ -64,33 +66,39 @@ async fn test_search_chat_names_ids_only_mode(pool: Pool<Postgres>) -> anyhow::RUuid::parse_str("55555555-5555-5555-5555-555555555555")?, // Budget Discussion - won't match];- let results = search_chat_names(+ let response = search_chat_names(&pool,&user_id,&chat_ids,"project".to_string(),true,10,- 0,+ None,).await?;// Should only return the 2 chats that match "project" from the provided IDs- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);// Verify results contain expected chats (ordered by updatedAt DESC)assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");- assert_eq!(results[0].entity_type, SearchEntityType::Chats);- assert_eq!(results[0].name, "Project Review Chat");+ assert_eq!(response.items[0].entity_type, SearchEntityType::Chats);+ assert_eq!(+ response.items[0].name,+ "<macro_em>Project</macro_em> Review Chat"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"11111111-1111-1111-1111-111111111111");- assert_eq!(results[1].name, "Project Planning Chat");+ assert_eq!(+ response.items[1].name,+ "<macro_em>Project</macro_em> Planning Chat"+ );Ok(())}@@ -107,24 +115,30 @@ async fn test_search_chat_names_normal_mode_owned_chats(.unwrap();// Search for "project" across all user1's owned chats- let results =- search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, 0).await?;+ let response =+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, None).await?;// Should return 3 chats matching "project" (2 lowercase + 1 uppercase)- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);// Verify ordering by updatedAt DESCassert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"66666666-6666-6666-6666-666666666666");- assert_eq!(results[0].name, "IMPORTANT PROJECT");+ assert_eq!(+ response.items[0].name,+ "IMPORTANT <macro_em>PROJECT</macro_em>"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");- assert_eq!(results[1].name, "Project Review Chat");+ assert_eq!(+ response.items[1].name,+ "<macro_em>Project</macro_em> Review Chat"+ );Ok(())}@@ -139,22 +153,22 @@ async fn test_search_chat_names_case_insensitive(pool: Pool<Postgres>) -> anyhow.unwrap();// Search with uppercase term should match both lowercase and uppercase names- let results =- search_chat_names(&pool, &user_id, &[], "PROJECT".to_string(), false, 10, 0).await?;+ let response =+ search_chat_names(&pool, &user_id, &[], "PROJECT".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);// Search with lowercase term should also match both- let results =- search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, 0).await?;+ let response =+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);// Search with mixed case- let results =- search_chat_names(&pool, &user_id, &[], "PrOjEcT".to_string(), false, 10, 0).await?;+ let response =+ search_chat_names(&pool, &user_id, &[], "PrOjEcT".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);Ok(())}@@ -171,28 +185,31 @@ async fn test_search_chat_names_with_shared_chats(pool: Pool<Postgres>) -> anyho// Include a chat from user3 (shared via chat_ids parameter)let shared_chat_ids = vec![Uuid::parse_str("99999999-9999-9999-9999-999999999999")?];- let results = search_chat_names(+ let response = search_chat_names(&pool,&user_id,&shared_chat_ids,"project".to_string(),false,10,- 0,+ None,).await?;// Should return user1's 3 "project" chats + user3's 1 "project" chat- assert_eq!(results.len(), 4);+ assert_eq!(response.items.len(), 4);// Verify user3's chat is included- let user3_chat = results.iter().find(|r| {+ let user3_chat = response.items.iter().find(|r| {r.entity_id.to_string().eq("99999999-9999-9999-9999-999999999999")});assert!(user3_chat.is_some());- assert_eq!(user3_chat.unwrap().name, "User3 Shared Project");+ assert_eq!(+ user3_chat.unwrap().name,+ "User3 Shared <macro_em>Project</macro_em>"+ );Ok(())}@@ -207,21 +224,24 @@ async fn test_search_chat_names_pagination_limit(pool: Pool<Postgres>) -> anyhow.unwrap();// Search with limit of 2- let results =- search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 2, 0).await?;+ let response =+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 2, None).await?;- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);// Should get the 2 most recently updated chats with "project"assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"66666666-6666-6666-6666-666666666666");assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");+ // Should have a next_cursor since there are more results+ assert!(response.cursor.has_more());+Ok(())}@@ -229,23 +249,67 @@ async fn test_search_chat_names_pagination_limit(pool: Pool<Postgres>) -> anyhowmigrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("chat")))]-async fn test_search_chat_names_pagination_offset(pool: Pool<Postgres>) -> anyhow::Result<()> {+async fn test_search_chat_names_pagination_cursor(pool: Pool<Postgres>) -> anyhow::Result<()> {let user_id = MacroUserId::parse_from_str("macro|[email protected]").map(|l| l.lowercase()).unwrap();- // Search with offset of 2- let results =- search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, 2).await?;+ // First page with limit of 2+ let first_response =+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 2, None).await?;++ assert_eq!(first_response.items.len(), 2);+ assert!(first_response.cursor.has_more());++ // Extract cursor for second page+ let cursor = match first_response.cursor {+ SearchCursorOption::NotDone(c) => c,+ SearchCursorOption::Done => panic!("Expected more results"),+ };- assert_eq!(results.len(), 1);+ // Second page using cursor+ let second_response = search_chat_names(+ &pool,+ &user_id,+ &[],+ "project".to_string(),+ false,+ 2,+ cursor,+ )+ .await?;- // Should skip the first 2 and get the next 1+ assert_eq!(second_response.items.len(), 1);++ // Should get the next chat (skipping the first 2)assert_eq!(- results[0].entity_id.to_string(),+ second_response.items[0].entity_id.to_string(),"11111111-1111-1111-1111-111111111111");+ // Should NOT have next_cursor since we've reached the end+ assert!(second_response.cursor.is_done());++ // Verify no overlap between pages+ let first_ids: Vec<String> = first_response+ .items+ .iter()+ .map(|r| r.entity_id.to_string())+ .collect();+ let second_ids: Vec<String> = second_response+ .items+ .iter()+ .map(|r| r.entity_id.to_string())+ .collect();++ for id in &first_ids {+ assert!(+ !second_ids.contains(id),+ "Found duplicate ID between pages: {}",+ id+ );+ }+Ok(())}@@ -259,18 +323,19 @@ async fn test_search_chat_names_no_results(pool: Pool<Postgres>) -> anyhow::Resu.unwrap();// Search for a term that doesn't match any chats- let results = search_chat_names(+ let response = search_chat_names(&pool,&user_id,&[],"nonexistent".to_string(),false,10,- 0,+ None,).await?;- assert_eq!(results.len(), 0);+ assert_eq!(response.items.len(), 0);+ assert!(response.cursor.is_done());Ok(())}@@ -285,20 +350,27 @@ async fn test_search_chat_names_partial_match(pool: Pool<Postgres>) -> anyhow::R.unwrap();// Search for partial term "meet" should match "meeting"- let results = search_chat_names(&pool, &user_id, &[], "meet".to_string(), false, 10, 0).await?;+ let response =+ search_chat_names(&pool, &user_id, &[], "meet".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"44444444-4444-4444-4444-444444444444");- assert_eq!(results[0].name, "Client Meeting");+ assert_eq!(+ response.items[0].name,+ "Client <macro_em>Meet</macro_em>ing"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"33333333-3333-3333-3333-333333333333");- assert_eq!(results[1].name, "Team Meeting Chat");+ assert_eq!(+ response.items[1].name,+ "Team <macro_em>Meet</macro_em>ing Chat"+ );Ok(())}@@ -313,11 +385,11 @@ async fn test_search_chat_names_user_isolation(pool: Pool<Postgres>) -> anyhow::.unwrap();// Search for "User2" - user1 should not see user2's private chats- let results =- search_chat_names(&pool, &user_id, &[], "User2".to_string(), false, 10, 0).await?;+ let response =+ search_chat_names(&pool, &user_id, &[], "User2".to_string(), false, 10, None).await?;// Should return 0 results (user2's chats are not owned by user1 and not shared)- assert_eq!(results.len(), 0);+ assert_eq!(response.items.len(), 0);Ok(())}@@ -332,18 +404,18 @@ async fn test_search_chat_names_excludes_soft_deleted(pool: Pool<Postgres>) -> a.unwrap();// Search for "project" - should NOT include soft-deleted chat- let results =- search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, 0).await?;+ let response =+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, None).await?;// Should NOT include the deleted chat (id: 77777777-7777-7777-7777-777777777777)- assert!(!results.iter().any(|r| {+ assert!(!response.items.iter().any(|r| {r.entity_id.to_string().eq("77777777-7777-7777-7777-777777777777")}));// Should include non-deleted chats- assert!(results.iter().any(|r| {+ assert!(response.items.iter().any(|r| {r.entity_id.to_string().eq("11111111-1111-1111-1111-111111111111")diff --git a/rust/cloud-storage/name_search/src/document.rs b/rust/cloud-storage/name_search/src/document.rsindex b9f52ffed3..6dd5ef587f 100644--- a/rust/cloud-storage/name_search/src/document.rs+++ b/rust/cloud-storage/name_search/src/document.rs@@ -1,56 +1,84 @@//! This module contains logic for searching documents by name+#[cfg(not(test))]+use cached::proc_macro::cached;+use chrono::{DateTime, Utc};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};use sqlx::{Pool, Postgres};use uuid::Uuid;-use crate::{NameSearchError, NameSearchResult, SearchEntityType};+use crate::{NameSearchError, NameSearchResult, PaginatedResult, SearchEntityType, escape_regex};/// Searches documents by IDs onlyasync fn ids_search(db: &Pool<Postgres>,document_ids: &[Uuid],search_pattern: String,+ highlight_pattern: String,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {if document_ids.is_empty() {return Err(NameSearchError::EmptyIdsWithIdsOnly);}+ let (cursor_updated_at, cursor_entity_id) = cursor+ .as_ref()+ .map(|c| (Some(c.updated_at), Some(c.entity_id.to_string())))+ .unwrap_or((None, None));++ // Fetch limit + 1 to determine if there are more results+ let fetch_limit = limit as i64 + 1;+let rows = sqlx::query!(r#"SELECT- d.id as entity_id,- d.name -- If there is a name match name obviously name exists+ d.id as entity_id,+ d.name,+ regexp_replace(+ d.name,+ $6,+ '<macro_em>\1</macro_em>',+ 'gi'+ ) as name_highlighted,+ d."updatedAt" as updated_atFROM "Document" dWHERE d.id = ANY($1)AND d."deletedAt" IS NULLAND d.name ILIKE $2- ORDER BY d."updatedAt" DESC+ AND (+ $4::timestamptz IS NULL+ OR (d."updatedAt", d.id) < ($4, $5)+ )+ ORDER BY d."updatedAt" DESC, d.id DESCLIMIT $3- OFFSET $4"#,&document_ids.iter().map(|d| d.to_string()).collect::<Vec<String>>(),search_pattern,- limit as i64,- offset as i64,+ fetch_limit,+ cursor_updated_at,+ cursor_entity_id,+ highlight_pattern,).fetch_all(db).await.map_err(NameSearchError::DatabaseError)?;- Ok(rows+ let results: Vec<NameSearchResult> = rows.into_iter().map(|row| NameSearchResult {entity_id: row.entity_id.parse().unwrap(),entity_type: SearchEntityType::Documents,- name: row.name,+ name: row.name_highlighted.unwrap_or(row.name),+ updated_at: DateTime::<Utc>::from_naive_utc_and_offset(row.updated_at, Utc),})- .collect())+ .collect();++ Ok(SearchCursorOption::paginate(results, limit as usize))}/// Searches documents by owner or IDs@@ -59,21 +87,40 @@ async fn owner_search<'a>(macro_user_id: &MacroUserId<Lowercase<'a>>,document_ids: &[Uuid],search_pattern: String,+ highlight_pattern: String,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> 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())))+ .unwrap_or((None, None));++ // Fetch limit + 1 to determine if there are more results+ let fetch_limit = limit as i64 + 1;+let rows = sqlx::query!(r#"SELECTd.id as entity_id,- d.name+ d.name,+ regexp_replace(+ d.name,+ $7,+ '<macro_em>\1</macro_em>',+ 'gi'+ ) as name_highlighted,+ d."updatedAt" as updated_atFROM "Document" dWHERE (d.owner = $1 OR d.id = ANY($2))AND d."deletedAt" IS NULLAND d.name ILIKE $3- ORDER BY d."updatedAt" DESC+ AND (+ $5::timestamptz IS NULL+ OR (d."updatedAt", d.id) < ($5, $6)+ )+ ORDER BY d."updatedAt" DESC, d.id DESCLIMIT $4- OFFSET $5"#,macro_user_id.as_ref(),&document_ids@@ -81,25 +128,39 @@ async fn owner_search<'a>(.map(|d| d.to_string()).collect::<Vec<String>>(),search_pattern,- limit as i64,- offset as i64,+ fetch_limit,+ cursor_updated_at,+ cursor_entity_id,+ highlight_pattern,).fetch_all(db).await.map_err(NameSearchError::DatabaseError)?;- Ok(rows+ let results: Vec<NameSearchResult> = rows.into_iter().map(|row| NameSearchResult {entity_id: row.entity_id.parse().unwrap(),entity_type: SearchEntityType::Documents,- name: row.name,+ name: row.name_highlighted.unwrap_or(row.name),+ updated_at: DateTime::<Utc>::from_naive_utc_and_offset(row.updated_at, Utc),})- .collect())+ .collect();++ Ok(SearchCursorOption::paginate(results, limit as usize))}/// Searches over the users documents by name#[tracing::instrument(skip(db), err)]+#[cfg_attr(+ not(test),+ cached(+ 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()) }"#+ )+)]pub async fn search_document_names<'a>(db: &Pool<Postgres>,macro_user_id: &MacroUserId<Lowercase<'a>>,@@ -107,24 +168,34 @@ pub async fn search_document_names<'a>(term: String,ids_only: bool,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {if term.is_empty() {return Err(NameSearchError::EmptySearchTerm);}let search_pattern = format!("%{term}%");+ let highlight_pattern = format!("({})", escape_regex(&term));if ids_only {- ids_search(db, document_ids, search_pattern, limit, offset).await+ ids_search(+ db,+ document_ids,+ search_pattern,+ highlight_pattern,+ limit,+ cursor,+ )+ .await} else {owner_search(db,macro_user_id,document_ids,search_pattern,+ highlight_pattern,limit,- offset,+ cursor,).await}diff --git a/rust/cloud-storage/name_search/src/document/test.rs b/rust/cloud-storage/name_search/src/document/test.rsindex 00d8dbc0c0..a9b6519fb3 100644--- a/rust/cloud-storage/name_search/src/document/test.rs+++ b/rust/cloud-storage/name_search/src/document/test.rs@@ -1,6 +1,7 @@//! Tests for document moduleuse macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_search_cursor::SearchCursorOption;use sqlx::{Pool, Postgres};use uuid::Uuid;@@ -15,7 +16,7 @@ async fn test_search_document_names_empty_term(pool: Pool<Postgres>) -> anyhow::.map(|l| l.lowercase()).unwrap();- let result = search_document_names(&pool, &user_id, &[], "".to_string(), false, 10, 0).await;+ let result = search_document_names(&pool, &user_id, &[], "".to_string(), false, 10, None).await;assert!(result.is_err());assert!(matches!(@@ -38,7 +39,7 @@ async fn test_search_document_names_ids_only_with_empty_ids(.unwrap();let result =- search_document_names(&pool, &user_id, &[], "report".to_string(), true, 10, 0).await;+ search_document_names(&pool, &user_id, &[], "report".to_string(), true, 10, None).await;assert!(result.is_err());assert!(matches!(@@ -65,25 +66,39 @@ async fn test_search_document_names_ids_only_mode(pool: Pool<Postgres>) -> anyhoUuid::parse_str("66666666-6666-6666-6666-666666666666")?, // Budget Analysis - won't match];- let results =- search_document_names(&pool, &user_id, &doc_ids, "report".to_string(), true, 10, 0).await?;+ let response = search_document_names(+ &pool,+ &user_id,+ &doc_ids,+ "report".to_string(),+ true,+ 10,+ None,+ )+ .await?;// Should only return the 2 documents that match "report" from the provided IDs- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);// Verify results contain expected documents (ordered by updatedAt DESC)assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");- assert_eq!(results[0].entity_type, SearchEntityType::Documents);- assert_eq!(results[0].name, "Sales Report December");+ assert_eq!(response.items[0].entity_type, SearchEntityType::Documents);+ assert_eq!(+ response.items[0].name,+ "Sales <macro_em>Report</macro_em> December"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"11111111-1111-1111-1111-111111111111");- assert_eq!(results[1].name, "Quarterly Report 2024");+ assert_eq!(+ response.items[1].name,+ "Quarterly <macro_em>Report</macro_em> 2024"+ );Ok(())}@@ -100,24 +115,30 @@ async fn test_search_document_names_normal_mode_owned_documents(.unwrap();// Search for "report" across all user1's owned documents- let results =- search_document_names(&pool, &user_id, &[], "report".to_string(), false, 10, 0).await?;+ let response =+ search_document_names(&pool, &user_id, &[], "report".to_string(), false, 10, None).await?;// Should return 4 documents matching "report" (3 lowercase + 1 uppercase)- assert_eq!(results.len(), 4);+ assert_eq!(response.items.len(), 4);// Verify ordering by updatedAt DESCassert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"88888888-8888-8888-8888-888888888888");- assert_eq!(results[0].name, "ANNUAL REPORT 2024");+ assert_eq!(+ response.items[0].name,+ "ANNUAL <macro_em>REPORT</macro_em> 2024"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"33333333-3333-3333-3333-333333333333");- assert_eq!(results[1].name, "Financial Report Q3");+ assert_eq!(+ response.items[1].name,+ "Financial <macro_em>Report</macro_em> Q3"+ );Ok(())}@@ -132,22 +153,22 @@ async fn test_search_document_names_case_insensitive(pool: Pool<Postgres>) -> an.unwrap();// Search with uppercase term should match both lowercase and uppercase names- let results =- search_document_names(&pool, &user_id, &[], "REPORT".to_string(), false, 10, 0).await?;+ let response =+ search_document_names(&pool, &user_id, &[], "REPORT".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 4);+ assert_eq!(response.items.len(), 4);// Search with lowercase term should also match both- let results =- search_document_names(&pool, &user_id, &[], "report".to_string(), false, 10, 0).await?;+ let response =+ search_document_names(&pool, &user_id, &[], "report".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 4);+ assert_eq!(response.items.len(), 4);// Search with mixed case- let results =- search_document_names(&pool, &user_id, &[], "RePoRt".to_string(), false, 10, 0).await?;+ let response =+ search_document_names(&pool, &user_id, &[], "RePoRt".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 4);+ assert_eq!(response.items.len(), 4);Ok(())}@@ -166,28 +187,31 @@ async fn test_search_document_names_with_shared_documents(// Include a document from user3 (shared via document_ids parameter)let shared_doc_ids = vec![Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?];- let results = search_document_names(+ let response = search_document_names(&pool,&user_id,&shared_doc_ids,"report".to_string(),false,10,- 0,+ None,).await?;// Should return user1's 4 "report" documents + user3's 1 "report" document- assert_eq!(results.len(), 5);+ assert_eq!(response.items.len(), 5);// Verify user3's document is included- let user3_doc = results.iter().find(|r| {+ let user3_doc = response.items.iter().find(|r| {r.entity_id.to_string().eq("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")});assert!(user3_doc.is_some());- assert_eq!(user3_doc.unwrap().name, "User3 Report Shared");+ assert_eq!(+ user3_doc.unwrap().name,+ "User3 <macro_em>Report</macro_em> Shared"+ );Ok(())}@@ -202,21 +226,24 @@ async fn test_search_document_names_pagination_limit(pool: Pool<Postgres>) -> an.unwrap();// Search with limit of 2- let results =- search_document_names(&pool, &user_id, &[], "report".to_string(), false, 2, 0).await?;+ let response =+ search_document_names(&pool, &user_id, &[], "report".to_string(), false, 2, None).await?;- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);// Should get the 2 most recently updated documents with "report"assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"88888888-8888-8888-8888-888888888888");assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"33333333-3333-3333-3333-333333333333");+ // Should have a next_cursor since there are more results+ assert!(response.cursor.has_more());+Ok(())}@@ -224,27 +251,63 @@ async fn test_search_document_names_pagination_limit(pool: Pool<Postgres>) -> anmigrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("document")))]-async fn test_search_document_names_pagination_offset(pool: Pool<Postgres>) -> anyhow::Result<()> {+async fn test_search_document_names_pagination_cursor(pool: Pool<Postgres>) -> anyhow::Result<()> {let user_id = MacroUserId::parse_from_str("macro|[email protected]").map(|l| l.lowercase()).unwrap();- // Search with offset of 2- let results =- search_document_names(&pool, &user_id, &[], "report".to_string(), false, 10, 2).await?;+ // First page with limit of 2+ let first_response =+ search_document_names(&pool, &user_id, &[], "report".to_string(), false, 2, None).await?;++ assert_eq!(first_response.items.len(), 2);+ assert!(first_response.cursor.has_more());++ // Extract cursor for second page+ let cursor = match first_response.cursor {+ SearchCursorOption::NotDone(c) => c,+ SearchCursorOption::Done => panic!("Expected more results"),+ };- assert_eq!(results.len(), 2);+ // Second page using cursor+ let second_response =+ search_document_names(&pool, &user_id, &[], "report".to_string(), false, 2, cursor).await?;- // Should skip the first 2 and get the next 2+ assert_eq!(second_response.items.len(), 2);++ // Should get the next 2 documents (skipping the first 2)assert_eq!(- results[0].entity_id.to_string(),+ second_response.items[0].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");assert_eq!(- results[1].entity_id.to_string(),+ second_response.items[1].entity_id.to_string(),"11111111-1111-1111-1111-111111111111");+ // Should NOT have next_cursor since we've reached the end (fetched limit+1, got only 2)+ assert!(second_response.cursor.is_done());++ // Verify no overlap between pages+ let first_ids: Vec<String> = first_response+ .items+ .iter()+ .map(|r| r.entity_id.to_string())+ .collect();+ let second_ids: Vec<String> = second_response+ .items+ .iter()+ .map(|r| r.entity_id.to_string())+ .collect();++ for id in &first_ids {+ assert!(+ !second_ids.contains(id),+ "Found duplicate ID between pages: {}",+ id+ );+ }+Ok(())}@@ -258,18 +321,19 @@ async fn test_search_document_names_no_results(pool: Pool<Postgres>) -> anyhow::.unwrap();// Search for a term that doesn't match any documents- let results = search_document_names(+ let response = search_document_names(&pool,&user_id,&[],"nonexistent".to_string(),false,10,- 0,+ None,).await?;- assert_eq!(results.len(), 0);+ assert_eq!(response.items.len(), 0);+ assert!(response.cursor.is_done());Ok(())}@@ -284,21 +348,27 @@ async fn test_search_document_names_partial_match(pool: Pool<Postgres>) -> anyho.unwrap();// Search for partial term "meet" should match "meeting"- let results =- search_document_names(&pool, &user_id, &[], "meet".to_string(), false, 10, 0).await?;+ let response =+ search_document_names(&pool, &user_id, &[], "meet".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"55555555-5555-5555-5555-555555555555");- assert_eq!(results[0].name, "Client Meeting Agenda");+ assert_eq!(+ response.items[0].name,+ "Client <macro_em>Meet</macro_em>ing Agenda"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"44444444-4444-4444-4444-444444444444");- assert_eq!(results[1].name, "Team Meeting Notes");+ assert_eq!(+ response.items[1].name,+ "Team <macro_em>Meet</macro_em>ing Notes"+ );Ok(())}@@ -313,11 +383,11 @@ async fn test_search_document_names_user_isolation(pool: Pool<Postgres>) -> anyh.unwrap();// Search for "User2" - user1 should not see user2's private documents- let results =- search_document_names(&pool, &user_id, &[], "User2".to_string(), false, 10, 0).await?;+ let response =+ search_document_names(&pool, &user_id, &[], "User2".to_string(), false, 10, None).await?;// Should return 0 results (user2's documents are not owned by user1 and not shared)- assert_eq!(results.len(), 0);+ assert_eq!(response.items.len(), 0);Ok(())}diff --git a/rust/cloud-storage/name_search/src/email.rs b/rust/cloud-storage/name_search/src/email.rsindex c54dd1eabc..3c09a0bcc7 100644--- a/rust/cloud-storage/name_search/src/email.rs+++ b/rust/cloud-storage/name_search/src/email.rs@@ -1,21 +1,34 @@//! This module contains logic for searching email threads by oldest message subject-use crate::{NameSearchError, NameSearchResult, SearchEntityType};+#[cfg(not(test))]+use cached::proc_macro::cached;use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};use sqlx::{Pool, Postgres};use uuid::Uuid;+use crate::{NameSearchError, NameSearchResult, PaginatedResult, SearchEntityType, escape_regex};+/// Searches email threads by IDs onlyasync fn ids_search(db: &Pool<Postgres>,thread_ids: &[Uuid],search_pattern: String,+ highlight_pattern: String,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {if thread_ids.is_empty() {return Err(NameSearchError::EmptyIdsWithIdsOnly);}+ let (cursor_updated_at, cursor_entity_id) = cursor+ .as_ref()+ .map(|c| (Some(c.updated_at), Some(c.entity_id)))+ .unwrap_or((None, None));++ // Fetch limit + 1 to determine if there are more results+ let fetch_limit = limit as i64 + 1;+let rows = sqlx::query!(r#"WITH oldest_messages AS (@@ -28,31 +41,48 @@ async fn ids_search()SELECTt.id as entity_id,- om.subject as "name!"+ om.subject as "name!",+ regexp_replace(+ om.subject,+ $6,+ '<macro_em>\1</macro_em>',+ 'gi'+ ) as name_highlighted,+ t.latest_non_spam_message_ts as updated_atFROM email_threads tINNER JOIN oldest_messages om ON om.thread_id = t.idWHERE om.subject ILIKE $2- ORDER BY t.latest_non_spam_message_ts DESC+ AND (+ $4::timestamptz IS NULL+ OR (t.latest_non_spam_message_ts, t.id) < ($4, $5)+ )+ ORDER BY t.latest_non_spam_message_ts DESC, t.id DESCLIMIT $3- OFFSET $4"#,thread_ids,search_pattern,- limit as i64,- offset as i64,+ fetch_limit,+ cursor_updated_at,+ cursor_entity_id,+ highlight_pattern,).fetch_all(db).await.map_err(NameSearchError::DatabaseError)?;- Ok(rows+ let results: Vec<NameSearchResult> = rows.into_iter()- .map(|row| NameSearchResult {- entity_id: row.entity_id,- entity_type: SearchEntityType::Emails,- name: row.name,+ .filter_map(|row| {+ row.updated_at.map(|updated_at| NameSearchResult {+ entity_id: row.entity_id,+ entity_type: SearchEntityType::Emails,+ name: row.name_highlighted.unwrap_or(row.name),+ updated_at,+ })})- .collect())+ .collect();++ Ok(SearchCursorOption::paginate(results, limit as usize))}/// Searches email threads by owner or IDs@@ -61,9 +91,18 @@ async fn owner_search<'a>(macro_user_id: &MacroUserId<Lowercase<'a>>,thread_ids: &[Uuid],search_pattern: String,+ highlight_pattern: String,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {+ let (cursor_updated_at, cursor_entity_id) = cursor+ .as_ref()+ .map(|c| (Some(c.updated_at), Some(c.entity_id)))+ .unwrap_or((None, None));++ // Fetch limit + 1 to determine if there are more results+ let fetch_limit = limit as i64 + 1;+let rows = sqlx::query!(r#"WITH oldest_messages AS (@@ -79,40 +118,66 @@ async fn owner_search<'a>()SELECTt.id as entity_id,- om.subject as "name!"+ om.subject as "name!",+ regexp_replace(+ om.subject,+ $8,+ '<macro_em>\1</macro_em>',+ 'gi'+ ) as name_highlighted,+ t.latest_non_spam_message_ts as updated_atFROM email_threads tINNER JOIN oldest_messages om ON om.thread_id = t.idWHERE t.link_id IN (SELECT id FROM email_links WHERE macro_id = $1)AND om.subject ILIKE $4- ORDER BY t.latest_non_spam_message_ts DESC+ AND (+ $6::timestamptz IS NULL+ OR (t.latest_non_spam_message_ts, t.id) < ($6, $7)+ )+ ORDER BY t.latest_non_spam_message_ts DESC, t.id DESCLIMIT $5- OFFSET $6"#,macro_user_id.as_ref(),&thread_ids,thread_ids.is_empty(), // If empty, don't filter by thread_idssearch_pattern,- limit as i64,- offset as i64,+ fetch_limit,+ cursor_updated_at,+ cursor_entity_id,+ highlight_pattern,).fetch_all(db).await.map_err(NameSearchError::DatabaseError)?;- Ok(rows+ let results: Vec<NameSearchResult> = rows.into_iter()- .map(|row| NameSearchResult {- entity_id: row.entity_id,- entity_type: SearchEntityType::Emails,- name: row.name,+ .filter_map(|row| {+ row.updated_at.map(|updated_at| NameSearchResult {+ entity_id: row.entity_id,+ entity_type: SearchEntityType::Emails,+ name: row.name_highlighted.unwrap_or(row.name),+ updated_at,+ })})- .collect())+ .collect();++ Ok(SearchCursorOption::paginate(results, limit as usize))}/// Searches over email threads by the subject of the oldest message in each thread#[tracing::instrument(skip(db), err)]+#[cfg_attr(+ not(test),+ cached(+ time = 30,+ result = true,+ key = "String",+ convert = r#"{ format!("{}-{:?}-{}-{}-{}-{}", macro_user_id.as_ref(), thread_ids, term, ids_only, limit, cursor.as_ref().map(|c| format!("{}-{}", c.entity_id, c.updated_at)).unwrap_or_default()) }"#+ )+)]pub async fn search_email_subjects<'a>(db: &Pool<Postgres>,macro_user_id: &MacroUserId<Lowercase<'a>>,@@ -120,18 +185,36 @@ pub async fn search_email_subjects<'a>(term: String,ids_only: bool,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {if term.is_empty() {return Err(NameSearchError::EmptySearchTerm);}let search_pattern = format!("%{term}%");+ let highlight_pattern = format!("({})", escape_regex(&term));if ids_only {- ids_search(db, thread_ids, search_pattern, limit, offset).await+ ids_search(+ db,+ thread_ids,+ search_pattern,+ highlight_pattern,+ limit,+ cursor,+ )+ .await} else {- owner_search(db, macro_user_id, thread_ids, search_pattern, limit, offset).await+ owner_search(+ db,+ macro_user_id,+ thread_ids,+ search_pattern,+ highlight_pattern,+ limit,+ cursor,+ )+ .await}}diff --git a/rust/cloud-storage/name_search/src/email/test.rs b/rust/cloud-storage/name_search/src/email/test.rsindex bf7ea0ca28..67f9bf9f68 100644--- a/rust/cloud-storage/name_search/src/email/test.rs+++ b/rust/cloud-storage/name_search/src/email/test.rs@@ -1,6 +1,7 @@//! Tests for email moduleuse macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_search_cursor::SearchCursorOption;use sqlx::{Pool, Postgres};use uuid::Uuid;@@ -15,7 +16,7 @@ async fn test_search_email_subjects_empty_term(pool: Pool<Postgres>) -> anyhow::.map(|l| l.lowercase()).unwrap();- let result = search_email_subjects(&pool, &user_id, &[], "".to_string(), false, 10, 0).await;+ let result = search_email_subjects(&pool, &user_id, &[], "".to_string(), false, 10, None).await;assert!(result.is_err());assert!(matches!(@@ -38,7 +39,7 @@ async fn test_search_email_subjects_ids_only_with_empty_ids(.unwrap();let result =- search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), true, 10, 0).await;+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), true, 10, None).await;assert!(result.is_err());assert!(matches!(@@ -65,33 +66,39 @@ async fn test_search_email_subjects_ids_only_mode(pool: Pool<Postgres>) -> anyhoUuid::parse_str("55555555-5555-5555-5555-555555555555")?, // Weekly Update - won't match];- let results = search_email_subjects(+ let response = search_email_subjects(&pool,&user_id,&thread_ids,"invoice".to_string(),true,10,- 0,+ None,).await?;// Should only return the 2 threads that match "invoice" from the provided IDs- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);// Verify results contain expected threads (ordered by latest_non_spam_message_ts DESC)assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");- assert_eq!(results[0].entity_type, SearchEntityType::Emails);- assert_eq!(results[0].name, "Re: Monthly Invoice - December");+ assert_eq!(response.items[0].entity_type, SearchEntityType::Emails);+ assert_eq!(+ response.items[0].name,+ "Re: Monthly <macro_em>Invoice</macro_em> - December"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"11111111-1111-1111-1111-111111111111");- assert_eq!(results[1].name, "Invoice from Q1 2024");+ assert_eq!(+ response.items[1].name,+ "<macro_em>Invoice</macro_em> from Q1 2024"+ );Ok(())}@@ -108,24 +115,30 @@ async fn test_search_email_subjects_normal_mode_owned_threads(.unwrap();// Search for "invoice" across all user1's email threads- let results =- search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, 0).await?;+ let response =+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, None).await?;// Should return 3 threads matching "invoice" (2 with "invoice" + 1 with "INVOICE")- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);// Verify ordering by latest_non_spam_message_ts DESCassert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"66666666-6666-6666-6666-666666666666");- assert_eq!(results[0].name, "IMPORTANT: INVOICE DUE");+ assert_eq!(+ response.items[0].name,+ "IMPORTANT: <macro_em>INVOICE</macro_em> DUE"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");- assert_eq!(results[1].name, "Re: Monthly Invoice - December");+ assert_eq!(+ response.items[1].name,+ "Re: Monthly <macro_em>Invoice</macro_em> - December"+ );Ok(())}@@ -140,22 +153,22 @@ async fn test_search_email_subjects_case_insensitive(pool: Pool<Postgres>) -> an.unwrap();// Search with uppercase term should match both lowercase and uppercase subjects- let results =- search_email_subjects(&pool, &user_id, &[], "INVOICE".to_string(), false, 10, 0).await?;+ let response =+ search_email_subjects(&pool, &user_id, &[], "INVOICE".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);// Search with lowercase term should also match both- let results =- search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, 0).await?;+ let response =+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);// Search with mixed case- let results =- search_email_subjects(&pool, &user_id, &[], "InVoIcE".to_string(), false, 10, 0).await?;+ let response =+ search_email_subjects(&pool, &user_id, &[], "InVoIcE".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);Ok(())}@@ -177,20 +190,20 @@ async fn test_search_email_subjects_with_shared_threads(// so it won't be accessible to user1.let user3_thread_id = vec![Uuid::parse_str("99999999-9999-9999-9999-999999999999")?];- let results = search_email_subjects(+ let response = search_email_subjects(&pool,&user_id,&user3_thread_id,"invoice".to_string(),false,10,- 0,+ None,).await?;// Should return 0 results because user3's thread doesn't belong to user1's link_id// Email isolation is enforced via link_id, not just thread ownership- assert_eq!(results.len(), 0);+ assert_eq!(response.items.len(), 0);Ok(())}@@ -205,21 +218,24 @@ async fn test_search_email_subjects_pagination_limit(pool: Pool<Postgres>) -> an.unwrap();// Search with limit of 2- let results =- search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 2, 0).await?;+ let response =+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 2, None).await?;- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);// Should get the 2 most recently updated threads with "invoice"assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"66666666-6666-6666-6666-666666666666");assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");+ // Should have a next_cursor since there are more results+ assert!(response.cursor.has_more());+Ok(())}@@ -227,23 +243,67 @@ async fn test_search_email_subjects_pagination_limit(pool: Pool<Postgres>) -> anmigrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("email")))]-async fn test_search_email_subjects_pagination_offset(pool: Pool<Postgres>) -> anyhow::Result<()> {+async fn test_search_email_subjects_pagination_cursor(pool: Pool<Postgres>) -> anyhow::Result<()> {let user_id = MacroUserId::parse_from_str("macro|[email protected]").map(|l| l.lowercase()).unwrap();- // Search with offset of 2- let results =- search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, 2).await?;+ // First page with limit of 2+ let first_response =+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 2, None).await?;++ assert_eq!(first_response.items.len(), 2);+ assert!(first_response.cursor.has_more());++ // Extract cursor for second page+ let cursor = match first_response.cursor {+ SearchCursorOption::NotDone(c) => c,+ SearchCursorOption::Done => panic!("Expected more results"),+ };++ // Second page using cursor+ let second_response = search_email_subjects(+ &pool,+ &user_id,+ &[],+ "invoice".to_string(),+ false,+ 2,+ cursor,+ )+ .await?;- assert_eq!(results.len(), 1);+ assert_eq!(second_response.items.len(), 1);- // Should skip the first 2 and get the next 1+ // Should get the next thread (skipping the first 2)assert_eq!(- results[0].entity_id.to_string(),+ second_response.items[0].entity_id.to_string(),"11111111-1111-1111-1111-111111111111");+ // Should NOT have next_cursor since we've reached the end+ assert!(second_response.cursor.is_done());++ // Verify no overlap between pages+ let first_ids: Vec<String> = first_response+ .items+ .iter()+ .map(|r| r.entity_id.to_string())+ .collect();+ let second_ids: Vec<String> = second_response+ .items+ .iter()+ .map(|r| r.entity_id.to_string())+ .collect();++ for id in &first_ids {+ assert!(+ !second_ids.contains(id),+ "Found duplicate ID between pages: {}",+ id+ );+ }+Ok(())}@@ -257,18 +317,19 @@ async fn test_search_email_subjects_no_results(pool: Pool<Postgres>) -> anyhow::.unwrap();// Search for a term that doesn't match any email subjects- let results = search_email_subjects(+ let response = search_email_subjects(&pool,&user_id,&[],"nonexistent".to_string(),false,10,- 0,+ None,).await?;- assert_eq!(results.len(), 0);+ assert_eq!(response.items.len(), 0);+ assert!(response.cursor.is_done());Ok(())}@@ -283,21 +344,27 @@ async fn test_search_email_subjects_partial_match(pool: Pool<Postgres>) -> anyho.unwrap();// Search for partial term "meet" should match "meeting"- let results =- search_email_subjects(&pool, &user_id, &[], "meet".to_string(), false, 10, 0).await?;+ let response =+ search_email_subjects(&pool, &user_id, &[], "meet".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"44444444-4444-4444-4444-444444444444");- assert_eq!(results[0].name, "Fwd: Client Meeting Tomorrow");+ assert_eq!(+ response.items[0].name,+ "Fwd: Client <macro_em>Meet</macro_em>ing Tomorrow"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"33333333-3333-3333-3333-333333333333");- assert_eq!(results[1].name, "Team Meeting Notes");+ assert_eq!(+ response.items[1].name,+ "Team <macro_em>Meet</macro_em>ing Notes"+ );Ok(())}@@ -312,11 +379,11 @@ async fn test_search_email_subjects_user_isolation(pool: Pool<Postgres>) -> anyh.unwrap();// Search for "User2" - user1 should not see user2's private email threads- let results =- search_email_subjects(&pool, &user_id, &[], "User2".to_string(), false, 10, 0).await?;+ let response =+ search_email_subjects(&pool, &user_id, &[], "User2".to_string(), false, 10, None).await?;// Should return 0 results (user2's emails are not linked to user1)- assert_eq!(results.len(), 0);+ assert_eq!(response.items.len(), 0);Ok(())}@@ -338,36 +405,36 @@ async fn test_search_email_subjects_searches_oldest_message(// 3. Newest (2024-12-02): "Re: Re: Re: Payment Processed"// Searching for "Monthly Invoice" should find the thread because the oldest message matches- let results = search_email_subjects(+ let response = search_email_subjects(&pool,&user_id,&[],"Monthly Invoice".to_string(),false,10,- 0,+ None,).await?;- assert!(results.iter().any(|r| {+ assert!(response.items.iter().any(|r| {r.entity_id.to_string().eq("22222222-2222-2222-2222-222222222222")}));// Searching for "Payment Processed" should NOT find it because oldest message doesn't match- let results = search_email_subjects(+ let response = search_email_subjects(&pool,&user_id,&[],"Payment Processed".to_string(),false,10,- 0,+ None,).await?;- assert!(!results.iter().any(|r| {+ assert!(!response.items.iter().any(|r| {r.entity_id.to_string().eq("22222222-2222-2222-2222-222222222222")@@ -388,11 +455,12 @@ async fn test_search_email_subjects_multiple_messages_per_thread(.unwrap();// Thread 11111111 has multiple messages - should return thread only once with oldest subject- let results =- search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, 0).await?;+ let response =+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, None).await?;// Count how many times thread 11111111 appears (should be exactly once)- let count = results+ let count = response+ .items.iter().filter(|r| {r.entity_id@@ -403,7 +471,8 @@ async fn test_search_email_subjects_multiple_messages_per_thread(assert_eq!(count, 1);// Verify it returns the oldest message's subject- let thread_result = results+ let thread_result = response+ .items.iter().find(|r| {r.entity_id@@ -411,7 +480,10 @@ async fn test_search_email_subjects_multiple_messages_per_thread(.eq("11111111-1111-1111-1111-111111111111")}).unwrap();- assert_eq!(thread_result.name, "Invoice from Q1 2024");+ assert_eq!(+ thread_result.name,+ "<macro_em>Invoice</macro_em> from Q1 2024"+ );Ok(())}diff --git a/rust/cloud-storage/name_search/src/lib.rs b/rust/cloud-storage/name_search/src/lib.rsindex 5b2f6046d6..28d37551c3 100644--- a/rust/cloud-storage/name_search/src/lib.rs+++ b/rust/cloud-storage/name_search/src/lib.rs@@ -10,8 +10,24 @@ pub use chat::*;pub use document::*;pub use email::*;pub use models_opensearch::SearchEntityType;+use models_search_cursor::{PaginatedResult, SearchCursorAttributes};pub use project::*;+/// Escapes special regex characters in a search term+pub(crate) fn escape_regex(term: &str) -> String {+ let special_chars = [+ '\\', '.', '+', '*', '?', '(', ')', '[', ']', '{', '}', '^', '$', '|',+ ];+ let mut escaped = String::with_capacity(term.len() * 2);+ for c in term.chars() {+ if special_chars.contains(&c) {+ escaped.push('\\');+ }+ escaped.push(c);+ }+ escaped+}+/// Errors for name search crate#[derive(Debug, thiserror::Error)]pub enum NameSearchError {@@ -35,4 +51,16 @@ pub struct NameSearchResult {pub entity_type: SearchEntityType,/// The name that was matchedpub name: String,+ /// The timestamp used for cursor-based pagination+ pub updated_at: chrono::DateTime<chrono::Utc>,+}++impl SearchCursorAttributes for NameSearchResult {+ fn entity_id(&self) -> uuid::Uuid {+ self.entity_id+ }++ fn updated_at(&self) -> chrono::DateTime<chrono::Utc> {+ self.updated_at+ }}diff --git a/rust/cloud-storage/name_search/src/project.rs b/rust/cloud-storage/name_search/src/project.rsindex 322786368c..8b86696856 100644--- a/rust/cloud-storage/name_search/src/project.rs+++ b/rust/cloud-storage/name_search/src/project.rs@@ -1,56 +1,84 @@//! This module contains logic for searching projects by name+#[cfg(not(test))]+use cached::proc_macro::cached;+use chrono::{DateTime, Utc};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};use sqlx::{Pool, Postgres};use uuid::Uuid;-use crate::{NameSearchError, NameSearchResult, SearchEntityType};+use crate::{NameSearchError, NameSearchResult, PaginatedResult, SearchEntityType, escape_regex};/// Searches projects by IDs onlyasync fn ids_search(db: &Pool<Postgres>,project_ids: &[Uuid],search_pattern: String,+ highlight_pattern: String,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {if project_ids.is_empty() {return Err(NameSearchError::EmptyIdsWithIdsOnly);}+ let (cursor_updated_at, cursor_entity_id) = cursor+ .as_ref()+ .map(|c| (Some(c.updated_at), Some(c.entity_id.to_string())))+ .unwrap_or((None, None));++ // Fetch limit + 1 to determine if there are more results+ let fetch_limit = limit as i64 + 1;+let rows = sqlx::query!(r#"SELECT- p.id as entity_id,- p.name+ p.id as entity_id,+ p.name,+ regexp_replace(+ p.name,+ $6,+ '<macro_em>\1</macro_em>',+ 'gi'+ ) as name_highlighted,+ p."updatedAt" as updated_atFROM "Project" pWHERE p.id = ANY($1)AND p."deletedAt" IS NULLAND p.name ILIKE $2- ORDER BY p."updatedAt" DESC+ AND (+ $4::timestamptz IS NULL+ OR (p."updatedAt", p.id) < ($4, $5)+ )+ ORDER BY p."updatedAt" DESC, p.id DESCLIMIT $3- OFFSET $4"#,&project_ids.iter().map(|id| id.to_string()).collect::<Vec<String>>(),search_pattern,- limit as i64,- offset as i64,+ fetch_limit,+ cursor_updated_at,+ cursor_entity_id,+ highlight_pattern,).fetch_all(db).await.map_err(NameSearchError::DatabaseError)?;- Ok(rows+ let results: Vec<NameSearchResult> = rows.into_iter().map(|row| NameSearchResult {entity_id: row.entity_id.parse().unwrap(),entity_type: SearchEntityType::Projects,- name: row.name,+ name: row.name_highlighted.unwrap_or(row.name),+ updated_at: DateTime::<Utc>::from_naive_utc_and_offset(row.updated_at, Utc),})- .collect())+ .collect();++ Ok(SearchCursorOption::paginate(results, limit as usize))}/// Searches projects by owner or IDs@@ -59,21 +87,40 @@ async fn owner_search<'a>(macro_user_id: &MacroUserId<Lowercase<'a>>,project_ids: &[Uuid],search_pattern: String,+ highlight_pattern: String,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> 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())))+ .unwrap_or((None, None));++ // Fetch limit + 1 to determine if there are more results+ let fetch_limit = limit as i64 + 1;+let rows = sqlx::query!(r#"SELECTp.id as entity_id,- p.name+ p.name,+ regexp_replace(+ p.name,+ $7,+ '<macro_em>\1</macro_em>',+ 'gi'+ ) as name_highlighted,+ p."updatedAt" as updated_atFROM "Project" pWHERE (p."userId" = $1 OR p.id = ANY($2))AND p."deletedAt" IS NULLAND p.name ILIKE $3- ORDER BY p."updatedAt" DESC+ AND (+ $5::timestamptz IS NULL+ OR (p."updatedAt", p.id) < ($5, $6)+ )+ ORDER BY p."updatedAt" DESC, p.id DESCLIMIT $4- OFFSET $5"#,macro_user_id.as_ref(),&project_ids@@ -81,25 +128,39 @@ async fn owner_search<'a>(.map(|id| id.to_string()).collect::<Vec<String>>(),search_pattern,- limit as i64,- offset as i64,+ fetch_limit,+ cursor_updated_at,+ cursor_entity_id,+ highlight_pattern,).fetch_all(db).await.map_err(NameSearchError::DatabaseError)?;- Ok(rows+ let results: Vec<NameSearchResult> = rows.into_iter().map(|row| NameSearchResult {entity_id: row.entity_id.parse().unwrap(),entity_type: SearchEntityType::Projects,- name: row.name,+ name: row.name_highlighted.unwrap_or(row.name),+ updated_at: DateTime::<Utc>::from_naive_utc_and_offset(row.updated_at, Utc),})- .collect())+ .collect();++ Ok(SearchCursorOption::paginate(results, limit as usize))}/// Searches over the user's projects by name#[tracing::instrument(skip(db), err)]+#[cfg_attr(+ not(test),+ cached(+ 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()) }"#+ )+)]pub async fn search_project_names<'a>(db: &Pool<Postgres>,macro_user_id: &MacroUserId<Lowercase<'a>>,@@ -107,24 +168,34 @@ pub async fn search_project_names<'a>(term: String,ids_only: bool,limit: u32,- offset: u32,-) -> Result<Vec<NameSearchResult>, NameSearchError> {+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {if term.is_empty() {return Err(NameSearchError::EmptySearchTerm);}let search_pattern = format!("%{term}%");+ let highlight_pattern = format!("({})", escape_regex(&term));if ids_only {- ids_search(db, project_ids, search_pattern, limit, offset).await+ ids_search(+ db,+ project_ids,+ search_pattern,+ highlight_pattern,+ limit,+ cursor,+ )+ .await} else {owner_search(db,macro_user_id,project_ids,search_pattern,+ highlight_pattern,limit,- offset,+ cursor,).await}diff --git a/rust/cloud-storage/name_search/src/project/test.rs b/rust/cloud-storage/name_search/src/project/test.rsindex 9c9bb82999..3c3384cc8c 100644--- a/rust/cloud-storage/name_search/src/project/test.rs+++ b/rust/cloud-storage/name_search/src/project/test.rs@@ -1,6 +1,7 @@//! Tests for project moduleuse macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_search_cursor::SearchCursorOption;use sqlx::{Pool, Postgres};use uuid::Uuid;@@ -15,7 +16,7 @@ async fn test_search_project_names_empty_term(pool: Pool<Postgres>) -> anyhow::R.map(|l| l.lowercase()).unwrap();- let result = search_project_names(&pool, &user_id, &[], "".to_string(), false, 10, 0).await;+ let result = search_project_names(&pool, &user_id, &[], "".to_string(), false, 10, None).await;assert!(result.is_err());assert!(matches!(@@ -38,7 +39,7 @@ async fn test_search_project_names_ids_only_with_empty_ids(.unwrap();let result =- search_project_names(&pool, &user_id, &[], "mobile".to_string(), true, 10, 0).await;+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), true, 10, None).await;assert!(result.is_err());assert!(matches!(@@ -65,33 +66,39 @@ async fn test_search_project_names_ids_only_mode(pool: Pool<Postgres>) -> anyhowUuid::parse_str("55555555-5555-5555-5555-555555555555")?, // Marketing Campaign - won't match];- let results = search_project_names(+ let response = search_project_names(&pool,&user_id,&project_ids,"mobile".to_string(),true,10,- 0,+ None,).await?;// Should only return the 2 projects that match "mobile" from the provided IDs- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);// Verify results contain expected projects (ordered by updatedAt DESC)assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");- assert_eq!(results[0].entity_type, SearchEntityType::Projects);- assert_eq!(results[0].name, "Mobile App Redesign");+ assert_eq!(response.items[0].entity_type, SearchEntityType::Projects);+ assert_eq!(+ response.items[0].name,+ "<macro_em>Mobile</macro_em> App Redesign"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"11111111-1111-1111-1111-111111111111");- assert_eq!(results[1].name, "Mobile Development");+ assert_eq!(+ response.items[1].name,+ "<macro_em>Mobile</macro_em> Development"+ );Ok(())}@@ -108,24 +115,30 @@ async fn test_search_project_names_normal_mode_owned_projects(.unwrap();// Search for "mobile" across all user1's owned projects- let results =- search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, 0).await?;+ let response =+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, None).await?;// Should return 3 projects matching "mobile" (2 lowercase + 1 uppercase)- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);// Verify ordering by updatedAt DESCassert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"66666666-6666-6666-6666-666666666666");- assert_eq!(results[0].name, "MOBILE PLATFORM");+ assert_eq!(+ response.items[0].name,+ "<macro_em>MOBILE</macro_em> PLATFORM"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");- assert_eq!(results[1].name, "Mobile App Redesign");+ assert_eq!(+ response.items[1].name,+ "<macro_em>Mobile</macro_em> App Redesign"+ );Ok(())}@@ -140,22 +153,22 @@ async fn test_search_project_names_case_insensitive(pool: Pool<Postgres>) -> any.unwrap();// Search with uppercase term should match both lowercase and uppercase names- let results =- search_project_names(&pool, &user_id, &[], "MOBILE".to_string(), false, 10, 0).await?;+ let response =+ search_project_names(&pool, &user_id, &[], "MOBILE".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);// Search with lowercase term should also match both- let results =- search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, 0).await?;+ let response =+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);// Search with mixed case- let results =- search_project_names(&pool, &user_id, &[], "MoBiLe".to_string(), false, 10, 0).await?;+ let response =+ search_project_names(&pool, &user_id, &[], "MoBiLe".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 3);+ assert_eq!(response.items.len(), 3);Ok(())}@@ -174,28 +187,31 @@ async fn test_search_project_names_with_shared_projects(// Include a project from user3 (shared via project_ids parameter)let shared_project_ids = vec![Uuid::parse_str("99999999-9999-9999-9999-999999999999")?];- let results = search_project_names(+ let response = search_project_names(&pool,&user_id,&shared_project_ids,"mobile".to_string(),false,10,- 0,+ None,).await?;// Should return user1's 3 "mobile" projects + user3's 1 "mobile" project- assert_eq!(results.len(), 4);+ assert_eq!(response.items.len(), 4);// Verify user3's project is included- let user3_project = results.iter().find(|r| {+ let user3_project = response.items.iter().find(|r| {r.entity_id.to_string().eq("99999999-9999-9999-9999-999999999999")});assert!(user3_project.is_some());- assert_eq!(user3_project.unwrap().name, "User3 Shared Mobile");+ assert_eq!(+ user3_project.unwrap().name,+ "User3 Shared <macro_em>Mobile</macro_em>"+ );Ok(())}@@ -210,21 +226,24 @@ async fn test_search_project_names_pagination_limit(pool: Pool<Postgres>) -> any.unwrap();// Search with limit of 2- let results =- search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 2, 0).await?;+ let response =+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 2, None).await?;- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);// Should get the 2 most recently updated projects with "mobile"assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"66666666-6666-6666-6666-666666666666");assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"22222222-2222-2222-2222-222222222222");+ // Should have a next_cursor since there are more results+ assert!(response.cursor.has_more());+Ok(())}@@ -232,23 +251,59 @@ async fn test_search_project_names_pagination_limit(pool: Pool<Postgres>) -> anymigrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("project")))]-async fn test_search_project_names_pagination_offset(pool: Pool<Postgres>) -> anyhow::Result<()> {+async fn test_search_project_names_pagination_cursor(pool: Pool<Postgres>) -> anyhow::Result<()> {let user_id = MacroUserId::parse_from_str("macro|[email protected]").map(|l| l.lowercase()).unwrap();- // Search with offset of 2- let results =- search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, 2).await?;+ // First page with limit of 2+ let first_response =+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 2, None).await?;++ assert_eq!(first_response.items.len(), 2);+ assert!(first_response.cursor.has_more());++ // Extract cursor for second page+ let cursor = match first_response.cursor {+ SearchCursorOption::NotDone(c) => c,+ SearchCursorOption::Done => panic!("Expected more results"),+ };- assert_eq!(results.len(), 1);+ // Second page using cursor+ let second_response =+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 2, cursor).await?;- // Should skip the first 2 and get the next 1+ assert_eq!(second_response.items.len(), 1);++ // Should get the next project (skipping the first 2)assert_eq!(- results[0].entity_id.to_string(),+ second_response.items[0].entity_id.to_string(),"11111111-1111-1111-1111-111111111111");+ // Should NOT have next_cursor since we've reached the end+ assert!(second_response.cursor.is_done());++ // Verify no overlap between pages+ let first_ids: Vec<String> = first_response+ .items+ .iter()+ .map(|r| r.entity_id.to_string())+ .collect();+ let second_ids: Vec<String> = second_response+ .items+ .iter()+ .map(|r| r.entity_id.to_string())+ .collect();++ for id in &first_ids {+ assert!(+ !second_ids.contains(id),+ "Found duplicate ID between pages: {}",+ id+ );+ }+Ok(())}@@ -262,18 +317,19 @@ async fn test_search_project_names_no_results(pool: Pool<Postgres>) -> anyhow::R.unwrap();// Search for a term that doesn't match any projects- let results = search_project_names(+ let response = search_project_names(&pool,&user_id,&[],"nonexistent".to_string(),false,10,- 0,+ None,).await?;- assert_eq!(results.len(), 0);+ assert_eq!(response.items.len(), 0);+ assert!(response.cursor.is_done());Ok(())}@@ -288,21 +344,27 @@ async fn test_search_project_names_partial_match(pool: Pool<Postgres>) -> anyhow.unwrap();// Search for partial term "web" should match "website"- let results =- search_project_names(&pool, &user_id, &[], "web".to_string(), false, 10, 0).await?;+ let response =+ search_project_names(&pool, &user_id, &[], "web".to_string(), false, 10, None).await?;- assert_eq!(results.len(), 2);+ assert_eq!(response.items.len(), 2);assert_eq!(- results[0].entity_id.to_string(),+ response.items[0].entity_id.to_string(),"44444444-4444-4444-4444-444444444444");- assert_eq!(results[0].name, "Website Optimization");+ assert_eq!(+ response.items[0].name,+ "<macro_em>Web</macro_em>site Optimization"+ );assert_eq!(- results[1].entity_id.to_string(),+ response.items[1].entity_id.to_string(),"33333333-3333-3333-3333-333333333333");- assert_eq!(results[1].name, "Web Platform Upgrade");+ assert_eq!(+ response.items[1].name,+ "<macro_em>Web</macro_em> Platform Upgrade"+ );Ok(())}@@ -317,11 +379,11 @@ async fn test_search_project_names_user_isolation(pool: Pool<Postgres>) -> anyho.unwrap();// Search for "User2" - user1 should not see user2's private projects- let results =- search_project_names(&pool, &user_id, &[], "User2".to_string(), false, 10, 0).await?;+ let response =+ search_project_names(&pool, &user_id, &[], "User2".to_string(), false, 10, None).await?;// Should return 0 results (user2's projects are not owned by user1 and not shared)- assert_eq!(results.len(), 0);+ assert_eq!(response.items.len(), 0);Ok(())}@@ -338,18 +400,18 @@ async fn test_search_project_names_excludes_soft_deleted(.unwrap();// Search for "mobile" - should NOT include soft-deleted project- let results =- search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, 0).await?;+ let response =+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, None).await?;// Should NOT include the deleted project (id: 77777777-7777-7777-7777-777777777777)- assert!(!results.iter().any(|r| {+ assert!(!response.items.iter().any(|r| {r.entity_id.to_string().eq("77777777-7777-7777-7777-777777777777")}));// Should include non-deleted projects- assert!(results.iter().any(|r| {+ assert!(response.items.iter().any(|r| {r.entity_id.to_string().eq("11111111-1111-1111-1111-111111111111")diff --git a/rust/cloud-storage/opensearch_client/Cargo.toml b/rust/cloud-storage/opensearch_client/Cargo.tomlindex b9433fd6b0..8982588e9f 100644--- a/rust/cloud-storage/opensearch_client/Cargo.toml+++ b/rust/cloud-storage/opensearch_client/Cargo.toml@@ -6,7 +6,6 @@ publish = falseversion = "0.1.0"[dev-dependencies]-chrono = { workspace = true }macro_entrypoint = { path = "../macro_entrypoint" }tokio = { workspace = true }uuid = { workspace = true }@@ -14,7 +13,9 @@ uuid = { workspace = true }[dependencies]anyhow = { workspace = true }+chrono = { workspace = true }models_opensearch = { path = "../models_opensearch" }+models_search_cursor = { path = "../models_search_cursor" }opensearch = { version = "2.3.0" }opensearch_query_builder = { version = "0.2.8", default-features = false }serde = { workspace = true }diff --git a/rust/cloud-storage/opensearch_client/src/error.rs b/rust/cloud-storage/opensearch_client/src/error.rsindex bf80fcc9cc..4ecf6bb51c 100644--- a/rust/cloud-storage/opensearch_client/src/error.rs+++ b/rust/cloud-storage/opensearch_client/src/error.rs@@ -54,6 +54,9 @@ pub enum OpensearchClientError {#[error("unsupported search_on")]InvalidSearchOn,++ #[error("searching with exhausted cursor")]+ SearchWithExhaustedCursor,}impl From<anyhow::Error> for OpensearchClientError {diff --git a/rust/cloud-storage/opensearch_client/src/lib.rs b/rust/cloud-storage/opensearch_client/src/lib.rsindex 21ad9e4ad7..6a28f140ed 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 name;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/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rsindex 7851eee4af..9cb3ddbd5d 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs@@ -8,6 +8,7 @@ use crate::search::query::Keys;use crate::search::query::QueryKey;use crate::search::query::generate_terms_must_query;use models_opensearch::SearchEntityType;+use models_search_cursor::SearchMethodCursor;use opensearch_query_builder::*;/// A macro for generating delegation methods that forward calls to an inner field@@ -57,7 +58,8 @@ pub(crate) fn create_highlight_field<'a>(.number_of_fragments(number_of_fragments)}-/// Creates sort vec to sort by the updated_at with a fallback to score sort+/// Creates sort vec to sort by the updated_at with entity_id as a tiebreaker.+/// Items without a timestamp are pushed to the end by returning 0L (DESC order).pub(crate) fn updated_at_sort<'a>() -> Vec<SortType<'a>> {vec![SortType::ScriptSort(ScriptSort::new(@@ -67,15 +69,23 @@ pub(crate) fn updated_at_sort<'a>() -> Vec<SortType<'a>> {} else if (doc.containsKey('updated_at_seconds') && doc['updated_at_seconds'].size() > 0) {return doc['updated_at_seconds'].value.toInstant().toEpochMilli();} else {- return 0L; // Or Long.MAX_VALUE to push to end+ return 0L;}"#,),ScriptSortType::Number,SortOrder::Desc,)),- SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),+ SortType::Field(FieldSort::new("entity_id", SortOrder::Asc)),]}++pub(crate) fn search_after(cursor: SearchMethodCursor) -> Vec<serde_json::Value> {+ vec![+ serde_json::json!(cursor.updated_at.timestamp_millis()),+ serde_json::json!(cursor.entity_id.to_string()),+ ]+}+pub trait SearchQueryConfig {/// Key for item idconst ID_KEY: &'static str = "entity_id";@@ -269,58 +279,6 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {inner_bool_query.minimum_should_match(1);- // For email search, we want to search over the participants- // For all other indices we want to search over the owner- match T::ENTITY_INDEX {- SearchEntityType::Emails => {- let mut participant_queries: Vec<QueryType> = Vec::new();- for term in &self.terms {- let formatted_term = format!("{}*", term);- participant_queries.push(- WildcardQuery::new("sender", formatted_term.clone(), true, Some(5000.0))- .into(),- );- participant_queries.push(- WildcardQuery::new("cc", formatted_term.clone(), true, Some(5000.0)).into(),- );- participant_queries.push(- WildcardQuery::new("bcc", formatted_term.clone(), true, Some(5000.0))- .into(),- );- participant_queries.push(- WildcardQuery::new(- "recipients",- formatted_term.clone(),- true,- Some(5000.0),- )- .into(),- );- }-- for participant_query in participant_queries {- inner_bool_query.should(participant_query);- }- }- _ => {- // Create a vec of owner queries for each term- // We want to search over the content **and** the owner here- let mut owner_queries: Vec<QueryType> = Vec::new();- for term in &self.terms {- let formatted_term = format!("macro|{}*", term);- owner_queries.push(- WildcardQuery::new(T::USER_ID_KEY, formatted_term, true, Some(5000.0))- .into(),- );- }-- // Add the owner queries to the bool query- for owner_query in owner_queries {- inner_bool_query.should(owner_query);- }- }- }-for must in term_must_array {inner_bool_query.should(must);}diff --git a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs b/rust/cloud-storage/opensearch_client/src/search/builder/test.rsindex 15d01a0194..cae80e2714 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs@@ -307,15 +307,6 @@ fn test_build_bool_query() -> anyhow::Result<()> {"bool": {"minimum_should_match": 1,"should": [- {- "wildcard": {- "test_user_id": {- "value": "macro|test*",- "case_insensitive": true,- "boost": 5000.0- }- }- },{"match_phrase": {"content": "test"@@ -360,15 +351,6 @@ fn test_build_bool_query() -> anyhow::Result<()> {"bool": {"minimum_should_match": 1,"should": [- {- "wildcard": {- "test_user_id": {- "value": "macro|test*",- "case_insensitive": true,- "boost": 5000.0- }- }- },{"match_phrase_prefix": {"content": {@@ -407,15 +389,6 @@ fn test_build_bool_query() -> anyhow::Result<()> {"bool": {"minimum_should_match": 1,"should": [- {- "wildcard": {- "test_user_id": {- "case_insensitive": true,- "value": "macro|test*",- "boost": 5000.0- }- }- },{"match_phrase_prefix": {"content": {diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rsindex 23278cde09..2ee7655477 100644--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs@@ -230,6 +230,7 @@ pub(crate) async fn search_channel_messages(score: hit.score,highlight,goto: None,+ updated_at: None,},ChannelMessageNameIndex::ChannelMessage(a) => SearchHit {entity_id: a.entity_id,@@ -243,6 +244,7 @@ pub(crate) async fn search_channel_messages(created_at: a.created_at_seconds,updated_at: a.updated_at_seconds,})),+ updated_at: chrono::DateTime::from_timestamp(a.updated_at_seconds, 0),},}})diff --git a/rust/cloud-storage/opensearch_client/src/search/channels/test.rs b/rust/cloud-storage/opensearch_client/src/search/channels/test.rsindex 7e68e4044c..8749ef7829 100644--- a/rust/cloud-storage/opensearch_client/src/search/channels/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/channels/test.rs@@ -30,15 +30,6 @@ fn test_build_search_request() -> anyhow::Result<()> {"bool": {"minimum_should_match": 1,"should": [- {- "wildcard": {- "sender_id": {- "case_insensitive": true,- "value": "macro|test*",- "boost": 5000.0- }- }- },{"match_phrase": {"content": "test"diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rsindex c454a7877d..e72c3c7dea 100644--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs@@ -25,6 +25,7 @@ pub(crate) struct ChatIndex {pub role: String,pub title: String,pub content: String,+ pub updated_at_seconds: Option<i64>,}#[derive(Debug, serde::Serialize, serde::Deserialize)]@@ -195,6 +196,7 @@ pub(crate) async fn search_chats(score: hit.score,highlight,goto: None,+ updated_at: None,},ChatNameIndex::Chat(a) => SearchHit {entity_id: a.entity_id,@@ -205,6 +207,7 @@ pub(crate) async fn search_chats(chat_message_id: a.chat_message_id,role: a.role,})),+ updated_at: None,},}})diff --git a/rust/cloud-storage/opensearch_client/src/search/chats/test.rs b/rust/cloud-storage/opensearch_client/src/search/chats/test.rsindex 5f01127610..8e407f17fe 100644--- a/rust/cloud-storage/opensearch_client/src/search/chats/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/chats/test.rs@@ -77,15 +77,6 @@ fn test_build_search_request() -> anyhow::Result<()> {"bool": {"minimum_should_match": 1,"should": [- {- "wildcard": {- "user_id": {- "boost": 5000.0,- "case_insensitive": true,- "value": "macro|test*"- }- }- },{"match_phrase": {"content": "test"diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rsindex ea5af95e80..929c051407 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs@@ -80,6 +80,7 @@ pub(crate) struct DocumentIndex {pub content: String,pub owner_id: String,pub file_type: String,+ pub updated_at_seconds: Option<i64>,}#[derive(Debug, serde::Serialize, serde::Deserialize)]@@ -184,6 +185,7 @@ pub(crate) async fn search_documents(score: hit.score,highlight,goto: None,+ updated_at: None,},DocumentNameIndex::Document(a) => SearchHit {entity_id: a.entity_id,@@ -194,6 +196,7 @@ pub(crate) async fn search_documents(node_id: a.node_id,raw_content: a.raw_content,})),+ updated_at: None,},}})diff --git a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs b/rust/cloud-storage/opensearch_client/src/search/documents/test.rsindex d64e90d558..e89feb3708 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs@@ -53,15 +53,6 @@ fn test_build_search_request() -> anyhow::Result<()> {"bool": {"minimum_should_match": 1,"should": [- {- "wildcard": {- "owner_id": {- "boost": 5000.0,- "case_insensitive": true,- "value": "macro|test*"- }- }- },{"match_phrase": {"content": "test"diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex 723a51be23..5ce01fbf6b 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -2,7 +2,7 @@ use crate::{Result, delegate_methods,error::{OpensearchClientError, ResponseExt},search::{- builder::{SearchQueryBuilder, SearchQueryConfig, create_highlight_field},+ builder::{SearchQueryBuilder, SearchQueryConfig},model::{NameIndex, SearchGotoContent, SearchGotoEmail, SearchHit, parse_highlight_hit},query::Keys,utils::should_wildcard_field_query_builder,@@ -22,16 +22,6 @@ impl SearchQueryConfig for EmailSearchConfig {const USER_ID_KEY: &'static str = "user_id";const TITLE_KEY: &'static str = "name";const ENTITY_INDEX: SearchEntityType = SearchEntityType::Emails;-- fn append_owner_highlights<'a>(- highlight: opensearch_query_builder::Highlight<'a>,- ) -> opensearch_query_builder::Highlight<'a> {- let highlight = highlight.field("sender", create_highlight_field("plain", 1));- let highlight = highlight.field("recipients", create_highlight_field("plain", 1));- let highlight = highlight.field("cc", create_highlight_field("plain", 1));-- highlight.field("bcc", create_highlight_field("plain", 1))- }}pub(crate) struct EmailQueryBuilder {@@ -289,6 +279,7 @@ pub(crate) async fn search_emails(goto: None,score: hit.score,highlight,+ updated_at: None,},EmailNameIndex::Email(a) => SearchHit {entity_id: a.entity_id,@@ -304,6 +295,9 @@ pub(crate) async fn search_emails(sender: a.sender,recipients: a.recipients,})),+ updated_at: a+ .sent_at_seconds+ .and_then(|s| chrono::DateTime::from_timestamp(s, 0)),},}})diff --git a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs b/rust/cloud-storage/opensearch_client/src/search/emails/test.rsindex 3309489c9a..0ac0fbb341 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs@@ -123,42 +123,6 @@ fn test_build_search_request() -> anyhow::Result<()> {"bool": {"minimum_should_match": 1,"should": [- {- "wildcard": {- "sender": {- "boost": 5000.0,- "case_insensitive": true,- "value": "test*"- }- }- },- {- "wildcard": {- "cc": {- "boost": 5000.0,- "case_insensitive": true,- "value": "test*"- }- }- },- {- "wildcard": {- "bcc": {- "boost": 5000.0,- "case_insensitive": true,- "value": "test*"- }- }- },- {- "wildcard": {- "recipients": {- "boost": 5000.0,- "case_insensitive": true,- "value": "test*"- }- }- },{"match_phrase": {"content": "test"diff --git a/rust/cloud-storage/opensearch_client/src/search/model.rs b/rust/cloud-storage/opensearch_client/src/search/model.rsindex d579f05d56..22cf96f8eb 100644--- a/rust/cloud-storage/opensearch_client/src/search/model.rs+++ b/rust/cloud-storage/opensearch_client/src/search/model.rs@@ -1,5 +1,6 @@use std::{collections::HashMap, fmt::Display};+use chrono::{DateTime, Utc};use models_opensearch::SearchEntityType;use crate::search::query::Keys;@@ -218,4 +219,7 @@ pub struct SearchHit {pub highlight: Highlight,/// The goto content for the entitypub goto: Option<SearchGotoContent>,+ /// Timestamp for sorting across sources (None sorts to bottom)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub updated_at: Option<DateTime<Utc>>,}diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsindex 34ddd42018..d17416edbd 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -1,17 +1,164 @@-use crate::search::{- builder::SearchQueryConfig,- channels::{ChannelMessageIndex, ChannelMessageSearchConfig},- chats::{ChatIndex, ChatSearchConfig},- documents::{DocumentIndex, DocumentSearchConfig},- emails::{EmailIndex, EmailSearchConfig},- model::{- Hit, NameIndex, SearchGotoChannel, SearchGotoChat, SearchGotoContent, SearchGotoDocument,- SearchGotoEmail, SearchHit, parse_highlight_hit,+use std::collections::HashSet;++use crate::{+ Result,+ error::{OpensearchClientError, ResponseExt},+ search::{+ builder::{SearchQueryConfig, search_after, updated_at_sort},+ channels::{+ ChannelMessageIndex, ChannelMessageQueryBuilder, ChannelMessageSearchArgs,+ ChannelMessageSearchConfig,+ },+ chats::{ChatIndex, ChatQueryBuilder, ChatSearchArgs, ChatSearchConfig},+ documents::{+ DocumentIndex, DocumentQueryBuilder, DocumentSearchArgs, DocumentSearchConfig,+ },+ emails::{EmailIndex, EmailQueryBuilder, EmailSearchArgs, EmailSearchConfig},+ model::{+ DefaultSearchResponse, Hit, MacroEm, SearchGotoChannel, SearchGotoChat,+ SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHit, parse_highlight_hit,+ },+ query::Keys,},- query::Keys,};+use chrono::{DateTime, Utc};+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};+use crate::SearchOn;use models_opensearch::SearchEntityType;+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 cursor to use+ pub cursor: SearchCursorOption,+ /// The indices to search over+ pub search_indices: HashSet<SearchEntityType>,+ /// 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,+}++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,+ }+ }+}++#[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 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)]@@ -21,7 +168,6 @@ pub(crate) enum UnifiedSearchIndex {Document(DocumentIndex),Chat(ChatIndex),Email(EmailIndex),- Name(NameIndex),}pub struct SplitUnifiedSearchResponseValues {@@ -101,6 +247,7 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {created_at: a.created_at_seconds,updated_at: a.updated_at_seconds,})),+ updated_at: DateTime::from_timestamp(a.updated_at_seconds, 0),},UnifiedSearchIndex::Document(a) => SearchHit {entity_id: a.entity_id,@@ -122,6 +269,9 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {node_id: a.node_id,raw_content: a.raw_content,})),+ updated_at: a+ .updated_at_seconds+ .and_then(|s| DateTime::from_timestamp(s, 0)),},UnifiedSearchIndex::Email(a) => SearchHit {entity_id: a.entity_id,@@ -148,8 +298,10 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {sender: a.sender,recipients: a.recipients,})),+ updated_at: a+ .sent_at_seconds+ .and_then(|s| DateTime::from_timestamp(s, 0)),},-UnifiedSearchIndex::Chat(a) => SearchHit {entity_id: a.entity_id,entity_type: SearchEntityType::Chats,@@ -170,25 +322,174 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {chat_message_id: a.chat_message_id,role: a.role,})),- },- UnifiedSearchIndex::Name(a) => SearchHit {- entity_id: a.entity_id,- entity_type: a.entity_type,- score: index.score,- highlight: index- .highlight- .map(|h| {- parse_highlight_hit(- h,- Keys {- title_key: "name",- content_key: "",- },- )- })- .unwrap_or_default(),- goto: None,+ updated_at: a+ .updated_at_seconds+ .and_then(|s| DateTime::from_timestamp(s, 0)),},}}}++#[tracing::instrument(skip(args), err)]+fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequest<'static>> {+ // We don't support searching over an exhausted (done) cursor+ let cursor = match args.cursor.clone() {+ SearchCursorOption::NotDone(search_method_cursor) => search_method_cursor.clone(),+ SearchCursorOption::Done => return Err(OpensearchClientError::SearchWithExhaustedCursor),+ };++ // We don't support name search in opensearch+ if let SearchOn::Name = args.search_on {+ return Err(OpensearchClientError::InvalidSearchOn);+ }++ if args.search_indices.is_empty() {+ return Err(OpensearchClientError::EmptySearchIndices);+ }++ let mut bool_query = BoolQueryBuilder::new();++ // There will always be 1 query as the indices are never empty+ bool_query.minimum_should_match(1);++ if args.search_indices.contains(&SearchEntityType::Documents) {+ let document_search_args: DocumentSearchArgs = args.clone().into();+ let document_query_builder: DocumentQueryBuilder = document_search_args.into();+ let document_bool_query = document_query_builder.build_bool_query()?;+ let query_type: QueryType = document_bool_query.build().into();+ bool_query.should(query_type.to_owned());+ }++ if args.search_indices.contains(&SearchEntityType::Emails) {+ let email_search_args: EmailSearchArgs = args.clone().into();+ let email_query_builder: EmailQueryBuilder = email_search_args.into();+ let email_bool_query = email_query_builder.build_bool_query()?;+ let query_type: QueryType = email_bool_query.build().into();+ bool_query.should(query_type.to_owned());+ }++ // We can only search over channels if we are not explicitly searching by name+ if args.search_indices.contains(&SearchEntityType::Channels) && args.search_on != SearchOn::Name+ {+ let channel_message_search_args: ChannelMessageSearchArgs = args.clone().into();+ let channel_message_query_builder: ChannelMessageQueryBuilder =+ channel_message_search_args.into();+ let channel_message_bool_query = channel_message_query_builder.build_bool_query()?;+ let query_type: QueryType = channel_message_bool_query.build().into();+ bool_query.should(query_type.to_owned());+ }++ if args.search_indices.contains(&SearchEntityType::Chats) {+ let chat_search_args: ChatSearchArgs = args.clone().into();+ let chat_query_builder: ChatQueryBuilder = chat_search_args.into();+ let chat_bool_query = chat_query_builder.build_bool_query()?;+ let query_type: QueryType = chat_bool_query.build().into();+ bool_query.should(query_type.to_owned());+ }++ // create the search request+ let mut search_request_builder = SearchRequestBuilder::new();++ if let Some(cursor) = cursor {+ search_request_builder.set_search_after(search_after(cursor));+ }++ search_request_builder.size(args.page_size + 1);++ if args.collapse {+ search_request_builder.collapse(Collapse::new("entity_id"));+ }++ // Build sort+ let sort = updated_at_sort();++ for sort in sort {+ search_request_builder.add_sort(sort);+ }++ // Build highlight+ let highlight = 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),+ );++ search_request_builder.highlight(highlight);++ let query_object = bool_query.build();++ let built_query: QueryType = query_object.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<SearchHit>, SearchCursorOption)> {+ let search_request = build_unified_search_request(&args)?.to_json();++ tracing::trace!("search request {:?}", search_request);++ // We cannot search over the projects index in opensearch as it doesn't exist+ let search_indices: Vec<&str> = args+ .search_indices+ .iter()+ .filter(|i| **i != SearchEntityType::Projects)+ .map(|i| i.as_ref())+ .collect();++ // After we filter out invalid search entities if we have nothing we should return that the cursor is exhausted+ if search_indices.is_empty() {+ return Ok((Vec::new(), SearchCursorOption::Done));+ }++ let response = client+ .search(opensearch::SearchParts::Index(&search_indices))+ .body(search_request)+ .send()+ .await+ .map_client_error()+ .await?;++ let bytes = response+ .bytes()+ .await+ .map_err(|e| OpensearchClientError::HttpBytesError {+ details: e.to_string(),+ })?;++ let result: DefaultSearchResponse<UnifiedSearchIndex> = 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(|h| h.into()).collect();++ let has_more = results.len() > args.page_size as usize;++ if has_more {+ results.pop(); // Remove the extra item+ }++ let cursor = if has_more {+ SearchCursorOption::NotDone(results.last().map(|last| SearchMethodCursor {+ entity_id: last.entity_id,+ updated_at: last.updated_at.unwrap_or(Utc::now()),+ }))+ } else {+ SearchCursorOption::Done+ };++ Ok((results, cursor))+}++#[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..7a48d48a6e--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs@@ -0,0 +1,956 @@+use super::*;++use chrono::Utc;+use models_search_cursor::SearchMethodCursor;+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_fail_on_name_search() {+ let err = build_unified_search_request(&UnifiedSearchArgs {+ search_on: SearchOn::Name,+ ..Default::default()+ })+ .err()+ .unwrap();++ assert_eq!(err, OpensearchClientError::InvalidSearchOn);+}++#[test]+fn test_build_unified_search_request_content() -> anyhow::Result<()> {+ let entity_id = uuid::Uuid::new_v4();+ let time = Utc::now();++ let unified_search_args = UnifiedSearchArgs {+ search_indices: vec![+ SearchEntityType::Documents,+ SearchEntityType::Emails,+ SearchEntityType::Projects,+ SearchEntityType::Channels,+ SearchEntityType::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,+ },+ cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor {+ entity_id,+ updated_at: time,+ })),+ };++ let result = build_unified_search_request(&unified_search_args)?;++ let expected = serde_json::json!({+ "collapse": {+ "field": "entity_id"+ },+ "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": {+ "filter": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "terms": {+ "entity_id": ["id1", "id2"]+ }+ },+ {+ "term": {+ "owner_id": "user"+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "documents"+ }+ }+ ],+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase": {+ "content": "test"+ }+ }+ ]+ }+ }+ ]+ }+ },+ {+ "bool": {+ "filter": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "terms": {+ "entity_id": ["id1", "id2"]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "emails"+ }+ },+ {+ "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*"+ }+ }+ }+ ]+ }+ }+ ],+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase": {+ "content": "test"+ }+ }+ ]+ }+ }+ ],+ "must_not": [+ {+ "term": {+ "labels": "TRASH"+ }+ }+ ]+ }+ },+ {+ "bool": {+ "filter": [+ {+ "terms": {+ "entity_id": ["id1", "id2"]+ }+ },+ {+ "term": {+ "_index": "channels"+ }+ },+ {+ "terms": {+ "thread_id": ["id1", "id2"]+ }+ },+ {+ "terms": {+ "mentions": ["id1", "id2"]+ }+ },+ {+ "terms": {+ "sender_id": ["id1", "id2"]+ }+ }+ ],+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase": {+ "content": "test"+ }+ }+ ]+ }+ }+ ]+ }+ },+ {+ "bool": {+ "filter": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "terms": {+ "entity_id": ["id1", "id2"]+ }+ },+ {+ "term": {+ "user_id": "user"+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "chats"+ }+ },+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id1*"+ }+ }+ },+ {+ "wildcard": {+ "role": {+ "case_insensitive": true,+ "value": "*id2*"+ }+ }+ }+ ]+ }+ }+ ],+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase": {+ "content": "test"+ }+ }+ ]+ }+ }+ ]+ }+ }+ ]+ }+ },+ "search_after": [time.timestamp_millis(), entity_id.to_string()],+ "size": 21,+ "sort": updated_at_sort().iter().map(|s| s.to_json()).collect::<Vec<_>>(),+ });++ assert_eq!(result.to_json(), expected);++ let unified_search_args = UnifiedSearchArgs {+ search_indices: vec![+ SearchEntityType::Documents,+ SearchEntityType::Emails,+ SearchEntityType::Projects,+ SearchEntityType::Channels,+ SearchEntityType::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,+ },+ cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor {+ entity_id,+ updated_at: time,+ })),+ };++ let result = build_unified_search_request(&unified_search_args)?;++ 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![SearchEntityType::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"+ },+ "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": {+ "filter": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "terms": {+ "entity_id": ["id1", "id2"]+ }+ },+ {+ "term": {+ "owner_id": "user"+ }+ }+ ]+ }+ },+ {+ "term": {+ "_index": "documents"+ }+ }+ ],+ "must": [+ {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ {+ "match_phrase": {+ "content": "test"+ }+ }+ ]+ }+ }+ ]+ }+ }+ ]+ }+ },+ "size": 21,+ "sort": updated_at_sort().iter().map(|s| s.to_json()).collect::<Vec<_>>(),+ });++ 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..8a134cf325--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/unified.rs@@ -0,0 +1,17 @@+use models_search_cursor::SearchCursorOption;++use crate::{+ OpensearchClient, Result,+ search::{self, model::SearchHit, unified::UnifiedSearchArgs},+};++impl OpensearchClient {+ /// Performs a unified search+ #[tracing::instrument(skip(self, args))]+ pub async fn search_unified(+ &self,+ args: UnifiedSearchArgs,+ ) -> Result<(Vec<SearchHit>, SearchCursorOption)> {+ search::unified::search_unified(&self.inner, args).await+ }+}diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.tomlindex 2abd355d03..4c08d2fcf3 100644--- a/rust/cloud-storage/search_service/Cargo.toml+++ b/rust/cloud-storage/search_service/Cargo.toml@@ -13,6 +13,7 @@ chrono = { workspace = true }comms_service_client = { path = "../comms_service_client" }document_storage_service_client = { path = "../document_storage_service_client" }document_sub_type = { path = "../document_sub_type" }+email_contact_search = { path = "../email_contact_search" }email_service_client = { path = "../email_service_client" }futures = { workspace = true }http-body-util = { workspace = true }@@ -31,6 +32,7 @@ model = { path = "../model" }models_email = { path = "../models_email" }models_opensearch = { path = "../models_opensearch" }models_search = { path = "../models_search" }+models_search_cursor = { path = "../models_search_cursor" }name_search = { path = "../name_search" }opensearch_client = { path = "../opensearch_client" }secretsmanager_client = { path = "../secretsmanager_client" }diff --git a/rust/cloud-storage/search_service/src/api/search/channel.rs b/rust/cloud-storage/search_service/src/api/search/channel.rsindex ac3bcb0cf7..29771fc097 100644--- a/rust/cloud-storage/search_service/src/api/search/channel.rs+++ b/rust/cloud-storage/search_service/src/api/search/channel.rs@@ -1,20 +1,11 @@-use crate::api::search::simple::{SearchError, simple_channel::search_channels};+use crate::api::search::simple::SearchError;use indexmap::IndexMap;use std::collections::HashMap;-use super::SearchPaginationParams;use crate::api::ApiContext;-use axum::{- Extension,- extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},-};use model::comms::{ChannelHistoryInfo, GetChannelsHistoryRequest};-use model::{response::ErrorResponse, user::UserContext};use models_search::channel::{- ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem,- ChannelSearchResponseItemWithMetadata, ChannelSearchResult,+ ChannelSearchResponseItem, ChannelSearchResponseItemWithMetadata, ChannelSearchResult,};use opensearch_client::search::model::SearchGotoContent;use sqlx::types::Uuid;@@ -55,61 +46,6 @@ pub(in crate::api::search) async fn enrich_channels(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,- path = "/search/channel",- operation_id = "channel_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=ChannelSearchResponse),- (status = 400, body=ErrorResponse),- (status = 401, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )- )]-#[tracing::instrument(skip(ctx, user_context, query_params), 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<ChannelSearchRequest>,-) -> Result<Response, SearchError> {- tracing::info!("channel_search");-- let results = search_channels_enriched(- &ctx,- user_context.user_id.as_str(),- user_context.organization_id,- &query_params,- req,- )- .await?;-- let result = ChannelSearchResponse { results };-- Ok((StatusCode::OK, Json(result)).into_response())-}-pub fn construct_search_result(search_results: Vec<opensearch_client::search::model::SearchHit>,channel_histories: HashMap<Uuid, ChannelHistoryInfo>,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.rsindex 38a2957762..2655f20997 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@@ -33,6 +33,7 @@ fn test_construct_search_result_single_channel() {content: vec!["Test message content".to_string()],..Default::default()},+ updated_at: None,}];let mut channel_histories = HashMap::new();@@ -91,6 +92,7 @@ fn test_construct_search_result_multiple_messages_same_channel() {content: vec!["First message".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: channel_uuid,@@ -112,6 +114,7 @@ fn test_construct_search_result_multiple_messages_same_channel() {content: vec!["Second message".to_string()],..Default::default()},+ updated_at: None,},];@@ -171,6 +174,7 @@ fn test_construct_search_result_filters_messages_without_content() {content: vec!["Message with content".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: channel_uuid,@@ -192,6 +196,7 @@ fn test_construct_search_result_filters_messages_without_content() {content: vec![],..Default::default()},+ updated_at: None,},];@@ -241,6 +246,7 @@ fn create_test_channel_response(content: content.unwrap_or_default(),..Default::default()},+ updated_at: None,}}@@ -407,6 +413,7 @@ fn test_sort_stability() {content: vec!["third".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: channel_ids[1],@@ -428,6 +435,7 @@ fn test_sort_stability() {content: vec!["first".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: channel_ids[2],@@ -449,6 +457,7 @@ fn test_sort_stability() {content: vec!["fifth".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: channel_ids[3],@@ -470,6 +479,7 @@ fn test_sort_stability() {content: vec!["second".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: channel_ids[4],@@ -491,6 +501,7 @@ fn test_sort_stability() {content: vec!["fourth".to_string()],..Default::default()},+ updated_at: None,},];diff --git a/rust/cloud-storage/search_service/src/api/search/chat.rs b/rust/cloud-storage/search_service/src/api/search/chat.rsindex 8ff3ecae9d..e679fe0b08 100644--- a/rust/cloud-storage/search_service/src/api/search/chat.rs+++ b/rust/cloud-storage/search_service/src/api/search/chat.rs@@ -1,24 +1,13 @@use crate::api::ApiContext;use crate::api::search::simple::SearchError;-use crate::api::search::simple::simple_chat::search_chats;-use axum::{- Extension,- extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},-};use indexmap::IndexMap;-use model::{response::ErrorResponse, user::UserContext};use models_search::chat::{- ChatMessageSearchResult, ChatSearchRequest, ChatSearchResponse, ChatSearchResponseItem,- ChatSearchResponseItemWithMetadata,+ ChatMessageSearchResult, ChatSearchResponseItem, ChatSearchResponseItemWithMetadata,};use opensearch_client::search::model::SearchGotoContent;use sqlx::types::Uuid;use std::collections::HashMap;-use super::SearchPaginationParams;-/// Enriches chat search results with metadata#[tracing::instrument(skip(ctx, results), err)]pub(in crate::api::search) async fn enrich_chats(@@ -50,52 +39,6 @@ pub(in crate::api::search) async fn enrich_chats(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,- path = "/search/chat",- operation_id = "chat_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=ChatSearchResponse),- (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<ChatSearchRequest>,-) -> Result<Response, SearchError> {- tracing::info!("chat_search");- let user_id = user_context.user_id.as_str();-- let results = search_chats_enriched(&ctx, user_id, &query_params, req).await?;-- let result = ChatSearchResponse { results };-- Ok((StatusCode::OK, Json(result)).into_response())-}-pub fn construct_search_result(search_results: Vec<opensearch_client::search::model::SearchHit>,chat_histories: HashMap<String, macro_db_client::chat::get::ChatHistoryInfo>,diff --git a/rust/cloud-storage/search_service/src/api/search/chat/test.rs b/rust/cloud-storage/search_service/src/api/search/chat/test.rsindex 5ac69b9eed..b785a82340 100644--- a/rust/cloud-storage/search_service/src/api/search/chat/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/chat/test.rs@@ -24,6 +24,7 @@ fn create_test_response(content: content.unwrap_or_default(),..Default::default()},+ updated_at: None,}}diff --git a/rust/cloud-storage/search_service/src/api/search/document.rs b/rust/cloud-storage/search_service/src/api/search/document.rsindex 31cd9dfcf7..cb00c224d7 100644--- a/rust/cloud-storage/search_service/src/api/search/document.rs+++ b/rust/cloud-storage/search_service/src/api/search/document.rs@@ -1,16 +1,8 @@-use crate::api::search::simple::{SearchError, simple_document::search_documents};-use axum::{- Extension,- extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},-};+use crate::api::search::simple::SearchError;use indexmap::IndexMap;-use model::{response::ErrorResponse, user::UserContext};use models_opensearch::SearchEntityType;use models_search::document::{- DocumentSearchRequest, DocumentSearchResponse, DocumentSearchResponseItem,- DocumentSearchResponseItemWithMetadata, DocumentSearchResult,+ DocumentSearchResponseItem, DocumentSearchResponseItemWithMetadata, DocumentSearchResult,};use opensearch_client::search::model::SearchGotoContent;use sqlx::types::Uuid;@@ -18,8 +10,6 @@ use std::collections::HashMap;use crate::api::ApiContext;-use super::SearchPaginationParams;-/// Enriches document search results with metadata#[tracing::instrument(skip(ctx, results), err)]pub(in crate::api::search) async fn enrich_documents(@@ -55,51 +45,6 @@ pub(in crate::api::search) async fn enrich_documents(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,- path = "/search/document",- operation_id = "document_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=DocumentSearchResponse),- (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<DocumentSearchRequest>,-) -> Result<Response, SearchError> {- let user_id = user_context.user_id.as_str();-- let results = search_documents_enriched(&ctx, user_id, &query_params, req).await?;-- let result = DocumentSearchResponse { results };-- Ok((StatusCode::OK, Json(result)).into_response())-}-pub fn construct_search_result(search_results: Vec<opensearch_client::search::model::SearchHit>,document_histories: HashMap<diff --git a/rust/cloud-storage/search_service/src/api/search/document/test.rs b/rust/cloud-storage/search_service/src/api/search/document/test.rsindex f0a7339a42..10696474c7 100644--- a/rust/cloud-storage/search_service/src/api/search/document/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/document/test.rs@@ -29,6 +29,7 @@ fn test_construct_search_result_single_document() {content: vec!["Test content".to_string()],..Default::default()},+ updated_at: None,}];let mut document_histories = HashMap::new();@@ -98,6 +99,7 @@ fn test_construct_search_result_multiple_nodes_same_document() {content: vec!["First content".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: "11111111-1111-1111-1111-111111111111".parse().unwrap(),@@ -116,6 +118,7 @@ fn test_construct_search_result_multiple_nodes_same_document() {content: vec!["Second content".to_string()],..Default::default()},+ updated_at: None,},];@@ -184,6 +187,7 @@ fn create_test_document_response(content: content.unwrap_or_default(),..Default::default()},+ updated_at: None,}}@@ -492,6 +496,7 @@ fn test_sort_stability() {content: vec!["third".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: "11111111-1111-1111-1111-111111111111".parse().unwrap(),@@ -510,6 +515,7 @@ fn test_sort_stability() {content: vec!["first".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: "55555555-5555-5555-5555-555555555555".parse().unwrap(),@@ -528,6 +534,7 @@ fn test_sort_stability() {content: vec!["fifth".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: "22222222-2222-2222-2222-222222222222".parse().unwrap(),@@ -546,6 +553,7 @@ fn test_sort_stability() {content: vec!["second".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: "44444444-4444-4444-4444-444444444444".parse().unwrap(),@@ -564,6 +572,7 @@ fn test_sort_stability() {content: vec!["fourth".to_string()],..Default::default()},+ updated_at: None,},];diff --git a/rust/cloud-storage/search_service/src/api/search/email.rs b/rust/cloud-storage/search_service/src/api/search/email.rsindex 27d44f0a4c..e27df80401 100644--- a/rust/cloud-storage/search_service/src/api/search/email.rs+++ b/rust/cloud-storage/search_service/src/api/search/email.rs@@ -1,27 +1,16 @@use crate::api::ApiContext;use crate::api::search::simple::SearchError;-use crate::api::search::simple::simple_email::search_emails;-use axum::{- Extension,- extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},-};use indexmap::IndexMap;-use model::{response::ErrorResponse, user::UserContext};use models_email::service::message::{MessageSenderInfo, MessageSendersRequest, ThreadHistoryInfo, ThreadHistoryRequest,};use models_search::email::{- EmailSearchRequest, EmailSearchResponse, EmailSearchResponseItem,- EmailSearchResponseItemWithMetadata, EmailSearchResult,+ EmailSearchResponseItem, EmailSearchResponseItemWithMetadata, EmailSearchResult,};use opensearch_client::search::model::SearchGotoContent;use sqlx::types::Uuid;use std::collections::{HashMap, HashSet};-use super::SearchPaginationParams;-/// Enriches email search results with metadata#[tracing::instrument(skip(ctx, results), err)]pub(in crate::api::search) async fn enrich_emails(@@ -86,53 +75,6 @@ pub(in crate::api::search) async fn enrich_emails(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,- path = "/search/email",- operation_id = "email_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=EmailSearchResponse),- (status = 400, body=ErrorResponse),- (status = 401, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )- )]-#[tracing::instrument(skip(ctx, user_context, query_params), fields(user_id=user_context.user_id), err)]-pub async fn handler(- user_context: Extension<UserContext>,- State(ctx): State<ApiContext>,- extract::Query(query_params): extract::Query<SearchPaginationParams>,- extract::Json(req): extract::Json<EmailSearchRequest>,-) -> Result<Response, SearchError> {- tracing::info!("email_search");- let user_id = user_context.user_id.as_str();-- let results = search_emails_enriched(&ctx, user_id, &query_params, req).await?;-- let result = EmailSearchResponse { results };-- Ok((StatusCode::OK, Json(result)).into_response())-}-pub fn construct_search_result(search_results: Vec<opensearch_client::search::model::SearchHit>,thread_histories: HashMap<Uuid, ThreadHistoryInfo>,diff --git a/rust/cloud-storage/search_service/src/api/search/email/test.rs b/rust/cloud-storage/search_service/src/api/search/email/test.rsindex abc91ba7f4..dd68ef29b8 100644--- a/rust/cloud-storage/search_service/src/api/search/email/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/email/test.rs@@ -49,6 +49,7 @@ fn test_construct_search_result_single_thread() {content: vec!["Test content".to_string()],..Default::default()},+ updated_at: None,}];let mut thread_histories = HashMap::new();@@ -105,6 +106,7 @@ fn test_sort_stability() {content: vec!["third".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: thread_ids[1],@@ -126,6 +128,7 @@ fn test_sort_stability() {content: vec!["first".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: thread_ids[2],@@ -147,6 +150,7 @@ fn test_sort_stability() {content: vec!["fifth".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: thread_ids[3],@@ -168,6 +172,7 @@ fn test_sort_stability() {content: vec!["second".to_string()],..Default::default()},+ updated_at: None,},opensearch_client::search::model::SearchHit {entity_id: thread_ids[4],@@ -189,6 +194,7 @@ fn test_sort_stability() {content: vec!["fourth".to_string()],..Default::default()},+ updated_at: None,},];diff --git a/rust/cloud-storage/search_service/src/api/search/mod.rs b/rust/cloud-storage/search_service/src/api/search/mod.rsindex 76bbe36416..a6ee60273e 100644--- a/rust/cloud-storage/search_service/src/api/search/mod.rs+++ b/rust/cloud-storage/search_service/src/api/search/mod.rs@@ -14,11 +14,6 @@ pub(in crate::api) mod unified;pub fn router() -> Router<ApiContext> {Router::new().route("/", post(unified::handler))- .route("/document", post(document::handler))- .route("/chat", post(chat::handler))- .route("/email", post(email::handler))- .route("/channel", post(channel::handler))- .route("/project", post(project::handler)).nest("/simple", simple::router())}@@ -26,4 +21,5 @@ pub fn router() -> Router<ApiContext> {pub struct SearchPaginationParams {pub page: Option<u32>,pub page_size: Option<u32>,+ pub cursor: Option<String>,}diff --git a/rust/cloud-storage/search_service/src/api/search/project.rs b/rust/cloud-storage/search_service/src/api/search/project.rsindex 7eba96e7ac..03866fbd6a 100644--- a/rust/cloud-storage/search_service/src/api/search/project.rs+++ b/rust/cloud-storage/search_service/src/api/search/project.rs@@ -1,23 +1,13 @@-use crate::api::search::simple::{SearchError, simple_project::search_projects};-use axum::{- Extension,- extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},-};+use crate::api::search::simple::SearchError;use indexmap::IndexMap;-use model::{response::ErrorResponse, user::UserContext};use models_search::project::{- ProjectSearchRequest, ProjectSearchResponse, ProjectSearchResponseItem,- ProjectSearchResponseItemWithMetadata, ProjectSearchResult,+ ProjectSearchResponseItem, ProjectSearchResponseItemWithMetadata, ProjectSearchResult,};use sqlx::types::Uuid;use std::collections::HashMap;use crate::api::ApiContext;-use super::SearchPaginationParams;-/// Enriches project search results with metadata#[tracing::instrument(skip(ctx, results), err)]pub(in crate::api::search) async fn enrich_projects(@@ -53,53 +43,6 @@ pub(in crate::api::search) async fn enrich_projects(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,- path = "/search/project",- operation_id = "project_search",- params(- ("page" = Option<i64>, Query, description = "The page. Defaults to 0."),- ("page_size" = Option<i64>, Query, description = "The page size. Defaults to 10."),- ),- responses(- (status = 200, body=ProjectSearchResponse),- (status = 400, body=ErrorResponse),- (status = 401, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )- )]-#[tracing::instrument(skip(ctx, user_context, query_params), 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<ProjectSearchRequest>,-) -> Result<Response, SearchError> {- tracing::info!("project_search");- let user_id = user_context.user_id.as_str();-- let results = search_projects_enriched(&ctx, user_id, &query_params, req).await?;-- let result = ProjectSearchResponse { results };-- Ok((StatusCode::OK, Json(result)).into_response())-}-pub fn construct_search_result(search_results: Vec<opensearch_client::search::model::SearchHit>,project_histories: HashMap<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..2be4b8977a--- /dev/null+++ b/rust/cloud-storage/search_service/src/api/search/simple/filter.rs@@ -0,0 +1,159 @@+//! 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,+};++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(Default, Debug, Clone)]+pub struct UnifiedProjectSearchArgs {+ pub project_ids: Vec<String>,+ pub ids_only: bool,+}++/// Trait to convert item_filters into search args+pub(super) trait FilterVariantToSearchArgs {+ type Output;++ fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ user_organization_id: Option<i32>,+ should_include: bool,+ ) -> impl Future<Output = Result<Self::Output, SearchError>> + Send;+}++impl FilterVariantToSearchArgs for item_filters::DocumentFilters {+ type Output = UnifiedDocumentSearchArgs;++ async fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ _user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<Self::Output, SearchError> {+ if !should_include {+ Ok(UnifiedDocumentSearchArgs::default())+ } else {+ let filter_document_response = filter_documents(ctx, user_id, self).await?;++ Ok(UnifiedDocumentSearchArgs {+ document_ids: filter_document_response.document_ids,+ ids_only: filter_document_response.ids_only,+ })+ }+ }+}++impl FilterVariantToSearchArgs for item_filters::ChannelFilters {+ type Output = UnifiedChannelMessageSearchArgs;++ async fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<Self::Output, SearchError> {+ if !should_include {+ Ok(UnifiedChannelMessageSearchArgs::default())+ } else {+ let filter_channel_response =+ filter_channels(ctx, user_id, user_organization_id, self).await?;++ Ok(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 {+ type Output = UnifiedChatSearchArgs;++ async fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ _user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<Self::Output, SearchError> {+ if !should_include {+ Ok(UnifiedChatSearchArgs::default())+ } else {+ let filter_chat_response = filter_chats(ctx, user_id, self).await?;++ Ok(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 {+ type Output = UnifiedProjectSearchArgs;++ async fn filter_to_search_args(+ &self,+ ctx: &ApiContext,+ user_id: &str,+ _user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<Self::Output, SearchError> {+ if !should_include {+ Ok(UnifiedProjectSearchArgs::default())+ } else {+ let filter_project_response = filter_projects(ctx, user_id, self).await?;++ Ok(UnifiedProjectSearchArgs {+ project_ids: filter_project_response.project_ids,+ ids_only: filter_project_response.ids_only,+ })+ }+ }+}++impl FilterVariantToSearchArgs for item_filters::EmailFilters {+ type Output = UnifiedEmailSearchArgs;++ async fn filter_to_search_args(+ &self,+ _ctx: &ApiContext,+ _user_id: &str,+ _user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<Self::Output, SearchError> {+ if !should_include {+ Ok(UnifiedEmailSearchArgs::default())+ } else {+ Ok(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 5bede8bfa5..848e35b727 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@@ -5,10 +5,12 @@ use axum::{response::{IntoResponse, Response},routing::post,};+use email_contact_search::EmailContactSearchError;use model::response::ErrorResponse;use name_search::NameSearchError;use opensearch_client::error::OpensearchClientError;+pub(in crate::api) mod filter;pub(in crate::api) mod simple_channel;pub(in crate::api) mod simple_chat;pub(in crate::api) mod simple_document;@@ -17,13 +19,7 @@ pub(in crate::api) mod simple_project;pub(in crate::api) mod simple_unified;pub fn router() -> Router<ApiContext> {- Router::new()- .route("/", post(simple_unified::handler))- .route("/document", post(simple_document::handler))- .route("/chat", post(simple_chat::handler))- .route("/email", post(simple_email::handler))- .route("/channel", post(simple_channel::handler))- .route("/project", post(simple_project::handler))+ Router::new().route("/", post(simple_unified::handler))}#[derive(thiserror::Error, Debug)]@@ -43,12 +39,18 @@ pub enum SearchError {/// No query or terms provided#[error("query or terms must be provided and at least 3 characters")]NoQueryOrTermsProvided,+ #[error("searching with an invalid cursor")]+ /// Searching with an invalid cursor+ InvalidCursor,/// Opensearch error occurred#[error("unable to search")]Search(#[from] OpensearchClientError),/// Name search error occurred#[error("unable to name search")]NameSearch(#[from] NameSearchError),+ /// Email contact search error occurred+ #[error("unable to search email contacts")]+ EmailContactSearch(#[from] EmailContactSearchError),/// Internal error occurred#[error("internal error")]InternalError(#[from] anyhow::Error),@@ -60,10 +62,12 @@ impl IntoResponse for SearchError {SearchError::NoUserId | SearchError::InvalidUserId(_) => StatusCode::UNAUTHORIZED,SearchError::InvalidPageSize| SearchError::InvalidQuerySize+ | SearchError::InvalidCursor| SearchError::NoQueryOrTermsProvided => StatusCode::BAD_REQUEST,- SearchError::Search(_) | SearchError::NameSearch(_) | SearchError::InternalError(_) => {- StatusCode::INTERNAL_SERVER_ERROR- }+ SearchError::Search(_)+ | SearchError::NameSearch(_)+ | SearchError::EmailContactSearch(_)+ | SearchError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,};(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 914a32ec88..aa75fabb36 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,61 +1,9 @@-use crate::api::search::{SearchPaginationParams, simple::SearchError};+use crate::api::search::simple::SearchError;use item_filters::ChannelFilters;use std::collections::HashSet;-use axum::{- Extension,- extract::{self, State},- response::Json,-};-use model::{response::ErrorResponse, user::UserContext};-use models_search::{- SearchOn, SimpleSearchResponse,- channel::{ChannelSearchRequest, SimpleChannelSearchResponse},-};-use opensearch_client::search::channels::ChannelMessageSearchArgs;-use crate::api::ApiContext;-/// Perform a search through your channels-/// This is a simple search where we do not group your results by channel id.-#[utoipa::path(- post,- path = "/search/simple/channel",- operation_id = "simple_channel_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=SimpleChannelSearchResponse),- (status = 400, body=ErrorResponse),- (status = 401, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )- )]-#[tracing::instrument(skip(ctx, user_context, query_params), 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<ChannelSearchRequest>,-) -> Result<Json<SimpleSearchResponse>, SearchError> {- tracing::info!("simple_channel_search");-- let results = search_channels(- &ctx,- user_context.user_id.as_str(),- user_context.organization_id,- &query_params,- req,- )- .await?;-- Ok(Json(SimpleSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }))-}-pub(in crate::api::search) struct FilterChannelResponse {pub channel_ids: Vec<sqlx::types::Uuid>,}@@ -106,79 +54,3 @@ pub(in crate::api::search) async fn filter_channels(Ok(FilterChannelResponse { channel_ids })}--pub(in crate::api::search) async fn search_channels(- ctx: &ApiContext,- user_id: &str,- organization_id: Option<i32>,- query_params: &SearchPaginationParams,- req: ChannelSearchRequest,-) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {- // We don't support searching on channels by name- if let SearchOn::Name = req.search_on {- 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_channel_response = filter_channels(ctx, user_id, organization_id, &filters).await?;-- 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: filter_channel_response- .channel_ids- .iter()- .map(|c| c.to_string())- .collect(),- thread_ids: filters.thread_ids,- mentions: filters.mentions,- page,- page_size,- match_type: req.match_type.to_string(),- sender_ids: filters.sender_ids,- search_on: req.search_on.into(),- collapse: req.collapse.unwrap_or(false),- ids_only: true, // For channel message search, we always want to search over the channel ids only- disable_recency: req.disable_recency,- })- .await- .map_err(SearchError::Search)?;-- Ok(results)-}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 1550af5f33..2ac9797259 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@@ -1,64 +1,13 @@-use std::future::ready;--use crate::api::search::{SearchPaginationParams, simple::SearchError};-use axum::{- Extension,- extract::{self, State},- response::Json,-};-use futures::future::Either;+use crate::api::search::simple::SearchError;use item_filters::ChatFilters;use macro_user_id::user_id::MacroUserId;-use model::{- item::{ShareableItem, ShareableItemType},- response::ErrorResponse,- user::UserContext,-};-use models_search::{- SearchOn, SimpleSearchResponse,- chat::{ChatSearchRequest, SimpleChatSearchResponse},-};-use opensearch_client::search::{- chats::ChatSearchArgs,- model::{Highlight, SearchHit},-};-use sqlx::types::Uuid;+use model::item::{ShareableItem, ShareableItemType};+use opensearch_client::search::model::{Highlight, SearchHit};+use sqlx::{Pool, Postgres, types::Uuid};use crate::api::ApiContext;-/// Perform a search through your chats-/// This is a simple search where we do not group your results by chat id.-#[utoipa::path(- post,- path = "/search/simple/chat",- operation_id = "simple_chat_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=SimpleChatSearchResponse),- (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<ChatSearchRequest>,-) -> Result<Json<SimpleSearchResponse>, SearchError> {- tracing::info!("simple_chat_search");-- let results = search_chats(&ctx, user_context.user_id.as_str(), &query_params, req).await?;-- Ok(Json(SimpleSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }))-}-+#[derive(Debug)]pub(in crate::api::search) struct FilterChatResponse {pub chat_ids: Vec<String>,pub ids_only: bool,@@ -149,110 +98,57 @@ pub(in crate::api::search) async fn filter_chats(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::model::SearchHit>, SearchError> {- 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 = 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);+/// Performs the name search over chat names+#[tracing::instrument(skip(db), err)]+pub(in crate::api::search::simple) async fn search_names<'a>(+ db: &Pool<Postgres>,+ user_id: &MacroUserId<macro_user_id::lowercased::Lowercase<'a>>,+ filter_chat_response: &FilterChatResponse,+ term: String,+ limit: u32,+ cursor: models_search_cursor::SearchCursorOption,+) -> Result<(Vec<SearchHit>, models_search_cursor::SearchCursorOption), SearchError> {+ // If cursor is Done, no more results to fetch+ let inner_cursor = match cursor {+ models_search_cursor::SearchCursorOption::Done => {+ return Ok((vec![], models_search_cursor::SearchCursorOption::Done));}-- vec![query]- } else {- return Err(SearchError::NoQueryOrTermsProvided);+ models_search_cursor::SearchCursorOption::NotDone(c) => c,};- let filters = req.filters.unwrap_or_default();-- let filter_chat_response = filter_chats(ctx, user_id.as_ref(), &filters).await?;-- if filter_chat_response.chat_ids.is_empty() && filter_chat_response.ids_only {- return Ok(Vec::new());- }-let chat_uuids = filter_chat_response.chat_ids.iter().map(|c| c.parse().unwrap()).collect::<Vec<Uuid>>();- let name_results = match req.search_on {- SearchOn::Name | SearchOn::NameContent => Either::Left(name_search::search_chat_names(- &ctx.db,- &user_id,- &chat_uuids,- terms[0].clone(),- filter_chat_response.ids_only,- page_size,- page * page_size,- )),- SearchOn::Content => Either::Right(ready(Ok(Vec::new()))),- };-- let content_results = match req.search_on {- SearchOn::Content | SearchOn::NameContent => {- Either::Left(ctx.opensearch_client.search_chats(ChatSearchArgs {- terms,- user_id: user_id.as_ref().to_string(),- 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: filter_chat_response.ids_only,- disable_recency: req.disable_recency,- }))- }- SearchOn::Name => Either::Right(ready(Ok(Vec::new()))),- };-- let (name_result, content_result) = tokio::join!(name_results, content_results);- let name_result = name_result.map_err(SearchError::NameSearch)?;- let content_result = content_result.map_err(SearchError::Search)?;-- let results: Vec<SearchHit> = name_result- .into_iter()- .map(|n| SearchHit {- entity_id: n.entity_id,- entity_type: n.entity_type,- score: None,- highlight: Highlight {- name: Some(n.name),- ..Default::default()- },- goto: None,- })- .chain(content_result)- .collect();-- Ok(results)+ name_search::search_chat_names(+ db,+ user_id,+ &chat_uuids,+ term,+ filter_chat_response.ids_only,+ limit,+ inner_cursor,+ )+ .await+ .map_err(SearchError::NameSearch)+ .map(|response| {+ let hits = response+ .items+ .into_iter()+ .map(|n| SearchHit {+ entity_id: n.entity_id,+ entity_type: n.entity_type,+ score: None,+ highlight: Highlight {+ name: Some(n.name),+ ..Default::default()+ },+ goto: None,+ updated_at: Some(n.updated_at),+ })+ .collect();+ (hits, response.cursor)+ })}diff --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 584bb28a4d..a6f55d9453 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@@ -1,64 +1,13 @@-use std::future::ready;--use crate::api::search::{SearchPaginationParams, simple::SearchError};-use axum::{- Extension,- extract::{self, State},- response::Json,-};-use futures::future::Either;+use crate::api::search::simple::SearchError;use item_filters::DocumentFilters;-use macro_user_id::user_id::MacroUserId;-use model::{- item::{ShareableItem, ShareableItemType},- response::ErrorResponse,- user::UserContext,-};-use models_search::{- SearchOn, SimpleSearchResponse,- document::{DocumentSearchRequest, SimpleDocumentSearchResponse},-};-use opensearch_client::search::{- documents::DocumentSearchArgs,- model::{Highlight, SearchHit},-};-use sqlx::types::Uuid;+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use model::item::{ShareableItem, ShareableItemType};+use opensearch_client::search::model::{Highlight, SearchHit};+use sqlx::{Pool, Postgres, types::Uuid};use crate::api::ApiContext;-/// Perform a search through your documents-/// This is a simple search where we do not group yor results by document id.-#[utoipa::path(- post,- path = "/search/simple/document",- operation_id = "simple_document_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=SimpleDocumentSearchResponse),- (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<DocumentSearchRequest>,-) -> Result<Json<SimpleSearchResponse>, SearchError> {- tracing::info!("simple_document_search");-- let results = search_documents(&ctx, user_context.user_id.as_str(), &query_params, req).await?;-- Ok(Json(SimpleSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }))-}-+#[derive(Debug)]pub(in crate::api::search) struct FilterDocumentResponse {pub document_ids: Vec<String>,pub ids_only: bool,@@ -176,109 +125,57 @@ pub(in crate::api::search) async fn filter_documents(})}-/// 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<SearchHit>, SearchError> {- 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 = 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);+/// Performs the name search over document names+#[tracing::instrument(skip(db), err)]+pub(in crate::api::search::simple) async fn search_names<'a>(+ db: &Pool<Postgres>,+ user_id: &MacroUserId<Lowercase<'a>>,+ filter_document_response: &FilterDocumentResponse,+ term: String,+ limit: u32,+ cursor: models_search_cursor::SearchCursorOption,+) -> Result<(Vec<SearchHit>, models_search_cursor::SearchCursorOption), SearchError> {+ // If cursor is Done, no more results to fetch+ let inner_cursor = match cursor {+ models_search_cursor::SearchCursorOption::Done => {+ return Ok((vec![], models_search_cursor::SearchCursorOption::Done));}-- vec![query.clone()]- } else {- return Err(SearchError::NoQueryOrTermsProvided);+ models_search_cursor::SearchCursorOption::NotDone(c) => c,};- let filter_document_response =- filter_documents(ctx, user_id.as_ref(), &req.filters.unwrap_or_default()).await?;-- if filter_document_response.document_ids.is_empty() && filter_document_response.ids_only {- return Ok(Vec::new());- }-let document_uuids = filter_document_response.document_ids.iter().map(|d| d.parse().unwrap()).collect::<Vec<Uuid>>();- let name_results = match req.search_on {- SearchOn::Name | SearchOn::NameContent => Either::Left(name_search::search_document_names(- &ctx.db,- &user_id,- &document_uuids,- terms[0].clone(),- filter_document_response.ids_only,- page_size,- page * page_size,- )),- SearchOn::Content => Either::Right(ready(Ok(Vec::new()))),- };-- let content_results = match req.search_on {- SearchOn::Content | SearchOn::NameContent => {- Either::Left(ctx.opensearch_client.search_documents(DocumentSearchArgs {- terms: terms.clone(),- user_id: user_id.as_ref().to_string(),- document_ids: filter_document_response.document_ids.clone(),- page,- page_size,- match_type: req.match_type.to_string(),- search_on: req.search_on.into(),- collapse: req.collapse.unwrap_or(false),- ids_only: filter_document_response.ids_only,- disable_recency: req.disable_recency,- }))- }- SearchOn::Name => Either::Right(ready(Ok(Vec::new()))),- };-- let (name_result, content_result) = tokio::join!(name_results, content_results);- let name_result = name_result.map_err(SearchError::NameSearch)?;- let content_result = content_result.map_err(SearchError::Search)?;-- let results: Vec<SearchHit> = name_result- .into_iter()- .map(|n| SearchHit {- entity_id: n.entity_id,- entity_type: n.entity_type,- score: None,- highlight: Highlight {- name: Some(n.name),- ..Default::default()- },- goto: None,- })- .chain(content_result)- .collect();-- Ok(results)+ name_search::search_document_names(+ db,+ user_id,+ &document_uuids,+ term,+ filter_document_response.ids_only,+ limit,+ inner_cursor,+ )+ .await+ .map_err(SearchError::NameSearch)+ .map(|response| {+ let hits = response+ .items+ .into_iter()+ .map(|n| SearchHit {+ entity_id: n.entity_id,+ entity_type: n.entity_type,+ score: None,+ highlight: Highlight {+ name: Some(n.name),+ ..Default::default()+ },+ goto: None,+ updated_at: Some(n.updated_at),+ })+ .collect();+ (hits, response.cursor)+ })}diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rsindex f41a95f42f..e3bf62651a 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs@@ -1,159 +1,148 @@-use std::future::ready;--use crate::api::search::{SearchPaginationParams, simple::SearchError};-use axum::{- Extension,- extract::{self, State},- response::Json,-};-use futures::future::Either;+use crate::api::search::simple::SearchError;+use email_contact_search::ContactType;use macro_user_id::user_id::MacroUserId;-use model::{response::ErrorResponse, user::UserContext};-use models_search::{- SearchOn, SimpleSearchResponse,- email::{EmailSearchRequest, SimpleEmailSearchResponse},-};-use opensearch_client::search::{- emails::EmailSearchArgs,- model::{Highlight, SearchHit},-};-use sqlx::types::Uuid;--use crate::api::ApiContext;--/// Perform a search through your emails-/// This is a simple search where we do not group your results by thread id.-#[utoipa::path(- post,- path = "/search/simple/email",- operation_id = "simple_email_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=SimpleEmailSearchResponse),- (status = 400, body=ErrorResponse),- (status = 401, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )- )]-#[tracing::instrument(skip(ctx, user_context, query_params), 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<EmailSearchRequest>,-) -> Result<Json<SimpleSearchResponse>, SearchError> {- tracing::info!("simple_email_search");-- let results = search_emails(&ctx, user_context.user_id.as_str(), &query_params, req).await?;-- Ok(Json(SimpleSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }))+use models_opensearch::SearchEntityType;+use opensearch_client::search::model::{Highlight, SearchGotoContent, SearchGotoEmail, SearchHit};+use sqlx::{Pool, Postgres, types::Uuid};++#[derive(Debug)]+pub(in crate::api::search) struct FilterEmailResponse {+ pub thread_ids: Vec<String>,+ pub ids_only: bool,}-pub(in crate::api::search) async fn search_emails(- ctx: &ApiContext,- user_id: &str,- query_params: &SearchPaginationParams,- req: EmailSearchRequest,-) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {- 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 = 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);+/// Performs the name search over email subjects+#[tracing::instrument(skip(db), err)]+pub(in crate::api::search::simple) async fn search_names<'a>(+ db: &Pool<Postgres>,+ user_id: &MacroUserId<macro_user_id::lowercased::Lowercase<'a>>,+ filter_email_response: &FilterEmailResponse,+ term: String,+ limit: u32,+ cursor: models_search_cursor::SearchCursorOption,+) -> Result<(Vec<SearchHit>, models_search_cursor::SearchCursorOption), SearchError> {+ // If cursor is Done, no more results to fetch+ let inner_cursor = match cursor {+ models_search_cursor::SearchCursorOption::Done => {+ return Ok((vec![], models_search_cursor::SearchCursorOption::Done));}-- vec![query.clone()]- } else {- return Err(SearchError::NoQueryOrTermsProvided);+ models_search_cursor::SearchCursorOption::NotDone(c) => c,};- let filters = req.filters.unwrap_or_default();-- // For emails, thread_ids are not pre-filtered like documents/chats- // Empty vec means search all accessible emails for the user- let thread_uuids: Vec<Uuid> = vec![];-- let name_results = match req.search_on {- SearchOn::Name | SearchOn::NameContent => Either::Left(name_search::search_email_subjects(- &ctx.db,- &user_id,- &thread_uuids,- terms[0].clone(),- false, // ids_only is false since we're not pre-filtering- page_size,- page * page_size,- )),- SearchOn::Content => Either::Right(ready(Ok(Vec::new()))),- };+ let thread_uuids = filter_email_response+ .thread_ids+ .iter()+ .map(|t| t.parse().unwrap())+ .collect::<Vec<Uuid>>();++ name_search::search_email_subjects(+ db,+ user_id,+ &thread_uuids,+ term,+ filter_email_response.ids_only,+ limit,+ inner_cursor,+ )+ .await+ .map_err(SearchError::NameSearch)+ .map(|response| {+ let hits = response+ .items+ .into_iter()+ .map(|n| SearchHit {+ entity_id: n.entity_id,+ entity_type: n.entity_type,+ score: None,++ highlight: Highlight {+ name: Some(n.name),+ ..Default::default()+ },+ goto: None,++ updated_at: Some(n.updated_at),+ })+ .collect();+ (hits, response.cursor)+ })+}- let content_results = match req.search_on {- SearchOn::Content | SearchOn::NameContent => {- Either::Left(ctx.opensearch_client.search_emails(EmailSearchArgs {- terms: terms.clone(),- user_id: user_id.as_ref().to_string(),- thread_ids: vec![],- link_ids: vec![],- sender: filters.senders,- cc: filters.cc,- bcc: filters.bcc,- recipients: filters.recipients,- page,- page_size,- match_type: req.match_type.to_string(),- search_on: req.search_on.into(),- collapse: req.collapse.unwrap_or(false),- ids_only: false,- disable_recency: req.disable_recency,- }))+/// Performs the contact search over email contacts (sender, recipients, cc, bcc)+#[tracing::instrument(skip(db), err)]+pub(in crate::api::search::simple) async fn search_contacts<'a>(+ db: &Pool<Postgres>,+ user_id: MacroUserId<macro_user_id::lowercased::Lowercase<'a>>,+ term: String,+ limit: u32,+ cursor: models_search_cursor::SearchCursorOption,+) -> Result<(Vec<SearchHit>, models_search_cursor::SearchCursorOption), SearchError> {+ // If cursor is Done, no more results to fetch+ let inner_cursor = match cursor {+ models_search_cursor::SearchCursorOption::Done => {+ return Ok((vec![], models_search_cursor::SearchCursorOption::Done));}- SearchOn::Name => Either::Right(ready(Ok(Vec::new()))),+ models_search_cursor::SearchCursorOption::NotDone(c) => c,};- let (name_result, content_result) = tokio::join!(name_results, content_results);- let name_result = name_result.map_err(SearchError::NameSearch)?;- let content_result = content_result.map_err(SearchError::Search)?;-- let results: Vec<SearchHit> = name_result- .into_iter()- .map(|n| SearchHit {- entity_id: n.entity_id,- entity_type: n.entity_type,- score: None,- highlight: Highlight {- name: Some(n.name),- ..Default::default()- },- goto: None,+ email_contact_search::search_email_contacts(db, user_id, term, limit, inner_cursor)+ .await+ .map_err(SearchError::EmailContactSearch)+ .map(|response| {+ let hits = response+ .items+ .into_iter()+ .map(|contact| {+ // Build highlight based on contact type+ let highlight = match contact.contact_type {+ ContactType::From => Highlight {+ sender: contact.contact_name.or(Some(contact.contact_email.clone())),+ ..Default::default()+ },+ ContactType::To => Highlight {+ recipients: vec![+ contact+ .contact_name+ .unwrap_or_else(|| contact.contact_email.clone()),+ ],+ ..Default::default()+ },+ ContactType::Cc => Highlight {+ cc: vec![+ contact+ .contact_name+ .unwrap_or_else(|| contact.contact_email.clone()),+ ],+ ..Default::default()+ },+ ContactType::Bcc => Highlight {+ bcc: vec![+ contact+ .contact_name+ .unwrap_or_else(|| contact.contact_email.clone()),+ ],+ ..Default::default()+ },+ };++ SearchHit {+ entity_id: contact.thread_id,+ entity_type: SearchEntityType::Emails,+ score: None,+ highlight,+ goto: Some(SearchGotoContent::Emails(SearchGotoEmail {+ email_message_id: contact.message_id,+ bcc: vec![],+ cc: vec![],+ labels: vec![],+ sent_at: None,+ sender: contact.contact_email,+ recipients: vec![],+ })),+ updated_at: Some(contact.updated_at),+ }+ })+ .collect();+ (hits, response.cursor)})- .chain(content_result)- .collect();-- Ok(results)}diff --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 b543b162f4..0f3a708c55 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@@ -1,56 +1,13 @@-use crate::api::search::{SearchPaginationParams, simple::SearchError};-use axum::{- Extension,- extract::{self, State},- response::Json,-};+use crate::api::search::simple::SearchError;use item_filters::ProjectFilters;use macro_user_id::user_id::MacroUserId;-use model::{- item::{ShareableItem, ShareableItemType},- response::ErrorResponse,- user::UserContext,-};-use models_search::project::{ProjectSearchRequest, SimpleProjectSearchResponse};-use models_search::{SearchOn, SimpleSearchResponse};+use model::item::{ShareableItem, ShareableItemType};use opensearch_client::search::model::{Highlight, SearchHit};-use sqlx::types::Uuid;+use sqlx::{Pool, Postgres, types::Uuid};use crate::api::ApiContext;-/// Perform a search through your projects-/// This is a simple search where we do not group your results by project id.-#[utoipa::path(- post,- path = "/search/simple/project",- operation_id = "simple_project_search",- params(- ("page" = Option<i64>, Query, description = "The page. Defaults to 0."),- ("page_size" = Option<i64>, Query, description = "The page size. Defaults to 10."),- ),- responses(- (status = 200, body=SimpleProjectSearchResponse),- (status = 400, body=ErrorResponse),- (status = 401, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )- )]-#[tracing::instrument(skip(ctx, user_context, query_params), 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<ProjectSearchRequest>,-) -> Result<Json<SimpleSearchResponse>, SearchError> {- tracing::info!("simple_project_search");-- let results = search_projects(&ctx, user_context.user_id.as_str(), &query_params, req).await?;-- Ok(Json(SimpleSearchResponse {- results: results.into_iter().map(|a| a.into()).collect(),- }))-}-+#[derive(Debug)]pub(in crate::api::search) struct FilterProjectResponse {pub project_ids: Vec<String>,pub ids_only: bool,@@ -139,89 +96,57 @@ pub(in crate::api::search) async fn filter_projects(})}-pub(in crate::api::search) async fn search_projects(- ctx: &ApiContext,- user_id: &str,- query_params: &SearchPaginationParams,- req: ProjectSearchRequest,-) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {- // content search is not applicable for projects- if let SearchOn::Content = req.search_on {- return Ok(Vec::new());- }-- 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 = 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);+/// Performs the name search over project names+#[tracing::instrument(skip(db), err)]+pub(in crate::api::search::simple) async fn search_names<'a>(+ db: &Pool<Postgres>,+ user_id: &MacroUserId<macro_user_id::lowercased::Lowercase<'a>>,+ filter_project_response: &FilterProjectResponse,+ term: String,+ limit: u32,+ cursor: models_search_cursor::SearchCursorOption,+) -> Result<(Vec<SearchHit>, models_search_cursor::SearchCursorOption), SearchError> {+ // If cursor is Done, no more results to fetch+ let inner_cursor = match cursor {+ models_search_cursor::SearchCursorOption::Done => {+ return Ok((vec![], models_search_cursor::SearchCursorOption::Done));}-- vec![query]- } else {- return Err(SearchError::NoQueryOrTermsProvided);+ models_search_cursor::SearchCursorOption::NotDone(c) => c,};- let filters = req.filters.unwrap_or_default();-- let filter_project_response = filter_projects(ctx, user_id.as_ref(), &filters).await?;-- if filter_project_response.project_ids.is_empty() && filter_project_response.ids_only {- return Ok(Vec::new());- }-- let project_ids = filter_project_response+ let project_uuids = filter_project_response.project_ids.iter().map(|p| p.parse().unwrap()).collect::<Vec<Uuid>>();- let results = name_search::search_project_names(- &ctx.db,- &user_id,- &project_ids,- terms[0].clone(),+ name_search::search_project_names(+ db,+ user_id,+ &project_uuids,+ term,filter_project_response.ids_only,- page_size,- page * page_size,+ limit,+ inner_cursor,)- .await?;-- let results: Vec<SearchHit> = results- .into_iter()- .map(|n| SearchHit {- entity_id: n.entity_id,- entity_type: n.entity_type,- score: None,- highlight: Highlight {- name: Some(n.name),- ..Default::default()- },- goto: None,- })- .collect();-- Ok(results)+ .await+ .map_err(SearchError::NameSearch)+ .map(|response| {+ let hits = response+ .items+ .into_iter()+ .map(|n| SearchHit {+ entity_id: n.entity_id,+ entity_type: n.entity_type,+ score: None,+ highlight: Highlight {+ name: Some(n.name),+ ..Default::default()+ },+ goto: None,+ updated_at: Some(n.updated_at),+ })+ .collect();+ (hits, response.cursor)+ })}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.rsindex 24887ab38d..eaa733822d 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,29 +1,86 @@+use crate::api::search::simple::filter::FilterVariantToSearchArgs;++use crate::api::search::simple::{simple_chat, simple_document, simple_email, simple_project};use crate::api::{ApiContext,- search::{- SearchPaginationParams,- simple::{- SearchError, simple_channel::search_channels, simple_chat::search_chats,- simple_document::search_documents, simple_email::search_emails,- simple_project::search_projects,- },- },+ search::{SearchPaginationParams, simple::SearchError},};use axum::{Extension,extract::{self, State},response::Json,};+use macro_user_id::user_id::MacroUserId;use model::{response::ErrorResponse, user::UserContext};+use models_search::unified::generate_unified_search_indices;use models_search::{- SimpleSearchResponse,- channel::ChannelSearchRequest,- chat::ChatSearchRequest,- document::DocumentSearchRequest,- email::EmailSearchRequest,- project::ProjectSearchRequest,+ SearchOn, SimpleSearchResponse,unified::{SimpleUnifiedSearchResponse, UnifiedSearchIndex, UnifiedSearchRequest},};+use models_search_cursor::{SearchCursor, SearchCursorOption, SearchMethodCursor};+use opensearch_client::search::model::SearchHit;+use opensearch_client::search::unified::UnifiedSearchArgs;++/// Identifies the source of a search result for cursor regeneration+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum SearchSource {+ DocumentName,+ ChatName,+ EmailSubject,+ EmailContact,+ ProjectName,+ Content,+}++/// Wrapper for SearchHit that tracks its source for cursor regeneration+struct TaggedSearchHit {+ hit: SearchHit,+ source: SearchSource,+}++/// Find the last TaggedSearchHit matching a given source+fn find_last_of_source(+ results: &[TaggedSearchHit],+ source: SearchSource,+) -> Option<&TaggedSearchHit> {+ results.iter().rev().find(|h| h.source == source)+}++/// 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,+ })+}++/// 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)+fn compute_next_cursor(+ next_cursor_from_search: &SearchCursorOption,+ included_count: usize,+ original_count: usize,+ last_included_hit: Option<&TaggedSearchHit>,+ original_cursor: &SearchCursorOption,+) -> SearchCursorOption {+ if next_cursor_from_search.is_done() {+ SearchCursorOption::Done+ } else if included_count < original_count || next_cursor_from_search.has_more() {+ if included_count > 0 {+ SearchCursorOption::NotDone(last_included_hit.and_then(cursor_from_tagged))+ } else {+ original_cursor.clone()+ }+ } else {+ SearchCursorOption::Done+ }+}/// Creates a unified search request and performs the search/// by calling individual simple search endpoints for each entity type@@ -33,12 +90,37 @@ pub(in crate::api::search) async fn perform_unified_search(user_context: &UserContext,query_params: SearchPaginationParams,req: UnifiedSearchRequest,-) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {- let user_id = &user_context.user_id;+) -> Result<+ (+ Vec<opensearch_client::search::model::SearchHit>,+ Option<String>,+ ),+ 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 search_on = req.search_on;+ let user_organization_id = user_context.organization_id;+ let collapse = req.collapse.unwrap_or(false);++ // Parse cursor from query params+ let cursor: Option<SearchCursor> = query_params+ .cursor+ .as_ref()+ .and_then(|c| SearchCursor::decode(c));++ if let Some(cursor) = cursor.as_ref()+ && cursor.is_exhausted()+ {+ return Err(SearchError::InvalidCursor);+ }let page_size = query_params.page_size.unwrap_or(10);if !(0..=100).contains(&page_size) {@@ -58,8 +140,16 @@ pub(in crate::api::search) async fn perform_unified_search(return Err(SearchError::NoQueryOrTermsProvided);}- let include = &req.include;+ let match_type = req.match_type;+ let disable_recency = req.disable_recency;+ let include = req.include;+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 doc_filters = filters.document.unwrap_or_default();+ let project_filters = filters.project.unwrap_or_default();let should_include_documents =include.is_empty() || include.contains(&UnifiedSearchIndex::Documents);@@ -70,112 +160,402 @@ pub(in crate::api::search) async fn perform_unified_search(include.is_empty() || include.contains(&UnifiedSearchIndex::Projects);let should_include_emails = include.is_empty() || include.contains(&UnifiedSearchIndex::Emails);- // Build individual search requests for each entity type- let doc_request = DocumentSearchRequest {- terms: Some(terms.clone()),- query: req.query.clone(),- match_type: req.match_type,- search_on: req.search_on,- collapse: req.collapse,- disable_recency: req.disable_recency,- filters: Some(filters.document.unwrap_or_default()),- };+ // Await all tasks in parallel+ let (+ filter_document_response,+ filter_channel_response,+ filter_chat_response,+ filter_email_response,+ filter_project_response,+ ) = tokio::try_join!(+ doc_filters.filter_to_search_args(+ ctx,+ user_id.as_ref(),+ user_organization_id,+ should_include_documents,+ ),+ channel_filters.filter_to_search_args(+ ctx,+ user_id.as_ref(),+ user_organization_id,+ should_include_channels,+ ),+ chat_filters.filter_to_search_args(+ ctx,+ user_id.as_ref(),+ user_organization_id,+ should_include_chats,+ ),+ email_filters.filter_to_search_args(+ ctx,+ user_id.as_ref(),+ user_organization_id,+ should_include_emails,+ ),+ project_filters.filter_to_search_args(+ ctx,+ user_id.as_ref(),+ user_organization_id,+ should_include_projects+ )+ )+ .map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;- let chat_request = ChatSearchRequest {- terms: Some(terms.clone()),- query: req.query.clone(),- match_type: req.match_type,- search_on: req.search_on,- collapse: req.collapse,- disable_recency: req.disable_recency,- filters: Some(filters.chat.unwrap_or_default()),- };+ // Clone terms for use in name searches+ let name_search_term = terms[0].clone();- let email_request = EmailSearchRequest {- terms: Some(terms.clone()),- query: req.query.clone(),- match_type: req.match_type,- search_on: req.search_on,- collapse: req.collapse,- disable_recency: req.disable_recency,- filters: Some(filters.email.unwrap_or_default()),- };+ // Extract individual cursors from the combined cursor (SearchCursorOption)+ // Clone for use in async blocks and for cursor regeneration+ let document_cursor = cursor+ .as_ref()+ .map(|c| c.document_name_cursor.clone())+ .unwrap_or_default();+ let chat_cursor = cursor+ .as_ref()+ .map(|c| c.chat_name_cursor.clone())+ .unwrap_or_default();+ let email_cursor = cursor+ .as_ref()+ .map(|c| c.email_subject_cursor.clone())+ .unwrap_or_default();+ let email_contact_cursor = cursor+ .as_ref()+ .map(|c| c.email_contact_cursor.clone())+ .unwrap_or_default();+ let project_cursor = cursor+ .as_ref()+ .map(|c| c.project_name_cursor.clone())+ .unwrap_or_default();- let project_request = ProjectSearchRequest {- terms: Some(terms.clone()),- query: req.query.clone(),- match_type: req.match_type,- search_on: req.search_on,- collapse: req.collapse,- disable_recency: req.disable_recency,- filters: Some(filters.project.unwrap_or_default()),- };+ let content_cursor = cursor+ .as_ref()+ .map(|c| c.content_cursor.clone())+ .unwrap_or_default();- let channel_request = ChannelSearchRequest {- terms: Some(terms.clone()),- query: req.query.clone(),- match_type: req.match_type,- search_on: req.search_on,- collapse: req.collapse,- disable_recency: req.disable_recency,- filters: Some(filters.channel.unwrap_or_default()),+ // Clone cursors for passing to search functions (originals needed for cursor regeneration)+ let document_cursor_for_search = document_cursor.clone();+ let chat_cursor_for_search = chat_cursor.clone();+ let email_cursor_for_search = email_cursor.clone();+ let email_contact_cursor_for_search = email_contact_cursor.clone();+ let project_cursor_for_search = project_cursor.clone();+ let content_cursor_for_search = content_cursor.clone();++ let unified_search_args = UnifiedSearchArgs {+ terms,+ user_id: user_id.as_ref().to_string(),+ page: 0, // With cursor-based pagination, we always start from "page 0" relative to cursor+ page_size,+ cursor: content_cursor_for_search,+ 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.clone(),+ email_search_args: filter_email_response.clone(),+ channel_message_search_args: filter_channel_response,+ chat_search_args: filter_chat_response.clone(),};// Call search functions in parallel for included entity types- let (doc_results, chat_results, email_results, project_results, channel_results) = tokio::join!(+ // search_names handles Done cursors internally by returning early+ let (+ doc_name_results,+ chat_results,+ email_results,+ email_contact_results,+ project_results,+ content_results,+ ) = tokio::join!(async {if should_include_documents {- search_documents(ctx, user_id, &query_params, doc_request).await+ match search_on {+ SearchOn::Name | SearchOn::NameContent => {+ simple_document::search_names(+ &ctx.db,+ &user_id,+ &simple_document::FilterDocumentResponse {+ ids_only: filter_document_response.ids_only,+ document_ids: filter_document_response.document_ids,+ },+ name_search_term.clone(),+ page_size,+ document_cursor_for_search,+ )+ .await+ }+ SearchOn::Content => Ok((vec![], SearchCursorOption::Done)),+ }} else {- Ok(vec![])+ Ok((vec![], SearchCursorOption::Done))}},async {if should_include_chats {- search_chats(ctx, user_id, &query_params, chat_request).await+ match search_on {+ SearchOn::Name | SearchOn::NameContent => {+ simple_chat::search_names(+ &ctx.db,+ &user_id,+ &simple_chat::FilterChatResponse {+ ids_only: filter_chat_response.ids_only,+ chat_ids: filter_chat_response.chat_ids,+ },+ name_search_term.clone(),+ page_size,+ chat_cursor_for_search,+ )+ .await+ }+ SearchOn::Content => Ok((vec![], SearchCursorOption::Done)),+ }} else {- Ok(vec![])+ Ok((vec![], SearchCursorOption::Done))}},async {if should_include_emails {- search_emails(ctx, user_id, &query_params, email_request).await+ match search_on {+ SearchOn::Name | SearchOn::NameContent => {+ simple_email::search_names(+ &ctx.db,+ &user_id,+ &simple_email::FilterEmailResponse {+ ids_only: false,+ thread_ids: filter_email_response.thread_ids,+ },+ name_search_term.clone(),+ page_size,+ email_cursor_for_search,+ )+ .await+ }+ SearchOn::Content => Ok((vec![], SearchCursorOption::Done)),+ }} else {- Ok(vec![])+ Ok((vec![], SearchCursorOption::Done))}},async {- if should_include_projects {- search_projects(ctx, user_id, &query_params, project_request).await+ if should_include_emails {+ match search_on {+ SearchOn::NameContent => {+ simple_email::search_contacts(+ &ctx.db,+ user_id.clone(),+ name_search_term.clone(),+ page_size,+ email_contact_cursor_for_search,+ )+ .await+ }+ SearchOn::Name | SearchOn::Content => Ok((vec![], SearchCursorOption::Done)),+ }} else {- Ok(vec![])+ Ok((vec![], SearchCursorOption::Done))}},async {- if should_include_channels {- search_channels(- ctx,- user_id,- user_context.organization_id,- &query_params,- channel_request,- )- .await+ if should_include_projects {+ match search_on {+ SearchOn::Name | SearchOn::NameContent => {+ simple_project::search_names(+ &ctx.db,+ &user_id,+ &simple_project::FilterProjectResponse {+ ids_only: filter_project_response.ids_only,+ project_ids: filter_project_response.project_ids,+ },+ name_search_term.clone(),+ page_size,+ project_cursor_for_search,+ )+ .await+ }+ SearchOn::Content => Ok((vec![], SearchCursorOption::Done)),+ }} else {- Ok(vec![])+ Ok((vec![], SearchCursorOption::Done))+ }+ },+ async {+ // We only want to search over content if you are not searching name only+ match search_on {+ SearchOn::Content | SearchOn::NameContent => {+ if let SearchCursorOption::Done = unified_search_args.cursor {+ Ok((vec![], SearchCursorOption::Done))+ } else {+ ctx.opensearch_client+ .search_unified(unified_search_args)+ .await+ }+ }+ SearchOn::Name => Ok((vec![], SearchCursorOption::Done)),}},);- // Combine all results- let mut combined_results = Vec::new();- combined_results.extend(doc_results?);- combined_results.extend(chat_results?);- combined_results.extend(email_results?);- combined_results.extend(project_results?);- combined_results.extend(channel_results?);+ // Extract results and next cursors+ let (doc_hits, doc_next_cursor) = doc_name_results?;+ let (chat_hits, chat_next_cursor) = chat_results?;+ let (email_hits, email_next_cursor) = email_results?;+ let (email_contact_hits, email_contact_next_cursor) = email_contact_results?;+ let (project_hits, project_next_cursor) = project_results?;+ let (content_hits, content_next_cursor) = content_results?;++ println!("{:?} {:?}", content_next_cursor, content_hits.len());++ // Track original counts before combining+ let doc_name_count = doc_hits.len();+ let chat_name_count = chat_hits.len();+ let email_subject_count = email_hits.len();+ let email_contact_count = email_contact_hits.len();+ let project_name_count = project_hits.len();+ let content_count = content_hits.len();++ // Wrap results with source tags+ let mut combined: Vec<TaggedSearchHit> = Vec::new();+ combined.extend(doc_hits.into_iter().map(|hit| TaggedSearchHit {+ hit,+ source: SearchSource::DocumentName,+ }));+ combined.extend(chat_hits.into_iter().map(|hit| TaggedSearchHit {+ hit,+ source: SearchSource::ChatName,+ }));+ combined.extend(email_hits.into_iter().map(|hit| TaggedSearchHit {+ hit,+ source: SearchSource::EmailSubject,+ }));+ combined.extend(email_contact_hits.into_iter().map(|hit| TaggedSearchHit {+ hit,+ source: SearchSource::EmailContact,+ }));+ combined.extend(project_hits.into_iter().map(|hit| TaggedSearchHit {+ hit,+ source: SearchSource::ProjectName,+ }));+ combined.extend(content_hits.into_iter().map(|hit| TaggedSearchHit {+ hit,+ source: SearchSource::Content,+ }));++ // Sort: updated_at DESC (None to bottom), entity_id DESC as tiebreaker+ combined.sort_by(|a, b| match (&b.hit.updated_at, &a.hit.updated_at) {+ (Some(b_ts), Some(a_ts)) => b_ts+ .cmp(a_ts)+ .then_with(|| b.hit.entity_id.cmp(&a.hit.entity_id)),+ (Some(_), None) => std::cmp::Ordering::Less,+ (None, Some(_)) => std::cmp::Ordering::Greater,+ (None, None) => b.hit.entity_id.cmp(&a.hit.entity_id),+ });++ // Take only page_size results+ let page_size_usize = page_size as usize;+ let final_tagged: Vec<TaggedSearchHit> = combined.into_iter().take(page_size_usize).collect();++ // Count included results by source+ let included_doc_names = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::DocumentName)+ .count();+ let included_chat_names = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::ChatName)+ .count();+ let included_email_subjects = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::EmailSubject)+ .count();+ let included_email_contacts = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::EmailContact)+ .count();+ let included_project_names = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::ProjectName)+ .count();+ let included_content = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::Content)+ .count();+ // Content cursor deferred - always None for now++ // Generate new cursors using helper function+ let new_doc_cursor = compute_next_cursor(+ &doc_next_cursor,+ included_doc_names,+ doc_name_count,+ find_last_of_source(&final_tagged, SearchSource::DocumentName),+ &document_cursor,+ );++ let new_chat_cursor = compute_next_cursor(+ &chat_next_cursor,+ included_chat_names,+ chat_name_count,+ find_last_of_source(&final_tagged, SearchSource::ChatName),+ &chat_cursor,+ );- Ok(combined_results)+ let new_email_cursor = compute_next_cursor(+ &email_next_cursor,+ included_email_subjects,+ email_subject_count,+ find_last_of_source(&final_tagged, SearchSource::EmailSubject),+ &email_cursor,+ );++ let new_email_contact_cursor = compute_next_cursor(+ &email_contact_next_cursor,+ included_email_contacts,+ email_contact_count,+ find_last_of_source(&final_tagged, SearchSource::EmailContact),+ &email_contact_cursor,+ );++ let new_project_cursor = compute_next_cursor(+ &project_next_cursor,+ included_project_names,+ project_name_count,+ find_last_of_source(&final_tagged, SearchSource::ProjectName),+ &project_cursor,+ );++ let new_content_cursor = compute_next_cursor(+ &content_next_cursor,+ included_content,+ content_count,+ find_last_of_source(&final_tagged, SearchSource::Content),+ &content_cursor,+ );++ // Build next cursor if any source has more results+ let has_more = new_doc_cursor.has_more()+ || new_chat_cursor.has_more()+ || new_email_cursor.has_more()+ || new_email_contact_cursor.has_more()+ || new_project_cursor.has_more()+ || new_content_cursor.has_more();++ let next_cursor = if has_more {+ let cursor = SearchCursor {+ document_name_cursor: new_doc_cursor,+ chat_name_cursor: new_chat_cursor,+ content_cursor: new_content_cursor,+ email_subject_cursor: new_email_cursor,+ email_contact_cursor: new_email_contact_cursor,+ project_name_cursor: new_project_cursor,+ };+ cursor.encode()+ } else {+ None+ };++ // Extract final SearchHits from tagged results+ let final_results: Vec<SearchHit> = final_tagged.into_iter().map(|t| t.hit).collect();++ Ok((final_results, next_cursor))}/// Perform a search through all items.@@ -185,8 +565,8 @@ pub(in crate::api::search) async fn perform_unified_search(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."),+ ("cursor" = Option<String>, Query, description = "Base64 encoded cursor for pagination."),),responses((status = 200, body=SimpleUnifiedSearchResponse),@@ -204,9 +584,15 @@ pub async fn handler() -> Result<Json<SimpleSearchResponse>, SearchError> {tracing::info!("simple_unified_search");- let results = perform_unified_search(&ctx, &user_context, query_params, req).await?;+ let (results, _next_cursor) =+ perform_unified_search(&ctx, &user_context, query_params, req).await?;let results = results.into_iter().map(|a| a.into()).collect();+ // Note: SimpleSearchResponse doesn't have a next_cursor field+ // The cursor is returned by the unified search endpoint (/search)Ok(Json(SimpleSearchResponse { results }))}++#[cfg(test)]+mod test;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.rsnew file mode 100644index 0000000000..79241b36bf--- /dev/null+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs@@ -0,0 +1,339 @@+use super::*;+use chrono::{TimeZone, Utc};+use models_opensearch::SearchEntityType;+use opensearch_client::search::model::Highlight;+use sqlx::types::Uuid;++/// Helper to create a TaggedSearchHit for testing+fn make_tagged_hit(+ entity_id: Uuid,+ updated_at: Option<chrono::DateTime<Utc>>,+ source: SearchSource,+) -> TaggedSearchHit {+ TaggedSearchHit {+ hit: SearchHit {+ entity_id,+ entity_type: SearchEntityType::Documents,+ updated_at,+ score: Some(1.0),+ highlight: Highlight::default(),+ goto: None,+ },+ source,+ }+}++/// Helper to create a timestamp for testing+fn ts(secs: i64) -> chrono::DateTime<Utc> {+ Utc.timestamp_opt(secs, 0).unwrap()+}++// ==================== Tests for compute_next_cursor ====================++#[test]+fn test_compute_next_cursor_search_is_done_returns_done() {+ // When search returned Done, always return Done regardless of other params+ let result = compute_next_cursor(+ &SearchCursorOption::Done,+ 5, // included_count+ 10, // original_count (more than included)+ Some(&make_tagged_hit(+ Uuid::new_v4(),+ Some(ts(1000)),+ SearchSource::DocumentName,+ )),+ &SearchCursorOption::NotDone(None),+ );++ assert!(result.is_done());+}++#[test]+fn test_compute_next_cursor_excluded_results_with_included_generates_cursor() {+ // When some results were excluded (included < original) and we have included results,+ // generate cursor from the last included hit+ let entity_id = Uuid::new_v4();+ let timestamp = ts(1000);+ let last_hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::DocumentName);++ let result = compute_next_cursor(+ &SearchCursorOption::NotDone(None), // search says not done+ 3, // included_count+ 5, // original_count (more results were fetched)+ Some(&last_hit),+ &SearchCursorOption::NotDone(None),+ );++ match result {+ SearchCursorOption::NotDone(Some(cursor)) => {+ assert_eq!(cursor.entity_id, entity_id);+ assert_eq!(cursor.updated_at, timestamp);+ }+ _ => panic!("Expected NotDone with cursor, got {:?}", result),+ }+}++#[test]+fn test_compute_next_cursor_search_has_more_with_included_generates_cursor() {+ // When search indicates more results (has_more) and we have included results,+ // generate cursor from the last included hit+ let entity_id = Uuid::new_v4();+ let timestamp = ts(2000);+ let last_hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::ChatName);++ let result = compute_next_cursor(+ &SearchCursorOption::NotDone(Some(SearchMethodCursor {+ entity_id: Uuid::new_v4(),+ updated_at: ts(500),+ })), // search has more+ 5, // included_count+ 5, // original_count (all included)+ Some(&last_hit),+ &SearchCursorOption::NotDone(None),+ );++ match result {+ SearchCursorOption::NotDone(Some(cursor)) => {+ assert_eq!(cursor.entity_id, entity_id);+ assert_eq!(cursor.updated_at, timestamp);+ }+ _ => panic!("Expected NotDone with cursor, got {:?}", result),+ }+}++#[test]+fn test_compute_next_cursor_excluded_results_no_included_carries_forward() {+ // When results were excluded but none were included in final page,+ // carry forward the original cursor+ let original_entity_id = Uuid::new_v4();+ let original_timestamp = ts(500);+ let original_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor {+ entity_id: original_entity_id,+ updated_at: original_timestamp,+ }));++ let result = compute_next_cursor(+ &SearchCursorOption::NotDone(None), // search not done+ 0, // included_count (none included)+ 5, // original_count (had results)+ None, // no last hit+ &original_cursor,+ );++ match result {+ SearchCursorOption::NotDone(Some(cursor)) => {+ assert_eq!(cursor.entity_id, original_entity_id);+ assert_eq!(cursor.updated_at, original_timestamp);+ }+ _ => panic!("Expected original cursor carried forward, got {:?}", result),+ }+}++#[test]+fn test_compute_next_cursor_all_included_search_done_returns_done() {+ // When all results were included and search indicates it's done,+ // return Done+ let result = compute_next_cursor(+ &SearchCursorOption::Done, // search is done+ 5, // included_count+ 5, // original_count (all included)+ Some(&make_tagged_hit(+ Uuid::new_v4(),+ Some(ts(1000)),+ SearchSource::EmailSubject,+ )),+ &SearchCursorOption::NotDone(None),+ );++ assert!(result.is_done());+}++#[test]+fn test_compute_next_cursor_all_included_but_search_not_done_continues() {+ // When all fetched results were included but search indicates more exist,+ // generate cursor from last included (search may have more pages)+ let entity_id = Uuid::new_v4();+ let timestamp = ts(1000);+ let last_hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::EmailSubject);++ let result = compute_next_cursor(+ &SearchCursorOption::NotDone(None), // search says not done (more exists)+ 5, // included_count+ 5, // original_count (all fetched were included)+ Some(&last_hit),+ &SearchCursorOption::NotDone(None),+ );++ // 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);+ }+ _ => panic!("Expected NotDone with cursor, got {:?}", result),+ }+}++#[test]+fn test_compute_next_cursor_hit_without_timestamp_returns_none_cursor() {+ // When the last included hit has no timestamp, cursor should be NotDone(None)+ let entity_id = Uuid::new_v4();+ let last_hit = make_tagged_hit(entity_id, None, SearchSource::Content);++ let result = compute_next_cursor(+ &SearchCursorOption::NotDone(None),+ 3,+ 5,+ Some(&last_hit),+ &SearchCursorOption::NotDone(None),+ );++ match result {+ SearchCursorOption::NotDone(None) => {}+ _ => panic!("Expected NotDone(None), got {:?}", result),+ }+}++// ==================== Tests for find_last_of_source ====================++#[test]+fn test_find_last_of_source_finds_correct_source() {+ let doc_id = Uuid::new_v4();+ let chat_id = Uuid::new_v4();+ let doc2_id = Uuid::new_v4();++ let results = vec![+ make_tagged_hit(doc_id, Some(ts(1000)), SearchSource::DocumentName),+ make_tagged_hit(chat_id, Some(ts(2000)), SearchSource::ChatName),+ make_tagged_hit(doc2_id, Some(ts(3000)), SearchSource::DocumentName),+ ];++ let last_doc = find_last_of_source(&results, SearchSource::DocumentName);+ assert!(last_doc.is_some());+ assert_eq!(last_doc.unwrap().hit.entity_id, doc2_id);++ let last_chat = find_last_of_source(&results, SearchSource::ChatName);+ assert!(last_chat.is_some());+ assert_eq!(last_chat.unwrap().hit.entity_id, chat_id);+}++#[test]+fn test_find_last_of_source_returns_none_when_not_found() {+ let results = vec![+ make_tagged_hit(Uuid::new_v4(), Some(ts(1000)), SearchSource::DocumentName),+ make_tagged_hit(Uuid::new_v4(), Some(ts(2000)), SearchSource::ChatName),+ ];++ let last_email = find_last_of_source(&results, SearchSource::EmailSubject);+ assert!(last_email.is_none());+}++#[test]+fn test_find_last_of_source_empty_results() {+ let results: Vec<TaggedSearchHit> = vec![];+ let result = find_last_of_source(&results, SearchSource::DocumentName);+ assert!(result.is_none());+}++// ==================== Tests for cursor_from_tagged ====================++#[test]+fn test_cursor_from_tagged_with_timestamp() {+ let entity_id = Uuid::new_v4();+ let timestamp = ts(1000);+ let hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::DocumentName);++ 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);+}++#[test]+fn test_cursor_from_tagged_without_timestamp() {+ let entity_id = Uuid::new_v4();+ let hit = make_tagged_hit(entity_id, None, SearchSource::ChatName);++ let cursor = cursor_from_tagged(&hit);+ assert!(cursor.is_none());+}++// ==================== Integration-style tests ====================++#[test]+fn test_cursor_logic_pagination_scenario() {+ // Simulate a pagination scenario where:+ // - Search returned 10 documents+ // - Only 3 made it into the final page (others had newer timestamps from other sources)+ // - The cursor should point to the last included document++ let doc_ids: Vec<Uuid> = (0..10).map(|_| Uuid::new_v4()).collect();+ let timestamps: Vec<chrono::DateTime<Utc>> = (0..10).map(|i| ts(1000 + i * 100)).collect();++ // Create the final tagged results (simulating merged & sorted output)+ let final_tagged: Vec<TaggedSearchHit> = vec![+ make_tagged_hit(Uuid::new_v4(), Some(ts(5000)), SearchSource::ChatName),+ make_tagged_hit(doc_ids[9], Some(timestamps[9]), SearchSource::DocumentName),+ make_tagged_hit(Uuid::new_v4(), Some(ts(4000)), SearchSource::EmailSubject),+ make_tagged_hit(doc_ids[8], Some(timestamps[8]), SearchSource::DocumentName),+ make_tagged_hit(doc_ids[7], Some(timestamps[7]), SearchSource::DocumentName),+ ];++ let doc_next_cursor = SearchCursorOption::NotDone(Some(SearchMethodCursor {+ entity_id: doc_ids[6],+ updated_at: timestamps[6],+ }));++ let included_doc_names = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::DocumentName)+ .count();+ let doc_name_count = 10; // Original fetch returned 10++ let new_doc_cursor = compute_next_cursor(+ &doc_next_cursor,+ included_doc_names,+ doc_name_count,+ find_last_of_source(&final_tagged, SearchSource::DocumentName),+ &SearchCursorOption::NotDone(None),+ );++ // 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]);+ }+ _ => panic!(+ "Expected cursor from last included doc, got {:?}",+ new_doc_cursor+ ),+ }+}++#[test]+fn test_cursor_logic_source_exhausted_scenario() {+ // Simulate when a source is exhausted (returned fewer than requested)+ // - Search returned 3 documents (less than page_size of 10)+ // - All 3 made it into the final page+ // - Cursor should be Done since source is exhausted++ let final_tagged: Vec<TaggedSearchHit> = vec![+ make_tagged_hit(Uuid::new_v4(), Some(ts(3000)), SearchSource::DocumentName),+ make_tagged_hit(Uuid::new_v4(), Some(ts(2000)), SearchSource::DocumentName),+ make_tagged_hit(Uuid::new_v4(), Some(ts(1000)), SearchSource::DocumentName),+ ];++ let doc_next_cursor = SearchCursorOption::Done; // Search says done++ let new_doc_cursor = compute_next_cursor(+ &doc_next_cursor,+ 3, // all included+ 3, // all returned+ find_last_of_source(&final_tagged, SearchSource::DocumentName),+ &SearchCursorOption::NotDone(None),+ );++ assert!(new_doc_cursor.is_done());+}diff --git a/rust/cloud-storage/search_service/src/api/search/unified.rs b/rust/cloud-storage/search_service/src/api/search/unified.rsindex 9dd5f650d6..4d564e0a3b 100644--- a/rust/cloud-storage/search_service/src/api/search/unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/unified.rs@@ -9,8 +9,7 @@ use crate::api::{use axum::{Extension,extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},+ response::Json,};use model::{response::ErrorResponse, user::UserContext};use models_search::unified::{@@ -27,8 +26,8 @@ use std::cmp::Ordering;path = "/search",operation_id = "unified_search",params(- ("page" = i64, Query, description = "The page. Defaults to 0."),("page_size" = i64, Query, description = "The page size. Defaults to 10."),+ ("cursor" = Option<String>, Query, description = "Base64 encoded cursor value.")),responses((status = 200, body=UnifiedSearchResponse),@@ -43,10 +42,11 @@ pub async fn handler(user_context: Extension<UserContext>,extract::Query(query_params): extract::Query<SearchPaginationParams>,extract::Json(req): extract::Json<UnifiedSearchRequest>,-) -> Result<Response, SearchError> {+) -> Result<Json<UnifiedSearchResponse>, SearchError> {tracing::info!("unified_search");- let results = perform_unified_search(&ctx, &user_context, query_params, req).await?;+ let (results, next_cursor) =+ perform_unified_search(&ctx, &user_context, query_params, req).await?;// Split the results by entity typelet SplitUnifiedSearchResponseValues {@@ -107,7 +107,10 @@ pub async fn handler(results = sort_unified_search_results(results);- Ok((StatusCode::OK, Json(UnifiedSearchResponse { results })).into_response())+ Ok(Json(UnifiedSearchResponse {+ results,+ next_cursor,+ }))}/// Sorts the unified resultsdiff --git a/rust/cloud-storage/search_service/src/api/swagger.rs b/rust/cloud-storage/search_service/src/api/swagger.rsindex f049d2df26..b2fd488ad8 100644--- a/rust/cloud-storage/search_service/src/api/swagger.rs+++ b/rust/cloud-storage/search_service/src/api/swagger.rs@@ -42,19 +42,9 @@ use models_search::{MatchType, SearchHighlight};health::health_handler,/// /search- search::document::handler,- search::chat::handler,- search::email::handler,- search::channel::handler,search::unified::handler,- search::project::handler,/// /search/simple- search::simple::simple_document::handler,- search::simple::simple_chat::handler,- search::simple::simple_email::handler,- search::simple::simple_channel::handler,- search::simple::simple_project::handler,search::simple::simple_unified::handler,),components(diff --git a/rust/cloud-storage/search_service_client/src/lib.rs b/rust/cloud-storage/search_service_client/src/lib.rsindex 5fe200ef54..cea7b375ba 100644--- a/rust/cloud-storage/search_service_client/src/lib.rs+++ b/rust/cloud-storage/search_service_client/src/lib.rs@@ -1,8 +1,5 @@use constants::INTERNAL_API_KEY_HEADER;pub(crate) mod constants;-pub mod search_chats;-pub mod search_documents;-pub mod search_emails;pub mod search_unified;#[derive(Clone)]diff --git a/rust/cloud-storage/search_service_client/src/search_chats.rs b/rust/cloud-storage/search_service_client/src/search_chats.rsdeleted file mode 100644index a753049651..0000000000--- a/rust/cloud-storage/search_service_client/src/search_chats.rs+++ /dev/null@@ -1,38 +0,0 @@-use crate::{SearchServiceClient, constants::INTERNAL_MACRO_USER_ID_HEADER};--impl SearchServiceClient {- pub async fn search_chats(- &self,- user_id: &str,- body: models_search::chat::ChatSearchRequest,- page: i64,- page_size: i64,- ) -> anyhow::Result<models_search::chat::ChatSearchResponse> {- let res = self- .client- .post(format!(- "{}/internal/search/chat?page={}&page_size={}",- self.url, page, page_size- ))- .header(INTERNAL_MACRO_USER_ID_HEADER, user_id)- .json(&body)- .send()- .await?;-- match res.status() {- reqwest::StatusCode::OK => {- let result = res- .json::<models_search::chat::ChatSearchResponse>()- .await?;- Ok(result)- }- status_code => {- let body: String = res.text().await?;- anyhow::bail!(format!(- "unexpected response from search service status code {}: {}",- status_code, body- ))- }- }- }-}diff --git a/rust/cloud-storage/search_service_client/src/search_documents.rs b/rust/cloud-storage/search_service_client/src/search_documents.rsdeleted file mode 100644index 614e6979e4..0000000000--- a/rust/cloud-storage/search_service_client/src/search_documents.rs+++ /dev/null@@ -1,38 +0,0 @@-use crate::{SearchServiceClient, constants::INTERNAL_MACRO_USER_ID_HEADER};--impl SearchServiceClient {- pub async fn search_documents(- &self,- user_id: &str,- body: models_search::document::DocumentSearchRequest,- page: i64,- page_size: i64,- ) -> anyhow::Result<models_search::document::DocumentSearchResponse> {- let res = self- .client- .post(format!(- "{}/internal/search/document?page={}&page_size={}",- self.url, page, page_size- ))- .header(INTERNAL_MACRO_USER_ID_HEADER, user_id)- .json(&body)- .send()- .await?;-- match res.status() {- reqwest::StatusCode::OK => {- let result = res- .json::<models_search::document::DocumentSearchResponse>()- .await?;- Ok(result)- }- status_code => {- let body: String = res.text().await?;- anyhow::bail!(format!(- "unexpected response from search service status code {}: {}",- status_code, body- ))- }- }- }-}diff --git a/rust/cloud-storage/search_service_client/src/search_emails.rs b/rust/cloud-storage/search_service_client/src/search_emails.rsdeleted file mode 100644index 2f91126ccd..0000000000--- a/rust/cloud-storage/search_service_client/src/search_emails.rs+++ /dev/null@@ -1,38 +0,0 @@-use crate::{SearchServiceClient, constants::INTERNAL_MACRO_USER_ID_HEADER};--impl SearchServiceClient {- pub async fn search_emails(- &self,- user_id: &str,- body: models_search::email::EmailSearchRequest,- page: i64,- page_size: i64,- ) -> anyhow::Result<models_search::email::EmailSearchResponse> {- let res = self- .client- .post(format!(- "{}/internal/search/email?page={}&page_size={}",- self.url, page, page_size- ))- .header(INTERNAL_MACRO_USER_ID_HEADER, user_id)- .json(&body)- .send()- .await?;-- match res.status() {- reqwest::StatusCode::OK => {- let result = res- .json::<models_search::email::EmailSearchResponse>()- .await?;- Ok(result)- }- status_code => {- let body: String = res.text().await?;- anyhow::bail!(format!(- "unexpected response from search service status code {}: {}",- status_code, body- ))- }- }- }-}diff --git a/rust/cloud-storage/search_service_client/src/search_unified.rs b/rust/cloud-storage/search_service_client/src/search_unified.rsindex c4b2cbcf06..d7530c096a 100644--- a/rust/cloud-storage/search_service_client/src/search_unified.rs+++ b/rust/cloud-storage/search_service_client/src/search_unified.rs@@ -5,51 +5,20 @@ impl SearchServiceClient {&self,user_id: &str,body: models_search::unified::UnifiedSearchRequest,- page: i64,+ cursor: Option<String>,page_size: i64,) -> anyhow::Result<models_search::unified::UnifiedSearchResponse> {- let res = self- .client- .post(format!(- "{}/internal/search?page={}&page_size={}",- self.url, page, page_size- ))- .header(INTERNAL_MACRO_USER_ID_HEADER, user_id)- .json(&body)- .send()- .await?;+ let url = format!("{}/internal/search", self.url);- match res.status() {- reqwest::StatusCode::OK => {- let result = res- .json::<models_search::unified::UnifiedSearchResponse>()- .await?;- Ok(result)- }- status_code => {- let body: String = res.text().await?;- anyhow::bail!(- "unexpected response from search service status code {}: {}",- status_code,- body- )- }+ let mut query_params: Vec<(&str, String)> = vec![("page_size", page_size.to_string())];+ if let Some(cursor) = cursor {+ query_params.push(("cursor", cursor));}- }- pub async fn search_simple_unified(- &self,- user_id: &str,- body: models_search::unified::UnifiedSearchRequest,- page: i64,- page_size: i64,- ) -> anyhow::Result<models_search::SimpleSearchResponse> {let res = self.client- .post(format!(- "{}/internal/search/simple?page={}&page_size={}",- self.url, page, page_size- ))+ .post(url)+ .query(&query_params).header(INTERNAL_MACRO_USER_ID_HEADER, user_id).json(&body).send()@@ -57,7 +26,9 @@ impl SearchServiceClient {match res.status() {reqwest::StatusCode::OK => {- let result = res.json::<models_search::SimpleSearchResponse>().await?;+ let result = res+ .json::<models_search::unified::UnifiedSearchResponse>()+ .await?;Ok(result)}status_code => {