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
chore: migrate metric details side drawer in metrics explorer to v2 APIs (#9995)
Amlan Kumar Nandybc9701397e5c
diff --git a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsxindex 48be4233c2..217de4f68f 100644--- a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx+++ b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx@@ -349,7 +349,7 @@ function Explorer(): JSX.Element {isOneChartPerQuery={showOneChartPerQuery}splitedQueries={splitedQueries}/>- {isMetricDetailsOpen && (+ {isMetricDetailsOpen && selectedMetricName && (<MetricDetailsmetricName={selectedMetricName}isOpen={isMetricDetailsOpen}diff --git a/frontend/src/container/MetricsExplorer/Explorer/RelatedMetricsCard.tsx b/frontend/src/container/MetricsExplorer/Explorer/RelatedMetricsCard.tsxindex 2c2c57499a..4b9dcc55f5 100644--- a/frontend/src/container/MetricsExplorer/Explorer/RelatedMetricsCard.tsx+++ b/frontend/src/container/MetricsExplorer/Explorer/RelatedMetricsCard.tsx@@ -39,10 +39,7 @@ function RelatedMetricsCard({ metric }: RelatedMetricsCardProps): JSX.Element {dataSource={DataSource.METRICS}/>)}- <DashboardsAndAlertsPopover- dashboards={metric.dashboards}- alerts={metric.alerts}- />+ <DashboardsAndAlertsPopover metricName={metric.name} /></div>);}diff --git a/frontend/src/container/MetricsExplorer/Inspect/utils.tsx b/frontend/src/container/MetricsExplorer/Inspect/utils.tsxindex 1b1f0514e9..6275b8e227 100644--- a/frontend/src/container/MetricsExplorer/Inspect/utils.tsx+++ b/frontend/src/container/MetricsExplorer/Inspect/utils.tsx@@ -2,8 +2,8 @@import { useMemo, useState } from 'react';import { Card, Input, Select, Typography } from 'antd';import logEvent from 'api/common/logEvent';+import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';import { InspectMetricsSeries } from 'api/metricsExplorer/getInspectMetricsDetails';-import { MetricType } from 'api/metricsExplorer/getMetricsList';import classNames from 'classnames';import { initialQueriesMap } from 'constants/queryBuilder';import { AggregatorFilter } from 'container/QueryBuilder/filters';@@ -40,8 +40,10 @@ import {* returns true if the feature flag is enabled, false otherwise* Show the inspect button in metrics explorer if the feature flag is enabled*/-export function isInspectEnabled(metricType: MetricType | undefined): boolean {- return metricType === MetricType.GAUGE;+export function isInspectEnabled(+ metricType: MetrictypesTypeDTO | undefined,+): boolean {+ return metricType === MetrictypesTypeDTO.gauge;}export function getAllTimestampsOfMetrics(diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/AllAttributes.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/AllAttributes.tsxindex b6d8278ae5..2abfa46015 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/AllAttributes.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/AllAttributes.tsx@@ -1,8 +1,17 @@import { useCallback, useMemo, useState } from 'react';import { useCopyToClipboard } from 'react-use';-import { Button, Collapse, Input, Menu, Popover, Typography } from 'antd';+import {+ Button,+ Collapse,+ Input,+ Menu,+ Popover,+ Skeleton,+ Typography,+} from 'antd';import { ColumnsType } from 'antd/es/table';import logEvent from 'api/common/logEvent';+import { useGetMetricAttributes } from 'api/generated/services/metrics';import { ResizeTable } from 'components/ResizeTable';import { DataType } from 'container/LogDetailedView/TableView';import { useNotifications } from 'hooks/useNotifications';@@ -12,9 +21,33 @@ import { PANEL_TYPES } from '../../../constants/queryBuilder';import ROUTES from '../../../constants/routes';import { useHandleExplorerTabChange } from '../../../hooks/useHandleExplorerTabChange';import { MetricsExplorerEventKeys, MetricsExplorerEvents } from '../events';-import { AllAttributesProps, AllAttributesValueProps } from './types';+import MetricDetailsErrorState from './MetricDetailsErrorState';+import {+ AllAttributesEmptyTextProps,+ AllAttributesProps,+ AllAttributesValueProps,+} from './types';import { getMetricDetailsQuery } from './utils';+const ALL_ATTRIBUTES_KEY = 'all-attributes';++function AllAttributesEmptyText({+ isErrorAttributes,+ refetchAttributes,+}: AllAttributesEmptyTextProps): JSX.Element {+ if (isErrorAttributes) {+ return (+ <div className="all-attributes-error-state">+ <MetricDetailsErrorState+ refetch={refetchAttributes}+ errorMessage="Something went wrong while fetching attributes"+ />+ </div>+ );+ }+ return <Typography.Text>No attributes found</Typography.Text>;+}+export function AllAttributesValue({filterKey,filterValue,@@ -110,13 +143,23 @@ export function AllAttributesValue({function AllAttributes({metricName,- attributes,metricType,}: AllAttributesProps): JSX.Element {const [searchString, setSearchString] = useState('');- const [activeKey, setActiveKey] = useState<string | string[]>(- 'all-attributes',- );+ const [activeKey, setActiveKey] = useState<string[]>([ALL_ATTRIBUTES_KEY]);++ const {+ data: attributesData,+ isLoading: isLoadingAttributes,+ isError: isErrorAttributes,+ refetch: refetchAttributes,+ } = useGetMetricAttributes({+ metricName,+ });++ const attributes = useMemo(() => attributesData?.data.attributes ?? [], [+ attributesData,+ ]);const { handleExplorerTabChange } = useHandleExplorerTabChange();@@ -178,7 +221,7 @@ function AllAttributes({attributes.filter((attribute) =>attribute.key.toLowerCase().includes(searchString.toLowerCase()) ||- attribute.value.some((value) =>+ attribute.values?.some((value) =>value.toLowerCase().includes(searchString.toLowerCase()),),),@@ -195,7 +238,7 @@ function AllAttributes({},value: {key: attribute.key,- value: attribute.value,+ value: attribute.values,},})): [],@@ -270,6 +313,7 @@ function AllAttributes({onClick={(e): void => {e.stopPropagation();}}+ disabled={isLoadingAttributes || isErrorAttributes}/></div>),@@ -277,25 +321,49 @@ function AllAttributes({children: (<ResizeTablecolumns={columns}+ loading={isLoadingAttributes}tableLayout="fixed"dataSource={tableData}pagination={false}showHeader={false}className="metrics-accordion-content all-attributes-content"scroll={{ y: 600 }}+ locale={{+ emptyText: (+ <AllAttributesEmptyText+ isErrorAttributes={isErrorAttributes}+ refetchAttributes={refetchAttributes}+ />+ ),+ }}/>),},],- [columns, tableData, searchString],+ [+ searchString,+ isLoadingAttributes,+ isErrorAttributes,+ columns,+ tableData,+ refetchAttributes,+ ],);+ if (isLoadingAttributes) {+ return (+ <div className="all-attributes-skeleton-container">+ <Skeleton active paragraph={{ rows: 8 }} />+ </div>+ );+ }+return (<Collapsebordered- className="metrics-accordion metrics-metadata-accordion"+ className="metrics-accordion"activeKey={activeKey}- onChange={(keys): void => setActiveKey(keys)}+ onChange={(keys): void => setActiveKey(keys as string[])}items={items}/>);diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsxindex ef2ebbdbbb..be3c9bda49 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx@@ -2,36 +2,84 @@ import { useMemo } from 'react';import { generatePath } from 'react-router-dom';import { Color } from '@signozhq/design-tokens';import { Dropdown, Typography } from 'antd';+import { Skeleton } from 'antd/lib';+import {+ useGetMetricAlerts,+ useGetMetricDashboards,+} from 'api/generated/services/metrics';import { QueryParams } from 'constants/query';import ROUTES from 'constants/routes';import { useSafeNavigate } from 'hooks/useSafeNavigate';import useUrlQuery from 'hooks/useUrlQuery';import history from 'lib/history';import { Bell, Grid } from 'lucide-react';+import { pluralize } from 'utils/pluralize';import { DashboardsAndAlertsPopoverProps } from './types';function DashboardsAndAlertsPopover({- alerts,- dashboards,+ metricName,}: DashboardsAndAlertsPopoverProps): JSX.Element | null {const { safeNavigate } = useSafeNavigate();const params = useUrlQuery();+ const {+ data: alertsData,+ isLoading: isLoadingAlerts,+ isError: isErrorAlerts,+ } = useGetMetricAlerts(+ {+ metricName,+ },+ {+ query: {+ enabled: !!metricName,+ },+ },+ );++ const {+ data: dashboardsData,+ isLoading: isLoadingDashboards,+ isError: isErrorDashboards,+ } = useGetMetricDashboards(+ {+ metricName,+ },+ {+ query: {+ enabled: !!metricName,+ },+ },+ );++ const alerts = useMemo(() => {+ return alertsData?.data.alerts ?? [];+ }, [alertsData]);++ const dashboards = useMemo(() => {+ const currentDashboards = dashboardsData?.data.dashboards ?? [];+ // Remove duplicate dashboards+ return currentDashboards.filter(+ (dashboard, index, self) =>+ index === self.findIndex((t) => t.dashboardId === dashboard.dashboardId),+ );+ }, [dashboardsData]);+const alertsPopoverContent = useMemo(() => {if (alerts && alerts.length > 0) {return alerts.map((alert) => ({- key: alert.alert_id,+ key: alert.alertId,label: (<Typography.Link- key={alert.alert_id}+ key={alert.alertId}onClick={(): void => {- params.set(QueryParams.ruleId, alert.alert_id);+ params.set(QueryParams.ruleId, alert.alertId);history.push(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);}}className="dashboards-popover-content-item">- {alert.alert_name || alert.alert_id}+ {alert.alertName || alert.alertId}</Typography.Link>),}));@@ -39,41 +87,44 @@ function DashboardsAndAlertsPopover({return null;}, [alerts, params]);- const uniqueDashboards = useMemo(- () =>- dashboards?.filter(- (item, index, self) =>- index === self.findIndex((t) => t.dashboard_id === item.dashboard_id),- ),- [dashboards],- );-const dashboardsPopoverContent = useMemo(() => {- if (uniqueDashboards && uniqueDashboards.length > 0) {- return uniqueDashboards.map((dashboard) => ({- key: dashboard.dashboard_id,+ if (dashboards && dashboards.length > 0) {+ return dashboards.map((dashboard) => ({+ key: dashboard.dashboardId,label: (<Typography.Link- key={dashboard.dashboard_id}+ key={dashboard.dashboardId}onClick={(): void => {safeNavigate(generatePath(ROUTES.DASHBOARD, {- dashboardId: dashboard.dashboard_id,+ dashboardId: dashboard.dashboardId,}),);}}className="dashboards-popover-content-item">- {dashboard.dashboard_name || dashboard.dashboard_id}+ {dashboard.dashboardName || dashboard.dashboardId}</Typography.Link>),}));}return null;- }, [uniqueDashboards, safeNavigate]);+ }, [dashboards, safeNavigate]);- if (!dashboardsPopoverContent && !alertsPopoverContent) {- return null;+ if (isLoadingAlerts || isLoadingDashboards) {+ return (+ <div className="dashboards-and-alerts-popover-container">+ <Skeleton title={false} paragraph={{ rows: 1 }} active />+ </div>+ );+ }++ // If there are no dashboards or alerts or both have errors, don't show the popover+ const hidePopover =+ (!dashboardsPopoverContent && !alertsPopoverContent) ||+ (isErrorAlerts && isErrorDashboards);+ if (hidePopover) {+ return <div className="dashboards-and-alerts-popover-container" />;}return (@@ -92,8 +143,7 @@ function DashboardsAndAlertsPopover({><Grid size={12} color={Color.BG_SIENNA_500} /><Typography.Text>- {uniqueDashboards?.length} dashboard- {uniqueDashboards?.length === 1 ? '' : 's'}+ {pluralize(dashboards.length, 'dashboard')}</Typography.Text></div></Dropdown>@@ -112,7 +162,7 @@ function DashboardsAndAlertsPopover({><Bell size={12} color={Color.BG_SAKURA_500} /><Typography.Text>- {alerts?.length} alert {alerts?.length === 1 ? 'rule' : 'rules'}+ {pluralize(alerts.length, 'alert rule')}</Typography.Text></div></Dropdown>diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/Highlights.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/Highlights.tsxnew file mode 100644index 0000000000..1ebe7af0da--- /dev/null+++ b/frontend/src/container/MetricsExplorer/MetricDetails/Highlights.tsx@@ -0,0 +1,123 @@+import { Color } from '@signozhq/design-tokens';+import { Button, Skeleton, Tooltip, Typography } from 'antd';+import { useGetMetricHighlights } from 'api/generated/services/metrics';+import { InfoIcon } from 'lucide-react';++import { formatNumberIntoHumanReadableFormat } from '../Summary/utils';+import { HighlightsProps } from './types';+import {+ formatNumberToCompactFormat,+ formatTimestampToReadableDate,+} from './utils';++function Highlights({ metricName }: HighlightsProps): JSX.Element {+ const {+ data: metricHighlightsData,+ isLoading: isLoadingMetricHighlights,+ isError: isErrorMetricHighlights,+ refetch: refetchMetricHighlights,+ } = useGetMetricHighlights(+ {+ metricName,+ },+ {+ query: {+ enabled: !!metricName,+ },+ },+ );++ const metricHighlights = metricHighlightsData?.data;++ const timeSeriesActive = formatNumberToCompactFormat(+ metricHighlights?.activeTimeSeries,+ );+ const timeSeriesTotal = formatNumberToCompactFormat(+ metricHighlights?.totalTimeSeries,+ );+ const lastReceivedText = formatTimestampToReadableDate(+ metricHighlights?.lastReceived,+ );++ if (isLoadingMetricHighlights) {+ return (+ <div+ className="metric-details-content-grid"+ data-testid="metric-highlights-loading-state"+ >+ <Skeleton title={false} paragraph={{ rows: 2 }} active />+ </div>+ );+ }++ if (isErrorMetricHighlights) {+ return (+ <div className="metric-details-content-grid">+ <div+ className="metric-highlights-error-state"+ data-testid="metric-highlights-error-state"+ >+ <InfoIcon size={16} color={Color.BG_CHERRY_500} />+ <Typography.Text>+ Something went wrong while fetching metric highlights+ </Typography.Text>+ <Button+ type="link"+ size="large"+ onClick={(): void => {+ refetchMetricHighlights();+ }}+ >+ Retry ?+ </Button>+ </div>+ </div>+ );+ }++ return (+ <div className="metric-details-content-grid">+ <div className="labels-row">+ <Typography.Text type="secondary" className="metric-details-grid-label">+ SAMPLES+ </Typography.Text>+ <Typography.Text type="secondary" className="metric-details-grid-label">+ TIME SERIES+ </Typography.Text>+ <Typography.Text type="secondary" className="metric-details-grid-label">+ LAST RECEIVED+ </Typography.Text>+ </div>+ <div className="values-row">+ <Typography.Text+ className="metric-details-grid-value"+ data-testid="metric-highlights-data-points"+ >+ <Tooltip title={metricHighlights?.dataPoints?.toLocaleString()}>+ {formatNumberIntoHumanReadableFormat(metricHighlights?.dataPoints ?? 0)}+ </Tooltip>+ </Typography.Text>+ <Typography.Text+ className="metric-details-grid-value"+ data-testid="metric-highlights-time-series-total"+ >+ <Tooltip+ title="Active time series are those that have received data points in the last 1+ hour."+ placement="top"+ >+ <span>{`${timeSeriesTotal} total ⎯ ${timeSeriesActive} active`}</span>+ </Tooltip>+ </Typography.Text>+ <Typography.Text+ className="metric-details-grid-value"+ data-testid="metric-highlights-last-received"+ >+ <Tooltip title={lastReceivedText}>{lastReceivedText}</Tooltip>+ </Typography.Text>+ </div>+ </div>+ );+}++export default Highlights;diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsxindex 38a5477fb9..783e2ef250 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx@@ -1,45 +1,58 @@-import { useCallback, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';import { useQueryClient } from 'react-query';-import { Button, Collapse, Input, Select, Typography } from 'antd';+import { Button, Collapse, Input, Select, Skeleton, Typography } from 'antd';import { ColumnsType } from 'antd/es/table';import logEvent from 'api/common/logEvent';-import { Temporality } from 'api/metricsExplorer/getMetricDetails';-import { MetricType } from 'api/metricsExplorer/getMetricsList';-import { UpdateMetricMetadataProps } from 'api/metricsExplorer/updateMetricMetadata';+import {+ invalidateGetMetricMetadata,+ invalidateListMetrics,+ useUpdateMetricMetadata,+} from 'api/generated/services/metrics';+import {+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+ RenderErrorResponseDTO,+} from 'api/generated/services/sigNoz.schemas';+import { AxiosError } from 'axios';import { ResizeTable } from 'components/ResizeTable';import YAxisUnitSelector from 'components/YAxisUnitSelector';import { YAxisSource } from 'components/YAxisUnitSelector/types';import { getUniversalNameFromMetricUnit } from 'components/YAxisUnitSelector/utils';import FieldRenderer from 'container/LogDetailedView/FieldRenderer';import { DataType } from 'container/LogDetailedView/TableView';-import { useUpdateMetricMetadata } from 'hooks/metricsExplorer/useUpdateMetricMetadata';import { useNotifications } from 'hooks/useNotifications';import { Edit2, Save, X } from 'lucide-react';import { MetricsExplorerEventKeys, MetricsExplorerEvents } from '../events';+import { MetricTypeViewRenderer } from '../Summary/utils';import {- METRIC_TYPE_LABEL_MAP,- METRIC_TYPE_VALUES_MAP,-} from '../Summary/constants';-import { MetricTypeRenderer } from '../Summary/utils';-import { METRIC_METADATA_KEYS } from './constants';-import { MetadataProps } from './types';-import { determineIsMonotonic } from './utils';+ METRIC_METADATA_KEYS,+ METRIC_METADATA_TEMPORALITY_OPTIONS,+ METRIC_METADATA_TYPE_OPTIONS,+ METRIC_METADATA_UPDATE_ERROR_MESSAGE,+} from './constants';+import MetricDetailsErrorState from './MetricDetailsErrorState';+import { MetadataProps, MetricMetadataFormState, TableFields } from './types';+import { transformUpdateMetricMetadataRequest } from './utils';function Metadata({metricName,metadata,- refetchMetricDetails,+ isErrorMetricMetadata,+ isLoadingMetricMetadata,+ refetchMetricMetadata,}: MetadataProps): JSX.Element {const [isEditing, setIsEditing] = useState(false);+const [- metricMetadata,- setMetricMetadata,- ] = useState<UpdateMetricMetadataProps>({- metricType: metadata?.metric_type || MetricType.SUM,- description: metadata?.description || '',- temporality: metadata?.temporality,- unit: metadata?.unit,+ metricMetadataState,+ setMetricMetadataState,+ ] = useState<MetricMetadataFormState>({+ type: MetrictypesTypeDTO.sum,+ description: '',+ temporality: MetrictypesTemporalityDTO.unspecified,+ unit: '',+ isMonotonic: false,});const { notifications } = useNotifications();const {@@ -51,110 +64,135 @@ function Metadata({);const queryClient = useQueryClient();+ // Initialize state from metadata api data+ useEffect(() => {+ if (metadata) {+ setMetricMetadataState({+ type: metadata.type,+ description: metadata.description,+ temporality: metadata.temporality,+ unit: metadata.unit,+ isMonotonic: metadata.isMonotonic,+ });+ }+ }, [metadata]);+const tableData = useMemo(() =>metadata- ? Object.keys({- ...metadata,- temporality: metadata?.temporality,- })- // Filter out monotonic as user input is not required- .filter((key) => key !== 'monotonic')- .map((key) => ({+ ? Object.keys(metadata).map((key) => ({+ key,+ value: {+ value: metadata[key as keyof typeof metadata],key,- value: {- value: metadata[key as keyof typeof metadata],- key,- },- }))+ },+ })): [],[metadata],);// Render un-editable field value- const renderUneditableField = useCallback((key: string, value: string) => {- if (key === 'metric_type') {- return <MetricTypeRenderer type={value as MetricType} />;- }- let fieldValue = value;- if (key === 'unit') {- fieldValue = getUniversalNameFromMetricUnit(value);- }- return <FieldRenderer field={fieldValue || '-'} />;- }, []);+ const renderUneditableField = useCallback(+ (key: keyof MetricMetadataFormState, value: string) => {+ if (isErrorMetricMetadata) {+ return <FieldRenderer field="-" />;+ }+ if (key === TableFields.TYPE) {+ return <MetricTypeViewRenderer type={value as MetrictypesTypeDTO} />;+ }+ if (key === TableFields.IS_MONOTONIC) {+ return <FieldRenderer field={value ? 'Yes' : 'No'} />;+ }+ if (key === TableFields.Temporality) {+ const temporality = METRIC_METADATA_TEMPORALITY_OPTIONS.find(+ (option) => option.value === value,+ );+ return <FieldRenderer field={temporality?.label || '-'} />;+ }+ let fieldValue = value;+ if (key === TableFields.UNIT) {+ fieldValue = getUniversalNameFromMetricUnit(value);+ }+ return <FieldRenderer field={fieldValue || '-'} />;+ },+ [isErrorMetricMetadata],+ );const renderColumnValue = useCallback(- (field: { value: string; key: string }): JSX.Element => {+ (field: {+ value: string;+ key: keyof MetricMetadataFormState;+ }): JSX.Element => {if (!isEditing) {return renderUneditableField(field.key, field.value);}// Don't allow editing of unit if it's already set- const metricUnitAlreadySet = field.key === 'unit' && Boolean(metadata?.unit);+ const metricUnitAlreadySet =+ field.key === TableFields.UNIT && Boolean(metadata?.unit);if (metricUnitAlreadySet) {return renderUneditableField(field.key, field.value);}- if (field.key === 'metric_type') {+ // Monotonic is not editable+ if (field.key === TableFields.IS_MONOTONIC) {+ return renderUneditableField(field.key, field.value);+ }++ if (field.key === TableFields.TYPE) {return (<Selectdata-testid="metric-type-select"- options={Object.entries(METRIC_TYPE_VALUES_MAP).map(([key]) => ({- value: key,- label: METRIC_TYPE_LABEL_MAP[key as MetricType],- }))}- value={metricMetadata.metricType}+ options={METRIC_METADATA_TYPE_OPTIONS}+ value={metricMetadataState.type}onChange={(value): void => {- setMetricMetadata((prev) => ({+ setMetricMetadataState((prev) => ({...prev,- metricType: value as MetricType,+ type: value,}));}}/>);}- if (field.key === 'unit') {+ if (field.key === TableFields.UNIT) {return (<YAxisUnitSelector- value={metricMetadata.unit}+ value={metricMetadataState.unit}onChange={(value): void => {- setMetricMetadata((prev) => ({ ...prev, unit: value }));+ setMetricMetadataState((prev) => ({ ...prev, unit: value }));}}data-testid="unit-select"source={YAxisSource.EXPLORER}/>);}- if (field.key === 'temporality') {+ if (field.key === TableFields.Temporality) {+ const temporalityValue =+ metricMetadataState.temporality === MetrictypesTemporalityDTO.unspecified+ ? undefined+ : metricMetadataState.temporality;return (<Selectdata-testid="temporality-select"- options={Object.values(Temporality).map((key) => ({- value: key,- label: key,- }))}- value={metricMetadata.temporality}+ options={METRIC_METADATA_TEMPORALITY_OPTIONS}+ value={temporalityValue}onChange={(value): void => {- setMetricMetadata((prev) => ({+ setMetricMetadataState((prev) => ({...prev,- temporality: value as Temporality,+ temporality: value,}));}}/>);}- if (field.key === 'description') {+ if (field.key === TableFields.DESCRIPTION) {return (<Inputdata-testid="description-input"name={field.key}- defaultValue={- metricMetadata[- field.key as Exclude<keyof UpdateMetricMetadataProps, 'isMonotonic'>- ]- }+ defaultValue={metricMetadataState.description}onChange={(e): void => {- setMetricMetadata((prev) => ({+ setMetricMetadataState((prev) => ({...prev,[field.key]: e.target.value,}));@@ -164,7 +202,7 @@ function Metadata({}return <FieldRenderer field="-" />;},- [isEditing, metadata?.unit, metricMetadata, renderUneditableField],+ [isEditing, metadata?.unit, metricMetadataState, renderUneditableField],);const columns: ColumnsType<DataType> = useMemo(@@ -201,52 +239,61 @@ function Metadata({const handleSave = useCallback(() => {updateMetricMetadata({- metricName,- payload: {- ...metricMetadata,- isMonotonic: determineIsMonotonic(- metricMetadata.metricType,- metricMetadata.temporality,- ),+ pathParams: {+ metricName,},+ data: transformUpdateMetricMetadataRequest(metricName, metricMetadataState),},{- onSuccess: (response): void => {- if (response?.statusCode === 200) {- logEvent(MetricsExplorerEvents.MetricMetadataUpdated, {- [MetricsExplorerEventKeys.MetricName]: metricName,- [MetricsExplorerEventKeys.Tab]: 'summary',- [MetricsExplorerEventKeys.Modal]: 'metric-details',- });- notifications.success({- message: 'Metadata updated successfully',- });- refetchMetricDetails();- setIsEditing(false);- queryClient.invalidateQueries(['metricsList']);- } else {- notifications.error({- message:- 'Failed to update metadata, please try again. If the issue persists, please contact support.',- });- }+ onSuccess: (): void => {+ logEvent(MetricsExplorerEvents.MetricMetadataUpdated, {+ [MetricsExplorerEventKeys.MetricName]: metricName,+ [MetricsExplorerEventKeys.Tab]: 'summary',+ [MetricsExplorerEventKeys.Modal]: 'metric-details',+ });+ notifications.success({+ message: 'Metadata updated successfully',+ });+ setIsEditing(false);+ invalidateListMetrics(queryClient);+ invalidateGetMetricMetadata(queryClient, {+ metricName,+ });},- onError: (): void =>+ onError: (error): void => {+ const errorMessage = (error as AxiosError<RenderErrorResponseDTO>).response+ ?.data.error?.message;notifications.error({- message:- 'Failed to update metadata, please try again. If the issue persists, please contact support.',- }),+ message: errorMessage || METRIC_METADATA_UPDATE_ERROR_MESSAGE,+ });+ },},);}, [updateMetricMetadata,metricName,- metricMetadata,+ metricMetadataState,notifications,- refetchMetricDetails,queryClient,]);+ const cancelEdit = useCallback(+ (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {+ e.stopPropagation();+ if (metadata) {+ setMetricMetadataState({+ type: metadata.type,+ description: metadata.description,+ unit: metadata.unit,+ temporality: metadata.temporality,+ isMonotonic: metadata.isMonotonic,+ });+ }+ setIsEditing(false);+ },+ [metadata],+ );+const actionButton = useMemo(() => {if (isEditing) {return (@@ -254,10 +301,7 @@ function Metadata({<ButtonclassName="action-button"type="text"- onClick={(e): void => {- e.stopPropagation();- setIsEditing(false);- }}+ onClick={cancelEdit}disabled={isUpdatingMetricsMetadata}><X size={14} />@@ -278,6 +322,9 @@ function Metadata({</div>);}+ if (isErrorMetricMetadata) {+ return null;+ }return (<div className="action-menu"><Button@@ -294,7 +341,13 @@ function Metadata({</Button></div>);- }, [handleSave, isEditing, isUpdatingMetricsMetadata]);+ }, [+ isEditing,+ isErrorMetricMetadata,+ isUpdatingMetricsMetadata,+ cancelEdit,+ handleSave,+ ]);const items = useMemo(() => [@@ -306,7 +359,14 @@ function Metadata({</div>),key: 'metric-metadata',- children: (+ children: isErrorMetricMetadata ? (+ <div className="metric-metadata-error-state">+ <MetricDetailsErrorState+ refetch={refetchMetricMetadata}+ errorMessage="Something went wrong while fetching metric metadata"+ />+ </div>+ ) : (<ResizeTablecolumns={columns}tableLayout="fixed"@@ -318,9 +378,23 @@ function Metadata({),},],- [actionButton, columns, tableData],+ [+ actionButton,+ columns,+ isErrorMetricMetadata,+ refetchMetricMetadata,+ tableData,+ ],);+ if (isLoadingMetricMetadata) {+ return (+ <div className="metrics-metadata-skeleton-container">+ <Skeleton active paragraph={{ rows: 8 }} />+ </div>+ );+ }+return (<Collapsebordereddiff --git a/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.styles.scss b/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.styles.scssindex ad4f1ad31e..d28eef87d2 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.styles.scss+++ b/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.styles.scss@@ -38,7 +38,12 @@flex-direction: column;gap: 12px;+ .metrics-metadata-error {+ padding: 16px !important;+ }+.metric-details-content-grid {+ height: 50px;.labels-row,.values-row {display: grid;@@ -47,6 +52,18 @@align-items: center;}+ .metric-highlights-error-state {+ display: flex;+ gap: 8px;+ height: 100%;+ width: 100%;+ align-items: center;++ .ant-btn {+ padding: 2px 4px;+ }+ }+.labels-row {margin-bottom: 8px;@@ -72,6 +89,7 @@.dashboards-and-alerts-popover-container {display: flex;gap: 16px;+ height: 32px;.dashboards-and-alerts-popover {border-radius: 20px;@@ -102,7 +120,19 @@}}+ .metrics-metadata-skeleton-container {+ height: 330px;+ }++ .all-attributes-skeleton-container {+ height: 600px;+ }+.metrics-accordion {+ .all-attributes-error-state {+ height: 300px;+ }+.ant-table-body {&::-webkit-scrollbar {width: 2px;@@ -148,7 +178,6 @@.all-attributes-search-input {width: 300px;- border: 1px solid var(--bg-slate-300);}}@@ -161,6 +190,7 @@.ant-typography:first-child {font-family: 'Geist Mono';color: var(--bg-robin-400);+ background-color: transparent;}}.all-attributes-contribution {@@ -217,6 +247,10 @@.ant-collapse-content-box {padding: 0;++ .metric-metadata-error-state {+ height: 267px;+ }}.ant-collapse-header {@@ -237,6 +271,7 @@}.metric-metadata-value {+ height: 67px;background: rgba(22, 25, 34, 0.4);overflow-x: scroll;.field-renderer-container {@@ -330,18 +365,26 @@.metric-details-content {.metrics-accordion {.metrics-accordion-header {- .action-button {- .ant-typography {- color: var(--bg-slate-400);+ .action-menu {+ .action-button {+ .ant-typography {+ color: var(--bg-slate-400);+ }}}}.metrics-accordion-content {.metric-metadata-key {+ .field-renderer-container {+ .label {+ color: var(--bg-slate-300);+ }+ }+.all-attributes-key {.ant-typography:last-child {- color: var(--bg-slate-400);+ color: var(--bg-vanilla-200);background-color: var(--bg-robin-300);}}@@ -395,3 +438,13 @@}}}++.metric-details-error-state {+ display: flex;+ flex-direction: column;+ gap: 8px;+ align-items: center;+ justify-content: center;+ height: 100%;+ width: 100%;+}diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.tsxindex 24eb77452a..8c3546a13c 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.tsx@@ -1,16 +1,8 @@import { useCallback, useEffect, useMemo } from 'react';import { Color } from '@signozhq/design-tokens';-import {- Button,- Divider,- Drawer,- Empty,- Skeleton,- Tooltip,- Typography,-} from 'antd';+import { Button, Divider, Drawer, Typography } from 'antd';import logEvent from 'api/common/logEvent';-import { useGetMetricDetails } from 'hooks/metricsExplorer/useGetMetricDetails';+import { useGetMetricMetadata } from 'api/generated/services/metrics';import { useIsDarkMode } from 'hooks/useDarkMode';import { Compass, Crosshair, X } from 'lucide-react';@@ -19,16 +11,12 @@ import ROUTES from '../../../constants/routes';import { useHandleExplorerTabChange } from '../../../hooks/useHandleExplorerTabChange';import { MetricsExplorerEventKeys, MetricsExplorerEvents } from '../events';import { isInspectEnabled } from '../Inspect/utils';-import { formatNumberIntoHumanReadableFormat } from '../Summary/utils';import AllAttributes from './AllAttributes';import DashboardsAndAlertsPopover from './DashboardsAndAlertsPopover';+import Highlights from './Highlights';import Metadata from './Metadata';import { MetricDetailsProps } from './types';-import {- formatNumberToCompactFormat,- formatTimestampToReadableDate,- getMetricDetailsQuery,-} from './utils';+import { getMetricDetailsQuery } from './utils';import './MetricDetails.styles.scss';import '../Summary/Summary.styles.scss';@@ -43,55 +31,49 @@ function MetricDetails({const { handleExplorerTabChange } = useHandleExplorerTabChange();const {- data,- isLoading,- isFetching,- error: metricDetailsError,- refetch: refetchMetricDetails,- } = useGetMetricDetails(metricName ?? '', {- enabled: !!metricName,- });-- const metric = data?.payload?.data;-- const lastReceived = useMemo(() => {- if (!metric) {- return null;- }- return formatTimestampToReadableDate(metric.lastReceived);- }, [metric]);-- const showInspectFeature = useMemo(- () => isInspectEnabled(metric?.metadata?.metric_type),- [metric],+ data: metricMetadataResponse,+ isLoading: isLoadingMetricMetadata,+ isError: isErrorMetricMetadata,+ refetch: refetchMetricMetadata,+ } = useGetMetricMetadata(+ {+ metricName,+ },+ {+ query: {+ enabled: !!metricName,+ },+ },);- const isMetricDetailsLoading = isLoading || isFetching;-- const timeSeries = useMemo(() => {- if (!metric) {+ const metadata = useMemo(() => {+ if (!metricMetadataResponse) {return null;}- const timeSeriesActive = formatNumberToCompactFormat(metric.timeSeriesActive);- const timeSeriesTotal = formatNumberToCompactFormat(metric.timeSeriesTotal);+ const {+ type,+ description,+ unit,+ temporality,+ isMonotonic,+ } = metricMetadataResponse.data;++ return {+ type,+ description,+ unit,+ temporality,+ isMonotonic,+ };+ }, [metricMetadataResponse]);- return (- <Tooltip- title="Active time series are those that have received data points in the last 1- hour."- placement="top"- >- <span>{`${timeSeriesTotal} total ⎯ ${timeSeriesActive} active`}</span>- </Tooltip>- );- }, [metric]);+ const showInspectFeature = useMemo(() => isInspectEnabled(metadata?.type), [+ metadata?.type,+ ]);const goToMetricsExplorerwithSelectedMetric = useCallback(() => {if (metricName) {- const compositeQuery = getMetricDetailsQuery(- metricName,- metric?.metadata?.metric_type,- );+ const compositeQuery = getMetricDetailsQuery(metricName, metadata?.type);handleExplorerTabChange(PANEL_TYPES.TIME_SERIES,{@@ -107,9 +89,7 @@ function MetricDetails({[MetricsExplorerEventKeys.Modal]: 'metric-details',});}- }, [metricName, handleExplorerTabChange, metric?.metadata?.metric_type]);-- const isMetricDetailsError = metricDetailsError || !metric;+ }, [metricName, handleExplorerTabChange, metadata?.type]);useEffect(() => {logEvent(MetricsExplorerEvents.ModalOpened, {@@ -117,6 +97,9 @@ function MetricDetails({});}, []);+ const isActionButtonDisabled =+ !metricName || isLoadingMetricMetadata || isErrorMetricMetadata;+return (<Drawerwidth="60%"@@ -124,13 +107,13 @@ function MetricDetails({<div className="metric-details-header"><div className="metric-details-title"><Divider type="vertical" />- <Typography.Text>{metric?.name}</Typography.Text>+ <Typography.Text>{metricName}</Typography.Text></div><div className="metric-details-header-buttons"><ButtononClick={goToMetricsExplorerwithSelectedMetric}icon={<Compass size={16} />}- disabled={!metricName}+ disabled={isActionButtonDisabled}data-testid="open-in-explorer-button">Open in Explorer@@ -140,10 +123,11 @@ function MetricDetails({<ButtonclassName="inspect-metrics-button"aria-label="Inspect Metric"+ disabled={isActionButtonDisabled}icon={<Crosshair size={18} />}onClick={(): void => {- if (metric?.name) {- openInspectModal(metric.name);+ if (metricName) {+ openInspectModal(metricName);}}}data-testid="inspect-metric-button"@@ -163,60 +147,18 @@ function MetricDetails({destroyOnClosecloseIcon={<X size={16} />}>- {isMetricDetailsLoading && (- <div data-testid="metric-details-skeleton">- <Skeleton active />- </div>- )}- {isMetricDetailsError && !isMetricDetailsLoading && (- <Empty description="Error fetching metric details" />- )}- {!isMetricDetailsLoading && !isMetricDetailsError && (- <div className="metric-details-content">- <div className="metric-details-content-grid">- <div className="labels-row">- <Typography.Text type="secondary" className="metric-details-grid-label">- SAMPLES- </Typography.Text>- <Typography.Text type="secondary" className="metric-details-grid-label">- TIME SERIES- </Typography.Text>- <Typography.Text type="secondary" className="metric-details-grid-label">- LAST RECEIVED- </Typography.Text>- </div>- <div className="values-row">- <Typography.Text className="metric-details-grid-value">- <Tooltip title={metric?.samples.toLocaleString()}>- {formatNumberIntoHumanReadableFormat(metric?.samples)}- </Tooltip>- </Typography.Text>- <Typography.Text className="metric-details-grid-value">- <Tooltip title={timeSeries}>{timeSeries}</Tooltip>- </Typography.Text>- <Typography.Text className="metric-details-grid-value">- <Tooltip title={lastReceived}>{lastReceived}</Tooltip>- </Typography.Text>- </div>- </div>- <DashboardsAndAlertsPopover- dashboards={metric.dashboards}- alerts={metric.alerts}- />- <Metadata- metricName={metric?.name}- metadata={metric.metadata}- refetchMetricDetails={refetchMetricDetails}- />- {metric.attributes && (- <AllAttributes- metricName={metric?.name}- attributes={metric.attributes}- metricType={metric?.metadata?.metric_type}- />- )}- </div>- )}+ <div className="metric-details-content">+ <Highlights metricName={metricName} />+ <DashboardsAndAlertsPopover metricName={metricName} />+ <Metadata+ metricName={metricName}+ metadata={metadata}+ isErrorMetricMetadata={isErrorMetricMetadata}+ isLoadingMetricMetadata={isLoadingMetricMetadata}+ refetchMetricMetadata={refetchMetricMetadata}+ />+ <AllAttributes metricName={metricName} metricType={metadata?.type} />+ </div></Drawer>);}diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetailsErrorState.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetailsErrorState.tsxnew file mode 100644index 0000000000..4f11c2dac3--- /dev/null+++ b/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetailsErrorState.tsx@@ -0,0 +1,20 @@+import { Color } from '@signozhq/design-tokens';+import { Button, Typography } from 'antd';+import { InfoIcon } from 'lucide-react';++import { MetricDetailsErrorStateProps } from './types';++function MetricDetailsErrorState({+ refetch,+ errorMessage,+}: MetricDetailsErrorStateProps): JSX.Element {+ return (+ <div className="metric-details-error-state">+ <InfoIcon size={20} color={Color.BG_CHERRY_500} />+ <Typography.Text>{errorMessage}</Typography.Text>+ {refetch && <Button onClick={refetch}>Retry</Button>}+ </div>+ );+}++export default MetricDetailsErrorState;diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsxindex 7f748a4a19..7f31144549 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx@@ -1,11 +1,13 @@import * as reactUseHooks from 'react-use';-import { fireEvent, render, screen } from '@testing-library/react';-import { MetricType } from 'api/metricsExplorer/getMetricsList';+import { render, screen } from '@testing-library/react';+import * as metricsExplorerHooks from 'api/generated/services/metrics';+import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';import * as useHandleExplorerTabChange from 'hooks/useHandleExplorerTabChange';+import { userEvent } from 'tests/test-utils';-import { MetricDetailsAttribute } from '../../../../api/metricsExplorer/getMetricDetails';import ROUTES from '../../../../constants/routes';import AllAttributes, { AllAttributesValue } from '../AllAttributes';+import { getMockMetricAttributesData, MOCK_METRIC_NAME } from './testUtlls';jest.mock('react-router-dom', () => ({...jest.requireActual('react-router-dom'),@@ -20,33 +22,28 @@ jesthandleExplorerTabChange: mockHandleExplorerTabChange,});-const mockMetricName = 'test-metric';-const mockMetricType = MetricType.GAUGE;-const mockAttributes: MetricDetailsAttribute[] = [- {- key: 'attribute1',- value: ['value1', 'value2'],- valueCount: 2,- },- {- key: 'attribute2',- value: ['value3'],- valueCount: 1,- },-];-const mockUseCopyToClipboard = jest.fn();jest.spyOn(reactUseHooks, 'useCopyToClipboard').mockReturnValue([{ value: 'value1' }, mockUseCopyToClipboard] as any);+const useGetMetricAttributesMock = jest.spyOn(+ metricsExplorerHooks,+ 'useGetMetricAttributes',+);+describe('AllAttributes', () => {+ beforeEach(() => {+ useGetMetricAttributesMock.mockReturnValue({+ ...getMockMetricAttributesData(),+ });+ });+it('renders attributes section with title', () => {render(<AllAttributes- metricName={mockMetricName}- attributes={mockAttributes}- metricType={mockMetricType}+ metricName={MOCK_METRIC_NAME}+ metricType={MetrictypesTypeDTO.gauge}/>,);@@ -56,9 +53,8 @@ describe('AllAttributes', () => {it('renders all attribute keys and values', () => {render(<AllAttributes- metricName={mockMetricName}- attributes={mockAttributes}- metricType={mockMetricType}+ metricName={MOCK_METRIC_NAME}+ metricType={MetrictypesTypeDTO.gauge}/>,);@@ -75,9 +71,8 @@ describe('AllAttributes', () => {it('renders value counts correctly', () => {render(<AllAttributes- metricName={mockMetricName}- attributes={mockAttributes}- metricType={mockMetricType}+ metricName={MOCK_METRIC_NAME}+ metricType={MetrictypesTypeDTO.gauge}/>,);@@ -86,41 +81,44 @@ describe('AllAttributes', () => {});it('handles empty attributes array', () => {+ useGetMetricAttributesMock.mockReturnValue({+ ...getMockMetricAttributesData({+ data: {+ attributes: [],+ totalKeys: 0,+ },+ }),+ });render(<AllAttributes- metricName={mockMetricName}- attributes={[]}- metricType={mockMetricType}+ metricName={MOCK_METRIC_NAME}+ metricType={MetrictypesTypeDTO.gauge}/>,);expect(screen.getByText('All Attributes')).toBeInTheDocument();- expect(screen.queryByText('No data')).toBeInTheDocument();+ expect(screen.getByText('No attributes found')).toBeInTheDocument();});- it('clicking on an attribute key opens the explorer with the attribute filter applied', () => {+ it('clicking on an attribute key opens the explorer with the attribute filter applied', async () => {render(<AllAttributes- metricName={mockMetricName}- attributes={mockAttributes}- metricType={mockMetricType}+ metricName={MOCK_METRIC_NAME}+ metricType={MetrictypesTypeDTO.gauge}/>,);- fireEvent.click(screen.getByText('attribute1'));+ await userEvent.click(screen.getByText('attribute1'));expect(mockHandleExplorerTabChange).toHaveBeenCalled();});- it('filters attributes based on search input', () => {+ it('filters attributes based on search input', async () => {render(<AllAttributes- metricName={mockMetricName}- attributes={mockAttributes}- metricType={mockMetricType}+ metricName={MOCK_METRIC_NAME}+ metricType={MetrictypesTypeDTO.gauge}/>,);- fireEvent.change(screen.getByPlaceholderText('Search'), {- target: { value: 'value1' },- });+ await userEvent.type(screen.getByPlaceholderText('Search'), 'value1');expect(screen.getByText('attribute1')).toBeInTheDocument();expect(screen.getByText('value1')).toBeInTheDocument();@@ -144,7 +142,7 @@ describe('AllAttributesValue', () => {expect(screen.getByText('value2')).toBeInTheDocument();});- it('loads more attributes when show more button is clicked', () => {+ it('loads more attributes when show more button is clicked', async () => {render(<AllAttributesValuefilterKey="attribute1"@@ -155,7 +153,7 @@ describe('AllAttributesValue', () => {/>,);expect(screen.queryByText('value6')).not.toBeInTheDocument();- fireEvent.click(screen.getByText('Show More'));+ await userEvent.click(screen.getByText('Show More'));expect(screen.getByText('value6')).toBeInTheDocument();});@@ -172,7 +170,7 @@ describe('AllAttributesValue', () => {expect(screen.queryByText('Show More')).not.toBeInTheDocument();});- it('copy button should copy the attribute value to the clipboard', () => {+ it('copy button should copy the attribute value to the clipboard', async () => {render(<AllAttributesValuefilterKey="attribute1"@@ -183,13 +181,13 @@ describe('AllAttributesValue', () => {/>,);expect(screen.getByText('value1')).toBeInTheDocument();- fireEvent.click(screen.getByText('value1'));+ await userEvent.click(screen.getByText('value1'));expect(screen.getByText('Copy Attribute')).toBeInTheDocument();- fireEvent.click(screen.getByText('Copy Attribute'));+ await userEvent.click(screen.getByText('Copy Attribute'));expect(mockUseCopyToClipboard).toHaveBeenCalledWith('value1');});- it('explorer button should go to metrics explore with the attribute filter applied', () => {+ it('explorer button should go to metrics explore with the attribute filter applied', async () => {render(<AllAttributesValuefilterKey="attribute1"@@ -200,10 +198,10 @@ describe('AllAttributesValue', () => {/>,);expect(screen.getByText('value1')).toBeInTheDocument();- fireEvent.click(screen.getByText('value1'));+ await userEvent.click(screen.getByText('value1'));expect(screen.getByText('Open in Explorer')).toBeInTheDocument();- fireEvent.click(screen.getByText('Open in Explorer'));+ await userEvent.click(screen.getByText('Open in Explorer'));expect(mockGoToMetricsExploreWithAppliedAttribute).toHaveBeenCalledWith('attribute1','value1',diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/DashboardsAndAlertsPopover.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/DashboardsAndAlertsPopover.test.tsxindex f339a6e952..1b07a17d08 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/DashboardsAndAlertsPopover.test.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/DashboardsAndAlertsPopover.test.tsx@@ -1,26 +1,18 @@-import { fireEvent, render, screen } from '@testing-library/react';+import { render, screen } from '@testing-library/react';+import * as metricsExplorerHooks from 'api/generated/services/metrics';import { QueryParams } from 'constants/query';+import { userEvent } from 'tests/test-utils';import DashboardsAndAlertsPopover from '../DashboardsAndAlertsPopover';--const mockAlert1 = {- alert_id: '1',- alert_name: 'Alert 1',-};-const mockAlert2 = {- alert_id: '2',- alert_name: 'Alert 2',-};-const mockDashboard1 = {- dashboard_id: '1',- dashboard_name: 'Dashboard 1',-};-const mockDashboard2 = {- dashboard_id: '2',- dashboard_name: 'Dashboard 2',-};-const mockAlerts = [mockAlert1, mockAlert2];-const mockDashboards = [mockDashboard1, mockDashboard2];+import {+ getMockAlertsData,+ getMockDashboardsData,+ MOCK_ALERT_1,+ MOCK_ALERT_2,+ MOCK_DASHBOARD_1,+ MOCK_DASHBOARD_2,+ MOCK_METRIC_NAME,+} from './testUtlls';const mockSafeNavigate = jest.fn();jest.mock('hooks/useSafeNavigate', () => ({@@ -28,7 +20,6 @@ jest.mock('hooks/useSafeNavigate', () => ({safeNavigate: mockSafeNavigate,}),}));-const mockSetQuery = jest.fn();const mockUrlQuery = {set: mockSetQuery,@@ -39,125 +30,156 @@ jest.mock('hooks/useUrlQuery', () => ({default: jest.fn(() => mockUrlQuery),}));+const useGetMetricAlertsMock = jest.spyOn(+ metricsExplorerHooks,+ 'useGetMetricAlerts',+);+const useGetMetricDashboardsMock = jest.spyOn(+ metricsExplorerHooks,+ 'useGetMetricDashboards',+);+describe('DashboardsAndAlertsPopover', () => {+ beforeEach(() => {+ useGetMetricAlertsMock.mockReturnValue(getMockAlertsData());+ useGetMetricDashboardsMock.mockReturnValue(getMockDashboardsData());+ });+it('renders the popover correctly with multiple dashboards and alerts', () => {- render(- <DashboardsAndAlertsPopover- alerts={mockAlerts}- dashboards={mockDashboards}- />,- );+ render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);- expect(- screen.getByText(`${mockDashboards.length} dashboards`),- ).toBeInTheDocument();- expect(- screen.getByText(`${mockAlerts.length} alert rules`),- ).toBeInTheDocument();+ expect(screen.getByText(`2 dashboards`)).toBeInTheDocument();+ expect(screen.getByText(`2 alert rules`)).toBeInTheDocument();});it('renders null with no dashboards and alerts', () => {+ useGetMetricAlertsMock.mockReturnValue(+ getMockAlertsData({+ data: {+ alerts: [],+ },+ }),+ );+ useGetMetricDashboardsMock.mockReturnValue(+ getMockDashboardsData({+ data: {+ dashboards: [],+ },+ }),+ );+const { container } = render(- <DashboardsAndAlertsPopover alerts={[]} dashboards={[]} />,+ <DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />,);- expect(container).toBeEmptyDOMElement();+ expect(+ container.querySelector('dashboards-and-alerts-popover-container'),+ ).toBeNull();});it('renders popover with single dashboard and alert', () => {- render(- <DashboardsAndAlertsPopover- alerts={[mockAlert1]}- dashboards={[mockDashboard1]}- />,+ useGetMetricAlertsMock.mockReturnValue(+ getMockAlertsData({+ data: {+ alerts: [MOCK_ALERT_1],+ },+ }),+ );+ useGetMetricDashboardsMock.mockReturnValue(+ getMockDashboardsData({+ data: {+ dashboards: [MOCK_DASHBOARD_1],+ },+ }),);++ render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);+expect(screen.getByText(`1 dashboard`)).toBeInTheDocument();expect(screen.getByText(`1 alert rule`)).toBeInTheDocument();});- it('renders popover with dashboard id if name is not available', () => {- render(- <DashboardsAndAlertsPopover- alerts={mockAlerts}- dashboards={[{ ...mockDashboard1, dashboard_name: undefined } as any]}- />,+ it('renders popover with dashboard id if name is not available', async () => {+ useGetMetricDashboardsMock.mockReturnValue(+ getMockDashboardsData({+ data: {+ dashboards: [{ ...MOCK_DASHBOARD_1, dashboardName: '' }],+ },+ }),);- fireEvent.click(screen.getByText(`1 dashboard`));- expect(screen.getByText(mockDashboard1.dashboard_id)).toBeInTheDocument();+ render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);++ await userEvent.click(screen.getByText(`1 dashboard`));+ expect(screen.getByText(MOCK_DASHBOARD_1.dashboardId)).toBeInTheDocument();});- it('renders popover with alert id if name is not available', () => {- render(- <DashboardsAndAlertsPopover- alerts={[{ ...mockAlert1, alert_name: undefined } as any]}- dashboards={mockDashboards}- />,+ it('renders popover with alert id if name is not available', async () => {+ useGetMetricAlertsMock.mockReturnValue(+ getMockAlertsData({+ data: {+ alerts: [{ ...MOCK_ALERT_1, alertName: '' }],+ },+ }),);- fireEvent.click(screen.getByText(`1 alert rule`));- expect(screen.getByText(mockAlert1.alert_id)).toBeInTheDocument();+ render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);++ await userEvent.click(screen.getByText(`1 alert rule`));+ expect(screen.getByText(MOCK_ALERT_1.alertId)).toBeInTheDocument();});- it('navigates to the dashboard when the dashboard is clicked', () => {- render(- <DashboardsAndAlertsPopover- alerts={mockAlerts}- dashboards={mockDashboards}- />,- );+ it('navigates to the dashboard when the dashboard is clicked', async () => {+ render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);// Click on 2 dashboards button- fireEvent.click(screen.getByText(`${mockDashboards.length} dashboards`));+ await userEvent.click(screen.getByText(`2 dashboards`));// Popover showing list of 2 dashboards should be visible- expect(screen.getByText(mockDashboard1.dashboard_name)).toBeInTheDocument();- expect(screen.getByText(mockDashboard2.dashboard_name)).toBeInTheDocument();+ expect(screen.getByText(MOCK_DASHBOARD_1.dashboardName)).toBeInTheDocument();+ expect(screen.getByText(MOCK_DASHBOARD_2.dashboardName)).toBeInTheDocument();// Click on the first dashboard- fireEvent.click(screen.getByText(mockDashboard1.dashboard_name));+ await userEvent.click(screen.getByText(MOCK_DASHBOARD_1.dashboardName));// Should navigate to the dashboardexpect(mockSafeNavigate).toHaveBeenCalledWith(- `/dashboard/${mockDashboard1.dashboard_id}`,+ `/dashboard/${MOCK_DASHBOARD_1.dashboardId}`,);});- it('navigates to the alert when the alert is clicked', () => {- render(- <DashboardsAndAlertsPopover- alerts={mockAlerts}- dashboards={mockDashboards}- />,- );+ it('navigates to the alert when the alert is clicked', async () => {+ render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);// Click on 2 alert rules button- fireEvent.click(screen.getByText(`${mockAlerts.length} alert rules`));+ await userEvent.click(screen.getByText(`2 alert rules`));// Popover showing list of 2 alert rules should be visible- expect(screen.getByText(mockAlert1.alert_name)).toBeInTheDocument();- expect(screen.getByText(mockAlert2.alert_name)).toBeInTheDocument();+ expect(screen.getByText(MOCK_ALERT_1.alertName)).toBeInTheDocument();+ expect(screen.getByText(MOCK_ALERT_2.alertName)).toBeInTheDocument();// Click on the first alert rule- fireEvent.click(screen.getByText(mockAlert1.alert_name));+ await userEvent.click(screen.getByText(MOCK_ALERT_1.alertName));// Should navigate to the alert ruleexpect(mockSetQuery).toHaveBeenCalledWith(QueryParams.ruleId,- mockAlert1.alert_id,+ MOCK_ALERT_1.alertId,);});- it('renders unique dashboards even when there are duplicates', () => {- render(- <DashboardsAndAlertsPopover- alerts={mockAlerts}- dashboards={[...mockDashboards, mockDashboard1]}- />,+ it('renders unique dashboards even when there are duplicates', async () => {+ useGetMetricDashboardsMock.mockReturnValue(+ getMockDashboardsData({+ data: {+ dashboards: [MOCK_DASHBOARD_1, MOCK_DASHBOARD_2, MOCK_DASHBOARD_1],+ },+ }),);- expect(- screen.getByText(`${mockDashboards.length} dashboards`),- ).toBeInTheDocument();- fireEvent.click(screen.getByText(`${mockDashboards.length} dashboards`));- expect(screen.getByText(mockDashboard1.dashboard_name)).toBeInTheDocument();- expect(screen.getByText(mockDashboard2.dashboard_name)).toBeInTheDocument();+ render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);++ expect(screen.getByText('2 dashboards')).toBeInTheDocument();++ await userEvent.click(screen.getByText('2 dashboards'));+ expect(screen.getByText(MOCK_DASHBOARD_1.dashboardName)).toBeInTheDocument();+ expect(screen.getByText(MOCK_DASHBOARD_2.dashboardName)).toBeInTheDocument();});});diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Highlights.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Highlights.test.tsxnew file mode 100644index 0000000000..aef3f34c4f--- /dev/null+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Highlights.test.tsx@@ -0,0 +1,67 @@+import { render, screen } from '@testing-library/react';+import * as metricsExplorerHooks from 'api/generated/services/metrics';++import Highlights from '../Highlights';+import { formatTimestampToReadableDate } from '../utils';+import { getMockMetricHighlightsData, MOCK_METRIC_NAME } from './testUtlls';++const useGetMetricHighlightsMock = jest.spyOn(+ metricsExplorerHooks,+ 'useGetMetricHighlights',+);++describe('Highlights', () => {+ beforeEach(() => {+ useGetMetricHighlightsMock.mockReturnValue(getMockMetricHighlightsData());+ });++ it('should render all highlights data correctly', () => {+ render(<Highlights metricName={MOCK_METRIC_NAME} />);++ const dataPoints = screen.getByTestId('metric-highlights-data-points');+ const timeSeriesTotal = screen.getByTestId(+ 'metric-highlights-time-series-total',+ );+ const lastReceived = screen.getByTestId('metric-highlights-last-received');++ expect(dataPoints.textContent).toBe('1M+');+ expect(timeSeriesTotal.textContent).toBe('1M total ⎯ 1M active');+ expect(lastReceived.textContent).toBe(+ formatTimestampToReadableDate('2026-01-24T00:00:00Z'),+ );+ });++ it('should render error state correctly', () => {+ useGetMetricHighlightsMock.mockReturnValue(+ getMockMetricHighlightsData(+ {},+ {+ isError: true,+ },+ ),+ );++ render(<Highlights metricName={MOCK_METRIC_NAME} />);++ expect(+ screen.getByTestId('metric-highlights-error-state'),+ ).toBeInTheDocument();+ });++ it('should render loading state when data is loading', () => {+ useGetMetricHighlightsMock.mockReturnValue(+ getMockMetricHighlightsData(+ {},+ {+ isLoading: true,+ },+ ),+ );++ render(<Highlights metricName={MOCK_METRIC_NAME} />);++ expect(+ screen.getByTestId('metric-highlights-loading-state'),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Metadata.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Metadata.test.tsxindex 63e57753d8..086c148e16 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Metadata.test.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Metadata.test.tsx@@ -1,16 +1,24 @@/* eslint-disable sonarjs/no-duplicate-string */-import { fireEvent, render, screen } from '@testing-library/react';+import { render, screen } from '@testing-library/react';+import * as metricsExplorerHooks from 'api/generated/services/metrics';+import {+ GetMetricMetadata200,+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+} from 'api/generated/services/sigNoz.schemas';import { Temporality } from 'api/metricsExplorer/getMetricDetails';-import { MetricType } from 'api/metricsExplorer/getMetricsList';import {UniversalYAxisUnit,YAxisUnitSelectorProps,} from 'components/YAxisUnitSelector/types';-import * as useUpdateMetricMetadataHooks from 'hooks/metricsExplorer/useUpdateMetricMetadata';import * as useNotificationsHooks from 'hooks/useNotifications';+import { userEvent } from 'tests/test-utils';import { SelectOption } from 'types/common/select';import Metadata from '../Metadata';+import { MetricMetadata } from '../types';+import { transformMetricMetadata } from '../utils';+import { getMockMetricMetadataData, MOCK_METRIC_NAME } from './testUtlls';// Mock antd select for testingjest.mock('antd', () => ({@@ -72,13 +80,18 @@ jest.mock('react-query', () => ({}),}));+const mockUseUpdateMetricMetadataHook = jest.spyOn(+ metricsExplorerHooks,+ 'useUpdateMetricMetadata',+);+type UseUpdateMetricMetadataResult = ReturnType<+ typeof metricsExplorerHooks.useUpdateMetricMetadata+>;const mockUseUpdateMetricMetadata = jest.fn();-jest- .spyOn(useUpdateMetricMetadataHooks, 'useUpdateMetricMetadata')- .mockReturnValue({- mutate: mockUseUpdateMetricMetadata,- isLoading: false,- } as any);++const mockMetricMetadata = transformMetricMetadata(+ getMockMetricMetadataData().data as GetMetricMetadata200,+) as MetricMetadata;const mockErrorNotification = jest.fn();const mockSuccessNotification = jest.fn();@@ -89,47 +102,50 @@ jest.spyOn(useNotificationsHooks, 'useNotifications').mockReturnValue({},} as any);-const mockMetricName = 'test_metric';-const mockMetricMetadata = {- metric_type: MetricType.GAUGE,- description: 'test_description',- unit: 'test_unit',- temporality: Temporality.DELTA,-};-const mockRefetchMetricDetails = jest.fn();+const mockRefetchMetricMetadata = jest.fn();describe('Metadata', () => {+ beforeEach(() => {+ mockUseUpdateMetricMetadataHook.mockReturnValue(({+ mutate: mockUseUpdateMetricMetadata,+ } as Partial<UseUpdateMetricMetadataResult>) as UseUpdateMetricMetadataResult);+ });+it('should render the metadata properly', () => {render(<Metadata- metricName={mockMetricName}+ metricName={MOCK_METRIC_NAME}metadata={mockMetricMetadata}- refetchMetricDetails={mockRefetchMetricDetails}+ isErrorMetricMetadata={false}+ isLoadingMetricMetadata={false}+ refetchMetricMetadata={mockRefetchMetricMetadata}/>,);expect(screen.getByText('Metric Type')).toBeInTheDocument();- expect(screen.getByText(mockMetricMetadata.metric_type)).toBeInTheDocument();+ expect(screen.getByText('Gauge')).toBeInTheDocument();expect(screen.getByText('Description')).toBeInTheDocument();expect(screen.getByText(mockMetricMetadata.description)).toBeInTheDocument();expect(screen.getByText('Unit')).toBeInTheDocument();expect(screen.getByText(mockMetricMetadata.unit)).toBeInTheDocument();expect(screen.getByText('Temporality')).toBeInTheDocument();- expect(screen.getByText(mockMetricMetadata.temporality)).toBeInTheDocument();+ expect(screen.getByText('Delta')).toBeInTheDocument();});- it('editing the metadata should show the form inputs', () => {+ it('editing the metadata should show the form inputs', async () => {render(<Metadata- metricName={mockMetricName}+ metricName={MOCK_METRIC_NAME}metadata={mockMetricMetadata}- refetchMetricDetails={mockRefetchMetricDetails}+ isErrorMetricMetadata={false}+ isLoadingMetricMetadata={false}+ refetchMetricMetadata={mockRefetchMetricMetadata}/>,);const editButton = screen.getByText('Edit');expect(editButton).toBeInTheDocument();- fireEvent.click(editButton);+ await userEvent.click(editButton);expect(screen.getByTestId('metric-type-select')).toBeInTheDocument();expect(screen.getByTestId('temporality-select')).toBeInTheDocument();@@ -139,57 +155,53 @@ describe('Metadata', () => {it('should update the metadata when the form is submitted', async () => {render(<Metadata- metricName={mockMetricName}+ metricName={MOCK_METRIC_NAME}metadata={{...mockMetricMetadata,unit: '',}}- refetchMetricDetails={mockRefetchMetricDetails}+ isErrorMetricMetadata={false}+ isLoadingMetricMetadata={false}+ refetchMetricMetadata={mockRefetchMetricMetadata}/>,);const editButton = screen.getByText('Edit');expect(editButton).toBeInTheDocument();- fireEvent.click(editButton);+ await userEvent.click(editButton);const metricDescriptionInput = screen.getByTestId('description-input');expect(metricDescriptionInput).toBeInTheDocument();- fireEvent.change(metricDescriptionInput, {- target: { value: 'Updated description' },- });+ await userEvent.clear(metricDescriptionInput);+ await userEvent.type(metricDescriptionInput, 'Updated description');const metricTypeSelect = screen.getByTestId('metric-type-select');expect(metricTypeSelect).toBeInTheDocument();- fireEvent.change(metricTypeSelect, {- target: { value: MetricType.SUM },- });+ await userEvent.selectOptions(metricTypeSelect, MetrictypesTypeDTO.sum);const temporalitySelect = screen.getByTestId('temporality-select');expect(temporalitySelect).toBeInTheDocument();- fireEvent.change(temporalitySelect, {- target: { value: Temporality.CUMULATIVE },- });+ await userEvent.selectOptions(temporalitySelect, Temporality.CUMULATIVE);const unitSelect = screen.getByTestId('unit-select');expect(unitSelect).toBeInTheDocument();- fireEvent.change(unitSelect, {- target: { value: 'By' },- });+ await userEvent.selectOptions(unitSelect, 'By');const saveButton = screen.getByText('Save');expect(saveButton).toBeInTheDocument();- fireEvent.click(saveButton);+ await userEvent.click(saveButton);expect(mockUseUpdateMetricMetadata).toHaveBeenCalledWith(expect.objectContaining({- metricName: mockMetricName,- payload: expect.objectContaining({- description: 'Updated description',- metricType: MetricType.SUM,- temporality: Temporality.CUMULATIVE,+ data: expect.objectContaining({+ type: MetrictypesTypeDTO.sum,+ temporality: MetrictypesTemporalityDTO.cumulative,unit: 'By',isMonotonic: true,}),+ pathParams: {+ metricName: MOCK_METRIC_NAME,+ },}),expect.objectContaining({onSuccess: expect.any(Function),@@ -201,56 +213,56 @@ describe('Metadata', () => {it('should show success notification when metadata is updated successfully', async () => {render(<Metadata- metricName={mockMetricName}+ metricName={MOCK_METRIC_NAME}metadata={mockMetricMetadata}- refetchMetricDetails={mockRefetchMetricDetails}+ isErrorMetricMetadata={false}+ isLoadingMetricMetadata={false}+ refetchMetricMetadata={mockRefetchMetricMetadata}/>,);const editButton = screen.getByText('Edit');- fireEvent.click(editButton);+ await userEvent.click(editButton);const metricDescriptionInput = screen.getByTestId('description-input');- fireEvent.change(metricDescriptionInput, {- target: { value: 'Updated description' },- });+ await userEvent.clear(metricDescriptionInput);+ await userEvent.type(metricDescriptionInput, 'Updated description');const saveButton = screen.getByText('Save');- fireEvent.click(saveButton);+ await userEvent.click(saveButton);const onSuccessCallback =mockUseUpdateMetricMetadata.mock.calls[0][1].onSuccess;- onSuccessCallback({ statusCode: 200 });+ onSuccessCallback({ status: 200 });expect(mockSuccessNotification).toHaveBeenCalledWith({message: 'Metadata updated successfully',});- expect(mockRefetchMetricDetails).toHaveBeenCalled();});it('should show error notification when metadata update fails with non-200 response', async () => {render(<Metadata- metricName={mockMetricName}+ metricName={MOCK_METRIC_NAME}metadata={mockMetricMetadata}- refetchMetricDetails={mockRefetchMetricDetails}+ isErrorMetricMetadata={false}+ isLoadingMetricMetadata={false}+ refetchMetricMetadata={mockRefetchMetricMetadata}/>,);const editButton = screen.getByText('Edit');- fireEvent.click(editButton);+ await userEvent.click(editButton);const metricDescriptionInput = screen.getByTestId('description-input');- fireEvent.change(metricDescriptionInput, {- target: { value: 'Updated description' },- });+ await userEvent.clear(metricDescriptionInput);+ await userEvent.type(metricDescriptionInput, 'Updated description');const saveButton = screen.getByText('Save');- fireEvent.click(saveButton);+ await userEvent.click(saveButton);- const onSuccessCallback =- mockUseUpdateMetricMetadata.mock.calls[0][1].onSuccess;- onSuccessCallback({ statusCode: 500 });+ const onErrorCallback = mockUseUpdateMetricMetadata.mock.calls[0][1].onError;+ onErrorCallback({ status: 500 });expect(mockErrorNotification).toHaveBeenCalledWith({message:@@ -261,22 +273,23 @@ describe('Metadata', () => {it('should show error notification when metadata update fails', async () => {render(<Metadata- metricName={mockMetricName}+ metricName={MOCK_METRIC_NAME}metadata={mockMetricMetadata}- refetchMetricDetails={mockRefetchMetricDetails}+ isErrorMetricMetadata={false}+ isLoadingMetricMetadata={false}+ refetchMetricMetadata={mockRefetchMetricMetadata}/>,);const editButton = screen.getByText('Edit');- fireEvent.click(editButton);+ await userEvent.click(editButton);const metricDescriptionInput = screen.getByTestId('description-input');- fireEvent.change(metricDescriptionInput, {- target: { value: 'Updated description' },- });+ await userEvent.clear(metricDescriptionInput);+ await userEvent.type(metricDescriptionInput, 'Updated description');const saveButton = screen.getByText('Save');- fireEvent.click(saveButton);+ await userEvent.click(saveButton);const onErrorCallback = mockUseUpdateMetricMetadata.mock.calls[0][1].onError;@@ -289,39 +302,43 @@ describe('Metadata', () => {});});- it('cancel button should cancel the edit mode', () => {+ it('cancel button should cancel the edit mode', async () => {render(<Metadata- metricName={mockMetricName}+ metricName={MOCK_METRIC_NAME}metadata={mockMetricMetadata}- refetchMetricDetails={mockRefetchMetricDetails}+ isErrorMetricMetadata={false}+ isLoadingMetricMetadata={false}+ refetchMetricMetadata={mockRefetchMetricMetadata}/>,);const editButton = screen.getByText('Edit');expect(editButton).toBeInTheDocument();- fireEvent.click(editButton);+ await userEvent.click(editButton);const cancelButton = screen.getByText('Cancel');expect(cancelButton).toBeInTheDocument();- fireEvent.click(cancelButton);+ await userEvent.click(cancelButton);const editButton2 = screen.getByText('Edit');expect(editButton2).toBeInTheDocument();});- it('should not allow editing of unit if it is already set', () => {+ it('should not allow editing of unit if it is already set', async () => {render(<Metadata- metricName={mockMetricName}+ metricName={MOCK_METRIC_NAME}metadata={mockMetricMetadata}- refetchMetricDetails={mockRefetchMetricDetails}+ isErrorMetricMetadata={false}+ isLoadingMetricMetadata={false}+ refetchMetricMetadata={mockRefetchMetricMetadata}/>,);const editButton = screen.getByText('Edit');expect(editButton).toBeInTheDocument();- fireEvent.click(editButton);+ await userEvent.click(editButton);const unitSelect = screen.queryByTestId('unit-select');expect(unitSelect).not.toBeInTheDocument();diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsxindex 335572d714..a63ed44ce5 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx@@ -1,68 +1,16 @@-import { fireEvent, render, screen } from '@testing-library/react';-import { MetricDetails as MetricDetailsType } from 'api/metricsExplorer/getMetricDetails';-import { MetricType } from 'api/metricsExplorer/getMetricsList';-import { getUniversalNameFromMetricUnit } from 'components/YAxisUnitSelector/utils';+import { render, screen } from '@testing-library/react';+import * as metricsExplorerHooks from 'api/generated/services/metrics';import ROUTES from 'constants/routes';-import * as useGetMetricDetails from 'hooks/metricsExplorer/useGetMetricDetails';-import * as useUpdateMetricMetadata from 'hooks/metricsExplorer/useUpdateMetricMetadata';import * as useHandleExplorerTabChange from 'hooks/useHandleExplorerTabChange';+import { userEvent } from 'tests/test-utils';import MetricDetails from '../MetricDetails';+import { getMockMetricMetadataData } from './testUtlls';const mockMetricName = 'test-metric';-const mockMetricDescription = 'description for a test metric';-const mockMetricData: MetricDetailsType = {- name: mockMetricName,- description: mockMetricDescription,- unit: 'count',- attributes: [- {- key: 'test-attribute',- value: ['test-value'],- valueCount: 1,- },- ],- alerts: [],- dashboards: [],- metadata: {- metric_type: MetricType.SUM,- description: mockMetricDescription,- unit: 'count',- },- type: '',- timeseries: 0,- samples: 0,- timeSeriesTotal: 0,- timeSeriesActive: 0,- lastReceived: '',-};const mockOpenInspectModal = jest.fn();const mockOnClose = jest.fn();-const mockUseGetMetricDetailsData = {- data: {- payload: {- data: mockMetricData,- },- },- isLoading: false,- isFetching: false,- isError: false,- error: null,- refetch: jest.fn(),-};--jest- .spyOn(useGetMetricDetails, 'useGetMetricDetails')- .mockReturnValue(mockUseGetMetricDetailsData as any);--jest.spyOn(useUpdateMetricMetadata, 'useUpdateMetricMetadata').mockReturnValue({- mutate: jest.fn(),- isLoading: false,- isError: false,- error: null,-} as any);-const mockHandleExplorerTabChange = jest.fn();jest.spyOn(useHandleExplorerTabChange, 'useHandleExplorerTabChange')@@ -88,7 +36,50 @@ jest.mock('react-query', () => ({}),}));+jest.mock(+ 'container/MetricsExplorer/MetricDetails/AllAttributes',+ () =>+ function MockAllAttributes(): JSX.Element {+ return <div data-testid="all-attributes">All Attributes</div>;+ },+);+jest.mock(+ 'container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover',+ () =>+ function MockDashboardsAndAlertsPopover(): JSX.Element {+ return (+ <div data-testid="dashboards-and-alerts-popover">+ Dashboards and Alerts Popover+ </div>+ );+ },+);+jest.mock(+ 'container/MetricsExplorer/MetricDetails/Highlights',+ () =>+ function MockHighlights(): JSX.Element {+ return <div data-testid="highlights">Highlights</div>;+ },+);++jest.mock(+ 'container/MetricsExplorer/MetricDetails/Metadata',+ () =>+ function MockMetadata(): JSX.Element {+ return <div data-testid="metadata">Metadata</div>;+ },+);++const useGetMetricMetadataMock = jest.spyOn(+ metricsExplorerHooks,+ 'useGetMetricMetadata',+);+describe('MetricDetails', () => {+ beforeEach(() => {+ useGetMetricMetadataMock.mockReturnValue(getMockMetricMetadataData());+ });+it('renders metric details correctly', () => {render(<MetricDetails@@ -101,27 +92,15 @@ describe('MetricDetails', () => {);expect(screen.getByText(mockMetricName)).toBeInTheDocument();- expect(screen.getByText(mockMetricDescription)).toBeInTheDocument();+ expect(screen.getByTestId('all-attributes')).toBeInTheDocument();expect(- screen.getByText(getUniversalNameFromMetricUnit(mockMetricData.unit)),+ screen.getByTestId('dashboards-and-alerts-popover'),).toBeInTheDocument();+ expect(screen.getByTestId('highlights')).toBeInTheDocument();+ expect(screen.getByTestId('metadata')).toBeInTheDocument();});- it('renders the "open in explorer" and "inspect" buttons', () => {- jest.spyOn(useGetMetricDetails, 'useGetMetricDetails').mockReturnValueOnce({- ...mockUseGetMetricDetailsData,- data: {- payload: {- data: {- ...mockMetricData,- metadata: {- ...mockMetricData.metadata,- metric_type: MetricType.GAUGE,- },- },- },- },- } as any);+ it('renders the "open in explorer" and "inspect" buttons', async () => {render(<MetricDetailsonClose={mockOnClose}@@ -135,93 +114,10 @@ describe('MetricDetails', () => {expect(screen.getByTestId('open-in-explorer-button')).toBeInTheDocument();expect(screen.getByTestId('inspect-metric-button')).toBeInTheDocument();- fireEvent.click(screen.getByTestId('open-in-explorer-button'));+ await userEvent.click(screen.getByTestId('open-in-explorer-button'));expect(mockHandleExplorerTabChange).toHaveBeenCalled();- fireEvent.click(screen.getByTestId('inspect-metric-button'));+ await userEvent.click(screen.getByTestId('inspect-metric-button'));expect(mockOpenInspectModal).toHaveBeenCalled();});-- it('should render error state when metric details are not found', () => {- jest.spyOn(useGetMetricDetails, 'useGetMetricDetails').mockReturnValue({- ...mockUseGetMetricDetailsData,- isError: true,- error: {- message: 'Error fetching metric details',- },- } as any);-- render(- <MetricDetails- onClose={mockOnClose}- isOpen- metricName={mockMetricName}- isModalTimeSelection- openInspectModal={mockOpenInspectModal}- />,- );-- expect(screen.getByText('Error fetching metric details')).toBeInTheDocument();- });-- it('should render loading state when metric details are loading', () => {- jest.spyOn(useGetMetricDetails, 'useGetMetricDetails').mockReturnValue({- ...mockUseGetMetricDetailsData,- isLoading: true,- } as any);-- render(- <MetricDetails- onClose={mockOnClose}- isOpen- metricName={mockMetricName}- isModalTimeSelection- openInspectModal={mockOpenInspectModal}- />,- );-- expect(screen.getByTestId('metric-details-skeleton')).toBeInTheDocument();- });-- it('should render all attributes section', () => {- jest- .spyOn(useGetMetricDetails, 'useGetMetricDetails')- .mockReturnValue(mockUseGetMetricDetailsData as any);- render(- <MetricDetails- onClose={mockOnClose}- isOpen- metricName={mockMetricName}- isModalTimeSelection- openInspectModal={mockOpenInspectModal}- />,- );-- expect(screen.getByText('All Attributes')).toBeInTheDocument();- });-- it('should not render all attributes section when relevant data is not present', () => {- jest.spyOn(useGetMetricDetails, 'useGetMetricDetails').mockReturnValue({- ...mockUseGetMetricDetailsData,- data: {- payload: {- data: {- ...mockMetricData,- attributes: null,- },- },- },- } as any);- render(- <MetricDetails- onClose={mockOnClose}- isOpen- metricName={mockMetricName}- isModalTimeSelection- openInspectModal={mockOpenInspectModal}- />,- );-- expect(screen.queryByText('All Attributes')).not.toBeInTheDocument();- });});diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/testUtlls.ts b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/testUtlls.tsnew file mode 100644index 0000000000..0879546cd4--- /dev/null+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/testUtlls.ts@@ -0,0 +1,168 @@+import * as metricsExplorerHooks from 'api/generated/services/metrics';+import {+ GetMetricAlerts200,+ GetMetricAttributes200,+ GetMetricDashboards200,+ GetMetricHighlights200,+ GetMetricMetadata200,+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+} from 'api/generated/services/sigNoz.schemas';++export const MOCK_METRIC_NAME = 'test-metric';++export function getMockMetricHighlightsData(+ overrides?: Partial<GetMetricHighlights200>,+ {+ isLoading = false,+ isError = false,+ }: {+ isLoading?: boolean;+ isError?: boolean;+ } = {},+): ReturnType<typeof metricsExplorerHooks.useGetMetricHighlights> {+ return {+ data: {+ data: {+ dataPoints: 1000000,+ lastReceived: '2026-01-24T00:00:00Z',+ totalTimeSeries: 1000000,+ activeTimeSeries: 1000000,+ },+ status: 'success',+ ...overrides,+ },+ isLoading,+ isError,+ } as ReturnType<typeof metricsExplorerHooks.useGetMetricHighlights>;+}++export const MOCK_DASHBOARD_1 = {+ dashboardName: 'Dashboard 1',+ dashboardId: '1',+ widgetId: '1',+ widgetName: 'Widget 1',+};+export const MOCK_DASHBOARD_2 = {+ dashboardName: 'Dashboard 2',+ dashboardId: '2',+ widgetId: '2',+ widgetName: 'Widget 2',+};+export const MOCK_ALERT_1 = {+ alertName: 'Alert 1',+ alertId: '1',+};+export const MOCK_ALERT_2 = {+ alertName: 'Alert 2',+ alertId: '2',+};++export function getMockDashboardsData(+ overrides?: Partial<GetMetricDashboards200>,+ {+ isLoading = false,+ isError = false,+ }: {+ isLoading?: boolean;+ isError?: boolean;+ } = {},+): ReturnType<typeof metricsExplorerHooks.useGetMetricDashboards> {+ return {+ data: {+ data: {+ dashboards: [MOCK_DASHBOARD_1, MOCK_DASHBOARD_2],+ },+ status: 'success',+ ...overrides,+ },++ isLoading,+ isError,+ } as ReturnType<typeof metricsExplorerHooks.useGetMetricDashboards>;+}++export function getMockAlertsData(+ overrides?: Partial<GetMetricAlerts200>,+ {+ isLoading = false,+ isError = false,+ }: {+ isLoading?: boolean;+ isError?: boolean;+ } = {},+): ReturnType<typeof metricsExplorerHooks.useGetMetricAlerts> {+ return {+ data: {+ data: {+ alerts: [MOCK_ALERT_1, MOCK_ALERT_2],+ },+ status: 'success',+ ...overrides,+ },+ isLoading,+ isError,+ } as ReturnType<typeof metricsExplorerHooks.useGetMetricAlerts>;+}++export function getMockMetricAttributesData(+ overrides?: Partial<GetMetricAttributes200>,+ {+ isLoading = false,+ isError = false,+ }: {+ isLoading?: boolean;+ isError?: boolean;+ } = {},+): ReturnType<typeof metricsExplorerHooks.useGetMetricAttributes> {+ return {+ data: {+ data: {+ attributes: [+ {+ key: 'attribute1',+ values: ['value1', 'value2'],+ valueCount: 2,+ },+ {+ key: 'attribute2',+ values: ['value3'],+ valueCount: 1,+ },+ ],+ totalKeys: 2,+ },+ status: 'success',+ ...overrides,+ },+ isLoading,+ isError,+ } as ReturnType<typeof metricsExplorerHooks.useGetMetricAttributes>;+}++export function getMockMetricMetadataData(+ overrides?: Partial<GetMetricMetadata200>,+ {+ isLoading = false,+ isError = false,+ }: {+ isLoading?: boolean;+ isError?: boolean;+ } = {},+): ReturnType<typeof metricsExplorerHooks.useGetMetricMetadata> {+ return {+ data: {+ data: {+ description: 'test_description',+ type: MetrictypesTypeDTO.gauge,+ unit: 'test_unit',+ temporality: MetrictypesTemporalityDTO.delta,+ isMonotonic: false,+ },+ status: 'success',+ ...overrides,+ },+ isLoading,+ isError,+ } as ReturnType<typeof metricsExplorerHooks.useGetMetricMetadata>;+}diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/utils.test.ts b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/utils.test.tsindex d9fb6a9c67..35ceb67a9a 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/utils.test.ts+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/utils.test.ts@@ -1,5 +1,7 @@-import { Temporality } from 'api/metricsExplorer/getMetricDetails';-import { MetricType } from 'api/metricsExplorer/getMetricsList';+import {+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+} from 'api/generated/services/sigNoz.schemas';import {determineIsMonotonic,@@ -10,35 +12,48 @@ import {describe('MetricDetails utils', () => {describe('determineIsMonotonic', () => {it('should return true for histogram metrics', () => {- expect(determineIsMonotonic(MetricType.HISTOGRAM)).toBe(true);+ expect(determineIsMonotonic(MetrictypesTypeDTO.histogram)).toBe(true);});it('should return true for exponential histogram metrics', () => {- expect(determineIsMonotonic(MetricType.EXPONENTIAL_HISTOGRAM)).toBe(true);+ expect(determineIsMonotonic(MetrictypesTypeDTO.exponentialhistogram)).toBe(+ true,+ );});it('should return false for gauge metrics', () => {- expect(determineIsMonotonic(MetricType.GAUGE)).toBe(false);+ expect(determineIsMonotonic(MetrictypesTypeDTO.gauge)).toBe(false);});it('should return false for summary metrics', () => {- expect(determineIsMonotonic(MetricType.SUMMARY)).toBe(false);+ expect(determineIsMonotonic(MetrictypesTypeDTO.summary)).toBe(false);});it('should return true for sum metrics with cumulative temporality', () => {- expect(determineIsMonotonic(MetricType.SUM, Temporality.CUMULATIVE)).toBe(- true,- );+ expect(+ determineIsMonotonic(+ MetrictypesTypeDTO.sum,+ MetrictypesTemporalityDTO.cumulative,+ ),+ ).toBe(true);});it('should return false for sum metrics with delta temporality', () => {- expect(determineIsMonotonic(MetricType.SUM, Temporality.DELTA)).toBe(false);+ expect(+ determineIsMonotonic(+ MetrictypesTypeDTO.sum,+ MetrictypesTemporalityDTO.delta,+ ),+ ).toBe(false);});it('should return false by default', () => {- expect(determineIsMonotonic('' as MetricType, '' as Temporality)).toBe(- false,- );+ expect(+ determineIsMonotonic(+ '' as MetrictypesTypeDTO,+ '' as MetrictypesTemporalityDTO,+ ),+ ).toBe(false);});});@@ -115,13 +130,16 @@ describe('MetricDetails utils', () => {const API_GATEWAY = 'api-gateway';it('should create correct query for SUM metric type', () => {- const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.SUM);+ const query = getMetricDetailsQuery(+ TEST_METRIC_NAME,+ MetrictypesTypeDTO.sum,+ );expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(TEST_METRIC_NAME,);expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(- MetricType.SUM,+ MetrictypesTypeDTO.sum,);expect(query.builder.queryData[0]?.aggregateOperator).toBe('rate');expect(query.builder.queryData[0]?.timeAggregation).toBe('rate');@@ -129,13 +147,16 @@ describe('MetricDetails utils', () => {});it('should create correct query for GAUGE metric type', () => {- const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.GAUGE);+ const query = getMetricDetailsQuery(+ TEST_METRIC_NAME,+ MetrictypesTypeDTO.gauge,+ );expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(TEST_METRIC_NAME,);expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(- MetricType.GAUGE,+ MetrictypesTypeDTO.gauge,);expect(query.builder.queryData[0]?.aggregateOperator).toBe('avg');expect(query.builder.queryData[0]?.timeAggregation).toBe('avg');@@ -143,13 +164,16 @@ describe('MetricDetails utils', () => {});it('should create correct query for SUMMARY metric type', () => {- const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.SUMMARY);+ const query = getMetricDetailsQuery(+ TEST_METRIC_NAME,+ MetrictypesTypeDTO.summary,+ );expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(TEST_METRIC_NAME,);expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(- MetricType.SUMMARY,+ MetrictypesTypeDTO.summary,);expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');@@ -157,13 +181,16 @@ describe('MetricDetails utils', () => {});it('should create correct query for HISTOGRAM metric type', () => {- const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.HISTOGRAM);+ const query = getMetricDetailsQuery(+ TEST_METRIC_NAME,+ MetrictypesTypeDTO.histogram,+ );expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(TEST_METRIC_NAME,);expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(- MetricType.HISTOGRAM,+ MetrictypesTypeDTO.histogram,);expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');@@ -173,14 +200,14 @@ describe('MetricDetails utils', () => {it('should create correct query for EXPONENTIAL_HISTOGRAM metric type', () => {const query = getMetricDetailsQuery(TEST_METRIC_NAME,- MetricType.EXPONENTIAL_HISTOGRAM,+ MetrictypesTypeDTO.exponentialhistogram,);expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(TEST_METRIC_NAME,);expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(- MetricType.EXPONENTIAL_HISTOGRAM,+ MetrictypesTypeDTO.exponentialhistogram,);expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');@@ -203,7 +230,7 @@ describe('MetricDetails utils', () => {const filter = { key: 'service', value: API_GATEWAY };const query = getMetricDetailsQuery(TEST_METRIC_NAME,- MetricType.SUM,+ MetrictypesTypeDTO.sum,filter,);@@ -221,7 +248,7 @@ describe('MetricDetails utils', () => {const groupBy = 'service';const query = getMetricDetailsQuery(TEST_METRIC_NAME,- MetricType.SUM,+ MetrictypesTypeDTO.sum,undefined,groupBy,);@@ -236,7 +263,7 @@ describe('MetricDetails utils', () => {const groupBy = 'endpoint';const query = getMetricDetailsQuery(TEST_METRIC_NAME,- MetricType.SUM,+ MetrictypesTypeDTO.sum,filter,groupBy,);@@ -250,7 +277,10 @@ describe('MetricDetails utils', () => {});it('should not include filters or groupBy when not provided', () => {- const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.SUM);+ const query = getMetricDetailsQuery(+ TEST_METRIC_NAME,+ MetrictypesTypeDTO.sum,+ );expect(query.builder.queryData[0]?.filters?.items).toHaveLength(0);expect(query.builder.queryData[0]?.groupBy).toHaveLength(0);diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/constants.ts b/frontend/src/container/MetricsExplorer/MetricDetails/constants.tsindex 586abb5538..0bb6e8c83a 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/constants.ts+++ b/frontend/src/container/MetricsExplorer/MetricDetails/constants.ts@@ -1,6 +1,55 @@+import {+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+} from 'api/generated/services/sigNoz.schemas';+export const METRIC_METADATA_KEYS = {description: 'Description',unit: 'Unit',- metric_type: 'Metric Type',+ type: 'Metric Type',temporality: 'Temporality',+ isMonotonic: 'Monotonic',};++export const METRIC_METADATA_TEMPORALITY_OPTIONS: Array<{+ value: MetrictypesTemporalityDTO;+ label: string;+}> = [+ {+ value: MetrictypesTemporalityDTO.delta,+ label: 'Delta',+ },+ {+ value: MetrictypesTemporalityDTO.cumulative,+ label: 'Cumulative',+ },+];++export const METRIC_METADATA_TYPE_OPTIONS: Array<{+ value: MetrictypesTypeDTO;+ label: string;+}> = [+ {+ value: MetrictypesTypeDTO.sum,+ label: 'Sum',+ },+ {+ value: MetrictypesTypeDTO.gauge,+ label: 'Gauge',+ },+ {+ value: MetrictypesTypeDTO.histogram,+ label: 'Histogram',+ },+ {+ value: MetrictypesTypeDTO.summary,+ label: 'Summary',+ },+ {+ value: MetrictypesTypeDTO.exponentialhistogram,+ label: 'Exponential Histogram',+ },+];++export const METRIC_METADATA_UPDATE_ERROR_MESSAGE =+ 'Failed to update metadata, please try again. If the issue persists, please contact support.';diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/types.ts b/frontend/src/container/MetricsExplorer/MetricDetails/types.tsindex 803ea304e5..0fab50f00c 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/types.ts+++ b/frontend/src/container/MetricsExplorer/MetricDetails/types.ts@@ -1,34 +1,39 @@import {- MetricDetails,- MetricDetailsAlert,- MetricDetailsAttribute,- MetricDetailsDashboard,-} from 'api/metricsExplorer/getMetricDetails';-import { MetricType } from 'api/metricsExplorer/getMetricsList';+ MetricsexplorertypesMetricAlertDTO,+ MetricsexplorertypesMetricAttributeDTO,+ MetricsexplorertypesMetricDashboardDTO,+ MetricsexplorertypesMetricHighlightsResponseDTO,+ MetricsexplorertypesMetricMetadataDTO,+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+} from 'api/generated/services/sigNoz.schemas';export interface MetricDetailsProps {onClose: () => void;isOpen: boolean;- metricName: string | null;+ metricName: string;isModalTimeSelection: boolean;openInspectModal?: (metricName: string) => void;}+export interface HighlightsProps {+ metricName: string;+}export interface DashboardsAndAlertsPopoverProps {- dashboards: MetricDetailsDashboard[] | null;- alerts: MetricDetailsAlert[] | null;+ metricName: string;}export interface MetadataProps {metricName: string;- metadata: MetricDetails['metadata'] | undefined;- refetchMetricDetails: () => void;+ metadata: MetricMetadata | null;+ isErrorMetricMetadata: boolean;+ isLoadingMetricMetadata: boolean;+ refetchMetricMetadata: () => void;}export interface AllAttributesProps {- attributes: MetricDetailsAttribute[];metricName: string;- metricType: MetricType | undefined;+ metricType: MetrictypesTypeDTO | undefined;}export interface AllAttributesValueProps {@@ -36,3 +41,38 @@ export interface AllAttributesValueProps {filterValue: string[];goToMetricsExploreWithAppliedAttribute: (key: string, value: string) => void;}++export interface AllAttributesEmptyTextProps {+ isErrorAttributes: boolean;+ refetchAttributes: () => void;+}++export type MetricHighlight = MetricsexplorertypesMetricHighlightsResponseDTO;++export type MetricAlert = MetricsexplorertypesMetricAlertDTO;++export type MetricDashboard = MetricsexplorertypesMetricDashboardDTO;++export type MetricMetadata = MetricsexplorertypesMetricMetadataDTO;+export interface MetricMetadataFormState {+ type: MetrictypesTypeDTO;+ description: string;+ temporality?: MetrictypesTemporalityDTO;+ unit: string;+ isMonotonic: boolean;+}++export type MetricAttribute = MetricsexplorertypesMetricAttributeDTO;++export enum TableFields {+ DESCRIPTION = 'description',+ UNIT = 'unit',+ TYPE = 'type',+ Temporality = 'temporality',+ IS_MONOTONIC = 'isMonotonic',+}++export interface MetricDetailsErrorStateProps {+ refetch?: () => void;+ errorMessage: string;+}diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/utils.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/utils.tsxindex 5232c52c20..e623d5c1ad 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/utils.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/utils.tsx@@ -1,12 +1,23 @@-import { Temporality } from 'api/metricsExplorer/getMetricDetails';-import { MetricType } from 'api/metricsExplorer/getMetricsList';+import { UpdateMetricMetadataMutationBody } from 'api/generated/services/metrics';+import {+ GetMetricMetadata200,+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+} from 'api/generated/services/sigNoz.schemas';import { SpaceAggregation, TimeAggregation } from 'api/v5/v5';import { initialQueriesMap } from 'constants/queryBuilder';import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';import { Query } from 'types/api/queryBuilder/queryBuilderData';import { DataSource, ReduceOperators } from 'types/common/queryBuilder';-export function formatTimestampToReadableDate(timestamp: string): string {+import { MetricMetadata, MetricMetadataFormState } from './types';++export function formatTimestampToReadableDate(+ timestamp: number | string | undefined,+): string {+ if (!timestamp) {+ return '-';+ }const date = new Date(timestamp);const now = new Date();const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);@@ -39,7 +50,10 @@ export function formatTimestampToReadableDate(timestamp: string): string {return date.toLocaleDateString();}-export function formatNumberToCompactFormat(num: number): string {+export function formatNumberToCompactFormat(num: number | undefined): string {+ if (!num) {+ return '-';+ }return new Intl.NumberFormat('en-US', {notation: 'compact',maximumFractionDigits: 1,@@ -47,27 +61,30 @@ export function formatNumberToCompactFormat(num: number): string {}export function determineIsMonotonic(- metricType: MetricType,- temporality?: Temporality,+ metricType: MetrictypesTypeDTO,+ temporality?: MetrictypesTemporalityDTO,): boolean {if (- metricType === MetricType.HISTOGRAM ||- metricType === MetricType.EXPONENTIAL_HISTOGRAM+ metricType === MetrictypesTypeDTO.histogram ||+ metricType === MetrictypesTypeDTO.exponentialhistogram) {return true;}- if (metricType === MetricType.GAUGE || metricType === MetricType.SUMMARY) {+ if (+ metricType === MetrictypesTypeDTO.gauge ||+ metricType === MetrictypesTypeDTO.summary+ ) {return false;}- if (metricType === MetricType.SUM) {- return temporality === Temporality.CUMULATIVE;+ if (metricType === MetrictypesTypeDTO.sum) {+ return temporality === MetrictypesTemporalityDTO.cumulative;}return false;}export function getMetricDetailsQuery(metricName: string,- metricType: MetricType | undefined,+ metricType: MetrictypesTypeDTO | undefined,filter?: { key: string; value: string },groupBy?: string,): Query {@@ -75,23 +92,23 @@ export function getMetricDetailsQuery(let spaceAggregation;let aggregateOperator;switch (metricType) {- case MetricType.SUM:+ case MetrictypesTypeDTO.sum:timeAggregation = 'rate';spaceAggregation = 'sum';aggregateOperator = 'rate';break;- case MetricType.GAUGE:+ case MetrictypesTypeDTO.gauge:timeAggregation = 'avg';spaceAggregation = 'avg';aggregateOperator = 'avg';break;- case MetricType.SUMMARY:+ case MetrictypesTypeDTO.summary:timeAggregation = 'noop';spaceAggregation = 'sum';aggregateOperator = 'noop';break;- case MetricType.HISTOGRAM:- case MetricType.EXPONENTIAL_HISTOGRAM:+ case MetrictypesTypeDTO.histogram:+ case MetrictypesTypeDTO.exponentialhistogram:timeAggregation = 'noop';spaceAggregation = 'p90';aggregateOperator = 'noop';@@ -160,3 +177,38 @@ export function getMetricDetailsQuery(},};}++export function transformMetricMetadata(+ apiData: GetMetricMetadata200 | undefined,+): MetricMetadata | null {+ if (!apiData || !apiData.data) {+ return null;+ }+ const { type, description, unit, temporality, isMonotonic } = apiData.data;++ return {+ type,+ description,+ unit,+ temporality,+ isMonotonic,+ };+}++export function transformUpdateMetricMetadataRequest(+ metricName: string,+ metricMetadata: MetricMetadataFormState,+): UpdateMetricMetadataMutationBody {+ return {+ metricName: metricName,+ type: metricMetadata.type,+ description: metricMetadata.description,+ unit: metricMetadata.unit,+ temporality:+ metricMetadata.temporality ?? MetrictypesTemporalityDTO.unspecified,+ isMonotonic: determineIsMonotonic(+ metricMetadata.type,+ metricMetadata.temporality,+ ),+ };+}diff --git a/frontend/src/container/MetricsExplorer/Summary/Summary.tsx b/frontend/src/container/MetricsExplorer/Summary/Summary.tsxindex d40136fa34..e8b97e59f3 100644--- a/frontend/src/container/MetricsExplorer/Summary/Summary.tsx+++ b/frontend/src/container/MetricsExplorer/Summary/Summary.tsx@@ -5,6 +5,7 @@ import { useSearchParams } from 'react-router-dom-v5-compat';import * as Sentry from '@sentry/react';import logEvent from 'api/common/logEvent';import { initialQueriesMap } from 'constants/queryBuilder';+import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';import { usePageSize } from 'container/InfraMonitoringK8s/utils';import NoLogs from 'container/NoLogs/NoLogs';import { useGetMetricsList } from 'hooks/metricsExplorer/useGetMetricsList';@@ -128,7 +129,7 @@ function Summary(): JSX.Element {} = useGetMetricsList(metricsListQuery, {enabled: !!metricsListQuery && !isInspectModalOpen,queryKey: [- 'metricsList',+ REACT_QUERY_KEY.GET_METRICS_LIST,queryFiltersWithoutId,orderBy,pageSize,@@ -323,7 +324,7 @@ function Summary(): JSX.Element {</>)}</div>- {isMetricDetailsOpen && (+ {isMetricDetailsOpen && selectedMetricName && (<MetricDetailsisOpen={isMetricDetailsOpen}onClose={closeMetricDetails}diff --git a/frontend/src/container/MetricsExplorer/Summary/constants.ts b/frontend/src/container/MetricsExplorer/Summary/constants.tsindex 21b7722af7..f0cb38da76 100644--- a/frontend/src/container/MetricsExplorer/Summary/constants.ts+++ b/frontend/src/container/MetricsExplorer/Summary/constants.ts@@ -1,3 +1,4 @@+import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';import { MetricType } from 'api/metricsExplorer/getMetricsList';import { TreemapViewType } from './types';@@ -25,7 +26,16 @@ export const METRIC_TYPE_LABEL_MAP = {[MetricType.EXPONENTIAL_HISTOGRAM]: 'Exp. Histogram',};-export const METRIC_TYPE_VALUES_MAP = {+export const METRIC_TYPE_VIEW_LABEL_MAP: Record<MetrictypesTypeDTO, string> = {+ [MetrictypesTypeDTO.sum]: 'Sum',+ [MetrictypesTypeDTO.gauge]: 'Gauge',+ [MetrictypesTypeDTO.histogram]: 'Histogram',+ [MetrictypesTypeDTO.summary]: 'Summary',+ [MetrictypesTypeDTO.exponentialhistogram]: 'Exp. Histogram',+};++// TODO(@amlannandy): To remove this once API migration is complete+export const METRIC_TYPE_VALUES_MAP: Record<MetricType, string> = {[MetricType.SUM]: 'Sum',[MetricType.GAUGE]: 'Gauge',[MetricType.HISTOGRAM]: 'Histogram',@@ -33,6 +43,14 @@ export const METRIC_TYPE_VALUES_MAP = {[MetricType.EXPONENTIAL_HISTOGRAM]: 'ExponentialHistogram',};+export const METRIC_TYPE_VIEW_VALUES_MAP: Record<MetrictypesTypeDTO, string> = {+ [MetrictypesTypeDTO.sum]: 'Sum',+ [MetrictypesTypeDTO.gauge]: 'Gauge',+ [MetrictypesTypeDTO.histogram]: 'Histogram',+ [MetrictypesTypeDTO.summary]: 'Summary',+ [MetrictypesTypeDTO.exponentialhistogram]: 'ExponentialHistogram',+};+export const IS_METRIC_DETAILS_OPEN_KEY = 'isMetricDetailsOpen';export const IS_INSPECT_MODAL_OPEN_KEY = 'isInspectModalOpen';export const SELECTED_METRIC_NAME_KEY = 'selectedMetricName';diff --git a/frontend/src/container/MetricsExplorer/Summary/utils.tsx b/frontend/src/container/MetricsExplorer/Summary/utils.tsxindex d539bbfb47..de8b103b19 100644--- a/frontend/src/container/MetricsExplorer/Summary/utils.tsx+++ b/frontend/src/container/MetricsExplorer/Summary/utils.tsx@@ -2,6 +2,7 @@ import { useMemo } from 'react';import { Color } from '@signozhq/design-tokens';import { Tooltip, Typography } from 'antd';import { ColumnType } from 'antd/es/table';+import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';import {MetricsListItemData,MetricsListPayload,@@ -21,7 +22,7 @@ import {} from 'lucide-react';import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';-import { METRIC_TYPE_LABEL_MAP } from './constants';+import { METRIC_TYPE_LABEL_MAP, METRIC_TYPE_VIEW_LABEL_MAP } from './constants';import MetricNameSearch from './MetricNameSearch';import MetricTypeSearch from './MetricTypeSearch';import { MetricsListItemRowData, TreemapTile, TreemapViewType } from './types';@@ -143,6 +144,66 @@ export function MetricTypeRenderer({);}+export function MetricTypeViewRenderer({+ type,+}: {+ type: MetrictypesTypeDTO;+}): JSX.Element {+ const [icon, color] = useMemo(() => {+ switch (type) {+ case MetrictypesTypeDTO.sum:+ return [+ <Diff key={type} size={12} color={Color.BG_ROBIN_500} />,+ Color.BG_ROBIN_500,+ ];+ case MetrictypesTypeDTO.gauge:+ return [+ <Gauge key={type} size={12} color={Color.BG_SAKURA_500} />,+ Color.BG_SAKURA_500,+ ];+ case MetrictypesTypeDTO.histogram:+ return [+ <BarChart2 key={type} size={12} color={Color.BG_SIENNA_500} />,+ Color.BG_SIENNA_500,+ ];+ case MetrictypesTypeDTO.summary:+ return [+ <BarChartHorizontal key={type} size={12} color={Color.BG_FOREST_500} />,+ Color.BG_FOREST_500,+ ];+ case MetrictypesTypeDTO.exponentialhistogram:+ return [+ <BarChart key={type} size={12} color={Color.BG_AQUA_500} />,+ Color.BG_AQUA_500,+ ];+ default:+ return [null, ''];+ }+ }, [type]);++ const metricTypeRendererStyle = useMemo(+ () => ({+ backgroundColor: `${color}33`,+ border: `1px solid ${color}`,+ color,+ }),+ [color],+ );++ const metricTypeRendererTextStyle = useMemo(() => ({ color, fontSize: 12 }), [+ color,+ ]);++ return (+ <div className="metric-type-renderer" style={metricTypeRendererStyle}>+ {icon}+ <Typography.Text style={metricTypeRendererTextStyle}>+ {METRIC_TYPE_VIEW_LABEL_MAP[type]}+ </Typography.Text>+ </div>+ );+}+function ValidateRowValueWrapper({value,children,@@ -160,6 +221,9 @@ export const formatNumberIntoHumanReadableFormat = (num: number,addPlusSign = true,): string => {+ if (!num) {+ return '-';+ }function format(num: number, divisor: number, suffix: string): string {const value = num / divisor;return value % 1 === 0diff --git a/frontend/src/utils/pluralize.ts b/frontend/src/utils/pluralize.tsnew file mode 100644index 0000000000..980d92edda--- /dev/null+++ b/frontend/src/utils/pluralize.ts@@ -0,0 +1,13 @@+export function pluralize(+ count: number,+ singular: string,+ plural?: string,+): string {+ if (count === 1) {+ return `${count} ${singular}`;+ }+ if (plural) {+ return `${count} ${plural}`;+ }+ return `${count} ${singular}s`;+}