mirror of
https://github.com/grafana/grafana.git
synced 2025-01-09 07:33:42 -06:00
Alerting: Allow selecting the same custom group when swapping folders (#70337)
This commit is contained in:
parent
815e98ed95
commit
87884f4d41
@ -1,4 +1,4 @@
|
||||
import { render, waitFor, waitForElementToBeRemoved } from '@testing-library/react';
|
||||
import { render, waitFor, waitForElementToBeRemoved, within } from '@testing-library/react';
|
||||
import { setupServer } from 'msw/node';
|
||||
import React from 'react';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
@ -64,7 +64,6 @@ const ui = {
|
||||
labelValue: (idx: number) => byTestId(`label-value-${idx}`),
|
||||
},
|
||||
loadingIndicator: byText('Loading the rule'),
|
||||
loadingGroupIndicator: byText('Loading...'),
|
||||
};
|
||||
|
||||
function getProvidersWrapper() {
|
||||
@ -149,7 +148,7 @@ describe('CloneRuleEditor', function () {
|
||||
});
|
||||
|
||||
await waitForElementToBeRemoved(ui.loadingIndicator.query());
|
||||
await waitForElementToBeRemoved(ui.loadingGroupIndicator.query(), { container: ui.inputs.group.get() });
|
||||
await waitForElementToBeRemoved(within(ui.inputs.group.get()).getByTestId('Spinner'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(ui.inputs.name.get()).toHaveValue('First Grafana Rule (copy)');
|
||||
|
@ -244,7 +244,6 @@ export const AlertRuleForm = ({ existing, prefill, id }: Props) => {
|
||||
<>
|
||||
{type === RuleFormType.grafana ? (
|
||||
<GrafanaEvaluationBehavior
|
||||
initialFolder={defaultValues.folder}
|
||||
evaluateEvery={evaluateEvery}
|
||||
setEvaluateEvery={setEvaluateEvery}
|
||||
existing={Boolean(existing)}
|
||||
|
@ -1,18 +1,18 @@
|
||||
import { css } from '@emotion/css';
|
||||
import { debounce } from 'lodash';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { debounce, take, uniqueId } from 'lodash';
|
||||
import React, { useCallback, useEffect, useMemo } from 'react';
|
||||
import { useFormContext } from 'react-hook-form';
|
||||
|
||||
import { GrafanaTheme2, SelectableValue } from '@grafana/data';
|
||||
import { Stack } from '@grafana/experimental';
|
||||
import { AsyncSelect, Badge, Field, InputControl, Label, LoadingPlaceholder, useStyles2 } from '@grafana/ui';
|
||||
import { AsyncSelect, Badge, Field, InputControl, Label, useStyles2 } from '@grafana/ui';
|
||||
import { contextSrv } from 'app/core/core';
|
||||
import { AccessControlAction, useDispatch } from 'app/types';
|
||||
import { CombinedRuleGroup } from 'app/types/unified-alerting';
|
||||
|
||||
import { useCombinedRuleNamespaces } from '../../hooks/useCombinedRuleNamespaces';
|
||||
import { useUnifiedAlertingSelector } from '../../hooks/useUnifiedAlertingSelector';
|
||||
import { fetchRulerRulesIfNotFetchedYet } from '../../state/actions';
|
||||
import { fetchRulerRulesAction } from '../../state/actions';
|
||||
import { RuleFormValues } from '../../types/rule-form';
|
||||
import { GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource';
|
||||
import { MINUTE } from '../../utils/rule-form';
|
||||
@ -22,13 +22,17 @@ import { InfoIcon } from '../InfoIcon';
|
||||
import { Folder, RuleFolderPicker } from './RuleFolderPicker';
|
||||
import { checkForPathSeparator } from './util';
|
||||
|
||||
export const SLICE_GROUP_RESULTS_TO = 1000;
|
||||
|
||||
interface FolderAndGroupProps {
|
||||
initialFolder: Folder | null;
|
||||
}
|
||||
export const MAX_GROUP_RESULTS = 1000;
|
||||
|
||||
export const useGetGroupOptionsFromFolder = (folderTitle: string) => {
|
||||
const dispatch = useDispatch();
|
||||
|
||||
// fetch the ruler rules from the database so we can figure out what other "groups" are already defined
|
||||
// for our folders
|
||||
useEffect(() => {
|
||||
dispatch(fetchRulerRulesAction({ rulesSourceName: GRAFANA_RULES_SOURCE_NAME }));
|
||||
}, [dispatch]);
|
||||
|
||||
const rulerRuleRequests = useUnifiedAlertingSelector((state) => state.rulerRules);
|
||||
const groupfoldersForGrafana = rulerRuleRequests[GRAFANA_RULES_SOURCE_NAME];
|
||||
|
||||
@ -58,56 +62,33 @@ const sortByLabel = (a: SelectableValue<string>, b: SelectableValue<string>) =>
|
||||
return a.label?.localeCompare(b.label ?? '') || 0;
|
||||
};
|
||||
|
||||
export function FolderAndGroup({ initialFolder }: FolderAndGroupProps) {
|
||||
const findGroupMatchingLabel = (group: SelectableValue<string>, query: string) => {
|
||||
return group.label?.toLowerCase().includes(query.toLowerCase());
|
||||
};
|
||||
|
||||
export function FolderAndGroup() {
|
||||
const {
|
||||
formState: { errors },
|
||||
watch,
|
||||
setValue,
|
||||
control,
|
||||
} = useFormContext<RuleFormValues>();
|
||||
|
||||
const styles = useStyles2(getStyles);
|
||||
const dispatch = useDispatch();
|
||||
|
||||
const folder = watch('folder');
|
||||
const group = watch('group');
|
||||
const [selectedGroup, setSelectedGroup] = useState<SelectableValue<string>>({ label: group, title: group });
|
||||
const initialRender = useRef(true);
|
||||
|
||||
const { groupOptions, loading } = useGetGroupOptionsFromFolder(folder?.title ?? '');
|
||||
|
||||
useEffect(() => setSelectedGroup({ label: group, title: group }), [group, setSelectedGroup]);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetchRulerRulesIfNotFetchedYet(GRAFANA_RULES_SOURCE_NAME));
|
||||
}, [dispatch]);
|
||||
|
||||
const resetGroup = useCallback(() => {
|
||||
if (group && !initialRender.current && folder?.title) {
|
||||
setSelectedGroup({ label: '', title: '' });
|
||||
}
|
||||
initialRender.current = false;
|
||||
}, [group, folder?.title]);
|
||||
|
||||
const groupIsInGroupOptions = useCallback(
|
||||
(group_: string) => {
|
||||
return groupOptions.includes((groupInList: SelectableValue<string>) => groupInList.label === group_);
|
||||
},
|
||||
[groupOptions]
|
||||
);
|
||||
const sliceResults = (list: Array<SelectableValue<string>>) => list.slice(0, SLICE_GROUP_RESULTS_TO);
|
||||
setValue('group', '');
|
||||
}, [setValue]);
|
||||
|
||||
const getOptions = useCallback(
|
||||
async (query: string) => {
|
||||
const results = query
|
||||
? sliceResults(
|
||||
groupOptions.filter((el) => {
|
||||
const label = el.label ?? '';
|
||||
return label.toLowerCase().includes(query.toLowerCase());
|
||||
})
|
||||
)
|
||||
: sliceResults(groupOptions);
|
||||
|
||||
return results;
|
||||
const results = query ? groupOptions.filter((group) => findGroupMatchingLabel(group, query)) : groupOptions;
|
||||
return take(results, MAX_GROUP_RESULTS);
|
||||
},
|
||||
[groupOptions]
|
||||
);
|
||||
@ -116,6 +97,8 @@ export function FolderAndGroup({ initialFolder }: FolderAndGroupProps) {
|
||||
return debounce(getOptions, 300, { leading: true });
|
||||
}, [getOptions]);
|
||||
|
||||
const defaultGroupValue = group ? { value: group, label: group } : undefined;
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<Field
|
||||
@ -145,9 +128,7 @@ export function FolderAndGroup({ initialFolder }: FolderAndGroupProps) {
|
||||
enableReset={true}
|
||||
onChange={({ title, uid }) => {
|
||||
field.onChange({ title, uid });
|
||||
if (!groupIsInGroupOptions(selectedGroup.value ?? '')) {
|
||||
resetGroup();
|
||||
}
|
||||
resetGroup();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@ -170,43 +151,40 @@ export function FolderAndGroup({ initialFolder }: FolderAndGroupProps) {
|
||||
invalid={!!errors.group?.message}
|
||||
>
|
||||
<InputControl
|
||||
render={({ field: { ref, ...field }, fieldState }) =>
|
||||
loading ? (
|
||||
<LoadingPlaceholder text="Loading..." />
|
||||
) : (
|
||||
<AsyncSelect
|
||||
disabled={!folder}
|
||||
inputId="group"
|
||||
key={`my_unique_select_key__${selectedGroup?.title ?? ''}`}
|
||||
{...field}
|
||||
invalid={Boolean(folder) && !selectedGroup.title && Boolean(fieldState.error)}
|
||||
loadOptions={debouncedSearch}
|
||||
loadingMessage={'Loading groups...'}
|
||||
defaultOptions={groupOptions}
|
||||
defaultValue={selectedGroup}
|
||||
getOptionLabel={(option: SelectableValue<string>) => (
|
||||
<div>
|
||||
<span>{option.label}</span>
|
||||
{/* making the assumption here that it's provisioned when it's disabled, should probably change this */}
|
||||
{option.isDisabled && (
|
||||
<>
|
||||
{' '}
|
||||
<Badge color="purple" text="Provisioned" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
placeholder={'Evaluation group name'}
|
||||
onChange={(value) => {
|
||||
field.onChange(value.label ?? '');
|
||||
}}
|
||||
value={selectedGroup}
|
||||
allowCustomValue
|
||||
formatCreateLabel={(_) => '+ Add new '}
|
||||
noOptionsMessage="Start typing to create evaluation group"
|
||||
/>
|
||||
)
|
||||
}
|
||||
render={({ field: { ref, ...field }, fieldState }) => (
|
||||
<AsyncSelect
|
||||
disabled={!folder || loading}
|
||||
inputId="group"
|
||||
key={uniqueId()}
|
||||
{...field}
|
||||
onChange={(group) => {
|
||||
field.onChange(group.label ?? '');
|
||||
}}
|
||||
isLoading={loading}
|
||||
invalid={Boolean(folder) && !group && Boolean(fieldState.error)}
|
||||
loadOptions={debouncedSearch}
|
||||
cacheOptions
|
||||
loadingMessage={'Loading groups...'}
|
||||
defaultValue={defaultGroupValue}
|
||||
defaultOptions={groupOptions}
|
||||
getOptionLabel={(option: SelectableValue<string>) => (
|
||||
<div>
|
||||
<span>{option.label}</span>
|
||||
{/* making the assumption here that it's provisioned when it's disabled, should probably change this */}
|
||||
{option.isDisabled && (
|
||||
<>
|
||||
{' '}
|
||||
<Badge color="purple" text="Provisioned" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
placeholder={'Evaluation group name'}
|
||||
allowCustomValue
|
||||
formatCreateLabel={(_) => '+ Add new '}
|
||||
noOptionsMessage="Start typing to create evaluation group"
|
||||
/>
|
||||
)}
|
||||
name="group"
|
||||
control={control}
|
||||
rules={{
|
||||
|
@ -21,7 +21,6 @@ import { EditCloudGroupModal, evaluateEveryValidationOptions } from '../rules/Ed
|
||||
import { FolderAndGroup, useGetGroupOptionsFromFolder } from './FolderAndGroup';
|
||||
import { GrafanaAlertStatePicker } from './GrafanaAlertStatePicker';
|
||||
import { RuleEditorSection } from './RuleEditorSection';
|
||||
import { Folder } from './RuleFolderPicker';
|
||||
|
||||
export const MIN_TIME_RANGE_STEP_S = 10; // 10 seconds
|
||||
|
||||
@ -115,11 +114,9 @@ export const EvaluateEveryNewGroup = ({ rules }: { rules: RulerRulesConfigDTO |
|
||||
};
|
||||
|
||||
function FolderGroupAndEvaluationInterval({
|
||||
initialFolder,
|
||||
evaluateEvery,
|
||||
setEvaluateEvery,
|
||||
}: {
|
||||
initialFolder: Folder | null;
|
||||
evaluateEvery: string;
|
||||
setEvaluateEvery: (value: string) => void;
|
||||
}) {
|
||||
@ -167,7 +164,7 @@ function FolderGroupAndEvaluationInterval({
|
||||
|
||||
return (
|
||||
<div>
|
||||
<FolderAndGroup initialFolder={initialFolder} />
|
||||
<FolderAndGroup />
|
||||
{folderName && isEditingGroup && (
|
||||
<EditCloudGroupModal
|
||||
namespace={existingNamespace ?? emptyNamespace}
|
||||
@ -249,12 +246,10 @@ function ForInput({ evaluateEvery }: { evaluateEvery: string }) {
|
||||
}
|
||||
|
||||
export function GrafanaEvaluationBehavior({
|
||||
initialFolder,
|
||||
evaluateEvery,
|
||||
setEvaluateEvery,
|
||||
existing,
|
||||
}: {
|
||||
initialFolder: Folder | null;
|
||||
evaluateEvery: string;
|
||||
setEvaluateEvery: (value: string) => void;
|
||||
existing: boolean;
|
||||
@ -270,11 +265,7 @@ export function GrafanaEvaluationBehavior({
|
||||
// TODO remove "and alert condition" for recording rules
|
||||
<RuleEditorSection stepNo={3} title="Alert evaluation behavior">
|
||||
<Stack direction="column" justify-content="flex-start" align-items="flex-start">
|
||||
<FolderGroupAndEvaluationInterval
|
||||
initialFolder={initialFolder}
|
||||
setEvaluateEvery={setEvaluateEvery}
|
||||
evaluateEvery={evaluateEvery}
|
||||
/>
|
||||
<FolderGroupAndEvaluationInterval setEvaluateEvery={setEvaluateEvery} evaluateEvery={evaluateEvery} />
|
||||
<ForInput evaluateEvery={evaluateEvery} />
|
||||
|
||||
{existing && (
|
||||
|
Loading…
Reference in New Issue
Block a user