Skip to content

Commit f924b45

Browse files
committed
Update Frontend for Custom Result Index Query and Fix Issues
This PR finalizes the frontend changes related to PR #1225. The custom result index query now uses an index pattern instead of a single index. Additionally, this PR addresses an issue where missing custom result indices would appear because the original code checked for the existence of an index name, but now we use it as a prefix. We have updated the logic to perform a prefix search instead of checking for index name equality. This PR also resolves issue opensearch-project#765 by downgrading the version of jest-canvas-mock. Testing Done: * Added unit tests. * Verified that the custom result index missing callout is not shown. * Confirmed that the frontend can still display old and new results after a rollover. Signed-off-by: Kaituo Li <kaituo@amazon.com>
1 parent 1080d60 commit f924b45

File tree

8 files changed

+381
-7
lines changed

8 files changed

+381
-7
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
"babel-polyfill": "^6.26.0",
3030
"eslint-plugin-no-unsanitized": "^3.0.2",
3131
"eslint-plugin-prefer-object-spread": "^1.2.1",
32-
"jest-canvas-mock": "^2.5.2",
32+
"jest-canvas-mock": "^2.5.1",
3333
"lint-staged": "^9.2.0",
3434
"moment": "^2.24.0",
3535
"redux-mock-store": "^1.5.4",

public/pages/DetectorDetail/containers/DetectorDetail.tsx

