Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ResponseOps][Alerts] Add alerts grouping aggregations endpoint #186475

Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
ac35282
Add get alerts group aggregations endpoint
umbopepato Jun 19, 2024
15f9aa7
Add alerts group aggregation endpoint tests
umbopepato Jun 19, 2024
46fea59
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 19, 2024
a47b66f
Fix import
umbopepato Jun 19, 2024
e091401
Automatically add unitsCount subaggregation in groupByField aggregation
umbopepato Jun 19, 2024
ae8b482
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 19, 2024
0529905
Make aggregations field optional, improve documentation
umbopepato Jun 19, 2024
6f57233
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 19, 2024
e39bfa5
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 20, 2024
d848db0
Fix tests
umbopepato Jun 20, 2024
46fb4fd
Add tests and improve AlertsClient.find errors handling
umbopepato Jun 20, 2024
eaa7bd6
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 20, 2024
52485c3
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 21, 2024
e8b0329
Revert error response transformation
umbopepato Jun 21, 2024
de6c865
Use type instead of interface for validation
umbopepato Jun 21, 2024
62194c9
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 25, 2024
238e803
Restrict filters and pagination options validation
umbopepato Jun 25, 2024
1c1a1fd
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 26, 2024
0731496
Fix test
umbopepato Jun 26, 2024
ca88557
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jul 3, 2024
8869584
Improve typings and validations
umbopepato Jul 3, 2024
11ac1fc
Fix AlertsClient.find not returning result
umbopepato Jul 3, 2024
6fc8aee
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jul 3, 2024
cb2e535
Move alert group aggregations pagination tests
umbopepato Jul 3, 2024
90a86d1
Improve filters validation schema and searchAlerts control flow
umbopepato Jul 4, 2024
39e0ae2
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jul 4, 2024
c962e1f
Fix filter keys validation schema type assertion
umbopepato Jul 4, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/kbn-alerts-ui-shared/src/common/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from './use_load_alerting_framework_health';
export * from './use_create_rule';
export * from './use_update_rule';
export * from './use_resolve_rule';
export * from './use_get_alerts_group_aggregations_query';
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import type { HttpStart } from '@kbn/core-http-browser';
import { ToastsStart } from '@kbn/core-notifications-browser';
import { AlertConsumers } from '@kbn/rule-data-utils';

import { useGetAlertsGroupAggregationsQuery } from './use_get_alerts_group_aggregations_query';
import { waitFor } from '@testing-library/react';
import { BASE_RAC_ALERTS_API_PATH } from '../constants';

const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});

const wrapper = ({ children }: { children: Node }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);

const mockHttp = {
post: jest.fn(),
};
const http = mockHttp as unknown as HttpStart;

const mockToasts = {
addDanger: jest.fn(),
};
const toasts = mockToasts as unknown as ToastsStart;

const params = {
featureIds: [AlertConsumers.STACK_ALERTS],
groupByField: 'kibana.alert.rule.name',
};

