Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

chore: pre-populate the alert condition based on the selected reduce to and thresholds (#8352)

Amlan Kumar Nandy78df27a1400a
diff --git a/frontend/src/constants/query.ts b/frontend/src/constants/query.ts
index 9460602aec..656cdb0040 100644
--- a/frontend/src/constants/query.ts
+++ b/frontend/src/constants/query.ts
@@ -47,4 +47,5 @@ export enum QueryParams {
destination = 'destination',
kindString = 'kindString',
tab = 'tab',
+ thresholds = 'thresholds',
}
diff --git a/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx b/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx
index 1dc088d3d8..f7a1b1fb0f 100644
--- a/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx
+++ b/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx
@@ -1,4 +1,5 @@
import ROUTES from 'constants/routes';
+import * as usePrefillAlertConditions from 'container/FormAlertRules/usePrefillAlertConditions';
import CreateAlertPage from 'pages/CreateAlert';
import { MemoryRouter, Route } from 'react-router-dom';
import { act, fireEvent, render } from 'tests/test-utils';
@@ -33,6 +34,15 @@ jest.mock('hooks/useSafeNavigate', () => ({
}),
}));
+jest
+ .spyOn(usePrefillAlertConditions, 'usePrefillAlertConditions')
+ .mockReturnValue({
+ matchType: '3',
+ op: '1',
+ target: 100,
+ targetUnit: 'rpm',
+ });
+
let mockWindowOpen: jest.Mock;
window.ResizeObserver =
diff --git a/frontend/src/container/CreateAlertRule/AnomalyAlertDocumentationRedirection.test.tsx b/frontend/src/container/CreateAlertRule/AnomalyAlertDocumentationRedirection.test.tsx
index 498595d183..783f6f6585 100644
--- a/frontend/src/container/CreateAlertRule/AnomalyAlertDocumentationRedirection.test.tsx
+++ b/frontend/src/container/CreateAlertRule/AnomalyAlertDocumentationRedirection.test.tsx
@@ -1,4 +1,5 @@
import ROUTES from 'constants/routes';
+import * as usePrefillAlertConditions from 'container/FormAlertRules/usePrefillAlertConditions';
import CreateAlertPage from 'pages/CreateAlert';
import { MemoryRouter, Route } from 'react-router-dom';
import { act, fireEvent, render } from 'tests/test-utils';
@@ -41,6 +42,15 @@ jest.mock('hooks/useSafeNavigate', () => ({
safeNavigate: jest.fn(),
}),
}));
+jest
+ .spyOn(usePrefillAlertConditions, 'usePrefillAlertConditions')
+ .mockReturnValue({
+ matchType: '3',
+ op: '1',
+ target: 100,
+ targetUnit: 'rpm',
+ });
+
describe('Anomaly Alert Documentation Redirection', () => {
let mockWindowOpen: jest.Mock;
diff --git a/frontend/src/container/CreateAlertRule/index.tsx b/frontend/src/container/CreateAlertRule/index.tsx
index e17f6fe3bb..456aef8311 100644
--- a/frontend/src/container/CreateAlertRule/index.tsx
+++ b/frontend/src/container/CreateAlertRule/index.tsx
@@ -3,6 +3,7 @@ import logEvent from 'api/common/logEvent';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { QueryParams } from 'constants/query';
import FormAlertRules, { AlertDetectionTypes } from 'container/FormAlertRules';
+import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import history from 'lib/history';
import { useEffect, useState } from 'react';
@@ -32,6 +33,12 @@ function CreateRules(): JSX.Element {
? AlertTypes.ANOMALY_BASED_ALERT
: queryParams.get(QueryParams.alertType);
+ const { thresholds } = (location.state as {
+ thresholds: ThresholdProps[];
+ }) || {
+ thresholds: null,
+ };
+
const compositeQuery = useGetCompositeQueryParam();
function getAlertTypeFromDataSource(): AlertTypes | null {
if (!compositeQuery) {
@@ -96,7 +103,9 @@ function CreateRules(): JSX.Element {
}
const generatedUrl = `${location.pathname}?${queryParams.toString()}`;
- history.replace(generatedUrl);
+ history.replace(generatedUrl, {
+ thresholds,
+ });
};
useEffect(() => {
diff --git a/frontend/src/container/FormAlertRules/RuleOptions.tsx b/frontend/src/container/FormAlertRules/RuleOptions.tsx
index a30321fcfd..19f47220f1 100644
--- a/frontend/src/container/FormAlertRules/RuleOptions.tsx
+++ b/frontend/src/container/FormAlertRules/RuleOptions.tsx
@@ -390,7 +390,7 @@ function RuleOptions({
<Space direction="vertical" size="large">
{ruleType !== AlertDetectionTypes.ANOMALY_DETECTION_ALERT && (
<Space direction="horizontal" align="center">
- <Form.Item noStyle name={['condition', 'target']}>
+ <Form.Item noStyle>
<InputNumber
addonBefore={t('field_threshold')}
value={alertDef?.condition?.target}
diff --git a/frontend/src/container/FormAlertRules/__tests__/usePrefillAlertConditions.test.ts b/frontend/src/container/FormAlertRules/__tests__/usePrefillAlertConditions.test.ts
new file mode 100644
index 0000000000..96b56d9d3f
--- /dev/null
+++ b/frontend/src/container/FormAlertRules/__tests__/usePrefillAlertConditions.test.ts
@@ -0,0 +1,125 @@
+import { renderHook } from '@testing-library/react';
+
+import { usePrefillAlertConditions } from '../usePrefillAlertConditions';
+
+const TEST_MAPPINGS = {
+ op: {
+ '>': '1',
+ '<': '2',
+ '=': '3',
+ },
+ matchType: {
+ avg: '3',
+ sum: '4',
+ },
+};
+
+jest.mock('react-router-dom-v5-compat', () => {
+ const mockThreshold1 = {
+ index: '0d11f426-a02e-48da-867c-b79c6ef1ff06',
+ isEditEnabled: false,
+ keyIndex: 1,
+ selectedGraph: 'graph',
+ thresholdColor: 'Orange',
+ thresholdFormat: 'Text',
+ thresholdLabel: 'Caution',
+ thresholdOperator: '>',
+ thresholdTableOptions: 'A',
+ thresholdUnit: 'rpm',
+ thresholdValue: 800,
+ };
+ const mockThreshold2 = {
+ index: 'edbe8ef2-fa54-4cb9-b343-7afe883bb714',
+ isEditEnabled: false,
+ keyIndex: 0,
+ selectedGraph: 'graph',
+ thresholdColor: 'Red',
+ thresholdFormat: 'Text',
+ thresholdLabel: 'Danger',
+ thresholdOperator: '<',
+ thresholdTableOptions: 'A',
+ thresholdUnit: 'rpm',
+ thresholdValue: 900,
+ };
+ return {
+ ...jest.requireActual('react-router-dom-v5-compat'),
+ useLocation: jest.fn().mockReturnValue({
+ state: {
+ thresholds: [mockThreshold1, mockThreshold2],
+ },
+ }),
+ };
+});
+
+const mockStagedQuery = {
+ builder: {
+ queryData: [
+ {
+ reduceTo: 'avg',
+ },
+ ],
+ },
+};
+
+describe('usePrefillAlertConditions', () => {
+ it('returns the correct matchType for a single query', () => {
+ const { result } = renderHook(() =>
+ usePrefillAlertConditions(mockStagedQuery as any),
+ );
+ expect(result.current.matchType).toBe(TEST_MAPPINGS.matchType.avg);
+ });
+
+ it('returns null matchType for a single query with unsupported time aggregation', () => {
+ const { result } = renderHook(() =>
+ usePrefillAlertConditions({
+ builder: { queryData: [{ reduceTo: 'p90' }] },
+ } as any),
+ );
+ expect(result.current.matchType).toBe(null);
+ });
+
+ it('returns the correct matchType for multiple queries with same time aggregation', () => {
+ const { result } = renderHook(() =>
+ usePrefillAlertConditions({
+ builder: {
+ queryData: [
+ {
+ reduceTo: 'avg',
+ },
+ {
+ reduceTo: 'avg',
+ },
+ ],
+ },
+ } as any),
+ );
+ expect(result.current.matchType).toBe(TEST_MAPPINGS.matchType.avg);
+ });
+
+ it('returns null matchType for multiple queries with different time aggregation', () => {
+ const { result } = renderHook(() =>
+ usePrefillAlertConditions({
+ builder: {
+ queryData: [
+ {
+ reduceTo: 'avg',
+ },
+ {
+ reduceTo: 'sum',
+ },
+ ],
+ },
+ } as any),
+ );
+ expect(result.current.matchType).toBe(null);
+ });
+
+ it('returns the correct op, target, targetUnit from the higher priority threshold for multiple thresholds', () => {
+ const { result } = renderHook(() =>
+ usePrefillAlertConditions(mockStagedQuery as any),
+ );
+ expect(result.current.op).toBe(TEST_MAPPINGS.op['<']);
+ expect(result.current.target).toBe(900);
+ expect(result.current.targetUnit).toBe('rpm');
+ });
+});
diff --git a/frontend/src/container/FormAlertRules/index.tsx b/frontend/src/container/FormAlertRules/index.tsx
index 6a56beb058..736967d23f 100644
--- a/frontend/src/container/FormAlertRules/index.tsx
+++ b/frontend/src/container/FormAlertRules/index.tsx
@@ -57,6 +57,7 @@ import {
StepContainer,
StepHeading,
} from './styles';
+import { usePrefillAlertConditions } from './usePrefillAlertConditions';
import { getSelectedQueryOptions } from './utils';
export enum AlertDetectionTypes {
@@ -113,6 +114,9 @@ function FormAlertRules({
handleSetConfig,
redirectWithQueryBuilderData,
} = useQueryBuilder();
+ const { matchType, op, target, targetUnit } = usePrefillAlertConditions(
+ stagedQuery,
+ );
useEffect(() => {
handleSetConfig(panelType || PANEL_TYPES.TIME_SERIES, dataSource);
@@ -266,6 +270,13 @@ function FormAlertRules({
...initialValue,
broadcastToAll: !broadcastToSpecificChannels,
ruleType,
+ condition: {
+ ...initialValue.condition,
+ matchType: matchType || initialValue.condition.matchType,
+ op: op || initialValue.condition.op,
+ target: target || initialValue.condition.target,
+ targetUnit: targetUnit || initialValue.condition.targetUnit,
+ },
});
setDetectionMethod(ruleType);
diff --git a/frontend/src/container/FormAlertRules/usePrefillAlertConditions.ts b/frontend/src/container/FormAlertRules/usePrefillAlertConditions.ts
new file mode 100644
index 0000000000..0827aa4025
--- /dev/null
+++ b/frontend/src/container/FormAlertRules/usePrefillAlertConditions.ts
@@ -0,0 +1,87 @@
+import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';
+import { useMemo } from 'react';
+import { useLocation } from 'react-router-dom-v5-compat';
+import { Query } from 'types/api/queryBuilder/queryBuilderData';
+
+const THRESHOLD_COLORS_SORTING_ORDER = ['Red', 'Orange', 'Green', 'Blue'];
+
+export const usePrefillAlertConditions = (
+ stagedQuery: Query | null,
+): {
+ matchType: string | null;
+ op: string | null;
+ target: number | undefined;
+ targetUnit: string | undefined;
+} => {
+ const location = useLocation();
+
+ // Extract and set match type
+ const reduceTo = useMemo(() => {
+ if (!stagedQuery) return null;
+ const isSameTimeAggregation = stagedQuery.builder.queryData.every(
+ (queryData) =>
+ queryData.reduceTo === stagedQuery.builder.queryData[0].reduceTo,
+ );
+ return isSameTimeAggregation
+ ? stagedQuery.builder.queryData[0].reduceTo
+ : null;
+ }, [stagedQuery]);
+
+ const matchType = useMemo(() => {
+ switch (reduceTo) {
+ case 'avg':
+ return '3';
+ case 'sum':
+ return '4';
+ default:
+ return null;
+ }
+ }, [reduceTo]);
+
+ // Extract and set threshold operator, value and unit
+ const threshold = useMemo(() => {
+ const { thresholds } = (location.state as {
+ thresholds: ThresholdProps[];
+ }) || {
+ thresholds: null,
+ };
+ if (!thresholds || thresholds.length === 0) return null;
+ const sortedThresholds = thresholds.sort((a, b) => {
+ const aIndex = THRESHOLD_COLORS_SORTING_ORDER.indexOf(
+ a.thresholdColor || '',
+ );
+ const bIndex = THRESHOLD_COLORS_SORTING_ORDER.indexOf(
+ b.thresholdColor || '',
+ );
+ return aIndex - bIndex;
+ });
+ return sortedThresholds[0];
+ }, [location.state]);
+
+ const thresholdOperator = useMemo(() => {
+ const op = threshold?.thresholdOperator;
+ switch (op) {
+ case '>':
+ case '>=':
+ return '1';
+ case '<':
+ case '<=':
+ return '2';
+ case '=':
+ return '3';
+ default:
+ return null;
+ }
+ }, [threshold]);
+
+ const thresholdUnit = useMemo(() => threshold?.thresholdUnit, [threshold]);
+
+ const thresholdValue = useMemo(() => threshold?.thresholdValue, [threshold]);
+
+ return {
+ matchType,
+ op: thresholdOperator,
+ target: thresholdValue,
+ targetUnit: thresholdUnit,
+ };
+};
diff --git a/frontend/src/container/NewWidget/RightContainer/index.tsx b/frontend/src/container/NewWidget/RightContainer/index.tsx
index f0e518ab06..8e63faa020 100644
--- a/frontend/src/container/NewWidget/RightContainer/index.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/index.tsx
@@ -130,7 +130,11 @@ function RightContainer({
const selectedGraphType =
GraphTypes.find((e) => e.name === selectedGraph)?.display || '';
- const onCreateAlertsHandler = useCreateAlerts(selectedWidget, 'panelView');
+ const onCreateAlertsHandler = useCreateAlerts(
+ selectedWidget,
+ 'panelView',
+ thresholds,
+ );
const allowThreshold = panelTypeVsThreshold[selectedGraph];
const allowSoftMinMax = panelTypeVsSoftMinMax[selectedGraph];
diff --git a/frontend/src/hooks/queryBuilder/useCreateAlerts.tsx b/frontend/src/hooks/queryBuilder/useCreateAlerts.tsx
index d85586ddfa..e4a36ebcbe 100644
--- a/frontend/src/hooks/queryBuilder/useCreateAlerts.tsx
+++ b/frontend/src/hooks/queryBuilder/useCreateAlerts.tsx
@@ -5,6 +5,7 @@ import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { MenuItemKeys } from 'container/GridCardLayout/WidgetHeader/contants';
+import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';
import { useNotifications } from 'hooks/useNotifications';
import { getDashboardVariables } from 'lib/dashbaordVariables/getDashboardVariables';
import { prepareQueryRangePayload } from 'lib/dashboard/prepareQueryRangePayload';
@@ -19,7 +20,11 @@ import { Widgets } from 'types/api/dashboard/getAll';
import { GlobalReducer } from 'types/reducer/globalTime';
import { getGraphType } from 'utils/getGraphType';
-const useCreateAlerts = (widget?: Widgets, caller?: string): VoidFunction => {
+const useCreateAlerts = (
+ widget?: Widgets,
+ caller?: string,
+ thresholds?: ThresholdProps[],
+): VoidFunction => {
const queryRangeMutation = useMutation(getQueryRangeFormat);
const { selectedTime: globalSelectedInterval } = useSelector<
@@ -66,13 +71,17 @@ const useCreateAlerts = (widget?: Widgets, caller?: string): VoidFunction => {
widget?.query,
);
- history.push(
- `${ROUTES.ALERTS_NEW}?${QueryParams.compositeQuery}=${encodeURIComponent(
- JSON.stringify(updatedQuery),
- )}&${QueryParams.panelTypes}=${widget.panelTypes}&version=${
- selectedDashboard?.data.version || DEFAULT_ENTITY_VERSION
- }`,
- );
+ const url = `${ROUTES.ALERTS_NEW}?${
+ QueryParams.compositeQuery
+ }=${encodeURIComponent(JSON.stringify(updatedQuery))}&${
+ QueryParams.panelTypes
+ }=${widget.panelTypes}&version=${
+ selectedDashboard?.data.version || DEFAULT_ENTITY_VERSION
+ }`;
+
+ history.push(url, {
+ thresholds,
+ });
},
onError: () => {
notifications.error({