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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
import {
// eslint-disable-next-line no-restricted-imports
createContext,
useCallback,
// eslint-disable-next-line no-restricted-imports
useContext,
useEffect,
useMemo,
useReducer,
useRef,
useState,
} from 'react';
import { useAppLocation } from 'lib/router/useAppLocation';
import {
useCreateRule,
useTestRule,
useUpdateRuleByID,
} from 'api/generated/services/rules';
import { QueryParams } from 'constants/query';
import { AlertDetectionTypes } from 'container/FormAlertRules';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import {
INITIAL_ANOMALY_THRESHOLD,
INITIAL_CREATE_ALERT_STATE,
INITIAL_EVALUATION_WINDOW_STATE,
} from './constants';
import {
EvaluationWindowPreset,
pickAlertPrefillParams,
resolveUrlAlertPrefill,
} from './resolveUrlAlertPrefill';
import {
AdvancedOptionsAction,
AlertThresholdAction,
CreateAlertAction,
CreateAlertSlice,
EvaluationWindowAction,
ICreateAlertContextProps,
ICreateAlertProviderProps,
NotificationSettingsAction,
} from './types';
import {
buildInitialAlertDef,
createAlertReducer,
getInitialAlertTypeFromURL,
} from './utils';
const CreateAlertContext = createContext<ICreateAlertContextProps | null>(null);
// Hook exposing context state for CreateAlert
export const useCreateAlertState = (): ICreateAlertContextProps => {
const context = useContext(CreateAlertContext);
if (!context) {
throw new Error(
'useCreateAlertState must be used within CreateAlertProvider',
);
}
return context;
};
export function CreateAlertProvider(
props: ICreateAlertProviderProps,
): JSX.Element {
const { children, initialAlertState, isEditMode, ruleId, initialAlertType } =
props;
const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();
const [createAlertState, setCreateAlertState] = useReducer(
createAlertReducer,
{
...INITIAL_CREATE_ALERT_STATE,
basic: {
...INITIAL_CREATE_ALERT_STATE.basic,
yAxisUnit: currentQuery.unit,
},
},
);
const setAlertState = useCallback(
(action: CreateAlertAction) => {
setCreateAlertState({
slice: CreateAlertSlice.BASIC,
action,
});
},
[setCreateAlertState],
);
const setThresholdState = useCallback(
(action: AlertThresholdAction) => {
setCreateAlertState({
slice: CreateAlertSlice.THRESHOLD,
action,
});
},
[setCreateAlertState],
);
const setEvaluationWindow = useCallback(
(action: EvaluationWindowAction) => {
setCreateAlertState({
slice: CreateAlertSlice.EVALUATION_WINDOW,
action,
});
},
[setCreateAlertState],
);
const setAdvancedOptions = useCallback(
(action: AdvancedOptionsAction) => {
setCreateAlertState({
slice: CreateAlertSlice.ADVANCED_OPTIONS,
action,
});
},
[setCreateAlertState],
);
const setNotificationSettings = useCallback(
(action: NotificationSettingsAction) => {
setCreateAlertState({
slice: CreateAlertSlice.NOTIFICATION_SETTINGS,
action,
});
},
[setCreateAlertState],
);
const location = useAppLocation();
const queryParams = new URLSearchParams(location.search);
const ruleNameFromURL = queryParams.get(QueryParams.ruleName);
const yAxisUnitFromURL = queryParams.get(QueryParams.yAxisUnit);
// Prefill declared in the URL; applied verbatim, agnostic of the producer.
const prefillParams = pickAlertPrefillParams(location.search);
const urlPrefill = useMemo(
() => resolveUrlAlertPrefill(new URLSearchParams(prefillParams)),
[prefillParams],
);
const [alertType, setAlertType] = useState<AlertTypes>(() => {
if (isEditMode) {
return initialAlertType;
}
return getInitialAlertTypeFromURL(queryParams, currentQuery);
});
const resetThresholdState = useCallback((type: AlertTypes): void => {
setCreateAlertState({
slice: CreateAlertSlice.THRESHOLD,
action: {
type: 'RESET',
},
});
if (type === AlertTypes.ANOMALY_BASED_ALERT) {
setCreateAlertState({
slice: CreateAlertSlice.THRESHOLD,
action: {
type: 'SET_THRESHOLDS',
payload: [INITIAL_ANOMALY_THRESHOLD],
},
});
}
}, []);
const handleAlertTypeChange = useCallback(
(value: AlertTypes): void => {
// Threshold and anomaly alerts share the metric query, so switching keeps it.
const metricAlertTypes = [
AlertTypes.METRICS_BASED_ALERT,
AlertTypes.ANOMALY_BASED_ALERT,
];
const keepsQuery =
value !== alertType &&
metricAlertTypes.includes(value) &&
metricAlertTypes.includes(alertType);
const queryToRedirect = keepsQuery
? currentQuery
: mapQueryDataFromApi(buildInitialAlertDef(value).condition.compositeQuery);
redirectWithQueryBuilderData(
queryToRedirect,
{
[QueryParams.alertType]: value,
[QueryParams.ruleType]:
value === AlertTypes.ANOMALY_BASED_ALERT
? AlertDetectionTypes.ANOMALY_DETECTION_ALERT
: AlertDetectionTypes.THRESHOLD_ALERT,
},
undefined,
true,
);
setAlertType(value);
if (isEditMode && keepsQuery) {
resetThresholdState(value);
}
if (
value === AlertTypes.ANOMALY_BASED_ALERT &&
createAlertState.evaluationWindow.windowType !== 'rolling'
) {
setEvaluationWindow({
type: 'SET_INITIAL_STATE',
payload: INITIAL_EVALUATION_WINDOW_STATE,
});
}
},
[
alertType,
createAlertState.evaluationWindow.windowType,
currentQuery,
isEditMode,
redirectWithQueryBuilderData,
resetThresholdState,
setEvaluationWindow,
],
);
const ruleNameAppliedRef = useRef(false);
const yAxisUnitAppliedRef = useRef(false);
useEffect(() => {
// URL-declared prefill is a create-flow concern. In edit mode the alert
// state is owned by SET_INITIAL_STATE; running the RESET below would wipe
// the loaded thresholds each time the query builder rewrites location.search
// (which yields a fresh urlPrefill object and re-triggers this effect).
if (isEditMode) {
return;
}
resetThresholdState(alertType);
if (urlPrefill.thresholds) {
setCreateAlertState({
slice: CreateAlertSlice.THRESHOLD,
action: {
type: 'SET_THRESHOLDS',
payload: urlPrefill.thresholds,
},
});
}
if (urlPrefill.matchType) {
setCreateAlertState({
slice: CreateAlertSlice.THRESHOLD,
action: {
type: 'SET_MATCH_TYPE',
payload: urlPrefill.matchType,
},
});
}
if (urlPrefill.operator) {
setCreateAlertState({
slice: CreateAlertSlice.THRESHOLD,
action: {
type: 'SET_OPERATOR',
payload: urlPrefill.operator,
},
});
}
if (
urlPrefill.evaluationWindowPreset === EvaluationWindowPreset.METER &&
alertType !== AlertTypes.ANOMALY_BASED_ALERT
) {
setCreateAlertState({
slice: CreateAlertSlice.EVALUATION_WINDOW,
action: {
type: 'SET_INITIAL_STATE_FOR_METER',
},
});
}
if (ruleNameFromURL && !ruleNameAppliedRef.current) {
ruleNameAppliedRef.current = true;
setCreateAlertState({
slice: CreateAlertSlice.BASIC,
action: {
type: 'SET_ALERT_NAME',
payload: ruleNameFromURL,
},
});
}
if (yAxisUnitFromURL && !yAxisUnitAppliedRef.current) {
yAxisUnitAppliedRef.current = true;
setCreateAlertState({
slice: CreateAlertSlice.BASIC,
action: {
type: 'SET_Y_AXIS_UNIT',
payload: yAxisUnitFromURL,
},
});
}
}, [
alertType,
urlPrefill,
ruleNameFromURL,
yAxisUnitFromURL,
isEditMode,
resetThresholdState,
]);
useEffect(() => {
if (isEditMode && initialAlertState) {
setCreateAlertState({
type: 'SET_INITIAL_STATE',
payload: initialAlertState,
});
}
}, [initialAlertState, isEditMode]);
const discardAlertRule = useCallback(() => {
setCreateAlertState({
type: 'RESET',
});
handleAlertTypeChange(AlertTypes.METRICS_BASED_ALERT);
}, [handleAlertTypeChange]);
const { mutate: createAlertRule, isLoading: isCreatingAlertRule } =
useCreateRule();
const { mutate: testAlertRule, isLoading: isTestingAlertRule } = useTestRule();
const { mutate: updateAlertRule, isLoading: isUpdatingAlertRule } =
useUpdateRuleByID();
const contextValue: ICreateAlertContextProps = useMemo(
() => ({
alertState: createAlertState.basic,
setAlertState,
alertType,
setAlertType: handleAlertTypeChange,
thresholdState: createAlertState.threshold,
setThresholdState,
evaluationWindow: createAlertState.evaluationWindow,
setEvaluationWindow,
advancedOptions: createAlertState.advancedOptions,
setAdvancedOptions,
notificationSettings: createAlertState.notificationSettings,
setNotificationSettings,
discardAlertRule,
createAlertRule,
isCreatingAlertRule,
testAlertRule,
isTestingAlertRule,
updateAlertRule,
isUpdatingAlertRule,
isEditMode: isEditMode || false,
ruleId: ruleId || '',
}),
[
createAlertState,
setAlertState,
setThresholdState,
setEvaluationWindow,
setAdvancedOptions,
setNotificationSettings,
alertType,
handleAlertTypeChange,
discardAlertRule,
createAlertRule,
isCreatingAlertRule,
testAlertRule,
isTestingAlertRule,
updateAlertRule,
isUpdatingAlertRule,
isEditMode,
ruleId,
],
);
return (
<CreateAlertContext.Provider value={contextValue}>
{children}
</CreateAlertContext.Provider>
);
}