describe('useAlertsGroupAggregationsQuery', () => {
afterEach(() => {
jest.clearAllMocks();
});

test('displays toast on errors', async () => {
mockHttp.post.mockRejectedValue(new Error('An error occurred'));
renderHook(
() =>
useGetAlertsGroupAggregationsQuery({
params,
enabled: true,
toasts,
http,
}),
{ wrapper }
);

await waitFor(() => expect(mockToasts.addDanger).toHaveBeenCalled());
});

test('calls API endpoint with the correct body', async () => {
renderHook(
() =>
useGetAlertsGroupAggregationsQuery({
params,
enabled: true,
toasts,
http,
}),
{ wrapper }
);

await waitFor(() =>
expect(mockHttp.post).toHaveBeenLastCalledWith(
`${BASE_RAC_ALERTS_API_PATH}/_group_aggregations`,
{
body: JSON.stringify(params),
}
)
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { i18n } from '@kbn/i18n';
import { useQuery } from '@tanstack/react-query';
import type { HttpStart } from '@kbn/core-http-browser';
import type { ToastsStart } from '@kbn/core-notifications-browser';
import { SearchResponseBody } from '@elastic/elasticsearch/lib/api/types';
import { AlertConsumers } from '@kbn/rule-data-utils';
import type {
AggregationsAggregationContainer,
QueryDslQueryContainer,
SortCombinations,
} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { BASE_RAC_ALERTS_API_PATH } from '../constants';

export interface UseGetAlertsGroupAggregationsQueryProps {
http: HttpStart;
toasts: ToastsStart;
enabled?: boolean;
params: {
featureIds: AlertConsumers[];
groupByField: string;
aggregations?: Record<string, AggregationsAggregationContainer>;
filters?: QueryDslQueryContainer[];
sort?: SortCombinations[];
pageIndex?: number;
pageSize?: number;
};
}

/**
* Fetches alerts aggregations for a given groupByField.
*
* Some default aggregations are applied:
* - `groupByFields`, to get the buckets based on the provided grouping field,
* - `unitsCount`, to count the number of alerts in each bucket,
* - `unitsCount`, to count the total number of alerts targeted by the query,
* - `groupsCount`, to count the total number of groups.
*
* The provided `aggregations` are applied within `groupByFields`. Here the `groupByField` runtime
* field can be used to perform grouping-based aggregations.
*
* Applies alerting RBAC through featureIds.
*/
export const useGetAlertsGroupAggregationsQuery = <T>({
Copy link
Contributor

@adcoelho adcoelho Jun 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add tests for this in packages/kbn-alerts-ui-shared/src/common/hooks/use_get_alerts_group_aggregations_query.test.ts? Stuff like displays error toast if params are not JSON or API gets called with the correct body..

http,
toasts,
enabled = true,
params,
}: UseGetAlertsGroupAggregationsQueryProps) => {
const onErrorFn = (error: Error) => {
if (error) {
toasts.addDanger(
i18n.translate(
'alertsUIShared.hooks.useFindAlertsQuery.unableToFetchAlertsGroupingAggregations',
{
defaultMessage: 'Unable to fetch alerts grouping aggregations',
}
)
);
}
};

return useQuery({
queryKey: ['getAlertsGroupAggregations', JSON.stringify(params)],
queryFn: () =>
http.post<SearchResponseBody<{}, T>>(`${BASE_RAC_ALERTS_API_PATH}/_group_aggregations`, {
body: JSON.stringify(params),
}),
onError: onErrorFn,
refetchOnWindowFocus: false,
enabled,
});
};
67 changes: 67 additions & 0 deletions x-pack/plugins/rule_registry/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,73 @@ export const bucketAggsSchemas = t.intersection([
),
]);

export const alertsAggregationsSchema = t.record(
t.string,
t.intersection([metricsAggsSchemas, bucketAggsSchemas])
);

export const alertsGroupFilterSchema = t.record(
t.union([
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have existing enums for these literals? Just so we can have a more centralized source of truth

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would have been nice, but I was only able to find type-level information. I added a type assertion to check that the keys are correctly aligned to the es types though 🙂

t.literal('bool'),
t.literal('boosting'),
t.literal('common'),
t.literal('combined_fields'),
t.literal('constant_score'),
t.literal('dis_max'),
t.literal('distance_feature'),
t.literal('exists'),
t.literal('function_score'),
t.literal('fuzzy'),
t.literal('geo_bounding_box'),
t.literal('geo_distance'),
t.literal('geo_polygon'),
t.literal('geo_shape'),
t.literal('has_child'),
t.literal('has_parent'),
t.literal('ids'),
t.literal('intervals'),
t.literal('knn'),
t.literal('match'),
t.literal('match_all'),
t.literal('match_bool_prefix'),
t.literal('match_none'),
t.literal('match_phrase'),
t.literal('match_phrase_prefix'),
t.literal('more_like_this'),
t.literal('multi_match'),
t.literal('nested'),
t.literal('parent_id'),
t.literal('percolate'),
t.literal('pinned'),
t.literal('prefix'),
t.literal('query_string'),
t.literal('range'),
t.literal('rank_feature'),
t.literal('regexp'),
t.literal('rule_query'),
t.literal('shape'),
t.literal('simple_query_string'),
t.literal('span_containing'),
t.literal('field_masking_span'),
t.literal('span_first'),
t.literal('span_multi'),
t.literal('span_near'),
t.literal('span_not'),
t.literal('span_or'),
t.literal('span_term'),
t.literal('span_within'),
t.literal('term'),
t.literal('terms'),
t.literal('terms_set'),
t.literal('text_expansion'),
t.literal('weighted_tokens'),
t.literal('wildcard'),
t.literal('wrapper'),
t.literal('type'),
]),
t.object
);

export type PutIndexTemplateRequest = estypes.IndicesPutIndexTemplateRequest & {
body?: { composed_of?: string[] };
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const createAlertsClientMock = () => {
bulkUpdate: jest.fn(),
bulkUpdateCases: jest.fn(),
find: jest.fn(),
getGroupAggregations: jest.fn(),
getFeatureIdsByRegistrationContexts: jest.fn(),
getBrowserFields: jest.fn(),
getAlertSummary: jest.fn(),
Expand Down
Loading