Compare commits

...

11 Commits

Author SHA1 Message Date
amlannandy
e4a4d0ad93 chore: update types 2026-02-06 14:09:45 +07:00
amlannandy
9cd6eee89a chore: address comments 2026-02-06 14:07:06 +07:00
amlannandy
c4bcc62c11 chore: additional changes 2026-02-06 14:06:28 +07:00
amlannandy
8876153826 chore: fix CI 2026-02-06 14:05:58 +07:00
amlannandy
ce9026349d chore: minor changes 2026-02-06 14:05:52 +07:00
amlannandy
1083a3971d chore: switch to generated apis 2026-02-06 14:04:58 +07:00
amlannandy
9cb29bd9ca chore: fix ci 2026-02-06 14:02:42 +07:00
amlannandy
1446e5051f chore: update tests 2026-02-06 14:02:37 +07:00
amlannandy
a69f7697eb chore: update loading state 2026-02-06 14:01:58 +07:00
amlannandy
10d83a3f5f chore: api migration 2026-02-06 14:01:56 +07:00
amlannandy
1040a756dd chore: add new v2 api func and hooks 2026-02-06 13:59:56 +07:00
21 changed files with 1181 additions and 623 deletions

View File

@@ -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>
);
}

View File

@@ -2,8 +2,8 @@
import { useMemo, useState } from 'react';
import { Card, Input, Select, Typography } from 'antd';
import logEvent from 'api/common/logEvent';
import { MetricsexplorertypesMetricMetadataDTOType } 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: MetricsexplorertypesMetricMetadataDTOType | undefined,
): boolean {
return metricType === MetricsexplorertypesMetricMetadataDTOType.gauge;
}
export function getAllTimestampsOfMetrics(

View File

@@ -1,8 +1,17 @@
import { useCallback, useMemo, useState } from 'react';
import { useCallback, useEffect, 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';
@@ -15,6 +24,8 @@ import { MetricsExplorerEventKeys, MetricsExplorerEvents } from '../events';
import { AllAttributesProps, AllAttributesValueProps } from './types';
import { getMetricDetailsQuery } from './utils';
const ALL_ATTRIBUTES_KEY = 'all-attributes';
export function AllAttributesValue({
filterKey,
filterValue,
@@ -110,12 +121,31 @@ 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,
mutate: getMetricAttributes,
} = useGetMetricAttributes();
useEffect(() => {
if (metricName) {
getMetricAttributes({
data: {
metricName,
},
});
}
}, [getMetricAttributes, metricName]);
const attributes = useMemo(
() => attributesData?.data?.data?.attributes ?? [],
[attributesData],
);
const { handleExplorerTabChange } = useHandleExplorerTabChange();
@@ -178,7 +208,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 +225,7 @@ function AllAttributes({
},
value: {
key: attribute.key,
value: attribute.value,
value: attribute.values,
},
}))
: [],
@@ -252,6 +282,12 @@ function AllAttributes({
],
);
const emptyText = useMemo(
() =>
isErrorAttributes ? 'Error fetching attributes' : 'No attributes found',
[isErrorAttributes],
);
const items = useMemo(
() => [
{
@@ -270,6 +306,7 @@ function AllAttributes({
onClick={(e): void => {
e.stopPropagation();
}}
disabled={isLoadingAttributes}
/>
</div>
),
@@ -277,25 +314,37 @@ function AllAttributes({
children: (
<ResizeTable
columns={columns}
loading={isLoadingAttributes}
tableLayout="fixed"
dataSource={tableData}
pagination={false}
showHeader={false}
className="metrics-accordion-content all-attributes-content"
scroll={{ y: 600 }}
locale={{
emptyText,
}}
/>
),
},
],
[columns, tableData, searchString],
[searchString, columns, isLoadingAttributes, tableData, emptyText],
);
if (isLoadingAttributes) {
return (
<div className="all-attributes-skeleton-container">
<Skeleton active paragraph={{ rows: 8 }} />
</div>
);
}
return (
<Collapse
bordered
className="metrics-accordion metrics-metadata-accordion"
className="metrics-accordion metrics-all-attributes-accordion"
activeKey={activeKey}
onChange={(keys): void => setActiveKey(keys)}
onChange={(keys): void => setActiveKey(keys as string[])}
items={items}
/>
);

View File

@@ -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 { 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';
import {
useGetMetricAlerts,
useGetMetricDashboards,
} from 'api/generated/services/metrics';
function DashboardsAndAlertsPopover({
alerts,
dashboards,
metricName,
}: DashboardsAndAlertsPopoverProps): JSX.Element | null {
const { safeNavigate } = useSafeNavigate();
const params = useUrlQuery();
const {
data: alertsData,
isLoading: isLoadingAlerts,
isError: isErrorAlerts,
} = useGetMetricAlerts(
{
metricName: metricName ?? '',
},
{
query: {
enabled: !!metricName,
},
},
);
const {
data: dashboardsData,
isLoading: isLoadingDashboards,
isError: isErrorDashboards,
} = useGetMetricDashboards(
{
metricName: metricName ?? '',
},
{
query: {
enabled: !!metricName,
},
},
);
const alerts = useMemo(() => {
return alertsData?.data?.data?.alerts ?? [];
}, [alertsData]);
const dashboards = useMemo(() => {
const currentDashboards = dashboardsData?.data?.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>

View File

@@ -0,0 +1,129 @@
import { Skeleton, Tooltip, Typography } from 'antd';
import { useMemo } from 'react';
import { formatNumberIntoHumanReadableFormat } from '../Summary/utils';
import { HighlightsProps } from './types';
import {
formatNumberToCompactFormat,
formatTimestampToReadableDate,
} from './utils';
import { useGetMetricHighlights } from 'api/generated/services/metrics';
function Highlights({ metricName }: HighlightsProps): JSX.Element {
const {
data: metricHighlightsData,
isLoading: isLoadingMetricHighlights,
isError: isErrorMetricHighlights,
} = useGetMetricHighlights(
{
metricName: metricName ?? '',
},
{
query: {
enabled: !!metricName,
},
},
);
const metricHighlights = useMemo(() => {
return metricHighlightsData?.data?.data ?? null;
}, [metricHighlightsData]);
const dataPoints = useMemo(() => {
if (!metricHighlights) {
return null;
}
if (isErrorMetricHighlights) {
return (
<Typography.Text className="metric-details-grid-value">-</Typography.Text>
);
}
return (
<Typography.Text className="metric-details-grid-value">
<Tooltip title={metricHighlights?.dataPoints?.toLocaleString()}>
{formatNumberIntoHumanReadableFormat(metricHighlights?.dataPoints ?? 0)}
</Tooltip>
</Typography.Text>
);
}, [metricHighlights, isErrorMetricHighlights]);
const timeSeries = useMemo(() => {
if (!metricHighlights) {
return null;
}
if (isErrorMetricHighlights) {
return (
<Typography.Text className="metric-details-grid-value">-</Typography.Text>
);
}
const timeSeriesActive = formatNumberToCompactFormat(
metricHighlights.activeTimeSeries,
);
const timeSeriesTotal = formatNumberToCompactFormat(
metricHighlights.totalTimeSeries,
);
return (
<Typography.Text className="metric-details-grid-value">
<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>
);
}, [metricHighlights, isErrorMetricHighlights]);
const lastReceived = useMemo(() => {
if (!metricHighlights) {
return null;
}
if (isErrorMetricHighlights) {
return (
<Typography.Text className="metric-details-grid-value">-</Typography.Text>
);
}
const displayText = formatTimestampToReadableDate(
metricHighlights.lastReceived,
);
return (
<Typography.Text className="metric-details-grid-value">
<Tooltip title={displayText}>{displayText}</Tooltip>
</Typography.Text>
);
}, [metricHighlights, isErrorMetricHighlights]);
if (isLoadingMetricHighlights) {
return (
<div className="metric-details-content-grid">
<Skeleton title={false} paragraph={{ rows: 2 }} active />
</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">
{dataPoints}
{timeSeries}
{lastReceived}
</div>
</div>
);
}
export default Highlights;

View File

@@ -1,18 +1,25 @@
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 {
invalidateGetMetricMetadata,
useUpdateMetricMetadata,
} from 'api/generated/services/metrics';
import {
MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality,
MetricsexplorertypesUpdateMetricMetadataRequestDTOType,
} from 'api/generated/services/sigNoz.schemas';
import { Temporality } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import { UpdateMetricMetadataProps } from 'api/metricsExplorer/updateMetricMetadata';
import { ResizeTable } from 'components/ResizeTable';
import YAxisUnitSelector from 'components/YAxisUnitSelector';
import { YAxisSource } from 'components/YAxisUnitSelector/types';
import { getUniversalNameFromMetricUnit } from 'components/YAxisUnitSelector/utils';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
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';
@@ -23,23 +30,27 @@ import {
} from '../Summary/constants';
import { MetricTypeRenderer } from '../Summary/utils';
import { METRIC_METADATA_KEYS } from './constants';
import { MetadataProps } from './types';
import { determineIsMonotonic } from './utils';
import { MetadataProps, MetricMetadataState, TableFields } from './types';
import {
transformMetricType,
transformTemporality,
transformUpdateMetricMetadataRequest,
} from './utils';
function Metadata({
metricName,
metadata,
refetchMetricDetails,
isErrorMetricMetadata,
isLoadingMetricMetadata,
}: 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,
const [metricMetadata, setMetricMetadata] = useState<MetricMetadataState>({
type: MetricsexplorertypesUpdateMetricMetadataRequestDTOType.sum,
description: '',
temporality:
MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality.unspecified,
unit: '',
});
const { notifications } = useNotifications();
const {
@@ -51,6 +62,18 @@ function Metadata({
);
const queryClient = useQueryClient();
// Initialize state from metadata api data
useEffect(() => {
if (metadata) {
setMetricMetadata({
type: transformMetricType(metadata.type),
description: metadata.description,
temporality: transformTemporality(metadata.temporality),
unit: metadata.unit,
});
}
}, [metadata]);
const tableData = useMemo(
() =>
metadata
@@ -59,7 +82,7 @@ function Metadata({
temporality: metadata?.temporality,
})
// Filter out monotonic as user input is not required
.filter((key) => key !== 'monotonic')
.filter((key) => key !== TableFields.IS_MONOTONIC)
.map((key) => ({
key,
value: {
@@ -72,30 +95,37 @@ function 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 MetricMetadataState, value: string) => {
if (isErrorMetricMetadata) {
return <FieldRenderer field="-" />;
}
if (key === TableFields.TYPE) {
return <MetricTypeRenderer type={value as MetricType} />;
}
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 MetricMetadataState }): 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') {
if (field.key === TableFields.TYPE) {
return (
<Select
data-testid="metric-type-select"
@@ -103,17 +133,17 @@ function Metadata({
value: key,
label: METRIC_TYPE_LABEL_MAP[key as MetricType],
}))}
value={metricMetadata.metricType}
value={metricMetadata.type}
onChange={(value): void => {
setMetricMetadata((prev) => ({
...prev,
metricType: value as MetricType,
metricType: value,
}));
}}
/>
);
}
if (field.key === 'unit') {
if (field.key === TableFields.UNIT) {
return (
<YAxisUnitSelector
value={metricMetadata.unit}
@@ -125,7 +155,7 @@ function Metadata({
/>
);
}
if (field.key === 'temporality') {
if (field.key === TableFields.Temporality) {
return (
<Select
data-testid="temporality-select"
@@ -137,22 +167,18 @@ function Metadata({
onChange={(value): void => {
setMetricMetadata((prev) => ({
...prev,
temporality: value as Temporality,
temporality: value,
}));
}}
/>
);
}
if (field.key === 'description') {
if (field.key === TableFields.DESCRIPTION) {
return (
<Input
data-testid="description-input"
name={field.key}
defaultValue={
metricMetadata[
field.key as Exclude<keyof UpdateMetricMetadataProps, 'isMonotonic'>
]
}
defaultValue={metricMetadata.description}
onChange={(e): void => {
setMetricMetadata((prev) => ({
...prev,
@@ -201,18 +227,14 @@ function Metadata({
const handleSave = useCallback(() => {
updateMetricMetadata(
{
metricName,
payload: {
...metricMetadata,
isMonotonic: determineIsMonotonic(
metricMetadata.metricType,
metricMetadata.temporality,
),
pathParams: {
metricName: metricName ?? '',
},
data: transformUpdateMetricMetadataRequest(metricName, metricMetadata),
},
{
onSuccess: (response): void => {
if (response?.statusCode === 200) {
if (response.status === 200) {
logEvent(MetricsExplorerEvents.MetricMetadataUpdated, {
[MetricsExplorerEventKeys.MetricName]: metricName,
[MetricsExplorerEventKeys.Tab]: 'summary',
@@ -221,9 +243,13 @@ function Metadata({
notifications.success({
message: 'Metadata updated successfully',
});
refetchMetricDetails();
setIsEditing(false);
queryClient.invalidateQueries(['metricsList']);
// TODO: To update this to use invalidateGetMetricList
// once we have switched to the V2 API in summary page
queryClient.invalidateQueries([REACT_QUERY_KEY.GET_METRICS_LIST]);
invalidateGetMetricMetadata(queryClient, {
metricName,
});
} else {
notifications.error({
message:
@@ -243,10 +269,24 @@ function Metadata({
metricName,
metricMetadata,
notifications,
refetchMetricDetails,
queryClient,
]);
const cancelEdit = useCallback(
(e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
e.stopPropagation();
if (metadata) {
setMetricMetadata({
type: transformMetricType(metadata.type),
description: metadata.description,
unit: metadata.unit,
});
}
setIsEditing(false);
},
[metadata],
);
const actionButton = useMemo(() => {
if (isEditing) {
return (
@@ -254,10 +294,7 @@ function Metadata({
<Button
className="action-button"
type="text"
onClick={(e): void => {
e.stopPropagation();
setIsEditing(false);
}}
onClick={cancelEdit}
disabled={isUpdatingMetricsMetadata}
>
<X size={14} />
@@ -294,7 +331,7 @@ function Metadata({
</Button>
</div>
);
}, [handleSave, isEditing, isUpdatingMetricsMetadata]);
}, [isEditing, isUpdatingMetricsMetadata, cancelEdit, handleSave]);
const items = useMemo(
() => [
@@ -321,6 +358,14 @@ function Metadata({
[actionButton, columns, tableData],
);
if (isLoadingMetricMetadata) {
return (
<div className="metrics-metadata-skeleton-container">
<Skeleton active paragraph={{ rows: 8 }} />
</div>
);
}
return (
<Collapse
bordered

View File

@@ -39,6 +39,7 @@
gap: 12px;
.metric-details-content-grid {
height: 50px;
.labels-row,
.values-row {
display: grid;
@@ -72,6 +73,7 @@
.dashboards-and-alerts-popover-container {
display: flex;
gap: 16px;
height: 32px;
.dashboards-and-alerts-popover {
border-radius: 20px;
@@ -102,6 +104,14 @@
}
}
.metrics-metadata-skeleton-container {
height: 330px;
}
.all-attributes-skeleton-container {
height: 600px;
}
.metrics-accordion {
.ant-table-body {
&::-webkit-scrollbar {
@@ -148,7 +158,6 @@
.all-attributes-search-input {
width: 300px;
border: 1px solid var(--bg-slate-300);
}
}
@@ -161,6 +170,7 @@
.ant-typography:first-child {
font-family: 'Geist Mono';
color: var(--bg-robin-400);
background-color: transparent;
}
}
.all-attributes-contribution {
@@ -237,6 +247,7 @@
}
.metric-metadata-value {
height: 67px;
background: rgba(22, 25, 34, 0.4);
overflow-x: scroll;
.field-renderer-container {
@@ -330,18 +341,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);
}
}

View File

@@ -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, Empty, 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,52 @@ 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,
} = useGetMetricMetadata(
{
metricName: metricName ?? '',
},
{
query: {
enabled: !!metricName,
},
},
);
const isMetricDetailsLoading = isLoading || isFetching;
const timeSeries = useMemo(() => {
if (!metric) {
const metadata = useMemo(() => {
if (
!metricMetadataResponse ||
!metricMetadataResponse.data ||
!metricMetadataResponse.data.data
) {
return null;
}
const timeSeriesActive = formatNumberToCompactFormat(metric.timeSeriesActive);
const timeSeriesTotal = formatNumberToCompactFormat(metric.timeSeriesTotal);
const {
type,
description,
unit,
temporality,
isMonotonic,
} = metricMetadataResponse.data.data;
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]);
return {
type,
description,
unit,
temporality,
isMonotonic,
};
}, [metricMetadataResponse]);
const showInspectFeature = useMemo(() => isInspectEnabled(metadata?.type), [
metadata,
]);
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 +92,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 +100,10 @@ function MetricDetails({
});
}, []);
if (!metricName) {
return <Empty description="Metric not found" />;
}
return (
<Drawer
width="60%"
@@ -124,7 +111,7 @@ 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">
<Button
@@ -142,8 +129,8 @@ function MetricDetails({
aria-label="Inspect Metric"
icon={<Crosshair size={18} />}
onClick={(): void => {
if (metric?.name) {
openInspectModal(metric.name);
if (metricName) {
openInspectModal(metricName);
}
}}
data-testid="inspect-metric-button"
@@ -163,60 +150,17 @@ function MetricDetails({
destroyOnClose
closeIcon={<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}
/>
<AllAttributes metricName={metricName} metricType={metadata?.type} />
</div>
</Drawer>
);
}

View File

@@ -1,11 +1,13 @@
import * as reactUseHooks from 'react-use';
import { fireEvent, render, screen } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
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 } from './testUtlls';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
@@ -22,32 +24,30 @@ jest
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',
);
const mockUseGetMetricAttributes = jest.fn();
describe('AllAttributes', () => {
beforeEach(() => {
useGetMetricAttributesMock.mockReturnValue({
...getMockMetricAttributesData(),
mutate: mockUseGetMetricAttributes,
});
});
it('renders attributes section with title', () => {
render(
<AllAttributes
metricName={mockMetricName}
attributes={mockAttributes}
metricType={mockMetricType}
/>,
<AllAttributes metricName={mockMetricName} metricType={mockMetricType} />,
);
expect(screen.getByText('All Attributes')).toBeInTheDocument();
@@ -55,11 +55,7 @@ describe('AllAttributes', () => {
it('renders all attribute keys and values', () => {
render(
<AllAttributes
metricName={mockMetricName}
attributes={mockAttributes}
metricType={mockMetricType}
/>,
<AllAttributes metricName={mockMetricName} metricType={mockMetricType} />,
);
// Check attribute keys are rendered
@@ -74,11 +70,7 @@ describe('AllAttributes', () => {
it('renders value counts correctly', () => {
render(
<AllAttributes
metricName={mockMetricName}
attributes={mockAttributes}
metricType={mockMetricType}
/>,
<AllAttributes metricName={mockMetricName} metricType={mockMetricType} />,
);
expect(screen.getByText('2')).toBeInTheDocument(); // For attribute1
@@ -86,41 +78,36 @@ describe('AllAttributes', () => {
});
it('handles empty attributes array', () => {
useGetMetricAttributesMock.mockReturnValue({
...getMockMetricAttributesData({
data: {
attributes: [],
totalKeys: 0,
},
}),
mutate: mockUseGetMetricAttributes,
});
render(
<AllAttributes
metricName={mockMetricName}
attributes={[]}
metricType={mockMetricType}
/>,
<AllAttributes metricName={mockMetricName} metricType={mockMetricType} />,
);
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}
/>,
<AllAttributes metricName={mockMetricName} metricType={mockMetricType} />,
);
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}
/>,
<AllAttributes metricName={mockMetricName} metricType={mockMetricType} />,
);
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 +131,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(
<AllAttributesValue
filterKey="attribute1"
@@ -155,7 +142,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 +159,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(
<AllAttributesValue
filterKey="attribute1"
@@ -183,13 +170,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(
<AllAttributesValue
filterKey="attribute1"
@@ -200,10 +187,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',

View File

@@ -1,26 +1,17 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import { QueryParams } from 'constants/query';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
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,
} from './testUtlls';
const mockSafeNavigate = jest.fn();
jest.mock('hooks/useSafeNavigate', () => ({
@@ -28,7 +19,6 @@ jest.mock('hooks/useSafeNavigate', () => ({
safeNavigate: mockSafeNavigate,
}),
}));
const mockSetQuery = jest.fn();
const mockUrlQuery = {
set: mockSetQuery,
@@ -39,125 +29,155 @@ jest.mock('hooks/useUrlQuery', () => ({
default: jest.fn(() => mockUrlQuery),
}));
describe('DashboardsAndAlertsPopover', () => {
it('renders the popover correctly with multiple dashboards and alerts', () => {
render(
<DashboardsAndAlertsPopover
alerts={mockAlerts}
dashboards={mockDashboards}
/>,
);
const MOCK_METRIC_NAME = 'test-metric';
expect(
screen.getByText(`${mockDashboards.length} dashboards`),
).toBeInTheDocument();
expect(
screen.getByText(`${mockAlerts.length} alert rules`),
).toBeInTheDocument();
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 metricName={MOCK_METRIC_NAME} />);
expect(screen.getByText(`2 dashboards`)).toBeInTheDocument();
expect(screen.getByText(`2 alert rules`)).toBeInTheDocument();
});
it('renders null with no dashboards and alerts', () => {
const { container } = render(
<DashboardsAndAlertsPopover alerts={[]} dashboards={[]} />,
useGetMetricAlertsMock.mockReturnValue(
getMockAlertsData({
data: undefined,
}),
);
expect(container).toBeEmptyDOMElement();
useGetMetricDashboardsMock.mockReturnValue(
getMockDashboardsData({
data: undefined,
}),
);
const { container } = render(
<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />,
);
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 dashboard
expect(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 rule
expect(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();
});
});

View File

@@ -0,0 +1,85 @@
import { render } from '@testing-library/react';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import Highlights from '../Highlights';
import { getMockMetricHighlightsData } from './testUtlls';
import { formatTimestampToReadableDate } from '../utils';
const MOCK_METRIC_NAME = 'test-metric';
const METRIC_DETAILS_GRID_VALUE_SELECTOR = '.metric-details-grid-value';
const useGetMetricHighlightsMock = jest.spyOn(
metricsExplorerHooks,
'useGetMetricHighlights',
);
describe('Highlights', () => {
beforeEach(() => {
useGetMetricHighlightsMock.mockReturnValue(getMockMetricHighlightsData());
});
it('should render all highlights data correctly', () => {
const { container } = render(<Highlights metricName={MOCK_METRIC_NAME} />);
const metricHighlightsValues = container.querySelectorAll(
METRIC_DETAILS_GRID_VALUE_SELECTOR,
);
expect(metricHighlightsValues).toHaveLength(3);
expect(metricHighlightsValues[0].textContent).toBe('1M+');
expect(metricHighlightsValues[1].textContent).toBe('1M total ⎯ 1M active');
expect(metricHighlightsValues[2].textContent).toBe(
formatTimestampToReadableDate('2026-01-24T00:00:00Z'),
);
});
it('should render "-" for highlights data when there is an error', () => {
useGetMetricHighlightsMock.mockReturnValue(
getMockMetricHighlightsData(
{},
{
isError: true,
},
),
);
const { container } = render(<Highlights metricName={MOCK_METRIC_NAME} />);
const metricHighlightsValues = container.querySelectorAll(
METRIC_DETAILS_GRID_VALUE_SELECTOR,
);
expect(metricHighlightsValues[0].textContent).toBe('-');
expect(metricHighlightsValues[1].textContent).toBe('-');
expect(metricHighlightsValues[2].textContent).toBe('-');
});
it('should render loading state when data is loading', () => {
useGetMetricHighlightsMock.mockReturnValue(
getMockMetricHighlightsData(
{},
{
isLoading: true,
},
),
);
const { container } = render(<Highlights metricName={MOCK_METRIC_NAME} />);
expect(container.querySelector('.ant-skeleton')).toBeInTheDocument();
});
it('should not render grid values when there is no data', () => {
useGetMetricHighlightsMock.mockReturnValue(
getMockMetricHighlightsData({
data: undefined,
}),
);
const { container } = render(<Highlights metricName={MOCK_METRIC_NAME} />);
const metricHighlightsValues = container.querySelectorAll(
METRIC_DETAILS_GRID_VALUE_SELECTOR,
);
expect(metricHighlightsValues).toHaveLength(0);
});
});

View File

@@ -1,16 +1,22 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { fireEvent, render, screen } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
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 metricsExplorerHooks from 'api/generated/services/metrics';
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 } from './testUtlls';
import { GetMetricMetadata200 } from 'api/generated/services/sigNoz.schemas';
import { AxiosResponse } from 'axios';
// Mock antd select for testing
jest.mock('antd', () => ({
@@ -72,13 +78,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 AxiosResponse<GetMetricMetadata200>).data,
) as MetricMetadata;
const mockErrorNotification = jest.fn();
const mockSuccessNotification = jest.fn();
@@ -90,26 +101,26 @@ 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();
describe('Metadata', () => {
beforeEach(() => {
mockUseUpdateMetricMetadataHook.mockReturnValue(({
mutate: mockUseUpdateMetricMetadata,
} as Partial<UseUpdateMetricMetadataResult>) as UseUpdateMetricMetadataResult);
});
it('should render the metadata properly', () => {
render(
<Metadata
metricName={mockMetricName}
metadata={mockMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
/>,
);
expect(screen.getByText('Metric Type')).toBeInTheDocument();
expect(screen.getByText(mockMetricMetadata.metric_type)).toBeInTheDocument();
expect(screen.getByText(mockMetricMetadata.metricType)).toBeInTheDocument();
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText(mockMetricMetadata.description)).toBeInTheDocument();
expect(screen.getByText('Unit')).toBeInTheDocument();
@@ -118,18 +129,19 @@ describe('Metadata', () => {
expect(screen.getByText(mockMetricMetadata.temporality)).toBeInTheDocument();
});
it('editing the metadata should show the form inputs', () => {
it('editing the metadata should show the form inputs', async () => {
render(
<Metadata
metricName={mockMetricName}
metadata={mockMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
/>,
);
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();
@@ -144,52 +156,47 @@ describe('Metadata', () => {
...mockMetricMetadata,
unit: '',
}}
refetchMetricDetails={mockRefetchMetricDetails}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
/>,
);
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, MetricType.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,
data: expect.objectContaining({
type: MetricType.SUM,
temporality: Temporality.CUMULATIVE,
unit: 'By',
isMonotonic: true,
}),
pathParams: {
metricName: mockMetricName,
},
}),
expect.objectContaining({
onSuccess: expect.any(Function),
@@ -203,29 +210,28 @@ describe('Metadata', () => {
<Metadata
metricName={mockMetricName}
metadata={mockMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
/>,
);
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 () => {
@@ -233,24 +239,24 @@ describe('Metadata', () => {
<Metadata
metricName={mockMetricName}
metadata={mockMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
/>,
);
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 });
onSuccessCallback({ status: 500 });
expect(mockErrorNotification).toHaveBeenCalledWith({
message:
@@ -263,20 +269,20 @@ describe('Metadata', () => {
<Metadata
metricName={mockMetricName}
metadata={mockMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
/>,
);
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 +295,41 @@ describe('Metadata', () => {
});
});
it('cancel button should cancel the edit mode', () => {
it('cancel button should cancel the edit mode', async () => {
render(
<Metadata
metricName={mockMetricName}
metadata={mockMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
/>,
);
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}
metadata={mockMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
/>,
);
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();

View File

@@ -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 ROUTES from 'constants/routes';
import * as useGetMetricDetails from 'hooks/metricsExplorer/useGetMetricDetails';
import * as useUpdateMetricMetadata from 'hooks/metricsExplorer/useUpdateMetricMetadata';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
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(
<MetricDetails
onClose={mockOnClose}
@@ -135,93 +114,24 @@ 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);
it('should render empty state when metric name is not provided', () => {
render(
<MetricDetails
onClose={mockOnClose}
isOpen
metricName={mockMetricName}
metricName={null}
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();
expect(screen.getByText('Metric not found')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,175 @@
import {
GetMetricAlerts200,
GetMetricAttributes200,
GetMetricDashboards200,
GetMetricHighlights200,
GetMetricMetadata200,
} from 'api/generated/services/sigNoz.schemas';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import { Temporality } from 'types/common/queryBuilder';
export function getMockMetricHighlightsData(
overrides?: Partial<GetMetricHighlights200>,
{
isLoading = false,
isError = false,
}: {
isLoading?: boolean;
isError?: boolean;
} = {},
): ReturnType<typeof metricsExplorerHooks.useGetMetricHighlights> {
return {
data: {
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: {
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: {
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: {
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: {
data: {
description: 'test_description',
type: 'gauge',
unit: 'test_unit',
temporality: Temporality.Delta,
isMonotonic: false,
},
status: 'success',
...overrides,
},
},
isLoading,
isError,
} as ReturnType<typeof metricsExplorerHooks.useGetMetricMetadata>;
}

View File

@@ -1,6 +1,6 @@
export const METRIC_METADATA_KEYS = {
description: 'Description',
unit: 'Unit',
metric_type: 'Metric Type',
metricType: 'Metric Type',
temporality: 'Temporality',
};

View File

@@ -1,10 +1,13 @@
import {
MetricDetails,
MetricDetailsAlert,
MetricDetailsAttribute,
MetricDetailsDashboard,
} from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
MetricsexplorertypesMetricAlertDTO,
MetricsexplorertypesMetricAttributeDTO,
MetricsexplorertypesMetricDashboardDTO,
MetricsexplorertypesMetricHighlightsResponseDTO,
MetricsexplorertypesMetricMetadataDTO,
MetricsexplorertypesMetricMetadataDTOType,
MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality,
MetricsexplorertypesUpdateMetricMetadataRequestDTOType,
} from 'api/generated/services/sigNoz.schemas';
export interface MetricDetailsProps {
onClose: () => void;
@@ -14,21 +17,23 @@ export interface MetricDetailsProps {
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;
}
export interface AllAttributesProps {
attributes: MetricDetailsAttribute[];
metricName: string;
metricType: MetricType | undefined;
metricType: MetricsexplorertypesMetricMetadataDTOType | undefined;
}
export interface AllAttributesValueProps {
@@ -36,3 +41,27 @@ export interface AllAttributesValueProps {
filterValue: string[];
goToMetricsExploreWithAppliedAttribute: (key: string, value: string) => void;
}
export type MetricHighlight = MetricsexplorertypesMetricHighlightsResponseDTO;
export type MetricAlert = MetricsexplorertypesMetricAlertDTO;
export type MetricDashboard = MetricsexplorertypesMetricDashboardDTO;
export type MetricMetadata = MetricsexplorertypesMetricMetadataDTO;
export interface MetricMetadataState {
type: MetricsexplorertypesUpdateMetricMetadataRequestDTOType;
description: string;
temporality?: MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality;
unit: string;
}
export type MetricAttribute = MetricsexplorertypesMetricAttributeDTO;
export enum TableFields {
DESCRIPTION = 'description',
UNIT = 'unit',
TYPE = 'type',
Temporality = 'temporality',
IS_MONOTONIC = 'isMonotonic',
}

View File

@@ -1,12 +1,25 @@
import { Temporality } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import { UpdateMetricMetadataMutationBody } from 'api/generated/services/metrics';
import {
GetMetricMetadata200,
MetricsexplorertypesMetricMetadataDTOTemporality,
MetricsexplorertypesMetricMetadataDTOType,
MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality,
MetricsexplorertypesUpdateMetricMetadataRequestDTOType,
} 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, MetricMetadataState } 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 +52,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 +63,37 @@ export function formatNumberToCompactFormat(num: number): string {
}
export function determineIsMonotonic(
metricType: MetricType,
temporality?: Temporality,
metricType: MetricsexplorertypesUpdateMetricMetadataRequestDTOType,
temporality?: MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality,
): boolean {
if (
metricType === MetricType.HISTOGRAM ||
metricType === MetricType.EXPONENTIAL_HISTOGRAM
metricType ===
MetricsexplorertypesUpdateMetricMetadataRequestDTOType.histogram ||
metricType ===
MetricsexplorertypesUpdateMetricMetadataRequestDTOType.exponentialhistogram
) {
return true;
}
if (metricType === MetricType.GAUGE || metricType === MetricType.SUMMARY) {
if (
metricType === MetricsexplorertypesUpdateMetricMetadataRequestDTOType.gauge ||
metricType === MetricsexplorertypesUpdateMetricMetadataRequestDTOType.summary
) {
return false;
}
if (metricType === MetricType.SUM) {
return temporality === Temporality.CUMULATIVE;
if (
metricType === MetricsexplorertypesUpdateMetricMetadataRequestDTOType.sum
) {
return (
temporality ===
MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality.cumulative
);
}
return false;
}
export function getMetricDetailsQuery(
metricName: string,
metricType: MetricType | undefined,
metricType: MetricsexplorertypesMetricMetadataDTOType | undefined,
filter?: { key: string; value: string },
groupBy?: string,
): Query {
@@ -75,23 +101,23 @@ export function getMetricDetailsQuery(
let spaceAggregation;
let aggregateOperator;
switch (metricType) {
case MetricType.SUM:
case MetricsexplorertypesMetricMetadataDTOType.sum:
timeAggregation = 'rate';
spaceAggregation = 'sum';
aggregateOperator = 'rate';
break;
case MetricType.GAUGE:
case MetricsexplorertypesMetricMetadataDTOType.gauge:
timeAggregation = 'avg';
spaceAggregation = 'avg';
aggregateOperator = 'avg';
break;
case MetricType.SUMMARY:
case MetricsexplorertypesMetricMetadataDTOType.summary:
timeAggregation = 'noop';
spaceAggregation = 'sum';
aggregateOperator = 'noop';
break;
case MetricType.HISTOGRAM:
case MetricType.EXPONENTIAL_HISTOGRAM:
case MetricsexplorertypesMetricMetadataDTOType.histogram:
case MetricsexplorertypesMetricMetadataDTOType.exponentialhistogram:
timeAggregation = 'noop';
spaceAggregation = 'p90';
aggregateOperator = 'noop';
@@ -160,3 +186,69 @@ 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: MetricMetadataState,
): UpdateMetricMetadataMutationBody {
return {
metricName: metricName,
type: metricMetadata.type,
description: metricMetadata.description,
unit: metricMetadata.unit,
temporality:
metricMetadata.temporality ??
MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality.unspecified,
isMonotonic: determineIsMonotonic(
metricMetadata.type,
metricMetadata.temporality,
),
};
}
export function transformMetricType(
type: MetricsexplorertypesMetricMetadataDTOType,
): MetricsexplorertypesUpdateMetricMetadataRequestDTOType {
switch (type) {
case MetricsexplorertypesMetricMetadataDTOType.sum:
return MetricsexplorertypesUpdateMetricMetadataRequestDTOType.sum;
case MetricsexplorertypesMetricMetadataDTOType.gauge:
return MetricsexplorertypesUpdateMetricMetadataRequestDTOType.gauge;
case MetricsexplorertypesMetricMetadataDTOType.histogram:
return MetricsexplorertypesUpdateMetricMetadataRequestDTOType.histogram;
case MetricsexplorertypesMetricMetadataDTOType.summary:
return MetricsexplorertypesUpdateMetricMetadataRequestDTOType.summary;
case MetricsexplorertypesMetricMetadataDTOType.exponentialhistogram:
return MetricsexplorertypesUpdateMetricMetadataRequestDTOType.exponentialhistogram;
}
}
export function transformTemporality(
temporality: MetricsexplorertypesMetricMetadataDTOTemporality,
): MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality {
switch (temporality) {
case MetricsexplorertypesMetricMetadataDTOTemporality.delta:
return MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality.delta;
case MetricsexplorertypesMetricMetadataDTOTemporality.cumulative:
return MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality.cumulative;
case MetricsexplorertypesMetricMetadataDTOTemporality.unspecified:
return MetricsexplorertypesUpdateMetricMetadataRequestDTOTemporality.unspecified;
}
}

View File

@@ -34,6 +34,7 @@ import {
formatDataForMetricsTable,
getMetricsListQuery,
} from './utils';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import './Summary.styles.scss';
@@ -128,7 +129,7 @@ function Summary(): JSX.Element {
} = useGetMetricsList(metricsListQuery, {
enabled: !!metricsListQuery && !isInspectModalOpen,
queryKey: [
'metricsList',
REACT_QUERY_KEY.GET_METRICS_LIST,
queryFiltersWithoutId,
orderBy,
pageSize,

View File

@@ -157,9 +157,12 @@ function ValidateRowValueWrapper({
}
export const formatNumberIntoHumanReadableFormat = (
num: number,
num: number | undefined,
addPlusSign = true,
): string => {
if (!num) {
return '-';
}
function format(num: number, divisor: number, suffix: string): string {
const value = num / divisor;
return value % 1 === 0

View File

@@ -1,5 +1,5 @@
import { useQueries, UseQueryOptions, UseQueryResult } from 'react-query';
import { getMetricMetadata } from 'api/metricsExplorer/v2/getMetricMetadata';
import { getMetricMetadata } from 'api/generated/services/metrics';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { SuccessResponseV2 } from 'types/api';
import { MetricMetadataResponse } from 'types/api/metricsExplorer/v2/getMetricMetadata';

View File

@@ -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`;
}