1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { ServiceRepository } from 'services/services';
6 import { MiddlewareAPI, Dispatch } from 'redux';
7 import { DataExplorerMiddlewareService, dataExplorerToListParams, listResultsToDataExplorerItemsMeta, getDataExplorerColumnFilters } from 'store/data-explorer/data-explorer-middleware-service';
8 import { RootState } from 'store/store';
9 import { snackbarActions, SnackbarKind } from 'store/snackbar/snackbar-actions';
10 import { DataExplorer, getDataExplorer } from 'store/data-explorer/data-explorer-reducer';
11 import { updateResources } from 'store/resources/resources-actions';
12 import { SortDirection } from 'components/data-table/data-column';
13 import { OrderDirection, OrderBuilder } from 'services/api/order-builder';
14 import { GroupContentsResource, GroupContentsResourcePrefix } from "services/groups-service/groups-service";
15 import { ListResults } from 'services/common-service/common-service';
16 import { searchResultsPanelActions } from 'store/search-results-panel/search-results-panel-actions';
20 getAdvancedDataFromQuery,
22 } from 'store/search-bar/search-bar-actions';
23 import { getSortColumn } from "store/data-explorer/data-explorer-reducer";
24 import { FilterBuilder, joinFilters } from 'services/api/filter-builder';
25 import { DataColumns } from 'components/data-table/data-table';
26 import { serializeResourceTypeFilters } from 'store//resource-type-filters/resource-type-filters';
27 import { SearchResultsPanelColumnNames } from 'views/search-results-panel/search-results-panel-view';
28 import { ResourceKind } from 'models/resource';
29 import { ContainerRequestResource } from 'models/container-request';
30 import { progressIndicatorActions } from 'store/progress-indicator/progress-indicator-actions';
31 import { dataExplorerActions } from 'store/data-explorer/data-explorer-action';
32 import { Session } from 'models/session';
33 import { SEARCH_RESULTS_PANEL_ID } from 'store/search-results-panel/search-results-panel-actions';
35 export class SearchResultsMiddlewareService extends DataExplorerMiddlewareService {
36 constructor(private services: ServiceRepository, id: string) {
40 async requestItems(api: MiddlewareAPI<Dispatch, RootState>, criteriaChanged?: boolean) {
41 const state = api.getState();
42 const dataExplorer = getDataExplorer(state.dataExplorer, this.getId());
43 const searchValue = state.searchBar.searchValue;
44 const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
45 const sessions = getSearchSessions(clusterId, state.auth.sessions);
47 if (searchValue.trim() === '') {
53 items: [] as GroupContentsResource[],
59 if (criteriaChanged) {
60 api.dispatch(setItems(initial));
63 const numberOfSessions = sessions.length;
64 let numberOfResolvedResponses = 0;
65 let totalNumItemsAvailable = 0;
66 api.dispatch(progressIndicatorActions.START_WORKING(this.id))
67 api.dispatch(dataExplorerActions.SET_IS_NOT_FOUND({ id: this.id, isNotFound: false }));
69 //In SearchResultsPanel, if we don't reset the items available, the items available will
70 //will be added to the previous value every time the 'load more' button is clicked.
71 api.dispatch(resetItemsAvailable());
73 sessions.forEach(session => {
74 const params = getParams(dataExplorer, searchValue, session.apiRevision);
75 //this prevents double fetching of the same search results when a new session is logged in
76 api.dispatch<any>(setSearchOffsets(session.clusterId, params.offset ));
78 this.services.groupsService.contents('', params, session)
80 api.dispatch(updateResources(response.items));
81 api.dispatch(appendItems(response));
82 numberOfResolvedResponses++;
83 // Used to determine if all results are empty, so items.length works as well as itemsAvailable
84 totalNumItemsAvailable += response.items.length;
85 if (numberOfResolvedResponses === numberOfSessions) {
86 api.dispatch(progressIndicatorActions.STOP_WORKING(this.id))
87 if(totalNumItemsAvailable === 0) api.dispatch(dataExplorerActions.SET_IS_NOT_FOUND({ id: this.id, isNotFound: true }))
89 // Request all containers for process status to be available
90 const containerRequests = response.items.filter((item) => item.kind === ResourceKind.CONTAINER_REQUEST) as ContainerRequestResource[];
91 const containerUuids = containerRequests.map(container => container.containerUuid).filter(uuid => uuid !== null) as string[];
92 containerUuids.length && this.services.containerService
94 filters: new FilterBuilder()
95 .addIn('uuid', containerUuids)
98 .then((containers) => {
99 api.dispatch(updateResources(containers.items));
102 api.dispatch(couldNotFetchSearchResults(session.clusterId));
103 api.dispatch(progressIndicatorActions.STOP_WORKING(this.id))
109 // Empty requestCount method since search relies on included itemsAvailable
110 async requestCount() {}
113 export const searchSingleCluster = (session: Session, searchValue: string) =>
114 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
115 const state = getState();
116 const dataExplorer = getDataExplorer(state.dataExplorer, SEARCH_RESULTS_PANEL_ID);
118 if (searchValue.trim() === '') {
122 const params = getParams(dataExplorer, searchValue, session.apiRevision);
124 // If the clusterId & search offset has already been fetched, we don't need to fetch the results again
125 if(state.searchBar.searchOffsets[session.clusterId] === params.offset) {
129 dispatch(progressIndicatorActions.START_WORKING(SEARCH_RESULTS_PANEL_ID))
131 services.groupsService.contents('', params, session)
132 .then((response) => {
133 dispatch<any>(setSearchOffsets(session.clusterId, params.offset ));
134 dispatch(updateResources(response.items));
135 dispatch(appendItems(response));
136 // Request all containers for process status to be available
137 const containerRequests = response.items.filter((item) => item.kind === ResourceKind.CONTAINER_REQUEST) as ContainerRequestResource[];
138 const containerUuids = containerRequests.map(container => container.containerUuid).filter(uuid => uuid !== null) as string[];
139 containerUuids.length && services.containerService
141 filters: new FilterBuilder()
142 .addIn('uuid', containerUuids)
145 .then((containers) => {
146 dispatch(updateResources(containers.items));
149 dispatch(couldNotFetchSearchResults(session.clusterId));
150 dispatch(progressIndicatorActions.STOP_WORKING(SEARCH_RESULTS_PANEL_ID))
152 dispatch(progressIndicatorActions.STOP_WORKING(SEARCH_RESULTS_PANEL_ID))
155 const typeFilters = (columns: DataColumns<string, GroupContentsResource>) => serializeResourceTypeFilters(getDataExplorerColumnFilters(columns, SearchResultsPanelColumnNames.TYPE));
157 export const getParams = (dataExplorer: DataExplorer, query: string, apiRevision: number) => ({
158 ...dataExplorerToListParams(dataExplorer),
159 filters: joinFilters(
160 queryToFilters(query, apiRevision),
161 typeFilters(dataExplorer.columns)
163 order: getOrder(dataExplorer),
164 includeTrash: getAdvancedDataFromQuery(query).inTrash,
165 includeOldVersions: getAdvancedDataFromQuery(query).pastVersions
168 const getOrder = (dataExplorer: DataExplorer) => {
169 const sortColumn = getSortColumn<GroupContentsResource>(dataExplorer);
170 const order = new OrderBuilder<GroupContentsResource>();
171 if (sortColumn && sortColumn.sort) {
172 const sortDirection = sortColumn.sort.direction === SortDirection.ASC
174 : OrderDirection.DESC;
176 // Use createdAt as a secondary sort column so we break ties consistently.
178 .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.COLLECTION)
179 .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.PROCESS)
180 .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.PROJECT)
181 .addOrder(OrderDirection.DESC, "createdAt", GroupContentsResourcePrefix.PROCESS)
184 return order.getOrder();
188 export const setItems = (listResults: ListResults<GroupContentsResource>) =>
189 searchResultsPanelActions.SET_ITEMS({
190 ...listResultsToDataExplorerItemsMeta(listResults),
191 items: listResults.items.map(resource => resource.uuid),
194 const resetItemsAvailable = () =>
195 searchResultsPanelActions.RESET_ITEMS_AVAILABLE();
197 export const appendItems = (listResults: ListResults<GroupContentsResource>) =>
198 searchResultsPanelActions.APPEND_ITEMS({
199 ...listResultsToDataExplorerItemsMeta(listResults),
200 items: listResults.items.map(resource => resource.uuid),
203 const couldNotFetchSearchResults = (cluster: string) =>
204 snackbarActions.OPEN_SNACKBAR({
205 message: `Could not fetch search results from ${cluster}.`,
206 kind: SnackbarKind.ERROR