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.

feat(meter): add ability to query meter data across product modules (#9142)

Yunus Mfd216fdee12f
diff --git a/frontend/src/components/QueryBuilderV2/QueryBuilderV2.styles.scss b/frontend/src/components/QueryBuilderV2/QueryBuilderV2.styles.scss
index fcfafc3688..e0195ef0fe 100644
--- a/frontend/src/components/QueryBuilderV2/QueryBuilderV2.styles.scss
+++ b/frontend/src/components/QueryBuilderV2/QueryBuilderV2.styles.scss
@@ -398,7 +398,7 @@
}
.qb-search-container {
- .metrics-select-container {
+ .metrics-container {
margin-bottom: 12px;
}
}
diff --git a/frontend/src/components/QueryBuilderV2/QueryBuilderV2.tsx b/frontend/src/components/QueryBuilderV2/QueryBuilderV2.tsx
index 7be666c270..9e2ba8ce77 100644
--- a/frontend/src/components/QueryBuilderV2/QueryBuilderV2.tsx
+++ b/frontend/src/components/QueryBuilderV2/QueryBuilderV2.tsx
@@ -22,6 +22,8 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
showOnlyWhereClause = false,
showTraceOperator = false,
version,
+ onSignalSourceChange,
+ signalSourceChangeEnabled = false,
}: QueryBuilderProps): JSX.Element {
const {
currentQuery,
@@ -175,6 +177,8 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
queryVariant={config?.queryVariant || 'dropdown'}
showOnlyWhereClause={showOnlyWhereClause}
isListViewPanel={isListViewPanel}
+ onSignalSourceChange={onSignalSourceChange || ((): void => {})}
+ signalSourceChangeEnabled={signalSourceChangeEnabled}
/>
) : (
currentQuery.builder.queryData.map((query, index) => (
@@ -193,7 +197,9 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
queryVariant={config?.queryVariant || 'dropdown'}
showOnlyWhereClause={showOnlyWhereClause}
isListViewPanel={isListViewPanel}
- signalSource={config?.signalSource || ''}
+ signalSource={query.source as 'meter' | ''}
+ onSignalSourceChange={onSignalSourceChange || ((): void => {})}
+ signalSourceChangeEnabled={signalSourceChangeEnabled}
/>
))
)}
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/MetricsSelect/MetricsSelect.styles.scss b/frontend/src/components/QueryBuilderV2/QueryV2/MetricsSelect/MetricsSelect.styles.scss
index 9038e8ce43..cfa74f8c93 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/MetricsSelect/MetricsSelect.styles.scss
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/MetricsSelect/MetricsSelect.styles.scss
@@ -1,5 +1,14 @@
-.metrics-select-container {
+.metrics-source-select-container {
margin-bottom: 8px;
+ display: flex;
+ flex-direction: row;
+ align-items: flex-start;
+ gap: 8px;
+ width: 100%;
+
+ .source-selector {
+ width: 120px;
+ }
.ant-select-selector {
width: 100%;
@@ -42,7 +51,7 @@
}
.lightMode {
- .metrics-select-container {
+ .metrics-source-select-container {
.ant-select-selector {
border: 1px solid var(--bg-vanilla-300) !important;
background: var(--bg-vanilla-100);
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/MetricsSelect/MetricsSelect.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/MetricsSelect/MetricsSelect.tsx
index 72470f0350..4a83fab1f8 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/MetricsSelect/MetricsSelect.tsx
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/MetricsSelect/MetricsSelect.tsx
@@ -1,21 +1,39 @@
import './MetricsSelect.styles.scss';
+import { Select } from 'antd';
+import {
+ initialQueriesMap,
+ initialQueryMeterWithType,
+ PANEL_TYPES,
+} from 'constants/queryBuilder';
import { AggregatorFilter } from 'container/QueryBuilder/filters';
+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
-import { memo, useCallback, useState } from 'react';
+import { memo, useCallback, useMemo, useState } from 'react';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+import { DataSource } from 'types/common/queryBuilder';
+import { SelectOption } from 'types/common/select';
+
+export const SOURCE_OPTIONS: SelectOption<string, string>[] = [
+ { value: 'metrics', label: 'Metrics' },
+ { value: 'meter', label: 'Meter' },
+];
export const MetricsSelect = memo(function MetricsSelect({
query,
index,
version,
signalSource,
+ onSignalSourceChange,
+ signalSourceChangeEnabled = false,
}: {
query: IBuilderQuery;
index: number;
version: string;
signalSource: 'meter' | '';
+ onSignalSourceChange: (value: string) => void;
+ signalSourceChangeEnabled: boolean;
}): JSX.Element {
const [attributeKeys, setAttributeKeys] = useState<BaseAutocompleteData[]>([]);
@@ -31,8 +49,67 @@ export const MetricsSelect = memo(function MetricsSelect({
},
[handleChangeAggregatorAttribute, attributeKeys],
);
+
+ const { updateAllQueriesOperators, handleSetQueryData } = useQueryBuilder();
+
+ const source = useMemo(
+ () => (signalSource === 'meter' ? 'meter' : 'metrics'),
+ [signalSource],
+ );
+
+ const defaultMeterQuery = useMemo(
+ () =>
+ updateAllQueriesOperators(
+ initialQueryMeterWithType,
+ PANEL_TYPES.BAR,
+ DataSource.METRICS,
+ 'meter' as 'meter' | '',
+ ),
+ [updateAllQueriesOperators],
+ );
+
+ const defaultMetricsQuery = useMemo(
+ () =>
+ updateAllQueriesOperators(
+ initialQueriesMap.metrics,
+ PANEL_TYPES.BAR,
+ DataSource.METRICS,
+ '',
+ ),
+ [updateAllQueriesOperators],
+ );
+
+ const handleSignalSourceChange = (value: string): void => {
+ onSignalSourceChange(value);
+ handleSetQueryData(
+ index,
+ value === 'meter'
+ ? {
+ ...defaultMeterQuery.builder.queryData[0],
+ source: 'meter',
+ queryName: query.queryName,
+ }
+ : {
+ ...defaultMetricsQuery.builder.queryData[0],
+ source: '',
+ queryName: query.queryName,
+ },
+ );
+ };
+
return (
- <div className="metrics-select-container">
+ <div className="metrics-source-select-container">
+ {signalSourceChangeEnabled && (
+ <Select
+ className="source-selector"
+ placeholder="Source"
+ options={SOURCE_OPTIONS}
+ value={source}
+ defaultValue="metrics"
+ onChange={handleSignalSourceChange}
+ />
+ )}
+
<AggregatorFilter
onChange={handleAggregatorAttributeChange}
query={query}
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QueryV2.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/QueryV2.tsx
index b628164efe..51ae0c94be 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/QueryV2.tsx
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QueryV2.tsx
@@ -33,7 +33,13 @@ export const QueryV2 = memo(function QueryV2({
showOnlyWhereClause = false,
signalSource = '',
isMultiQueryAllowed = false,
-}: QueryProps & { ref: React.RefObject<HTMLDivElement> }): JSX.Element {
+ onSignalSourceChange,
+ signalSourceChangeEnabled = false,
+}: QueryProps & {
+ ref: React.RefObject<HTMLDivElement>;
+ onSignalSourceChange: (value: string) => void;
+ signalSourceChangeEnabled: boolean;
+}): JSX.Element {
const { cloneQuery, panelType } = useQueryBuilder();
const showFunctions = query?.functions?.length > 0;
@@ -207,12 +213,14 @@ export const QueryV2 = memo(function QueryV2({
<div className="qb-elements-container">
<div className="qb-search-container">
{dataSource === DataSource.METRICS && (
- <div className="metrics-select-container">
+ <div className="metrics-container">
<MetricsSelect
query={query}
index={index}
version={ENTITY_VERSION_V5}
signalSource={signalSource as 'meter' | ''}
+ onSignalSourceChange={onSignalSourceChange}
+ signalSourceChangeEnabled={signalSourceChangeEnabled}
/>
</div>
)}
@@ -258,7 +266,7 @@ export const QueryV2 = memo(function QueryV2({
panelType={panelType}
query={query}
index={index}
- key={`metrics-aggregate-section-${query.queryName}-${query.dataSource}`}
+ key={`metrics-aggregate-section-${query.queryName}-${query.dataSource}-${signalSource}`}
version="v4"
signalSource={signalSource as 'meter' | ''}
/>
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/AlertThreshold.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/AlertThreshold.tsx
index bad143029f..6048bd943a 100644
--- a/frontend/src/container/CreateAlertV2/AlertCondition/AlertThreshold.tsx
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/AlertThreshold.tsx
@@ -11,12 +11,14 @@ import { v4 } from 'uuid';
import { useCreateAlertState } from '../context';
import {
+ INITIAL_EVALUATION_WINDOW_STATE,
INITIAL_INFO_THRESHOLD,
INITIAL_RANDOM_THRESHOLD,
INITIAL_WARNING_THRESHOLD,
THRESHOLD_MATCH_TYPE_OPTIONS,
THRESHOLD_OPERATOR_OPTIONS,
} from '../context/constants';
+import { AlertThresholdMatchType } from '../context/types';
import EvaluationSettings from '../EvaluationSettings/EvaluationSettings';
import ThresholdItem from './ThresholdItem';
import { AnomalyAndThresholdProps, UpdateThreshold } from './types';
@@ -38,12 +40,12 @@ function AlertThreshold({
alertState,
thresholdState,
setThresholdState,
+ setEvaluationWindow,
notificationSettings,
setNotificationSettings,
} = useCreateAlertState();
const { currentQuery } = useQueryBuilder();
-
const queryNames = getQueryNames(currentQuery);
useEffect(() => {
@@ -160,6 +162,54 @@ function AlertThreshold({
}),
);
+ const handleSetEvaluationDetailsForMeter = (): void => {
+ setEvaluationWindow({
+ type: 'SET_INITIAL_STATE_FOR_METER',
+ });
+
+ setThresholdState({
+ type: 'SET_MATCH_TYPE',
+ payload: AlertThresholdMatchType.IN_TOTAL,
+ });
+ };
+
+ const handleSelectedQueryChange = (value: string): void => {
+ // loop through currenttQuery and find the query that matches the selected query
+ const query = currentQuery?.builder?.queryData.find(
+ (query) => query.queryName === value,
+ );
+
+ const currentSelectedQuery = currentQuery?.builder?.queryData.find(
+ (query) => query.queryName === thresholdState.selectedQuery,
+ );
+
+ const newSelectedQuerySource = query?.source || '';
+ const currentSelectedQuerySource = currentSelectedQuery?.source || '';
+
+ if (newSelectedQuerySource === currentSelectedQuerySource) {
+ setThresholdState({
+ type: 'SET_SELECTED_QUERY',
+ payload: value,
+ });
+
+ return;
+ }
+
+ if (newSelectedQuerySource === 'meter') {
+ handleSetEvaluationDetailsForMeter();
+ } else {
+ setEvaluationWindow({
+ type: 'SET_INITIAL_STATE',
+ payload: INITIAL_EVALUATION_WINDOW_STATE,
+ });
+ }
+
+ setThresholdState({
+ type: 'SET_SELECTED_QUERY',
+ payload: value,
+ });
+ };
+
return (
<div
className={classNames(
@@ -175,12 +225,7 @@ function AlertThreshold({
</Typography.Text>
<Select
value={thresholdState.selectedQuery}
- onChange={(value): void => {
- setThresholdState({
- type: 'SET_SELECTED_QUERY',
- payload: value,
- });
- }}
+ onChange={handleSelectedQueryChange}
style={{ width: 80 }}
options={queryNames}
data-testid="alert-threshold-query-select"
diff --git a/frontend/src/container/CreateAlertV2/EvaluationSettings/EvaluationSettings.tsx b/frontend/src/container/CreateAlertV2/EvaluationSettings/EvaluationSettings.tsx
index 24cc163ded..3190c2b8bc 100644
--- a/frontend/src/container/CreateAlertV2/EvaluationSettings/EvaluationSettings.tsx
+++ b/frontend/src/container/CreateAlertV2/EvaluationSettings/EvaluationSettings.tsx
@@ -10,6 +10,7 @@ import { getEvaluationWindowTypeText, getTimeframeText } from './utils';
function EvaluationSettings(): JSX.Element {
const { evaluationWindow, setEvaluationWindow } = useCreateAlertState();
+
const [
isEvaluationWindowPopoverOpen,
setIsEvaluationWindowPopoverOpen,
diff --git a/frontend/src/container/CreateAlertV2/context/index.tsx b/frontend/src/container/CreateAlertV2/context/index.tsx
index 3557231e09..0da09dd04f 100644
--- a/frontend/src/container/CreateAlertV2/context/index.tsx
+++ b/frontend/src/container/CreateAlertV2/context/index.tsx
@@ -24,7 +24,11 @@ import {
INITIAL_EVALUATION_WINDOW_STATE,
INITIAL_NOTIFICATION_SETTINGS_STATE,
} from './constants';
-import { ICreateAlertContextProps, ICreateAlertProviderProps } from './types';
+import {
+ AlertThresholdMatchType,
+ ICreateAlertContextProps,
+ ICreateAlertProviderProps,
+} from './types';
import {
advancedOptionsReducer,
alertCreationReducer,
@@ -67,6 +71,7 @@ export function CreateAlertProvider(
const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
+ const thresholdsFromURL = queryParams.get(QueryParams.thresholds);
const [alertType, setAlertType] = useState<AlertTypes>(() => {
if (isEditMode) {
@@ -122,7 +127,28 @@ export function CreateAlertProvider(
setThresholdState({
type: 'RESET',
});
- }, [alertType]);
+
+ if (thresholdsFromURL) {
+ try {
+ const thresholds = JSON.parse(thresholdsFromURL);
+ setThresholdState({
+ type: 'SET_THRESHOLDS',
+ payload: thresholds,
+ });
+ } catch (error) {
+ console.error('Error parsing thresholds from URL:', error);
+ }
+
+ setEvaluationWindow({
+ type: 'SET_INITIAL_STATE_FOR_METER',
+ });
+
+ setThresholdState({
+ type: 'SET_MATCH_TYPE',
+ payload: AlertThresholdMatchType.IN_TOTAL,
+ });
+ }
+ }, [alertType, thresholdsFromURL]);
useEffect(() => {
if (isEditMode && initialAlertState) {
diff --git a/frontend/src/container/CreateAlertV2/context/types.ts b/frontend/src/container/CreateAlertV2/context/types.ts
index 8a3da59580..3ca416c96f 100644
--- a/frontend/src/container/CreateAlertV2/context/types.ts
+++ b/frontend/src/container/CreateAlertV2/context/types.ts
@@ -237,6 +237,7 @@ export type EvaluationWindowAction =
}
| { type: 'SET_EVALUATION_CADENCE_MODE'; payload: EvaluationCadenceMode }
| { type: 'SET_INITIAL_STATE'; payload: EvaluationWindowState }
+ | { type: 'SET_INITIAL_STATE_FOR_METER' }
| { type: 'RESET' };
export type EvaluationCadenceMode = 'default' | 'custom' | 'rrule';
diff --git a/frontend/src/container/CreateAlertV2/context/utils.tsx b/frontend/src/container/CreateAlertV2/context/utils.tsx
index be8a7b3381..f4d9347454 100644
--- a/frontend/src/container/CreateAlertV2/context/utils.tsx
+++ b/frontend/src/container/CreateAlertV2/context/utils.tsx
@@ -1,3 +1,5 @@
+import { UTC_TIMEZONE } from 'components/CustomTimePicker/timezoneUtils';
+import { UniversalYAxisUnit } from 'components/YAxisUnitSelector/types';
import { QueryParams } from 'constants/query';
import {
alertDefaults,
@@ -11,6 +13,7 @@ import { AlertDef } from 'types/api/alerts/def';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
+import { CumulativeWindowTimeframes } from '../EvaluationSettings/types';
import {
INITIAL_ADVANCED_OPTIONS_STATE,
INITIAL_ALERT_STATE,
@@ -210,6 +213,18 @@ export const evaluationWindowReducer = (
return INITIAL_EVALUATION_WINDOW_STATE;
case 'SET_INITIAL_STATE':
return action.payload;
+ case 'SET_INITIAL_STATE_FOR_METER':
+ return {
+ ...state,
+ windowType: 'cumulative',
+ timeframe: CumulativeWindowTimeframes.CURRENT_DAY,
+ startingAt: {
+ time: '00:00:00',
+ number: '0',
+ timezone: UTC_TIMEZONE.value,
+ unit: UniversalYAxisUnit.MINUTES,
+ },
+ };
default:
return state;
}
diff --git a/frontend/src/container/FormAlertRules/QuerySection.tsx b/frontend/src/container/FormAlertRules/QuerySection.tsx
index 1c0f50b2bc..3a23b1aebf 100644
--- a/frontend/src/container/FormAlertRules/QuerySection.tsx
+++ b/frontend/src/container/FormAlertRules/QuerySection.tsx
@@ -36,6 +36,7 @@ function QuerySection({
// init namespace for translations
const { t } = useTranslation('alerts');
const [currentTab, setCurrentTab] = useState(queryCategory);
+ const [signalSource, setSignalSource] = useState<string>('metrics');
const handleQueryCategoryChange = (queryType: string): void => {
setQueryCategory(queryType as EQueryType);
@@ -48,12 +49,17 @@ function QuerySection({
const isDarkMode = useIsDarkMode();
+ const handleSignalSourceChange = (value: string): void => {
+ setSignalSource(value);
+ };
+
const renderMetricUI = (): JSX.Element => (
<QueryBuilderV2
panelType={panelType}
config={{
queryVariant: 'static',
initialDataSource: ALERTS_DATA_SOURCE_MAP[alertType],
+ signalSource: signalSource === 'meter' ? 'meter' : '',
}}
showTraceOperator={alertType === AlertTypes.TRACES_BASED_ALERT}
showFunctions={
@@ -62,6 +68,8 @@ function QuerySection({
alertType === AlertTypes.LOGS_BASED_ALERT
}
version={alertDef.version || 'v3'}
+ onSignalSourceChange={handleSignalSourceChange}
+ signalSourceChangeEnabled
/>
);
diff --git a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
index e0b6c4dd3c..676d12f81f 100644
--- a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
@@ -324,6 +324,7 @@ function FullView({
panelType={selectedPanelType}
version={selectedDashboard?.data?.version || 'v3'}
isListViewPanel={selectedPanelType === PANEL_TYPES.LIST}
+ signalSourceChangeEnabled
// filterConfigs={filterConfigs}
// queryComponents={queryComponents}
/>
diff --git a/frontend/src/container/IngestionSettings/IngestionSettings.styles.scss b/frontend/src/container/IngestionSettings/IngestionSettings.styles.scss
index 3d1b795ab8..5ed8527797 100644
--- a/frontend/src/container/IngestionSettings/IngestionSettings.styles.scss
+++ b/frontend/src/container/IngestionSettings/IngestionSettings.styles.scss
@@ -418,6 +418,11 @@
font-size: 12px;
font-weight: 600;
}
+
+ .set-alert-btn {
+ cursor: pointer;
+ margin-left: 24px;
+ }
}
}
diff --git a/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx b/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx
index d7ed2e296f..2d385a40ca 100644
--- a/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx
+++ b/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx
@@ -19,6 +19,7 @@ import {
TablePaginationConfig,
TableProps as AntDTableProps,
Tag,
+ Tooltip,
Typography,
} from 'antd';
import { NotificationInstance } from 'antd/es/notification/interface';
@@ -34,15 +35,20 @@ import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
import Tags from 'components/Tags/Tags';
import { SOMETHING_WENT_WRONG } from 'constants/api';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
+import { QueryParams } from 'constants/query';
+import { initialQueryMeterWithType } from 'constants/queryBuilder';
+import ROUTES from 'constants/routes';
+import { INITIAL_ALERT_THRESHOLD_STATE } from 'container/CreateAlertV2/context/constants';
import dayjs from 'dayjs';
import { useGetDeploymentsData } from 'hooks/CustomDomain/useGetDeploymentsData';
import { useGetAllIngestionsKeys } from 'hooks/IngestionKeys/useGetAllIngestionKeys';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useNotifications } from 'hooks/useNotifications';
-import { isNil, isUndefined } from 'lodash-es';
+import { cloneDeep, isNil, isUndefined } from 'lodash-es';
import {
ArrowUpRight,
+ BellPlus,
CalendarClock,
Check,
Copy,
@@ -60,6 +66,7 @@ import { useTimezone } from 'providers/Timezone';
import { ChangeEvent, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useMutation } from 'react-query';
+import { useHistory } from 'react-router-dom';
import { useCopyToClipboard } from 'react-use';
import { ErrorResponse } from 'types/api';
import {
@@ -71,6 +78,7 @@ import {
IngestionKeyProps,
PaginationProps,
} from 'types/api/ingestionKeys/types';
+import { MeterAggregateOperator } from 'types/common/queryBuilder';
import { USER_ROLES } from 'types/roles';
import { getDaysUntilExpiry } from 'utils/timeUtils';
@@ -170,6 +178,8 @@ function MultiIngestionSettings(): JSX.Element {
const { isEnterpriseSelfHostedUser } = useGetTenantLicense();
+ const history = useHistory();
+
const [
hasCreateLimitForIngestionKeyError,
setHasCreateLimitForIngestionKeyError,
@@ -694,6 +704,68 @@ function MultiIngestionSettings(): JSX.Element {
const { formatTimezoneAdjustedTimestamp } = useTimezone();
+ const handleCreateAlert = (
+ APIKey: IngestionKeyProps,
+ signal: LimitProps,
+ ): void => {
+ let metricName = '';
+
+ switch (signal.signal) {
+ case 'metrics':
+ metricName = 'signoz.meter.metric.datapoint.count';
+ break;
+ case 'traces':
+ metricName = 'signoz.meter.span.size';
+ break;
+ case 'logs':
+ metricName = 'signoz.meter.log.size';
+ break;
+ default:
+ return;
+ }
+
+ const threshold =
+ signal.signal === 'metrics'
+ ? signal.config?.day?.count || 0
+ : signal.config?.day?.size || 0;
+
+ const query = {
+ ...initialQueryMeterWithType,
+ builder: {
+ ...initialQueryMeterWithType.builder,
+ queryData: [
+ {
+ ...initialQueryMeterWithType.builder.queryData[0],
+ aggregations: [
+ {
+ ...initialQueryMeterWithType.builder.queryData[0].aggregations?.[0],
+ metricName,
+ timeAggregation: MeterAggregateOperator.INCREASE,
+ spaceAggregation: MeterAggregateOperator.SUM,
+ },
+ ],
+ filter: {
+ expression: `signoz.workspace.key.id='${APIKey.id}'`,
+ },
+ },
+ ],
+ },
+ };
+
+ const stringifiedQuery = JSON.stringify(query);
+
+ const thresholds = cloneDeep(INITIAL_ALERT_THRESHOLD_STATE.thresholds);
+ thresholds[0].thresholdValue = threshold;
+
+ const URL = `${ROUTES.ALERTS_NEW}?showNewCreateAlertsPage=true&${
+ QueryParams.compositeQuery
+ }=${encodeURIComponent(stringifiedQuery)}&${
+ QueryParams.thresholds
+ }=${encodeURIComponent(JSON.stringify(thresholds))}`;
+
+ history.push(URL);
+ };
+
const columns: AntDTableProps<IngestionKeyProps>['columns'] = [
{
title: 'Ingestion Key',
@@ -1183,6 +1255,27 @@ function MultiIngestionSettings(): JSX.Element {
</>
))}
</div>
+
+ {((signalCfg.usesSize &&
+ limit?.config?.day?.size !== undefined) ||
+ (signalCfg.usesCount &&
+ limit?.config?.day?.count !== undefined)) && (
+ <Tooltip
+ title="Set alert on this limit"
+ placement="top"
+ arrow={false}
+ >
+ <Button
+ icon={<BellPlus size={14} color={Color.BG_CHERRY_400} />}
+ className="set-alert-btn periscope-btn ghost"
+ type="text"
+ data-testid={`set-alert-btn-${signalName}`}
+ onClick={(): void =>
+ handleCreateAlert(APIKey, limitsDict[signalName])
+ }
+ />
+ </Tooltip>
+ )}
</div>
{/* SECOND limit usage/limit */}
diff --git a/frontend/src/container/IngestionSettings/__tests__/MultiIngestionSettings.test.tsx b/frontend/src/container/IngestionSettings/__tests__/MultiIngestionSettings.test.tsx
index 0a269d7b53..e71a108e14 100644
--- a/frontend/src/container/IngestionSettings/__tests__/MultiIngestionSettings.test.tsx
+++ b/frontend/src/container/IngestionSettings/__tests__/MultiIngestionSettings.test.tsx
@@ -1,7 +1,56 @@
-import { render, screen } from 'tests/test-utils';
+import { QueryParams } from 'constants/query';
+import { rest, server } from 'mocks-server/server';
+import { render, screen, userEvent } from 'tests/test-utils';
+import { LimitProps } from 'types/api/ingestionKeys/limits/types';
+import {
+ AllIngestionKeyProps,
+ IngestionKeyProps,
+} from 'types/api/ingestionKeys/types';
import MultiIngestionSettings from '../MultiIngestionSettings';
+// Extend the existing types to include limits with proper structure
+interface TestIngestionKeyProps extends Omit<IngestionKeyProps, 'limits'> {
+ limits?: LimitProps[];
+}
+
+interface TestAllIngestionKeyProps extends Omit<AllIngestionKeyProps, 'data'> {
+ data: TestIngestionKeyProps[];
+}
+
+// Mock useHistory.push to capture navigation URL used by MultiIngestionSettings
+const mockPush = jest.fn() as jest.MockedFunction<(path: string) => void>;
+jest.mock('react-router-dom', () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const actual = jest.requireActual('react-router-dom');
+ return {
+ ...actual,
+ useHistory: (): { push: typeof mockPush } => ({ push: mockPush }),
+ };
+});
+
+// Mock deployments data hook to avoid unrelated network calls in this page
+jest.mock(
+ 'hooks/CustomDomain/useGetDeploymentsData',
+ (): Record<string, unknown> => ({
+ useGetDeploymentsData: (): {
+ data: undefined;
+ isLoading: boolean;
+ isFetching: boolean;
+ isError: boolean;
+ } => ({
+ data: undefined,
+ isLoading: false,
+ isFetching: false,
+ isError: false,
+ }),
+ }),
+);
+
+const TEST_CREATED_UPDATED = '2024-01-01T00:00:00Z';
+const TEST_EXPIRES_AT = '2030-01-01T00:00:00Z';
+const TEST_WORKSPACE_ID = 'w1';
+
describe('MultiIngestionSettings Page', () => {
beforeEach(() => {
render(<MultiIngestionSettings />);
@@ -27,4 +76,173 @@ describe('MultiIngestionSettings Page', () => {
expect(aboutKeyslink).toHaveClass('learn-more');
expect(aboutKeyslink).toHaveAttribute('rel', 'noreferrer');
});
+
+ it('navigates to create alert with metrics count threshold', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ // Arrange API response with a metrics daily count limit so the alert button is visible
+ const response: TestAllIngestionKeyProps = {
+ status: 'success',
+ data: [
+ {
+ name: 'Key One',
+ expires_at: TEST_EXPIRES_AT,
+ value: 'secret',
+ workspace_id: TEST_WORKSPACE_ID,
+ id: 'k1',
+ created_at: TEST_CREATED_UPDATED,
+ updated_at: TEST_CREATED_UPDATED,
+ tags: [],
+ limits: [
+ {
+ id: 'l1',
+ signal: 'metrics',
+ config: { day: { count: 1000 } },
+ },
+ ],
+ },
+ ],
+ _pagination: { page: 1, per_page: 10, pages: 1, total: 1 },
+ };
+
+ server.use(
+ rest.get('*/workspaces/me/keys*', (_req, res, ctx) =>
+ res(ctx.status(200), ctx.json(response)),
+ ),
+ );
+
+ // Render with initial route to test navigation
+ render(<MultiIngestionSettings />, undefined, {
+ initialRoute: '/ingestion-settings',
+ });
+ // Wait for ingestion key to load and expand the row to show limits
+ await screen.findByText('Key One');
+ const expandButton = screen.getByRole('button', { name: /right Key One/i });
+ await user.click(expandButton);
+
+ // Wait for limits section to render and click metrics alert button by test id
+ await screen.findByText('LIMITS');
+ const metricsAlertBtn = (await screen.findByTestId(
+ 'set-alert-btn-metrics',
+ )) as HTMLButtonElement;
+ await user.click(metricsAlertBtn);
+
+ // Assert: navigation occurred with correct query parameters
+ expect(mockPush).toHaveBeenCalledTimes(1);
+ const navigationCall = mockPush.mock.calls[0][0] as string;
+
+ // Check URL contains alerts/new route
+ expect(navigationCall).toContain('/alerts/new');
+ expect(navigationCall).toContain('showNewCreateAlertsPage=true');
+
+ // Parse query parameters
+ const urlParams = new URLSearchParams(navigationCall.split('?')[1]);
+
+ const thresholds = JSON.parse(urlParams.get(QueryParams.thresholds) || '{}');
+ expect(thresholds).toBeDefined();
+ expect(thresholds[0].thresholdValue).toBe(1000);
+
+ // Verify compositeQuery parameter exists and contains correct data
+ const compositeQuery = JSON.parse(
+ urlParams.get(QueryParams.compositeQuery) || '{}',
+ );
+ expect(compositeQuery.builder).toBeDefined();
+ expect(compositeQuery.builder.queryData).toBeDefined();
+
+ // Check that the query contains the correct filter expression for the key
+ const firstQueryData = compositeQuery.builder.queryData[0];
+ expect(firstQueryData.filter.expression).toContain(
+ "signoz.workspace.key.id='k1'",
+ );
+
+ // Verify metric name for metrics signal
+ expect(firstQueryData.aggregations[0].metricName).toBe(
+ 'signoz.meter.metric.datapoint.count',
+ );
+ });
+
+ it('navigates to create alert for logs with size threshold', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ // Arrange API response with a logs daily size limit so the alert button is visible
+ const response: TestAllIngestionKeyProps = {
+ status: 'success',
+ data: [
+ {
+ name: 'Key Two',
+ expires_at: TEST_EXPIRES_AT,
+ value: 'secret',
+ workspace_id: TEST_WORKSPACE_ID,
+ id: 'k2',
+ created_at: TEST_CREATED_UPDATED,
+ updated_at: TEST_CREATED_UPDATED,
+ tags: [],
+ limits: [
+ {
+ id: 'l2',
+ signal: 'logs',
+ config: { day: { size: 2048 } },
+ },
+ ],
+ },
+ ],
+ _pagination: { page: 1, per_page: 10, pages: 1, total: 1 },
+ };
+
+ server.use(
+ rest.get('*/workspaces/me/keys*', (_req, res, ctx) =>
+ res(ctx.status(200), ctx.json(response)),
+ ),
+ );
+
+ render(<MultiIngestionSettings />, undefined, {
+ initialRoute: '/ingestion-settings',
+ });
+
+ // Wait for ingestion key to load and expand the row to show limits
+ await screen.findByText('Key Two');
+ const expandButton = screen.getByRole('button', { name: /right Key Two/i });
+ await user.click(expandButton);
+
+ // Wait for limits section to render and click logs alert button by test id
+ await screen.findByText('LIMITS');
+ const logsAlertBtn = (await screen.findByTestId(
+ 'set-alert-btn-logs',
+ )) as HTMLButtonElement;
+ await user.click(logsAlertBtn);
+
+ // Assert: navigation occurred with correct query parameters
+ expect(mockPush).toHaveBeenCalledTimes(1);
+ const navigationCall = mockPush.mock.calls[0][0] as string;
+
+ // Check URL contains alerts/new route
+ expect(navigationCall).toContain('/alerts/new');
+ expect(navigationCall).toContain('showNewCreateAlertsPage=true');
+
+ // Parse query parameters
+ const urlParams = new URLSearchParams(navigationCall.split('?')[1]);
+
+ // Verify thresholds parameter
+ const thresholds = JSON.parse(urlParams.get(QueryParams.thresholds) || '{}');
+ expect(thresholds).toBeDefined();
+ expect(thresholds[0].thresholdValue).toBe(2048);
+
+ // Verify compositeQuery parameter exists and contains correct data
+ const compositeQuery = JSON.parse(
+ urlParams.get(QueryParams.compositeQuery) || '{}',
+ );
+ expect(compositeQuery.builder).toBeDefined();
+ expect(compositeQuery.builder.queryData).toBeDefined();
+
+ // Check that the query contains the correct filter expression for the key
+ const firstQueryData = compositeQuery.builder.queryData[0];
+ expect(firstQueryData.filter.expression).toContain(
+ "signoz.workspace.key.id='k2'",
+ );
+
+ // Verify metric name for logs signal
+ expect(firstQueryData.aggregations[0].metricName).toBe(
+ 'signoz.meter.log.size',
+ );
+ });
});
diff --git a/frontend/src/container/MeterExplorer/Explorer/Explorer.tsx b/frontend/src/container/MeterExplorer/Explorer/Explorer.tsx
index 3a7ac3b7c3..96df78776d 100644
--- a/frontend/src/container/MeterExplorer/Explorer/Explorer.tsx
+++ b/frontend/src/container/MeterExplorer/Explorer/Explorer.tsx
@@ -33,6 +33,7 @@ function Explorer(): JSX.Element {
handleRunQuery,
stagedQuery,
updateAllQueriesOperators,
+ handleSetQueryData,
currentQuery,
} = useQueryBuilder();
const { safeNavigate } = useSafeNavigate();
@@ -50,6 +51,15 @@ function Explorer(): JSX.Element {
[updateAllQueriesOperators],
);
+ useEffect(() => {
+ handleSetQueryData(0, {
+ ...initialQueryMeterWithType.builder.queryData[0],
+ source: 'meter',
+ });
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
const exportDefaultQuery = useMemo(
() =>
updateAllQueriesOperators(
diff --git a/frontend/src/container/MetricsExplorer/Summary/Summary.tsx b/frontend/src/container/MetricsExplorer/Summary/Summary.tsx
index c41dcc7202..85ae6f4d0f 100644
--- a/frontend/src/container/MetricsExplorer/Summary/Summary.tsx
+++ b/frontend/src/container/MetricsExplorer/Summary/Summary.tsx
@@ -290,13 +290,6 @@ function Summary(): JSX.Element {
],
);
- console.log({
- isMetricsListDataEmpty,
- isMetricsTreeMapDataEmpty,
- treeMapData,
- sec: treeMapData?.payload?.data[heatmapView],
- });
-
return (
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
<div className="metrics-explorer-summary-tab">
diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx
index 5049f278af..c32c8953fc 100644
--- a/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx
+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx
@@ -168,6 +168,7 @@ function QuerySection({
version={selectedDashboard?.data?.version || 'v3'}
isListViewPanel={selectedGraph === PANEL_TYPES.LIST}
queryComponents={queryComponents}
+ signalSourceChangeEnabled
/>
</div>
),
diff --git a/frontend/src/container/QueryBuilder/QueryBuilder.interfaces.ts b/frontend/src/container/QueryBuilder/QueryBuilder.interfaces.ts
index 798d45e897..6781f402a7 100644
--- a/frontend/src/container/QueryBuilder/QueryBuilder.interfaces.ts
+++ b/frontend/src/container/QueryBuilder/QueryBuilder.interfaces.ts
@@ -35,6 +35,8 @@ export type QueryBuilderProps = {
showTraceOperator?: boolean;
version: string;
onChangeTraceView?: (view: TraceView) => void;
+ onSignalSourceChange?: (value: string) => void;
+ signalSourceChangeEnabled?: boolean;
};
export enum TraceView {
diff --git a/frontend/src/container/QueryBuilder/filters/AggregatorFilter/AggregatorFilter.tsx b/frontend/src/container/QueryBuilder/filters/AggregatorFilter/AggregatorFilter.tsx
index 22c6c79b77..9fd5d728c5 100644
--- a/frontend/src/container/QueryBuilder/filters/AggregatorFilter/AggregatorFilter.tsx
+++ b/frontend/src/container/QueryBuilder/filters/AggregatorFilter/AggregatorFilter.tsx
@@ -52,6 +52,10 @@ export const AggregatorFilter = memo(function AggregatorFilter({
(query.aggregations?.[0] as MetricAggregation)?.metricName || '',
);
+ useEffect(() => {
+ setSearchText('');
+ }, [signalSource]);
+
const debouncedSearchText = useMemo(() => {
// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-unused-vars
const [_, value] = getAutocompleteValueAndType(searchText);
@@ -67,6 +71,7 @@ export const AggregatorFilter = memo(function AggregatorFilter({
queryAggregation.timeAggregation,
query.dataSource,
index,
+ signalSource,
],
async () =>
getAggregateAttribute({
@@ -100,6 +105,7 @@ export const AggregatorFilter = memo(function AggregatorFilter({
setOptionsData(options);
setAttributeKeys?.(data?.payload?.attributeKeys || []);
},
+ keepPreviousData: false,
},
);
@@ -164,8 +170,11 @@ export const AggregatorFilter = memo(function AggregatorFilter({
queryAggregation.timeAggregation,
query.dataSource,
index,
+ signalSource,
])?.payload?.attributeKeys || [];
+
setAttributeKeys?.(attributeKeys);
+
return attributeKeys;
}, [
debouncedValue,
@@ -173,6 +182,7 @@ export const AggregatorFilter = memo(function AggregatorFilter({
query.dataSource,
queryClient,
index,
+ signalSource,
setAttributeKeys,
]);
diff --git a/frontend/src/container/SideNav/menuItems.tsx b/frontend/src/container/SideNav/menuItems.tsx
index ca37cd0fea..89651deda1 100644
--- a/frontend/src/container/SideNav/menuItems.tsx
+++ b/frontend/src/container/SideNav/menuItems.tsx
@@ -271,7 +271,7 @@ export const defaultMoreMenuItems: SidebarItem[] = [
icon: <ChartArea size={16} />,
isNew: false,
isEnabled: true,
- isBeta: true,
+ isBeta: false,
itemKey: 'meter-explorer',
},
{