Merge branch '21909-r-sdk-3.0'
[arvados.git] / services / workbench2 / src / store / search-results-panel / search-results-middleware-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
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';
17 import {
18     getSearchSessions,
19     queryToFilters,
20     getAdvancedDataFromQuery,
21     setSearchOffsets,
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';
34
35 export class SearchResultsMiddlewareService extends DataExplorerMiddlewareService {
36     constructor(private services: ServiceRepository, id: string) {
37         super(id);
38     }
39
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);
46
47         if (searchValue.trim() === '') {
48             return;
49         }
50
51         const initial = {
52             itemsAvailable: 0,
53             items: [] as GroupContentsResource[],
54             kind: '',
55             offset: 0,
56             limit: 50
57         };
58
59         if (criteriaChanged) {
60             api.dispatch(setItems(initial));
61         }
62
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 }));
68
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());
72
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 ));
77
78             this.services.groupsService.contents('', params, session)
79                 .then((response) => {
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 }))
88                     }
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
93                         .list({
94                             filters: new FilterBuilder()
95                                 .addIn('uuid', containerUuids)
96                                 .getFilters()
97                         }, false)
98                         .then((containers) => {
99                             api.dispatch(updateResources(containers.items));
100                         });
101                     }).catch(() => {
102                         api.dispatch(couldNotFetchSearchResults(session.clusterId));
103                         api.dispatch(progressIndicatorActions.STOP_WORKING(this.id))
104                     });
105             }
106         );
107     }
108
109     // Empty requestCount method since search relies on included itemsAvailable
110     async requestCount() {}
111 }
112
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);
117
118         if (searchValue.trim() === '') {
119             return;
120         }
121
122         const params = getParams(dataExplorer, searchValue, session.apiRevision);
123
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) {
126             return;
127         }
128
129         dispatch(progressIndicatorActions.START_WORKING(SEARCH_RESULTS_PANEL_ID))
130
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
140                     .list({
141                         filters: new FilterBuilder()
142                             .addIn('uuid', containerUuids)
143                             .getFilters()
144                     }, false)
145                     .then((containers) => {
146                         dispatch(updateResources(containers.items));
147                     });
148                 }).catch(() => {
149                     dispatch(couldNotFetchSearchResults(session.clusterId));
150                     dispatch(progressIndicatorActions.STOP_WORKING(SEARCH_RESULTS_PANEL_ID))
151                 });
152         dispatch(progressIndicatorActions.STOP_WORKING(SEARCH_RESULTS_PANEL_ID))
153 }
154
155 const typeFilters = (columns: DataColumns<string, GroupContentsResource>) => serializeResourceTypeFilters(getDataExplorerColumnFilters(columns, SearchResultsPanelColumnNames.TYPE));
156
157 export const getParams = (dataExplorer: DataExplorer, query: string, apiRevision: number) => ({
158     ...dataExplorerToListParams(dataExplorer),
159     filters: joinFilters(
160         queryToFilters(query, apiRevision),
161         typeFilters(dataExplorer.columns)
162     ),
163     order: getOrder(dataExplorer),
164     includeTrash: getAdvancedDataFromQuery(query).inTrash,
165     includeOldVersions: getAdvancedDataFromQuery(query).pastVersions
166 });
167
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
173             ? OrderDirection.ASC
174             : OrderDirection.DESC;
175
176         // Use createdAt as a secondary sort column so we break ties consistently.
177         return order
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)
182             .getOrder();
183     } else {
184         return order.getOrder();
185     }
186 };
187
188 export const setItems = (listResults: ListResults<GroupContentsResource>) =>
189     searchResultsPanelActions.SET_ITEMS({
190         ...listResultsToDataExplorerItemsMeta(listResults),
191         items: listResults.items.map(resource => resource.uuid),
192     });
193
194 const resetItemsAvailable = () =>
195     searchResultsPanelActions.RESET_ITEMS_AVAILABLE();
196
197 export const appendItems = (listResults: ListResults<GroupContentsResource>) =>
198     searchResultsPanelActions.APPEND_ITEMS({
199         ...listResultsToDataExplorerItemsMeta(listResults),
200         items: listResults.items.map(resource => resource.uuid),
201     });
202
203 const couldNotFetchSearchResults = (cluster: string) =>
204     snackbarActions.OPEN_SNACKBAR({
205         message: `Could not fetch search results from ${cluster}.`,
206         kind: SnackbarKind.ERROR
207     });