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 { DataColumns, SortDirection } from 'components/data-table/data-column';
13 import { OrderDirection, OrderBuilder } from 'services/api/order-builder';
14 import { GroupContentsResource, GroupContentsResourcePrefix, ContentsArguments } 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 { serializeResourceTypeFilters } from 'store//resource-type-filters/resource-type-filters';
26 import { SearchResultsPanelColumnNames } from 'views/search-results-panel/search-results-panel-view';
27 import { ResourceKind } from 'models/resource';
28 import { ContainerRequestResource } from 'models/container-request';
29 import { progressIndicatorActions } from 'store/progress-indicator/progress-indicator-actions';
30 import { dataExplorerActions } from 'store/data-explorer/data-explorer-action';
31 import { Session } from 'models/session';
32 import { SEARCH_RESULTS_PANEL_ID } from 'store/search-results-panel/search-results-panel-actions';
33 import { GROUP_CONTENTS_INCLUDE_CONTAINER_UUID_MIN_API_REVISION } from 'common/app-info';
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: ContentsArguments = 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 || 0));
78 if (session.apiRevision >= GROUP_CONTENTS_INCLUDE_CONTAINER_UUID_MIN_API_REVISION) {
79 params.include = ["owner_uuid", "container_uuid"];
81 params.include = "owner_uuid";
84 this.services.groupsService.contents('', params, session)
86 api.dispatch(updateResources(response.items));
87 if (response.included) {
88 api.dispatch(updateResources(response.included));
90 api.dispatch(appendItems(response));
91 numberOfResolvedResponses++;
92 // Used to determine if all results are empty, so items.length works as well as itemsAvailable
93 totalNumItemsAvailable += response.items.length;
94 if (numberOfResolvedResponses === numberOfSessions) {
95 api.dispatch(progressIndicatorActions.STOP_WORKING(this.id))
96 if(totalNumItemsAvailable === 0) api.dispatch(dataExplorerActions.SET_IS_NOT_FOUND({ id: this.id, isNotFound: true }))
98 // Request all containers for process status to be available
99 // Required when contacting legacy API servers (pre-Arvados 3.0)
100 if (session.apiRevision < GROUP_CONTENTS_INCLUDE_CONTAINER_UUID_MIN_API_REVISION) {
101 const containerRequests = response.items.filter((item) => item.kind === ResourceKind.CONTAINER_REQUEST) as ContainerRequestResource[];
102 const containerUuids = containerRequests.map(container => container.containerUuid).filter(uuid => uuid !== null) as string[];
103 containerUuids.length && this.services.containerService
105 filters: new FilterBuilder()
106 .addIn('uuid', containerUuids)
109 .then((containers) => {
110 api.dispatch(updateResources(containers.items));
114 api.dispatch(couldNotFetchSearchResults(session.clusterId));
115 api.dispatch(progressIndicatorActions.STOP_WORKING(this.id))
121 // Empty requestCount method since search relies on included itemsAvailable
122 async requestCount() {}
125 export const searchSingleCluster = (session: Session, searchValue: string) =>
126 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
127 const state = getState();
128 const dataExplorer = getDataExplorer(state.dataExplorer, SEARCH_RESULTS_PANEL_ID);
130 if (searchValue.trim() === '') {
134 const params: ContentsArguments = getParams(dataExplorer, searchValue, session.apiRevision);
136 // If the clusterId & search offset has already been fetched, we don't need to fetch the results again
137 if(state.searchBar.searchOffsets[session.clusterId] === params.offset) {
141 if (session.apiRevision >= GROUP_CONTENTS_INCLUDE_CONTAINER_UUID_MIN_API_REVISION) {
142 params.include = ["owner_uuid", "container_uuid"];
144 params.include = "owner_uuid";
147 dispatch(progressIndicatorActions.START_WORKING(SEARCH_RESULTS_PANEL_ID))
149 services.groupsService.contents('', params, session)
150 .then((response) => {
151 dispatch<any>(setSearchOffsets(session.clusterId, params.offset || 0));
152 dispatch(updateResources(response.items));
153 if (response.included) {
154 dispatch(updateResources(response.included));
156 dispatch(appendItems(response));
157 // Request all containers for process status to be available
158 if (session.apiRevision < GROUP_CONTENTS_INCLUDE_CONTAINER_UUID_MIN_API_REVISION) {
159 const containerRequests = response.items.filter((item) => item.kind === ResourceKind.CONTAINER_REQUEST) as ContainerRequestResource[];
160 const containerUuids = containerRequests.map(container => container.containerUuid).filter(uuid => uuid !== null) as string[];
161 containerUuids.length && services.containerService
163 filters: new FilterBuilder()
164 .addIn('uuid', containerUuids)
167 .then((containers) => {
168 dispatch(updateResources(containers.items));
172 dispatch(couldNotFetchSearchResults(session.clusterId));
173 dispatch(progressIndicatorActions.STOP_WORKING(SEARCH_RESULTS_PANEL_ID))
175 dispatch(progressIndicatorActions.STOP_WORKING(SEARCH_RESULTS_PANEL_ID))
178 const typeFilters = (columns: DataColumns<string, GroupContentsResource>) => serializeResourceTypeFilters(getDataExplorerColumnFilters(columns, SearchResultsPanelColumnNames.TYPE));
180 export const getParams = (dataExplorer: DataExplorer, query: string, apiRevision: number) => ({
181 ...dataExplorerToListParams(dataExplorer),
182 filters: joinFilters(
183 queryToFilters(query, apiRevision),
184 typeFilters(dataExplorer.columns)
186 order: getOrder(dataExplorer),
187 includeTrash: getAdvancedDataFromQuery(query).inTrash,
188 includeOldVersions: getAdvancedDataFromQuery(query).pastVersions,
191 const getOrder = (dataExplorer: DataExplorer) => {
192 const sortColumn = getSortColumn<GroupContentsResource>(dataExplorer);
193 const order = new OrderBuilder<GroupContentsResource>();
194 if (sortColumn && sortColumn.sort) {
195 const sortDirection = sortColumn.sort.direction === SortDirection.ASC
197 : OrderDirection.DESC;
199 // Use createdAt as a secondary sort column so we break ties consistently.
201 .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.COLLECTION)
202 .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.PROCESS)
203 .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.PROJECT)
204 .addOrder(OrderDirection.DESC, "createdAt", GroupContentsResourcePrefix.PROCESS)
207 return order.getOrder();
211 export const setItems = (listResults: ListResults<GroupContentsResource>) =>
212 searchResultsPanelActions.SET_ITEMS({
213 ...listResultsToDataExplorerItemsMeta(listResults),
214 items: listResults.items.map(resource => resource.uuid),
217 const resetItemsAvailable = () =>
218 searchResultsPanelActions.RESET_ITEMS_AVAILABLE();
220 export const appendItems = (listResults: ListResults<GroupContentsResource>) =>
221 searchResultsPanelActions.APPEND_ITEMS({
222 ...listResultsToDataExplorerItemsMeta(listResults),
223 items: listResults.items.map(resource => resource.uuid),
226 const couldNotFetchSearchResults = (cluster: string) =>
227 snackbarActions.OPEN_SNACKBAR({
228 message: `Could not fetch search results from ${cluster}.`,
229 kind: SnackbarKind.ERROR