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

[ES|QL] Enable ESQL alerts from the Discover app #165973

Merged
merged 8 commits into from Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/kbn-discover-utils/src/__mocks__/data_view.ts
Expand Up @@ -92,6 +92,10 @@ export const buildDataViewMock = ({
return dataViewFields.find((field) => field.name === fieldName);
};

dataViewFields.getByType = (type: string) => {
return dataViewFields.filter((field) => field.type === type);
};

dataViewFields.getAll = () => {
return dataViewFields;
};
Expand Down
54 changes: 54 additions & 0 deletions src/plugins/discover/public/__mocks__/data_view_no_timefield.ts
@@ -0,0 +1,54 @@
/*
* 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 { DataView } from '@kbn/data-views-plugin/public';
import { buildDataViewMock } from '@kbn/discover-utils/src/__mocks__';

const fields = [
{
name: '_index',
type: 'string',
scripted: false,
filterable: true,
},
{
name: 'message',
displayName: 'message',
type: 'string',
scripted: false,
filterable: false,
},
{
name: 'extension',
displayName: 'extension',
type: 'string',
scripted: false,
filterable: true,
aggregatable: true,
},
{
name: 'bytes',
displayName: 'bytes',
type: 'number',
scripted: false,
filterable: true,
aggregatable: true,
},
{
name: 'scripted',
displayName: 'scripted',
type: 'number',
scripted: true,
filterable: false,
},
] as DataView['fields'];

export const dataViewWithNoTimefieldMock = buildDataViewMock({
name: 'index-pattern-with-timefield',
fields,
});
Expand Up @@ -53,6 +53,7 @@ export const getTopNavLinks = ({
services,
stateContainer: state,
adHocDataViews,
isPlainRecord,
});
},
testId: 'discoverAlertsButton',
Expand Down Expand Up @@ -232,7 +233,6 @@ export const getTopNavLinks = ({
if (
services.triggersActionsUi &&
services.capabilities.management?.insightsAndAlerting?.triggersActions &&
!isPlainRecord &&
!defaultMenu?.alertsItem?.disabled
) {
entries.push({ data: alerts, order: defaultMenu?.alertsItem?.order ?? 400 });
Expand Down
Expand Up @@ -13,10 +13,11 @@ import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public';
import { AlertsPopover } from './open_alerts_popover';
import { discoverServiceMock } from '../../../../__mocks__/services';
import { dataViewWithTimefieldMock } from '../../../../__mocks__/data_view_with_timefield';
import { dataViewWithNoTimefieldMock } from '../../../../__mocks__/data_view_no_timefield';
import { dataViewMock } from '@kbn/discover-utils/src/__mocks__';
import { getDiscoverStateMock } from '../../../../__mocks__/discover_state.mock';

const mount = (dataView = dataViewMock) => {
const mount = (dataView = dataViewMock, isPlainRecord = false) => {
const stateContainer = getDiscoverStateMock({ isTimeBased: true });
stateContainer.actions.setDataView(dataView);
return mountWithIntl(
Expand All @@ -25,6 +26,7 @@ const mount = (dataView = dataViewMock) => {
stateContainer={stateContainer}
anchorElement={document.createElement('div')}
adHocDataViews={[]}
isPlainRecord={isPlainRecord}
services={discoverServiceMock}
onClose={jest.fn()}
/>
Expand All @@ -33,18 +35,42 @@ const mount = (dataView = dataViewMock) => {
};

describe('OpenAlertsPopover', () => {
it('should render with the create search threshold rule button disabled if the data view has no time field', () => {
const component = mount();
expect(findTestSubject(component, 'discoverCreateAlertButton').prop('disabled')).toBeTruthy();
});
describe('Dataview mode', () => {
it('should render with the create search threshold rule button disabled if the data view has no time field', () => {
const component = mount();
expect(findTestSubject(component, 'discoverCreateAlertButton').prop('disabled')).toBeTruthy();
});

it('should render with the create search threshold rule button enabled if the data view has a time field', () => {
const component = mount(dataViewWithTimefieldMock);
expect(findTestSubject(component, 'discoverCreateAlertButton').prop('disabled')).toBeFalsy();
});

it('should render with the create search threshold rule button enabled if the data view has a time field', () => {
const component = mount(dataViewWithTimefieldMock);
expect(findTestSubject(component, 'discoverCreateAlertButton').prop('disabled')).toBeFalsy();
it('should render the manage rules and connectors link', () => {
const component = mount();
expect(findTestSubject(component, 'discoverManageAlertsButton').exists()).toBeTruthy();
});
});

it('should render the manage rules and connectors link', () => {
const component = mount();
expect(findTestSubject(component, 'discoverManageAlertsButton').exists()).toBeTruthy();
describe('ES|QL mode', () => {
it('should render with the create search threshold rule button enabled if the data view has no timeFieldName but at least one time field', () => {
const component = mount(dataViewMock, true);
expect(findTestSubject(component, 'discoverCreateAlertButton').prop('disabled')).toBeFalsy();
});

it('should render with the create search threshold rule button enabled if the data view has a time field', () => {
const component = mount(dataViewWithTimefieldMock, true);
expect(findTestSubject(component, 'discoverCreateAlertButton').prop('disabled')).toBeFalsy();
});

it('should render with the create search threshold rule button disabled if the data view has no time fields at all', () => {
const component = mount(dataViewWithNoTimefieldMock, true);
expect(findTestSubject(component, 'discoverCreateAlertButton').prop('disabled')).toBeTruthy();
});

it('should render the manage rules and connectors link', () => {
const component = mount();
expect(findTestSubject(component, 'discoverManageAlertsButton').exists()).toBeTruthy();
});
});
});
Expand Up @@ -28,6 +28,7 @@ interface AlertsPopoverProps {
savedQueryId?: string;
adHocDataViews: DataView[];
services: DiscoverServices;
isPlainRecord?: boolean;
}

interface EsQueryAlertMetaData {
Expand All @@ -41,8 +42,13 @@ export function AlertsPopover({
services,
stateContainer,
onClose: originalOnClose,
isPlainRecord,
}: AlertsPopoverProps) {
const dataView = stateContainer.internalState.getState().dataView;
const query = stateContainer.appState.getState().query;
const dateFields = dataView?.fields.getByType('date');
const timeField = dataView?.timeFieldName || dateFields?.[0]?.name;
stratoula marked this conversation as resolved.
Show resolved Hide resolved

const { triggersActionsUi } = services;
const [alertFlyoutVisible, setAlertFlyoutVisibility] = useState(false);
const onClose = useCallback(() => {
Expand All @@ -54,6 +60,13 @@ export function AlertsPopover({
* Provides the default parameters used to initialize the new rule
*/
const getParams = useCallback(() => {
if (isPlainRecord) {
return {
searchType: 'esqlQuery',
Copy link
Contributor

Choose a reason for hiding this comment

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

I am seeing this UI for the first time and "Alerts generated" label looks confusing when you are just creating a new alert. Can we remove or rephrase it?

Screenshot 2023-09-12 at 11 13 08

Copy link
Contributor Author

@stratoula stratoula Sep 12, 2023

Choose a reason for hiding this comment

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

This is not owned by us. If you have any recommendations for the alerting team it is better to create an issue for them cc @mikecote

esqlQuery: query,
timeField,
stratoula marked this conversation as resolved.
Show resolved Hide resolved
};
}
const savedQueryId = stateContainer.appState.getState().savedQuery;
return {
searchType: 'searchSource',
Expand All @@ -62,7 +75,7 @@ export function AlertsPopover({
.searchSource.getSerializedFields(),
savedQueryId,
};
}, [stateContainer]);
}, [isPlainRecord, stateContainer.appState, stateContainer.savedSearchState, query, timeField]);

const discoverMetadata: EsQueryAlertMetaData = useMemo(
() => ({
Expand Down Expand Up @@ -98,7 +111,14 @@ export function AlertsPopover({
});
}, [alertFlyoutVisible, triggersActionsUi, discoverMetadata, getParams, onClose, stateContainer]);

const hasTimeFieldName = Boolean(dataView?.timeFieldName);
const hasTimeFieldName: boolean = useMemo(() => {
if (!isPlainRecord) {
return Boolean(dataView?.timeFieldName);
} else {
return Boolean(timeField);
}
}, [dataView?.timeFieldName, isPlainRecord, timeField]);

const panels = [
{
id: 'mainPanel',
Expand Down Expand Up @@ -165,11 +185,13 @@ export function openAlertsPopover({
stateContainer,
services,
adHocDataViews,
isPlainRecord,
}: {
anchorElement: HTMLElement;
stateContainer: DiscoverStateContainer;
services: DiscoverServices;
adHocDataViews: DataView[];
isPlainRecord?: boolean;
}) {
if (isOpen) {
closeAlertsPopover();
Expand All @@ -188,6 +210,7 @@ export function openAlertsPopover({
stateContainer={stateContainer}
adHocDataViews={adHocDataViews}
services={services}
isPlainRecord={isPlainRecord}
Copy link
Contributor

Choose a reason for hiding this comment

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

  • Not related to this line

"View in app" link seems to be not working for ES|QL alerts:

Screenshot 2023-09-12 at 11 15 08

I would expect it to open ES|QL view in Discover if possible instead of this error:
Screenshot 2023-09-12 at 11 14 37

Copy link
Contributor Author

@stratoula stratoula Sep 12, 2023

Choose a reason for hiding this comment

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

Also not related to us cc @mikecote maybe it makes sense to have a look on this when this PR is being merged

Copy link
Contributor

Choose a reason for hiding this comment

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

We have it configured so rules created from discover navigate to the following path whenever a user clicks "View in app": /app/discover#/viewAlert/${alert.id}.

Is there something that should change with the path for ES|QL rules? The code comes from here: https://github.com/elastic/kibana/blob/main/x-pack/plugins/stack_alerts/public/rule_types/es_query/index.ts#L51C15-L51C51.

cc @XavierM as he is working on changing this in the recent release.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think I can take a look to see if we can make it work from Discover side.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I fixed that 👍

Copy link
Contributor

Choose a reason for hiding this comment

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

Great, thanks! Now the feature looks complete to me 🙂

@kertal Could you please also review this change 2800b2e if you have time?

Copy link
Member

Choose a reason for hiding this comment

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

thx Julia! Code looks good, but I wonder if it is used when generating the link to Discover? I've created a rule with a notification containing a {{context.link}} field:

Bildschirmfoto 2023-09-14 um 09 24 20

But what was ingested was the link to the alert rule:

Bildschirmfoto 2023-09-14 um 09 25 26

@stratoula we intend to link to Discover also in ES|QL cases right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This already exists in main unfortunately so better been handled on a separate PR. I synced with Matthias and we are going to open an issue on alerting.

/>
</KibanaContextProvider>
</KibanaRenderContextProvider>
Expand Down
2 changes: 1 addition & 1 deletion test/functional/apps/discover/group2/_esql_view.ts
Expand Up @@ -75,7 +75,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
// when Lens suggests a table, we render an ESQL based histogram
expect(await testSubjects.exists('unifiedHistogramChart')).to.be(true);
expect(await testSubjects.exists('unifiedHistogramQueryHits')).to.be(true);
expect(await testSubjects.exists('discoverAlertsButton')).to.be(false);
expect(await testSubjects.exists('discoverAlertsButton')).to.be(true);
expect(await testSubjects.exists('shareTopNavButton')).to.be(true);
expect(await testSubjects.exists('dataGridColumnSortingButton')).to.be(false);
expect(await testSubjects.exists('docTableExpandToggleColumn')).to.be(true);
Expand Down
Expand Up @@ -25,6 +25,7 @@ jest.mock('@kbn/text-based-editor', () => ({
fetchFieldsFromESQL: jest.fn(),
}));
const { fetchFieldsFromESQL } = jest.requireMock('@kbn/text-based-editor');
const { getFields } = jest.requireMock('@kbn/triggers-actions-ui-plugin/public');

const AppWrapper: React.FC<{ children: React.ReactElement }> = React.memo(({ children }) => (
<I18nProvider>{children}</I18nProvider>
Expand Down Expand Up @@ -133,6 +134,7 @@ describe('EsqlQueryRuleTypeExpression', () => {
},
],
});
getFields.mockResolvedValue([]);
const result = render(
<EsqlQueryExpression
unifiedSearch={unifiedSearchMock}
Expand Down
Expand Up @@ -76,6 +76,11 @@ export const EsqlQueryExpression: React.FC<
const setDefaultExpressionValues = async () => {
setRuleProperty('params', currentRuleParams);
setQuery(esqlQuery ?? { esql: '' });
if ('esql' in esqlQuery) {
if (esqlQuery.esql) {
refreshTimeFields(esqlQuery);
}
}
if (timeField) {
setTimeFieldOptions([firstFieldOption, { text: timeField, value: timeField }]);
}
Expand Down