Merge branch '21449-lsf-maxruntime'
[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 } from 'store/search-bar/search-bar-actions';
22 import { getSortColumn } from "store/data-explorer/data-explorer-reducer";
23 import { FilterBuilder, joinFilters } from 'services/api/filter-builder';
24 import { DataColumns } from 'components/data-table/data-table';
25 import { serializeResourceTypeFilters } from 'store//resource-type-filters/resource-type-filters';
26 import { ProjectPanelColumnNames } from 'views/project-panel/project-panel';
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
32 export class SearchResultsMiddlewareService extends DataExplorerMiddlewareService {
33     constructor(private services: ServiceRepository, id: string) {
34         super(id);
35     }
36
37     async requestItems(api: MiddlewareAPI<Dispatch, RootState>, criteriaChanged?: boolean) {
38         const state = api.getState();
39         const dataExplorer = getDataExplorer(state.dataExplorer, this.getId());
40         const searchValue = state.searchBar.searchValue;
41         const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
42         const sessions = getSearchSessions(clusterId, state.auth.sessions);
43
44         if (searchValue.trim() === '') {
45             return;
46         }
47
48         const initial = {
49             itemsAvailable: 0,
50             items: [] as GroupContentsResource[],
51             kind: '',
52             offset: 0,
53             limit: 10
54         };
55
56         if (criteriaChanged) {
57             api.dispatch(setItems(initial));
58         }
59
60         const numberOfSessions = sessions.length;
61         let numberOfResolvedResponses = 0;
62         let totalNumItemsAvailable = 0;
63         api.dispatch(progressIndicatorActions.START_WORKING(this.id))
64         api.dispatch(dataExplorerActions.SET_IS_NOT_FOUND({ id: this.id, isNotFound: false }));
65
66         sessions.forEach(session => {
67             const params = getParams(dataExplorer, searchValue, session.apiRevision);
68             this.services.groupsService.contents('', params, session)
69                 .then((response) => {
70                     api.dispatch(updateResources(response.items));
71                     api.dispatch(appendItems(response));
72                     numberOfResolvedResponses++;
73                     totalNumItemsAvailable += response.itemsAvailable;
74                     if (numberOfResolvedResponses === numberOfSessions) {
75                         api.dispatch(progressIndicatorActions.STOP_WORKING(this.id))
76                         if(totalNumItemsAvailable === 0) api.dispatch(dataExplorerActions.SET_IS_NOT_FOUND({ id: this.id, isNotFound: true }))
77                     }
78                     // Request all containers for process status to be available
79                     const containerRequests = response.items.filter((item) => item.kind === ResourceKind.CONTAINER_REQUEST) as ContainerRequestResource[];
80                     const containerUuids = containerRequests.map(container => container.containerUuid).filter(uuid => uuid !== null) as string[];
81                     containerUuids.length && this.services.containerService
82                         .list({
83                             filters: new FilterBuilder()
84                                 .addIn('uuid', containerUuids)
85                                 .getFilters()
86                         }, false)
87                         .then((containers) => {
88                             api.dispatch(updateResources(containers.items));
89                         });
90                     }).catch(() => {
91                         api.dispatch(couldNotFetchSearchResults(session.clusterId));
92                         api.dispatch(progressIndicatorActions.STOP_WORKING(this.id))
93                     });
94             }
95         );
96     }
97 }
98
99 const typeFilters = (columns: DataColumns<string, GroupContentsResource>) => serializeResourceTypeFilters(getDataExplorerColumnFilters(columns, ProjectPanelColumnNames.TYPE));
100
101 export const getParams = (dataExplorer: DataExplorer, query: string, apiRevision: number) => ({
102     ...dataExplorerToListParams(dataExplorer),
103     filters: joinFilters(
104         queryToFilters(query, apiRevision),
105         typeFilters(dataExplorer.columns)
106     ),
107     order: getOrder(dataExplorer),
108     includeTrash: getAdvancedDataFromQuery(query).inTrash,
109     includeOldVersions: getAdvancedDataFromQuery(query).pastVersions
110 });
111
112 const getOrder = (dataExplorer: DataExplorer) => {
113     const sortColumn = getSortColumn<GroupContentsResource>(dataExplorer);
114     const order = new OrderBuilder<GroupContentsResource>();
115     if (sortColumn && sortColumn.sort) {
116         const sortDirection = sortColumn.sort.direction === SortDirection.ASC
117             ? OrderDirection.ASC
118             : OrderDirection.DESC;
119
120         // Use createdAt as a secondary sort column so we break ties consistently.
121         return order
122             .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.COLLECTION)
123             .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.PROCESS)
124             .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.PROJECT)
125             .addOrder(OrderDirection.DESC, "createdAt", GroupContentsResourcePrefix.PROCESS)
126             .getOrder();
127     } else {
128         return order.getOrder();
129     }
130 };
131
132 export const setItems = (listResults: ListResults<GroupContentsResource>) =>
133     searchResultsPanelActions.SET_ITEMS({
134         ...listResultsToDataExplorerItemsMeta(listResults),
135         items: listResults.items.map(resource => resource.uuid),
136     });
137
138 export const appendItems = (listResults: ListResults<GroupContentsResource>) =>
139     searchResultsPanelActions.APPEND_ITEMS({
140         ...listResultsToDataExplorerItemsMeta(listResults),
141         items: listResults.items.map(resource => resource.uuid),
142     });
143
144 const couldNotFetchSearchResults = (cluster: string) =>
145     snackbarActions.OPEN_SNACKBAR({
146         message: `Could not fetch search results from ${cluster}.`,
147         kind: SnackbarKind.ERROR
148     });