+8-4
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,8 @@ import {
6262
prettifyErrorMessage,
6363
} from '../../../../server/utils/helpers';
6464
import { DETECTOR_STATE } from '../../../../server/utils/constants';
65-
import { CatIndex } from '../../../../server/models/types';
66-
import { containsIndex } from '../utils/helpers';
65+
import { CatIndex, IndexAlias } from '../../../../server/models/types';
66+
import { containsIndex, containsAlias } from '../utils/helpers';
6767
import { DataSourceViewConfig } from '../../../../../../src/plugins/data_source_management/public';
6868
import {
6969
getDataSourceManagementPlugin,
@@ -136,6 +136,9 @@ export const DetectorDetail = (props: DetectorDetailProps) => {
136136
const isCatIndicesRequesting = useSelector(
137137
(state: AppState) => state.opensearch.requesting
138138
) as boolean;
139+
const visibleAliases = useSelector(
140+
(state: AppState) => state.opensearch.aliases
141+
) as IndexAlias[];
139142

140143
/*
141144
Determine if the result index is missing based on several conditions:
@@ -146,6 +149,7 @@ export const DetectorDetail = (props: DetectorDetailProps) => {
146149
To be safe, we'd rather not show the error message and consider the result index not missing.
147150
- If the result index is not found in the visible indices, then it is missing.
148151
*/
152+
const resultIndexOrAlias = get(detector, 'resultIndex', '')
149153
const isResultIndexMissing = isLoadingDetector
150154
? false
151155
: isEmpty(get(detector, 'resultIndex', ''))
@@ -154,11 +158,11 @@ export const DetectorDetail = (props: DetectorDetailProps) => {
154158
? false
155159
: isEmpty(visibleIndices)
156160
? false
157-
: !containsIndex(get(detector, 'resultIndex', ''), visibleIndices);
161+
: !containsIndex(resultIndexOrAlias, visibleIndices) && !containsAlias(resultIndexOrAlias, visibleAliases);
158162

159163
// debug message: prints visibleIndices if isResultIndexMissing is true
160164
if (isResultIndexMissing) {
161-
console.log(`isResultIndexMissing is true, visibleIndices: ${visibleIndices}, detector result index: ${get(detector, 'resultIndex', '')}`);
165+
console.log(`isResultIndexMissing is true, visibleIndices: ${visibleIndices}, visibleAliases: ${visibleAliases}, detector result index: ${resultIndexOrAlias}`);
162166
}
163167

164168
// String to set in the modal if the realtime detector and/or historical analysis

public/pages/DetectorDetail/containers/__tests__/CustomIndexErrorMsg.test.tsx

+34
Original file line numberDiff line numberDiff line change
@@ -272,4 +272,38 @@ describe('detector detail', () => {
272272
// Assert that the element is not in the document
273273
expect(element).toBeNull();
274274
});
275+
276+
test('the result index prefix is found in the visible indices', () => {
277+
const detector = getRandomDetector(true, resultIndex);
278+
279+
// Set up the mock implementation for useFetchDetectorInfo
280+
(useFetchDetectorInfo as jest.Mock).mockImplementation(() => ({
281+
detector: detector,
282+
hasError: false,
283+
isLoadingDetector: false,
284+
errorMessage: undefined,
285+
}));
286+
287+
const initialState = {
288+
opensearch: {
289+
indices: [
290+
{ health: 'green', index: '.kibana_-962704462_v992471_1' },
291+
{ health: 'green', index: resultIndex + '-history-2024.06.05-1' },
292+
],
293+
requesting: false,
294+
},
295+
ad: {
296+
detectors: {},
297+
},
298+
alerting: {
299+
monitors: {},
300+
},
301+
};
302+
303+
renderWithRouter(detectorId, initialState);
304+
const element = screen.queryByTestId('missingResultIndexCallOut');
305+
306+
// Assert that the element is not in the document
307+
expect(element).toBeNull();
308+
});
275309
});

public/pages/DetectorDetail/utils/helpers.tsx

+24-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { DETECTOR_STATE } from '../../../../server/utils/constants';
1717
import { Detector } from '../../../models/interfaces';
1818
import { EuiHealth } from '@elastic/eui';
1919
import moment from 'moment';
20-
import { CatIndex } from '../../../../server/models/types';
20+
import { CatIndex, IndexAlias } from '../../../../server/models/types';
2121

2222
export const getInitFailureMessageAndActionItem = (error: string): object => {
2323
const failureDetails = Object.values(DETECTOR_INIT_FAILURES);
@@ -142,6 +142,17 @@ export const getDetectorStateDetails = (
142142
);
143143
};
144144

145+
/**
146+
* Checks if any of the given indices contain the specified index.
147+
*
148+
* This function iterates through an array of `CatIndex` objects and checks if the `index` property of any
149+
* `CatIndex` object equals to the specified `index` string. It returns `true` if such an `index` is found,
150+
* otherwise it returns `false`.
151+
*
152+
* @param index - The string to check against the `index` properties of the `CatIndex` objects.
153+
* @param indices - An array of `CatIndex` objects to search through.
154+
* @returns A boolean value indicating whether any `CatIndex` object's `index` property equals to the specified prefix.
155+
*/
145156
export const containsIndex = (index: string, indices: CatIndex[]) => {
146157
let containsIndex = false;
147158
if (!isEmpty(indices)) {
@@ -153,3 +164,15 @@ export const containsIndex = (index: string, indices: CatIndex[]) => {
153164
}
154165
return containsIndex;
155166
};
167+
168+
export const containsAlias = (alias: string, aliases: IndexAlias[]) => {
169+
let containsAlias = false;
170+
if (!isEmpty(aliases)) {
171+
aliases.forEach((catAlias: IndexAlias) => {
172+
if (get(catAlias, 'alias', '') == alias) {
173+
containsAlias = true;
174+
}
175+
});
176+
}
177+
return containsAlias;
178+
};

public/redux/reducers/__tests__/anomalyResults.test.ts

+160-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@ import { mockedStore } from '../../utils/testUtils';
1818
import reducer, {
1919
getDetectorResults,
2020
initialDetectorsState,
21+
searchResults,
2122
} from '../anomalyResults';
23+
import { ALL_CUSTOM_AD_RESULT_INDICES } from '../../../pages/utils/constants'
24+
import { getAnomalySummaryQuery } from '../../../pages/utils/anomalyResultUtils'
2225

2326
jest.mock('../../../services', () => ({
2427
...jest.requireActual('../../../services'),
@@ -78,7 +81,7 @@ describe('anomaly results reducer actions', () => {
7881
expect(httpMockedClient.get).toHaveBeenCalledWith(
7982
`..${
8083
AD_NODE_API.DETECTOR
81-
}/${tempDetectorId}/results/${false}/${resultIndex}/true`,
84+
}/${tempDetectorId}/results/${false}/${resultIndex}*/true`,
8285
{ query: queryParams }
8386
);
8487
});
@@ -117,5 +120,161 @@ describe('anomaly results reducer actions', () => {
117120
);
118121
}
119122
});
123+
test('result index pattern will not result in appended wildcard star', async () => {
124+
const response = {
125+
totalAnomalies: 1,
126+
results: [{ anomalyGrade: 0, confidence: 1, starTime: 1, endTime: 2 }],
127+
};
128+
httpMockedClient.get = jest
129+
.fn()
130+
.mockResolvedValue({ ok: true, response });
131+
const tempDetectorId = '123';
132+
let queryParams: DetectorResultsQueryParams = {
133+
from: 0,
134+
size: 20,
135+
sortDirection: SORT_DIRECTION.ASC,
136+
sortField: 'startTime',
137+
};
138+
await store.dispatch(
139+
getDetectorResults(
140+
tempDetectorId,
141+
'',
142+
queryParams,
143+
false,
144+
ALL_CUSTOM_AD_RESULT_INDICES,
145+
true
146+
)
147+
);
148+
const actions = store.getActions();
149+
150+
expect(actions[0].type).toBe('ad/DETECTOR_RESULTS_REQUEST');
151+
expect(reducer(initialDetectorsState, actions[0])).toEqual({
152+
...initialDetectorsState,
153+
requesting: true,
154+
});
155+
expect(actions[1].type).toBe('ad/DETECTOR_RESULTS_SUCCESS');
156+
expect(reducer(initialDetectorsState, actions[1])).toEqual({
157+
...initialDetectorsState,
158+
requesting: false,
159+
total: response.totalAnomalies,
160+
anomalies: response.results,
161+
featureData: undefined,
162+
});
163+
expect(httpMockedClient.get).toHaveBeenCalledWith(
164+
`..${
165+
AD_NODE_API.DETECTOR
166+
}/${tempDetectorId}/results/${false}/${ALL_CUSTOM_AD_RESULT_INDICES}/true`,
167+
{ query: queryParams }
168+
);
169+
});
170+
});
171+
test('searchResults should append wildcard star at the end of custom result index', async () => {
172+
const response = {
173+
aggregations: {
174+
top_entities: {
175+
doc_count: 0,
176+
top_entity_aggs: {
177+
doc_count_error_upper_bound: 0,
178+
sum_other_doc_count: 0,
179+
buckets: []
180+
}
181+
}
182+
}
183+
};
184+
185+
httpMockedClient.post = jest
186+
.fn()
187+
.mockResolvedValue({ ok: true, response });
188+
const tempDetectorId = '123';
189+
const resultIndex = 'opensearch-ad-plugin-result-test';
190+
const requestBody = getAnomalySummaryQuery(1717529636479, 1717529736479, tempDetectorId, undefined, false, undefined, undefined)
191+
await store.dispatch(
192+
searchResults(
193+
requestBody,
194+
resultIndex,
195+
'',
196+
true
197+
)
198+
);
199+
const actions = store.getActions();
200+
201+
expect(actions[0].type).toBe('ad/SEARCH_ANOMALY_RESULTS_REQUEST');
202+
expect(reducer(initialDetectorsState, actions[0])).toEqual({
203+
...initialDetectorsState,
204+
requesting: true,
205+
});
206+
expect(actions[1].type).toBe('ad/SEARCH_ANOMALY_RESULTS_SUCCESS');
207+
expect(reducer(initialDetectorsState, actions[1])).toEqual({
208+
...initialDetectorsState,
209+
requesting: false,
210+
});
211+
expect(httpMockedClient.post).toHaveBeenCalledWith(
212+
`..${
213+
AD_NODE_API.DETECTOR
214+
}/results/_search/${resultIndex}*/true`,
215+
{ body: JSON.stringify(requestBody) }
216+
);
217+
});
218+
test('searchResults should not append wildcard star at the end of custom result index', async () => {
219+
const response = {
220+
took: 1,
221+
timed_out: false,
222+
_shards: {
223+
total: 2,
224+
successful: 2,
225+
skipped: 0,
226+
failed: 0
227+
},
228+
hits: {
229+
total: {
230+
value: 0,
231+
relation: "eq"
232+
},
233+
max_score: null,
234+
hits: []
235+
},
236+
aggregations: {
237+
top_entities: {
238+
doc_count: 0,
239+
top_entity_aggs: {
240+
doc_count_error_upper_bound: 0,
241+
sum_other_doc_count: 0,
242+
buckets: []
243+
}
244+
}
245+
}
246+
};
247+
248+
httpMockedClient.post = jest
249+
.fn()
250+
.mockResolvedValue({ ok: true, response });
251+
const tempDetectorId = '123';
252+
const requestBody = getAnomalySummaryQuery(1717529636479, 1717529736479, tempDetectorId, undefined, false, undefined, undefined)
253+
await store.dispatch(
254+
searchResults(
255+
requestBody,
256+
ALL_CUSTOM_AD_RESULT_INDICES,
257+
'',
258+
true
259+
)
260+
);
261+
const actions = store.getActions();
262+
263+
expect(actions[0].type).toBe('ad/SEARCH_ANOMALY_RESULTS_REQUEST');
264+
expect(reducer(initialDetectorsState, actions[0])).toEqual({
265+
...initialDetectorsState,
266+
requesting: true,
267+
});
268+
expect(actions[1].type).toBe('ad/SEARCH_ANOMALY_RESULTS_SUCCESS');
269+
expect(reducer(initialDetectorsState, actions[1])).toEqual({
270+
...initialDetectorsState,
271+
requesting: false,
272+
});
273+
expect(httpMockedClient.post).toHaveBeenCalledWith(
274+
`..${
275+
AD_NODE_API.DETECTOR
276+
}/results/_search/${ALL_CUSTOM_AD_RESULT_INDICES}/true`,
277+
{ body: JSON.stringify(requestBody) }
278+
);
120279
});
121280
});

0 commit comments

Comments
 (0)