Skip to content

Commit

Permalink
[ResponseOps][Alerts] Migrate alerts fields fetching to TanStack Query (
Browse files Browse the repository at this point in the history
#188320)

## Summary

Migrates the `useFetchBrowserFieldCapabilities` hook (renamed to
`useFetchAlertsFieldsQuery`) to TanStack Query, following [this
organizational
logic](#186448 (comment)).

This PR focuses mainly on the fetching logic itself, leaving the
surrounding API surface mostly unchanged since it will be likely
addressed in subsequent PRs.

## To verify

1. Create rules that fire alerts in different solutions
2. Check that the alerts table usages work correctly ({O11y, Security,
Stack} alerts and rule details pages, ...)
1. Check that the alerts displayed in the table are coherent with the
solution, KQL query, time filter, pagination
    2. Check that pagination changes are reflected in the table
3. Check that changing the query when in pages > 0 resets the pagination
to the first page
4. Check that the fields browser shows and works correctly (`Fields`
button in the alerts table header)

Closes point 2 of #186448

### Checklist

- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios

---------

Co-authored-by: kibanamachine <[email protected]>
  • Loading branch information
umbopepato and kibanamachine authored Jul 29, 2024
1 parent d62334f commit f24e0cd
Show file tree
Hide file tree
Showing 24 changed files with 653 additions and 523 deletions.
29 changes: 29 additions & 0 deletions packages/kbn-alerting-types/alert_fields_type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* 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 { SerializedFieldFormat } from '@kbn/field-formats-plugin/common';
import type { IFieldSubType } from '@kbn/es-query';
import type { RuntimeField } from '@kbn/data-views-plugin/common';

export interface BrowserField {
aggregatable: boolean;
category: string;
description?: string | null;
example?: string | number | null;
fields: Readonly<Record<string, Partial<BrowserField>>>;
format?: SerializedFieldFormat;
indexes: string[];
name: string;
searchable: boolean;
type: string;
subType?: IFieldSubType;
readFromDocValues: boolean;
runtimeField?: RuntimeField;
}

export type BrowserFields = Record<string, Partial<BrowserField>>;
3 changes: 2 additions & 1 deletion packages/kbn-alerting-types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@

export * from './action_group_types';
export * from './action_variable';
export * from './alert_fields_type';
export * from './alert_type';
export * from './alerting_framework_health_types';
export * from './builtin_action_groups_types';
export * from './circuit_breaker_message_header';
export * from './r_rule_types';
export * from './rule_notify_when_type';
export * from './search_strategy_types';
export * from './rule_type_types';
export * from './rule_types';
export * from './search_strategy_types';
2 changes: 2 additions & 0 deletions packages/kbn-alerting-types/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
"@kbn/rrule",
"@kbn/core",
"@kbn/es-query",
"@kbn/field-formats-plugin",
"@kbn/data-views-plugin",
"@kbn/search-types"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* 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 { httpServiceMock } from '@kbn/core/public/mocks';
import { fetchAlertsFields } from '.';
import { AlertConsumers } from '@kbn/rule-data-utils';

describe('fetchAlertsFields', () => {
const http = httpServiceMock.createStartContract();
test('should call the browser_fields API with the correct parameters', async () => {
const featureIds = [AlertConsumers.STACK_ALERTS];
http.get.mockResolvedValueOnce({
browserFields: { fakeCategory: {} },
fields: [
{
name: 'fakeCategory',
},
],
});
const result = await fetchAlertsFields({ http, featureIds });
expect(result).toEqual({
browserFields: { fakeCategory: {} },
fields: [
{
name: 'fakeCategory',
},
],
});
expect(http.get).toHaveBeenLastCalledWith('/internal/rac/alerts/browser_fields', {
query: { featureIds },
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* 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 type { FieldDescriptor } from '@kbn/data-views-plugin/server';
import type { BrowserFields } from '@kbn/alerting-types';
import type { FetchAlertsFieldsParams } from './types';
import { BASE_RAC_ALERTS_API_PATH } from '../../constants';

export const fetchAlertsFields = ({ http, featureIds }: FetchAlertsFieldsParams) =>
http.get<{ browserFields: BrowserFields; fields: FieldDescriptor[] }>(
`${BASE_RAC_ALERTS_API_PATH}/browser_fields`,
{
query: { featureIds },
}
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
* 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.
*/

export * from './fetch_alerts_fields';
export * from './types';
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,16 @@
* Side Public License, v 1.
*/

import { HttpSetup } from '@kbn/core-http-browser';
import { ValidFeatureId } from '@kbn/rule-data-utils';
import { HttpSetup } from '@kbn/core/public';
import { FieldSpec } from '@kbn/data-views-plugin/common';
import { BASE_RAC_ALERTS_API_PATH } from '../constants';

export async function fetchAlertFields({
http,
featureIds,
}: {
export interface FetchAlertsFieldsParams {
// Dependencies
http: HttpSetup;

// Params
/**
* Array of feature ids used for authorization and area-based filtering
*/
featureIds: ValidFeatureId[];
}): Promise<FieldSpec[]> {
const { fields: alertFields = [] } = await http.get<{ fields: FieldSpec[] }>(
`${BASE_RAC_ALERTS_API_PATH}/browser_fields`,
{
query: { featureIds },
}
);
return alertFields;
}
13 changes: 7 additions & 6 deletions packages/kbn-alerts-ui-shared/src/common/apis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
* Side Public License, v 1.
*/

export * from './fetch_ui_health_status';
export * from './fetch_alerting_framework_health';
export * from './fetch_ui_config';
export * from './create_rule';
export * from './update_rule';
export * from './resolve_rule';
export * from './fetch_connectors';
export * from './fetch_alerting_framework_health';
export * from './fetch_alerts_fields';
export * from './fetch_connector_types';
export * from './fetch_connectors';
export * from './fetch_rule_type_aad_template_fields';
export * from './fetch_ui_config';
export * from './fetch_ui_health_status';
export * from './resolve_rule';
export * from './update_rule';
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import { AlertConsumers, ValidFeatureId } from '@kbn/rule-data-utils';
import type { ToastsStart, HttpStart } from '@kbn/core/public';

import { useQuery } from '@tanstack/react-query';
import { useFetchAlertsFieldsQuery } from './use_fetch_alerts_fields_query';
import { fetchAlertIndexNames } from '../apis/fetch_alert_index_names';
import { fetchAlertFields } from '../apis/fetch_alert_fields';

export interface UseAlertDataViewResult {
dataViews?: DataView[];
Expand Down Expand Up @@ -45,10 +45,6 @@ export function useAlertDataView(props: UseAlertDataViewProps): UseAlertDataView
return fetchAlertIndexNames({ http, features });
};

const queryAlertFieldsFn = () => {
return fetchAlertFields({ http, featureIds });
};

const onErrorFn = () => {
toasts.addDanger(
i18n.translate('alertsUIShared.hooks.useAlertDataView.useAlertDataMessage', {
Expand All @@ -72,18 +68,19 @@ export function useAlertDataView(props: UseAlertDataViewProps): UseAlertDataView
});

const {
data: alertFields,
data: { fields: alertFields },
isSuccess: isAlertFieldsSuccess,
isInitialLoading: isAlertFieldsInitialLoading,
isLoading: isAlertFieldsLoading,
} = useQuery({
queryKey: ['loadAlertFields', features],
queryFn: queryAlertFieldsFn,
onError: onErrorFn,
refetchOnWindowFocus: false,
staleTime: 60 * 1000,
enabled: hasNoSecuritySolution,
});
} = useFetchAlertsFieldsQuery(
{ http, featureIds },
{
onError: onErrorFn,
refetchOnWindowFocus: false,
staleTime: 60 * 1000,
enabled: hasNoSecuritySolution,
}
);

useEffect(() => {
return () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
* 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, { FunctionComponent } from 'react';
import type { HttpSetup } from '@kbn/core-http-browser';
import { AlertConsumers } from '@kbn/rule-data-utils';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks';
import { testQueryClientConfig } from '../test_utils/test_query_client_config';
import { useFetchAlertsFieldsQuery } from './use_fetch_alerts_fields_query';

const queryClient = new QueryClient(testQueryClientConfig);

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

const mockHttpClient = {
get: jest.fn(),
} as unknown as HttpSetup;

const emptyData = { browserFields: {}, fields: [] };

describe('useFetchAlertsFieldsQuery', () => {
const mockHttpGet = jest.mocked(mockHttpClient.get);

beforeEach(() => {
mockHttpGet.mockResolvedValue({
browserFields: { fakeCategory: {} },
fields: [
{
name: 'fakeCategory',
},
],
});
});

afterEach(() => {
mockHttpGet.mockClear();
queryClient.clear();
});

it('should not fetch for siem', () => {
const { result } = renderHook(
() => useFetchAlertsFieldsQuery({ http: mockHttpClient, featureIds: ['siem'] }),
{
wrapper,
}
);

expect(mockHttpGet).toHaveBeenCalledTimes(0);
expect(result.current.data).toEqual(emptyData);
});

it('should call the api only once', async () => {
const { result, rerender, waitForValueToChange } = renderHook(
() => useFetchAlertsFieldsQuery({ http: mockHttpClient, featureIds: ['apm'] }),
{
wrapper,
}
);

await waitForValueToChange(() => result.current.data);

expect(mockHttpGet).toHaveBeenCalledTimes(1);
expect(result.current.data).toEqual({
browserFields: { fakeCategory: {} },
fields: [
{
name: 'fakeCategory',
},
],
});

rerender();

expect(mockHttpGet).toHaveBeenCalledTimes(1);
expect(result.current.data).toEqual({
browserFields: { fakeCategory: {} },
fields: [
{
name: 'fakeCategory',
},
],
});
});

it('should not fetch if the only featureId is not valid', async () => {
const { result } = renderHook(
() =>
useFetchAlertsFieldsQuery({
http: mockHttpClient,
featureIds: ['alerts'] as unknown as AlertConsumers[],
}),
{
wrapper,
}
);

expect(mockHttpGet).toHaveBeenCalledTimes(0);
expect(result.current.data).toEqual(emptyData);
});

it('should not fetch if all featureId are not valid', async () => {
const { result } = renderHook(
() =>
useFetchAlertsFieldsQuery({
http: mockHttpClient,
featureIds: ['alerts', 'tomato'] as unknown as AlertConsumers[],
}),
{
wrapper,
}
);

expect(mockHttpGet).toHaveBeenCalledTimes(0);
expect(result.current.data).toEqual(emptyData);
});

it('should filter out the non valid feature id', async () => {
renderHook(
() =>
useFetchAlertsFieldsQuery({
http: mockHttpClient,
featureIds: ['alerts', 'apm', 'logs'] as AlertConsumers[],
}),
{
wrapper,
}
);

expect(mockHttpGet).toHaveBeenCalledTimes(1);
expect(mockHttpGet).toHaveBeenCalledWith('/internal/rac/alerts/browser_fields', {
query: { featureIds: ['apm', 'logs'] },
});
});
});
Loading

0 comments on commit f24e0cd

Please sign in to comment.