mirror of
https://github.com/SigNoz/signoz.git
synced 2026-06-25 17:40:32 +01:00
Compare commits
1 Commits
metric-red
...
metric-red
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3676f6b47 |
@@ -20,10 +20,7 @@ var (
|
||||
bufferSeriesTable = telemetrymetrics.DBName + "." + telemetrymetrics.TimeseriesV4BufferTableName
|
||||
)
|
||||
|
||||
const (
|
||||
timeSeriesBucketMilli = int64(time.Hour / time.Millisecond)
|
||||
sampleBucketMilli = int64(60 * time.Second / time.Millisecond)
|
||||
)
|
||||
const timeSeriesBucketMilli = int64(time.Hour / time.Millisecond)
|
||||
|
||||
type volumeRow struct {
|
||||
MetricName string
|
||||
@@ -422,23 +419,48 @@ func (c *clickhouse) countReducedSamples(ctx context.Context, table string, metr
|
||||
|
||||
// SeriesTimeseries returns ingested vs reduced series per 60s bucket from the samples tables, gated
|
||||
// to each metric's strict effective_from (see strictEffectiveFrom).
|
||||
func (c *clickhouse) SeriesTimeseries(ctx context.Context, metricNames []string, effectiveFrom map[string]int64, startMs, endMs int64) ([]volumePoint, error) {
|
||||
if len(metricNames) == 0 {
|
||||
func (c *clickhouse) SeriesTimeseries(ctx context.Context, allMetrics, reducedMetrics []string, effectiveFrom map[string]int64, startMs, endMs int64) ([]volumePoint, error) {
|
||||
if len(allMetrics) == 0 {
|
||||
return []volumePoint{}, nil
|
||||
}
|
||||
ctx = c.withThreads(ctx)
|
||||
|
||||
ingested, err := c.ingestedSeriesByBucket(ctx, metricNames, effectiveFrom, startMs, endMs)
|
||||
ingested, err := c.ingestedSeriesByBucket(ctx, allMetrics, effectiveFrom, startMs, endMs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reduced, err := c.reducedSeriesByBucket(ctx, metricNames, effectiveFrom, startMs, endMs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
retained := make(map[int64]uint64)
|
||||
if len(reducedMetrics) > 0 {
|
||||
reduced, err := c.reducedSeriesByBucket(ctx, reducedMetrics, effectiveFrom, startMs, endMs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for ts, count := range reduced {
|
||||
retained[ts] += count
|
||||
}
|
||||
}
|
||||
reducedSet := make(map[string]struct{}, len(reducedMetrics))
|
||||
for _, name := range reducedMetrics {
|
||||
reducedSet[name] = struct{}{}
|
||||
}
|
||||
nonReduced := make([]string, 0, len(allMetrics))
|
||||
for _, name := range allMetrics {
|
||||
if _, ok := reducedSet[name]; !ok {
|
||||
nonReduced = append(nonReduced, name)
|
||||
}
|
||||
}
|
||||
if len(nonReduced) > 0 {
|
||||
nonReducedIngested, err := c.ingestedSeriesByBucket(ctx, nonReduced, effectiveFrom, startMs, endMs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for ts, count := range nonReducedIngested {
|
||||
retained[ts] += count
|
||||
}
|
||||
}
|
||||
|
||||
return mergeVolumePoints(ingested, reduced), nil
|
||||
return mergeVolumePoints(ingested, retained), nil
|
||||
}
|
||||
|
||||
func mergeVolumePoints(ingested, reduced map[int64]uint64) []volumePoint {
|
||||
@@ -466,7 +488,7 @@ func mergeVolumePoints(ingested, reduced map[int64]uint64) []volumePoint {
|
||||
return points
|
||||
}
|
||||
|
||||
// ingestedSeriesByBucket counts distinct raw fingerprints per 60s bucket from the samples buffer.
|
||||
// ingestedSeriesByBucket counts distinct raw fingerprints per hourly bucket from the samples buffer.
|
||||
func (c *clickhouse) ingestedSeriesByBucket(ctx context.Context, metricNames []string, effectiveFrom map[string]int64, startMs, endMs int64) (map[int64]uint64, error) {
|
||||
names := make([]any, len(metricNames))
|
||||
for i, name := range metricNames {
|
||||
@@ -474,7 +496,7 @@ func (c *clickhouse) ingestedSeriesByBucket(ctx context.Context, metricNames []s
|
||||
}
|
||||
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
bucketExpr := "intDiv(unix_milli, " + sb.Var(sampleBucketMilli) + ") * " + sb.Var(sampleBucketMilli) + " AS bucket"
|
||||
bucketExpr := "toInt64(toUnixTimestamp(toStartOfInterval(toDateTime(intDiv(unix_milli, 1000)), toIntervalHour(1)))) * 1000 AS bucket"
|
||||
sb.Select(bucketExpr, "uniq(fingerprint)")
|
||||
sb.From(telemetrymetrics.DBName + "." + telemetrymetrics.SamplesV4BufferTableName)
|
||||
conds := []string{sb.In("metric_name", names...), sb.GE("unix_milli", startMs), sb.LT("unix_milli", endMs)}
|
||||
@@ -487,7 +509,7 @@ func (c *clickhouse) ingestedSeriesByBucket(ctx context.Context, metricNames []s
|
||||
return c.scanBuckets(ctx, sb)
|
||||
}
|
||||
|
||||
// reducedSeriesByBucket counts distinct reduced_fingerprints per 60s bucket, summed across the two
|
||||
// reducedSeriesByBucket counts distinct reduced_fingerprints per hourly bucket, summed across the two
|
||||
// reduced sample tables (a metric only lands in the table matching its type, so per-bucket sums are
|
||||
// exact).
|
||||
func (c *clickhouse) reducedSeriesByBucket(ctx context.Context, metricNames []string, effectiveFrom map[string]int64, startMs, endMs int64) (map[int64]uint64, error) {
|
||||
@@ -499,7 +521,7 @@ func (c *clickhouse) reducedSeriesByBucket(ctx context.Context, metricNames []st
|
||||
}
|
||||
|
||||
sb := sqlbuilder.NewSelectBuilder()
|
||||
bucketExpr := "intDiv(unix_milli, " + sb.Var(sampleBucketMilli) + ") * " + sb.Var(sampleBucketMilli) + " AS bucket"
|
||||
bucketExpr := "toInt64(toUnixTimestamp(toStartOfInterval(toDateTime(intDiv(unix_milli, 1000)), toIntervalHour(1)))) * 1000 AS bucket"
|
||||
sb.Select(bucketExpr, "uniq(reduced_fingerprint)")
|
||||
sb.From(telemetrymetrics.DBName + "." + table)
|
||||
conds := []string{sb.In("metric_name", names...), sb.GE("unix_milli", startMs), sb.LT("unix_milli", endMs)}
|
||||
|
||||
@@ -62,6 +62,7 @@ func NewModule(sqlStore sqlstore.SQLStore, telemetryStore telemetrystore.Telemet
|
||||
}
|
||||
|
||||
func (m *module) checkAccess(ctx context.Context, orgID valuer.UUID) error {
|
||||
return nil
|
||||
if !m.flagger.BooleanOrEmpty(ctx, flagger.FeatureEnableMetricsReduction, featuretypes.NewFlaggerEvaluationContext(orgID)) {
|
||||
return errors.Newf(errors.TypeUnsupported, metricreductionruletypes.ErrCodeMetricReductionRuleUnsupported, "metric volume control is not enabled")
|
||||
}
|
||||
@@ -310,20 +311,27 @@ func (m *module) Stats(ctx context.Context, orgID valuer.UUID) (*metricreduction
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ingestedSeries, reducedSeries uint64
|
||||
for _, volume := range volumes {
|
||||
var ingestedSeries, retainedSeries uint64
|
||||
reducedMetricNames := make([]string, 0, len(volumes))
|
||||
reducedEffectiveFrom := make(map[string]int64, len(volumes))
|
||||
for name, volume := range volumes {
|
||||
ingestedSeries += volume.Ingested
|
||||
reducedSeries += volume.Reduced
|
||||
retained := effectiveRetained(volume.Ingested, volume.Reduced)
|
||||
retainedSeries += retained
|
||||
if retained < volume.Ingested {
|
||||
reducedMetricNames = append(reducedMetricNames, name)
|
||||
reducedEffectiveFrom[name] = effectiveFrom[name]
|
||||
}
|
||||
}
|
||||
|
||||
ingestedSamples, reducedSamples, err := m.ch.SampleVolume(ctx, metricNames, effectiveFrom, startMs, endMs)
|
||||
ingestedSamples, reducedSamples, err := m.ch.SampleVolume(ctx, reducedMetricNames, reducedEffectiveFrom, startMs, endMs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &metricreductionruletypes.GettableReductionRuleStats{
|
||||
IngestedSeries: ingestedSeries,
|
||||
RetainedSeries: reducedSeries,
|
||||
RetainedSeries: retainedSeries,
|
||||
EstimatedMonthlySavingsUsd: monthlySavingsUSD(ingestedSamples, reducedSamples, startMs, endMs),
|
||||
}, nil
|
||||
}
|
||||
@@ -359,7 +367,18 @@ func (m *module) Timeseries(ctx context.Context, orgID valuer.UUID) (*querybuild
|
||||
effectiveFrom[rule.MetricName] = rule.EffectiveFrom.UnixMilli()
|
||||
}
|
||||
|
||||
points, err := m.ch.SeriesTimeseries(ctx, metricNames, effectiveFrom, startMs, endMs)
|
||||
volumes, err := m.ch.VolumeByMetric(ctx, metricNames, effectiveFrom, startMs, endMs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reducedNames := make([]string, 0, len(volumes))
|
||||
for name, volume := range volumes {
|
||||
if effectiveRetained(volume.Ingested, volume.Reduced) < volume.Ingested {
|
||||
reducedNames = append(reducedNames, name)
|
||||
}
|
||||
}
|
||||
|
||||
points, err := m.ch.SeriesTimeseries(ctx, metricNames, reducedNames, effectiveFrom, startMs, endMs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -396,20 +415,22 @@ func buildVolumeTimeseries(points []volumePoint) *querybuildertypesv5.QueryRange
|
||||
}
|
||||
|
||||
func (m *module) validateMetricForReduction(ctx context.Context, orgID valuer.UUID, metricName string) error {
|
||||
lastSeen, err := m.metadataStore.FetchLastSeenInfoMulti(ctx, metricName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lastSeen[metricName] == 0 {
|
||||
return errors.NewNotFoundf(errors.CodeNotFound, "metric not found: %q", metricName)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
startTs := uint64(now.Add(-defaultPreviewLookback).UnixMilli())
|
||||
endTs := uint64(now.UnixMilli())
|
||||
|
||||
_, types, _, err := m.metadataStore.FetchTemporalityAndTypeMulti(ctx, orgID, startTs, endTs, metricName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
metricType, ok := types[metricName]
|
||||
if !ok || metricType == metrictypes.UnspecifiedType {
|
||||
return errors.NewNotFoundf(errors.CodeNotFound, "metric not found: %q", metricName)
|
||||
}
|
||||
if metricType == metrictypes.ExpHistogramType {
|
||||
if types[metricName] == metrictypes.ExpHistogramType {
|
||||
return errors.Newf(errors.TypeInvalidInput, metricreductionruletypes.ErrCodeMetricReductionRuleUnsupportedMetricType,
|
||||
"exponential histogram metrics cannot be reduced in v1")
|
||||
}
|
||||
@@ -466,11 +487,18 @@ func toGettableReductionRule(rule *metricreductionruletypes.ReductionRule) metri
|
||||
}
|
||||
}
|
||||
|
||||
func effectiveRetained(ingested, reduced uint64) uint64 {
|
||||
if reduced == 0 || reduced > ingested {
|
||||
return ingested
|
||||
}
|
||||
return reduced
|
||||
}
|
||||
|
||||
func withVolume(rule metricreductionruletypes.GettableReductionRule, volume volumeRow) metricreductionruletypes.GettableReductionRule {
|
||||
rule.IngestedSeries = volume.Ingested
|
||||
rule.RetainedSeries = volume.Reduced
|
||||
if volume.Ingested > 0 && volume.Reduced <= volume.Ingested {
|
||||
rule.ReductionPercent = (1 - float64(volume.Reduced)/float64(volume.Ingested)) * 100
|
||||
rule.RetainedSeries = effectiveRetained(volume.Ingested, volume.Reduced)
|
||||
if volume.Ingested > 0 {
|
||||
rule.ReductionPercent = (1 - float64(rule.RetainedSeries)/float64(volume.Ingested)) * 100
|
||||
}
|
||||
return rule
|
||||
}
|
||||
|
||||
@@ -477,6 +477,13 @@ const routes: AppRoutes[] = [
|
||||
key: 'METRICS_EXPLORER_VIEWS',
|
||||
isPrivate: true,
|
||||
},
|
||||
{
|
||||
path: ROUTES.METRICS_EXPLORER_VOLUME_CONTROL,
|
||||
exact: true,
|
||||
component: MetricsExplorer,
|
||||
key: 'METRICS_EXPLORER_VOLUME_CONTROL',
|
||||
isPrivate: true,
|
||||
},
|
||||
|
||||
{
|
||||
path: ROUTES.METER,
|
||||
|
||||
@@ -13,4 +13,5 @@ export enum FeatureKeys {
|
||||
USE_FINE_GRAINED_AUTHZ = 'use_fine_grained_authz',
|
||||
USE_DASHBOARD_V2 = 'use_dashboard_v2',
|
||||
EMABLE_AI_OBSERVABILITY = 'enable_ai_observability',
|
||||
ENABLE_METRICS_REDUCTION = 'enable_metrics_reduction',
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ const ROUTES = {
|
||||
METRICS_EXPLORER: '/metrics-explorer/summary',
|
||||
METRICS_EXPLORER_EXPLORER: '/metrics-explorer/explorer',
|
||||
METRICS_EXPLORER_VIEWS: '/metrics-explorer/views',
|
||||
METRICS_EXPLORER_VOLUME_CONTROL: '/metrics-explorer/volume-control',
|
||||
API_MONITORING_BASE: '/api-monitoring',
|
||||
API_MONITORING: '/api-monitoring/explorer',
|
||||
METRICS_EXPLORER_BASE: '/metrics-explorer',
|
||||
|
||||
@@ -21,6 +21,7 @@ import AllAttributes from './AllAttributes';
|
||||
import DashboardsAndAlertsPopover from './DashboardsAndAlertsPopover';
|
||||
import Highlights from './Highlights';
|
||||
import Metadata from './Metadata';
|
||||
import VolumeControlSection from './VolumeControl/VolumeControlSection';
|
||||
import { MetricDetailsProps } from './types';
|
||||
import { getMetricDetailsQuery } from './utils';
|
||||
|
||||
@@ -190,6 +191,7 @@ function MetricDetails({
|
||||
isLoadingMetricMetadata={isLoadingMetricMetadata}
|
||||
refetchMetricMetadata={refetchMetricMetadata}
|
||||
/>
|
||||
<VolumeControlSection metricName={metricName} />
|
||||
<AllAttributes
|
||||
metricName={metricName}
|
||||
metricType={metadata?.type}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { Spin } from 'antd';
|
||||
import { MetricreductionruletypesGettableReductionRulePreviewDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { formatCompact } from './configUtils';
|
||||
import { RuleMode } from './types';
|
||||
import styles from './VolumeControlConfig.module.scss';
|
||||
|
||||
interface ImpactPanelProps {
|
||||
mode: RuleMode;
|
||||
preview?: MetricreductionruletypesGettableReductionRulePreviewDTO;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
function ImpactPanel({
|
||||
mode,
|
||||
preview,
|
||||
isLoading,
|
||||
}: ImpactPanelProps): JSX.Element {
|
||||
if (mode === 'all') {
|
||||
return (
|
||||
<div className={styles.impact} data-testid="volume-control-impact">
|
||||
<Typography.Text className={styles.impactNote}>
|
||||
All attributes remain queryable, no reduction.
|
||||
</Typography.Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const current = preview?.currentRetainedSeries ?? 0;
|
||||
const proposed = preview?.retainedSeries ?? 0;
|
||||
const deltaPct = current > 0 ? (1 - proposed / current) * 100 : 0;
|
||||
const reductionLabel = `${deltaPct >= 0 ? '−' : '+'}${Math.round(
|
||||
Math.abs(deltaPct),
|
||||
)}%`;
|
||||
|
||||
return (
|
||||
<div className={styles.impact} data-testid="volume-control-impact">
|
||||
{isLoading && <Spin size="small" />}
|
||||
{!isLoading && preview && (
|
||||
<div className={styles.meters}>
|
||||
<div className={styles.meter}>
|
||||
<span className={styles.meterLabel}>Current series</span>
|
||||
<span className={styles.meterValue}>{formatCompact(current)}</span>
|
||||
</div>
|
||||
<div className={styles.meter}>
|
||||
<span className={styles.meterLabel}>Proposed series</span>
|
||||
<span className={styles.meterValue}>{formatCompact(proposed)}</span>
|
||||
</div>
|
||||
<div className={styles.meter}>
|
||||
<span className={styles.meterLabel}>Reduction</span>
|
||||
<span
|
||||
className={`${styles.meterValue} ${
|
||||
deltaPct >= 0 ? styles.meterValueGood : ''
|
||||
}`}
|
||||
>
|
||||
{reductionLabel}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && !preview && (
|
||||
<Typography.Text className={styles.impactNote}>
|
||||
Select attributes to preview the impact.
|
||||
</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ImpactPanel;
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { Select } from 'antd';
|
||||
import { popupContainer } from 'utils/selectPopupContainer';
|
||||
|
||||
import { RuleMode } from './types';
|
||||
import styles from './VolumeControlConfig.module.scss';
|
||||
|
||||
interface LabelSelectorProps {
|
||||
mode: RuleMode;
|
||||
options: string[];
|
||||
value: string[];
|
||||
onChange: (labels: string[]) => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
function LabelSelector({
|
||||
mode,
|
||||
options,
|
||||
value,
|
||||
onChange,
|
||||
loading,
|
||||
}: LabelSelectorProps): JSX.Element {
|
||||
const helpText =
|
||||
mode === 'include'
|
||||
? 'Only the selected attributes will remain queryable.'
|
||||
: 'The selected attributes will be aggregated away; all others stay queryable.';
|
||||
|
||||
return (
|
||||
<div className={styles.field} data-testid="volume-control-label-selector">
|
||||
<Typography.Text className={styles.fieldLabel}>Attributes</Typography.Text>
|
||||
<Typography.Text className={styles.fieldHint}>{helpText}</Typography.Text>
|
||||
<Select
|
||||
mode="multiple"
|
||||
className={styles.labelSelect}
|
||||
placeholder="Select attributes"
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
loading={loading}
|
||||
options={options.map((key) => ({ label: key, value: key }))}
|
||||
getPopupContainer={popupContainer}
|
||||
data-testid="volume-control-label-select"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LabelSelector;
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import { RuleMode } from './types';
|
||||
import styles from './VolumeControlConfig.module.scss';
|
||||
|
||||
interface ModeOption {
|
||||
mode: RuleMode;
|
||||
title: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
const MODE_OPTIONS: ModeOption[] = [
|
||||
{
|
||||
mode: 'all',
|
||||
title: 'Allow all attributes',
|
||||
description: 'All attributes stay queryable. Removes any existing rule.',
|
||||
},
|
||||
{
|
||||
mode: 'include',
|
||||
title: 'Include attributes',
|
||||
description: 'Allowlist: only the selected attributes stay queryable.',
|
||||
},
|
||||
{
|
||||
mode: 'exclude',
|
||||
title: 'Exclude attributes',
|
||||
description: 'Blocklist: the selected attributes are aggregated away.',
|
||||
},
|
||||
];
|
||||
|
||||
interface ModeSelectorProps {
|
||||
mode: RuleMode;
|
||||
onChange: (mode: RuleMode) => void;
|
||||
}
|
||||
|
||||
function ModeSelector({ mode, onChange }: ModeSelectorProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.modeCards} data-testid="volume-control-mode-selector">
|
||||
{MODE_OPTIONS.map((option) => (
|
||||
<button
|
||||
type="button"
|
||||
key={option.mode}
|
||||
className={`${styles.modeCard} ${
|
||||
mode === option.mode ? styles.modeCardActive : ''
|
||||
}`}
|
||||
onClick={(): void => onChange(option.mode)}
|
||||
data-testid={`volume-control-mode-${option.mode}`}
|
||||
>
|
||||
<Typography.Text className={styles.modeTitle}>
|
||||
{option.title}
|
||||
</Typography.Text>
|
||||
<Typography.Text className={styles.modeDesc}>
|
||||
{option.description}
|
||||
</Typography.Text>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ModeSelector;
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Info } from '@signozhq/icons';
|
||||
import {
|
||||
MetricreductionruletypesAffectedAssetDTO,
|
||||
MetricreductionruletypesAssetTypeDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
|
||||
import styles from './VolumeControlConfig.module.scss';
|
||||
|
||||
const AssetType = MetricreductionruletypesAssetTypeDTO;
|
||||
|
||||
function assetHref(
|
||||
asset: MetricreductionruletypesAffectedAssetDTO,
|
||||
): string | undefined {
|
||||
if (!asset.id) {
|
||||
return undefined;
|
||||
}
|
||||
if (asset.type === AssetType.dashboard) {
|
||||
const base = ROUTES.DASHBOARD.replace(':dashboardId', asset.id);
|
||||
return asset.widget?.id
|
||||
? `${base}?${QueryParams.expandedWidgetId}=${asset.widget.id}`
|
||||
: base;
|
||||
}
|
||||
if (asset.type === AssetType.alert_rule) {
|
||||
return `${ROUTES.EDIT_ALERTS}?ruleId=${asset.id}`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
interface RelatedAssetsWarningProps {
|
||||
affectedAssets?: MetricreductionruletypesAffectedAssetDTO[] | null;
|
||||
}
|
||||
|
||||
function RelatedAssetsWarning({
|
||||
affectedAssets,
|
||||
}: RelatedAssetsWarningProps): JSX.Element | null {
|
||||
const impacted = (affectedAssets ?? []).filter(
|
||||
(asset) =>
|
||||
asset.type === AssetType.alert_rule ||
|
||||
(asset.impactedLabels ?? []).length > 0,
|
||||
);
|
||||
if (impacted.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const impactedLabels = Array.from(
|
||||
new Set(impacted.flatMap((asset) => asset.impactedLabels ?? [])),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.warning} data-testid="volume-control-warning">
|
||||
<Info size={14} />
|
||||
<div>
|
||||
<div className={styles.warningTitle}>
|
||||
This rule affects {impacted.length} related asset
|
||||
{impacted.length > 1 ? 's' : ''}.
|
||||
</div>
|
||||
{impactedLabels.length > 0 && (
|
||||
<div className={styles.warningDetail}>
|
||||
{impactedLabels.join(', ')} will no longer be queryable; affected panels
|
||||
fall back to aggregated data once the rule applies.
|
||||
</div>
|
||||
)}
|
||||
<ul className={styles.assetList}>
|
||||
{impacted.map((asset) => {
|
||||
const href = assetHref(asset);
|
||||
const label = `${asset.name}${
|
||||
asset.widget ? ` · ${asset.widget.name}` : ''
|
||||
}`;
|
||||
return (
|
||||
<li key={`${asset.type}-${asset.id}-${asset.widget?.id ?? ''}`}>
|
||||
{href ? (
|
||||
<a href={href} target="_blank" rel="noopener noreferrer">
|
||||
{label}
|
||||
</a>
|
||||
) : (
|
||||
label
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default RelatedAssetsWarning;
|
||||
@@ -0,0 +1,172 @@
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
padding: 4px 2px;
|
||||
}
|
||||
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.admin-tag {
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.03em;
|
||||
color: var(--bg-amber-400, #ffd778);
|
||||
border: 1px solid var(--bg-amber-500, #ffcc56);
|
||||
border-radius: 99px;
|
||||
padding: 1px 8px;
|
||||
}
|
||||
|
||||
/* mode cards */
|
||||
.mode-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.mode-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
text-align: left;
|
||||
border: 1px solid var(--bg-slate-400, #1d212d);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-ink-300, #16181d);
|
||||
padding: 12px;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
border-color 0.12s ease,
|
||||
background 0.12s ease;
|
||||
}
|
||||
|
||||
.mode-card:hover {
|
||||
border-color: var(--bg-slate-200, #2c3140);
|
||||
}
|
||||
|
||||
.mode-card-active {
|
||||
border-color: var(--bg-robin-500, #4e74f8);
|
||||
background: rgba(78, 116, 248, 0.08);
|
||||
}
|
||||
|
||||
.mode-title {
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
color: var(--bg-vanilla-100, #fff);
|
||||
}
|
||||
|
||||
.mode-desc {
|
||||
font-size: 11px;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
/* label selector */
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
color: var(--bg-vanilla-100, #fff);
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
font-size: 11px;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.label-select {
|
||||
width: 100%;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* impact panel */
|
||||
.impact {
|
||||
border: 1px solid var(--bg-slate-400, #1d212d);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-ink-300, #16181d);
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.impact-note {
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.meters {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.meter {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.meter-label {
|
||||
font-size: 10px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.meter-value {
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: 18px;
|
||||
color: var(--bg-vanilla-100, #fff);
|
||||
}
|
||||
|
||||
.meter-value-good {
|
||||
color: var(--bg-forest-400, #50e7a7);
|
||||
}
|
||||
|
||||
/* related-asset warning */
|
||||
.warning {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
padding: 11px 13px;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 204, 86, 0.07);
|
||||
border: 1px solid rgba(255, 204, 86, 0.3);
|
||||
color: var(--bg-amber-400, #ffd778);
|
||||
}
|
||||
|
||||
.warning-title {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--bg-vanilla-100, #fff);
|
||||
}
|
||||
|
||||
.warning-detail {
|
||||
font-size: 11.5px;
|
||||
color: var(--bg-vanilla-300, #e9e9e9);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.asset-list {
|
||||
margin: 6px 0 0;
|
||||
padding-left: 16px;
|
||||
font-size: 11.5px;
|
||||
color: var(--bg-vanilla-300, #e9e9e9);
|
||||
}
|
||||
|
||||
/* footer */
|
||||
.footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.footer-spacer {
|
||||
flex: 1;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { DrawerWrapper } from '@signozhq/ui/drawer';
|
||||
import { MetricreductionruletypesGettableReductionRuleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import ImpactPanel from './ImpactPanel';
|
||||
import LabelSelector from './LabelSelector';
|
||||
import ModeSelector from './ModeSelector';
|
||||
import RelatedAssetsWarning from './RelatedAssetsWarning';
|
||||
import { useVolumeControlConfig } from './useVolumeControlConfig';
|
||||
import styles from './VolumeControlConfig.module.scss';
|
||||
|
||||
interface VolumeControlConfigDrawerProps {
|
||||
metricName: string;
|
||||
existingRule: MetricreductionruletypesGettableReductionRuleDTO | null;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function VolumeControlConfigDrawer({
|
||||
metricName,
|
||||
existingRule,
|
||||
open,
|
||||
onClose,
|
||||
}: VolumeControlConfigDrawerProps): JSX.Element {
|
||||
const {
|
||||
mode,
|
||||
setMode,
|
||||
labels,
|
||||
setLabels,
|
||||
attributeKeys,
|
||||
isLoadingAttributes,
|
||||
preview,
|
||||
isPreviewLoading,
|
||||
save,
|
||||
remove,
|
||||
isSaving,
|
||||
isRemoving,
|
||||
hasExistingRule,
|
||||
isSaveDisabled,
|
||||
} = useVolumeControlConfig({ metricName, existingRule, open, onClose });
|
||||
|
||||
const footer = (
|
||||
<div className={styles.footer}>
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
onClick={onClose}
|
||||
data-testid="volume-control-cancel"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<div className={styles.footerSpacer} />
|
||||
{hasExistingRule && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="destructive"
|
||||
onClick={remove}
|
||||
loading={isRemoving}
|
||||
data-testid="volume-control-remove"
|
||||
>
|
||||
Remove rule
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={save}
|
||||
disabled={isSaveDisabled}
|
||||
loading={isSaving}
|
||||
data-testid="volume-control-save"
|
||||
>
|
||||
Save rule
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<DrawerWrapper
|
||||
open={open}
|
||||
onOpenChange={(next: boolean): void => {
|
||||
if (!next) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
title={`Manage attributes · ${metricName}`}
|
||||
direction="right"
|
||||
showCloseButton
|
||||
width="wide"
|
||||
footer={footer}
|
||||
showOverlay={false}
|
||||
className="volume-control-config-drawer"
|
||||
style={{ zIndex: 1100 }}
|
||||
>
|
||||
<div className={styles.body} data-testid="volume-control-config-drawer">
|
||||
<div className={styles.title}>
|
||||
<span className={styles.adminTag}>Admin only</span>
|
||||
</div>
|
||||
<ModeSelector mode={mode} onChange={setMode} />
|
||||
{mode !== 'all' && (
|
||||
<LabelSelector
|
||||
mode={mode}
|
||||
options={attributeKeys}
|
||||
value={labels}
|
||||
onChange={setLabels}
|
||||
loading={isLoadingAttributes}
|
||||
/>
|
||||
)}
|
||||
<ImpactPanel mode={mode} preview={preview} isLoading={isPreviewLoading} />
|
||||
<RelatedAssetsWarning affectedAssets={preview?.affectedAssets} />
|
||||
</div>
|
||||
</DrawerWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export default VolumeControlConfigDrawer;
|
||||
@@ -0,0 +1,114 @@
|
||||
.section {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.card {
|
||||
border: 1px solid var(--bg-slate-400, #1d212d);
|
||||
border-radius: 6px;
|
||||
padding: 12px 14px;
|
||||
background: var(--bg-ink-300, #16181d);
|
||||
}
|
||||
|
||||
.card-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.status-active {
|
||||
background: var(--bg-forest-500, #25e192);
|
||||
}
|
||||
|
||||
.status-pending {
|
||||
background: var(--bg-amber-500, #ffcc56);
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.mode {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.chip {
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg-ink-200, #23262e);
|
||||
border: 1px solid var(--bg-slate-400, #1d212d);
|
||||
color: var(--bg-vanilla-100, #fff);
|
||||
}
|
||||
|
||||
.empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
border: 1px dashed var(--bg-slate-300, #242834);
|
||||
border-radius: 6px;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.empty-text {
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.setup-button {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.edit-button {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.pending-banner {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 9px 12px;
|
||||
margin-bottom: 10px;
|
||||
border-radius: 6px;
|
||||
background: rgba(35, 196, 248, 0.07);
|
||||
border: 1px solid rgba(35, 196, 248, 0.25);
|
||||
color: var(--bg-aqua-400, #4bcff9);
|
||||
}
|
||||
|
||||
.pending-text {
|
||||
font-size: 11.5px;
|
||||
color: var(--bg-vanilla-300, #e9e9e9);
|
||||
line-height: 1.45;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { Gauge, Info } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { Skeleton } from 'antd';
|
||||
import { useListMetricReductionRules } from 'api/generated/services/metrics';
|
||||
import { useVolumeControlFeatureGate } from 'hooks/metricsExplorer/useVolumeControlFeatureGate';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { getLabelVerb, getMatchTypeLabel } from './utils';
|
||||
import VolumeControlConfigDrawer from './VolumeControlConfigDrawer';
|
||||
import styles from './VolumeControlSection.module.scss';
|
||||
|
||||
interface VolumeControlSectionProps {
|
||||
metricName: string;
|
||||
}
|
||||
|
||||
function VolumeControlSection({
|
||||
metricName,
|
||||
}: VolumeControlSectionProps): JSX.Element | null {
|
||||
const { isVolumeControlEnabled, canManageVolumeControl } =
|
||||
useVolumeControlFeatureGate();
|
||||
const [isConfigOpen, setIsConfigOpen] = useState(false);
|
||||
|
||||
const { data, isLoading, error } = useListMetricReductionRules(
|
||||
{ metricName },
|
||||
{
|
||||
query: {
|
||||
enabled: isVolumeControlEnabled && !!metricName,
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!isVolumeControlEnabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rule = data?.data.rules?.[0];
|
||||
const hasRule = !!rule && !error;
|
||||
|
||||
const openConfig = (): void => setIsConfigOpen(true);
|
||||
const closeConfig = (): void => setIsConfigOpen(false);
|
||||
|
||||
return (
|
||||
<div className={styles.section} data-testid="volume-control-section">
|
||||
<div className={styles.header}>
|
||||
<Gauge size={14} />
|
||||
<Typography.Text className={styles.title}>Volume control</Typography.Text>
|
||||
</div>
|
||||
|
||||
{isLoading && <Skeleton active title={false} paragraph={{ rows: 2 }} />}
|
||||
|
||||
{!isLoading && hasRule && rule && !rule.active && (
|
||||
<div
|
||||
className={styles.pendingBanner}
|
||||
data-testid="volume-control-pending-banner"
|
||||
>
|
||||
<Info size={13} />
|
||||
<Typography.Text className={styles.pendingText}>
|
||||
This metric's configuration was recently updated. Volume changes will
|
||||
take effect within a few minutes.
|
||||
</Typography.Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && hasRule && rule && (
|
||||
<div className={styles.card} data-testid="volume-control-active">
|
||||
<div className={styles.cardRow}>
|
||||
<span
|
||||
className={`${styles.statusDot} ${
|
||||
rule.active ? styles.statusActive : styles.statusPending
|
||||
}`}
|
||||
/>
|
||||
<Typography.Text className={styles.cardTitle}>
|
||||
{rule.active
|
||||
? 'Aggregation rule active'
|
||||
: 'Aggregation rule pending activation'}
|
||||
</Typography.Text>
|
||||
{canManageVolumeControl && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
className={styles.editButton}
|
||||
onClick={openConfig}
|
||||
data-testid="volume-control-edit"
|
||||
>
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Typography.Text className={styles.mode}>
|
||||
{getMatchTypeLabel(rule.matchType)}
|
||||
</Typography.Text>
|
||||
<div className={styles.chips}>
|
||||
{(rule.labels ?? []).map((label) => (
|
||||
<span className={styles.chip} key={label}>
|
||||
{getLabelVerb(rule.matchType)} {label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && !hasRule && (
|
||||
<div className={styles.empty} data-testid="volume-control-empty">
|
||||
<Typography.Text className={styles.emptyText}>
|
||||
No volume control rule. All series are retained. Aggregate away
|
||||
high-cardinality attributes to reduce cost.
|
||||
</Typography.Text>
|
||||
{canManageVolumeControl && (
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
className={styles.setupButton}
|
||||
onClick={openConfig}
|
||||
data-testid="volume-control-setup"
|
||||
>
|
||||
Set up volume control
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canManageVolumeControl && isConfigOpen && (
|
||||
<VolumeControlConfigDrawer
|
||||
metricName={metricName}
|
||||
existingRule={rule ?? null}
|
||||
open={isConfigOpen}
|
||||
onClose={closeConfig}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default VolumeControlSection;
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
MetricreductionruletypesMatchTypeDTO,
|
||||
MetricreductionruletypesGettableReductionRuleDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { RuleMode } from './types';
|
||||
|
||||
export function modeFromRule(
|
||||
rule: MetricreductionruletypesGettableReductionRuleDTO | null | undefined,
|
||||
): { mode: RuleMode; labels: string[] } {
|
||||
if (!rule) {
|
||||
return { mode: 'all', labels: [] };
|
||||
}
|
||||
return {
|
||||
mode:
|
||||
rule.matchType === MetricreductionruletypesMatchTypeDTO.keep
|
||||
? 'include'
|
||||
: 'exclude',
|
||||
labels: rule.labels ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export function matchTypeForMode(
|
||||
mode: RuleMode,
|
||||
): MetricreductionruletypesMatchTypeDTO {
|
||||
return mode === 'include'
|
||||
? MetricreductionruletypesMatchTypeDTO.keep
|
||||
: MetricreductionruletypesMatchTypeDTO.drop;
|
||||
}
|
||||
|
||||
export function formatCompact(value: number): string {
|
||||
if (value >= 1e9) {
|
||||
return `${(value / 1e9).toFixed(1)}B`;
|
||||
}
|
||||
if (value >= 1e6) {
|
||||
return `${(value / 1e6).toFixed(1)}M`;
|
||||
}
|
||||
if (value >= 1e3) {
|
||||
return `${(value / 1e3).toFixed(1)}K`;
|
||||
}
|
||||
return `${value}`;
|
||||
}
|
||||
|
||||
export function formatUsd(value: number): string {
|
||||
if (value >= 1e3) {
|
||||
return `$${(value / 1e3).toFixed(1)}K`;
|
||||
}
|
||||
return `$${value.toFixed(2)}`;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export type RuleMode = 'all' | 'include' | 'exclude';
|
||||
@@ -0,0 +1,211 @@
|
||||
import {
|
||||
invalidateListMetricReductionRules,
|
||||
invalidateListMetrics,
|
||||
useCreateMetricReductionRule,
|
||||
useDeleteMetricReductionRuleByID,
|
||||
useGetMetricAttributes,
|
||||
usePreviewMetricReductionRule,
|
||||
useUpdateMetricReductionRuleByID,
|
||||
} from 'api/generated/services/metrics';
|
||||
import {
|
||||
MetricreductionruletypesGettableReductionRuleDTO,
|
||||
MetricreductionruletypesGettableReductionRulePreviewDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import { matchTypeForMode, modeFromRule } from './configUtils';
|
||||
import { RuleMode } from './types';
|
||||
|
||||
interface UseVolumeControlConfigParams {
|
||||
metricName: string;
|
||||
existingRule: MetricreductionruletypesGettableReductionRuleDTO | null;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export interface UseVolumeControlConfigResult {
|
||||
mode: RuleMode;
|
||||
setMode: (mode: RuleMode) => void;
|
||||
labels: string[];
|
||||
setLabels: (labels: string[]) => void;
|
||||
attributeKeys: string[];
|
||||
isLoadingAttributes: boolean;
|
||||
preview?: MetricreductionruletypesGettableReductionRulePreviewDTO;
|
||||
isPreviewLoading: boolean;
|
||||
save: () => void;
|
||||
remove: () => void;
|
||||
isSaving: boolean;
|
||||
isRemoving: boolean;
|
||||
hasExistingRule: boolean;
|
||||
isSaveDisabled: boolean;
|
||||
}
|
||||
|
||||
const PREVIEW_DEBOUNCE_MS = 400;
|
||||
const SAVE_ERROR_MESSAGE = 'Failed to save volume control rule';
|
||||
const REMOVE_ERROR_MESSAGE = 'Failed to remove volume control rule';
|
||||
|
||||
export function useVolumeControlConfig({
|
||||
metricName,
|
||||
existingRule,
|
||||
open,
|
||||
onClose,
|
||||
}: UseVolumeControlConfigParams): UseVolumeControlConfigResult {
|
||||
const { notifications } = useNotifications();
|
||||
const queryClient = useQueryClient();
|
||||
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
|
||||
const initial = useMemo(() => modeFromRule(existingRule), [existingRule]);
|
||||
const [mode, setMode] = useState<RuleMode>(initial.mode);
|
||||
const [labels, setLabels] = useState<string[]>(initial.labels);
|
||||
|
||||
const existingRuleId = existingRule?.id;
|
||||
|
||||
const attributesQuery = useGetMetricAttributes(
|
||||
{
|
||||
metricName,
|
||||
start: minTime ? Math.floor(minTime / 1000000) : undefined,
|
||||
end: maxTime ? Math.floor(maxTime / 1000000) : undefined,
|
||||
},
|
||||
{ query: { enabled: open && !!metricName } },
|
||||
);
|
||||
const attributeKeys = useMemo(
|
||||
() => (attributesQuery.data?.data.attributes ?? []).map((attr) => attr.key),
|
||||
[attributesQuery.data],
|
||||
);
|
||||
|
||||
const previewMutation = usePreviewMetricReductionRule();
|
||||
const { mutate: previewMutate, reset: previewReset } = previewMutation;
|
||||
const [isPreviewPending, setIsPreviewPending] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || mode === 'all' || labels.length === 0) {
|
||||
previewReset();
|
||||
setIsPreviewPending(false);
|
||||
return undefined;
|
||||
}
|
||||
setIsPreviewPending(true);
|
||||
const timer = setTimeout(() => {
|
||||
previewMutate(
|
||||
{ data: { metricName, matchType: matchTypeForMode(mode), labels } },
|
||||
{ onSettled: () => setIsPreviewPending(false) },
|
||||
);
|
||||
}, PREVIEW_DEBOUNCE_MS);
|
||||
return (): void => clearTimeout(timer);
|
||||
}, [open, mode, labels, metricName, previewMutate, previewReset]);
|
||||
|
||||
const createMutation = useCreateMetricReductionRule();
|
||||
const updateMutation = useUpdateMetricReductionRuleByID();
|
||||
const deleteMutation = useDeleteMetricReductionRuleByID();
|
||||
|
||||
const invalidate = useCallback((): void => {
|
||||
void invalidateListMetricReductionRules(queryClient);
|
||||
void invalidateListMetrics(queryClient);
|
||||
}, [queryClient]);
|
||||
|
||||
const removeRule = useCallback((): void => {
|
||||
if (!existingRuleId) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
deleteMutation.mutate(
|
||||
{ pathParams: { id: existingRuleId } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
notifications.success({ message: 'Volume control rule removed' });
|
||||
invalidate();
|
||||
onClose();
|
||||
},
|
||||
onError: (error) =>
|
||||
notifications.error({
|
||||
message: error.response?.data?.error?.message ?? REMOVE_ERROR_MESSAGE,
|
||||
}),
|
||||
},
|
||||
);
|
||||
}, [deleteMutation, existingRuleId, notifications, invalidate, onClose]);
|
||||
|
||||
const save = useCallback((): void => {
|
||||
if (mode === 'all') {
|
||||
if (!existingRuleId) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
removeRule();
|
||||
return;
|
||||
}
|
||||
|
||||
const onSuccess = (): void => {
|
||||
notifications.success({ message: 'Volume control rule saved' });
|
||||
invalidate();
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (existingRuleId) {
|
||||
updateMutation.mutate(
|
||||
{
|
||||
pathParams: { id: existingRuleId },
|
||||
data: { matchType: matchTypeForMode(mode), labels },
|
||||
},
|
||||
{
|
||||
onSuccess,
|
||||
onError: (error) =>
|
||||
notifications.error({
|
||||
message: error.response?.data?.error?.message ?? SAVE_ERROR_MESSAGE,
|
||||
}),
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
createMutation.mutate(
|
||||
{
|
||||
data: { metricName, matchType: matchTypeForMode(mode), labels },
|
||||
},
|
||||
{
|
||||
onSuccess,
|
||||
onError: (error) =>
|
||||
notifications.error({
|
||||
message: error.response?.data?.error?.message ?? SAVE_ERROR_MESSAGE,
|
||||
}),
|
||||
},
|
||||
);
|
||||
}, [
|
||||
mode,
|
||||
labels,
|
||||
metricName,
|
||||
existingRuleId,
|
||||
createMutation,
|
||||
updateMutation,
|
||||
removeRule,
|
||||
notifications,
|
||||
invalidate,
|
||||
onClose,
|
||||
]);
|
||||
|
||||
return {
|
||||
mode,
|
||||
setMode,
|
||||
labels,
|
||||
setLabels,
|
||||
attributeKeys,
|
||||
isLoadingAttributes: attributesQuery.isLoading,
|
||||
preview: previewMutation.data?.data,
|
||||
isPreviewLoading: isPreviewPending,
|
||||
save,
|
||||
remove: removeRule,
|
||||
isSaving:
|
||||
createMutation.isLoading ||
|
||||
updateMutation.isLoading ||
|
||||
deleteMutation.isLoading,
|
||||
isRemoving: deleteMutation.isLoading,
|
||||
hasExistingRule: !!existingRuleId,
|
||||
isSaveDisabled: mode !== 'all' && labels.length === 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { MetricreductionruletypesMatchTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export function isKeepMode(
|
||||
matchType: MetricreductionruletypesMatchTypeDTO,
|
||||
): boolean {
|
||||
return matchType === MetricreductionruletypesMatchTypeDTO.keep;
|
||||
}
|
||||
|
||||
export function getMatchTypeLabel(
|
||||
matchType: MetricreductionruletypesMatchTypeDTO,
|
||||
): string {
|
||||
return isKeepMode(matchType) ? 'Include attributes' : 'Exclude attributes';
|
||||
}
|
||||
|
||||
export function getLabelVerb(
|
||||
matchType: MetricreductionruletypesMatchTypeDTO,
|
||||
): string {
|
||||
return isKeepMode(matchType) ? 'include' : 'exclude';
|
||||
}
|
||||
@@ -77,6 +77,14 @@ jest.mock(
|
||||
},
|
||||
);
|
||||
|
||||
jest.mock(
|
||||
'container/MetricsExplorer/MetricDetails/VolumeControl/VolumeControlSection',
|
||||
() =>
|
||||
function MockVolumeControlSection(): JSX.Element {
|
||||
return <div data-testid="volume-control-section-mock">Volume Control</div>;
|
||||
},
|
||||
);
|
||||
|
||||
const useGetMetricMetadataMock = jest.spyOn(
|
||||
metricsExplorerHooks,
|
||||
'useGetMetricMetadata',
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
height: 20px;
|
||||
padding: 0 8px;
|
||||
border-radius: 99px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.active {
|
||||
color: var(--bg-forest-400, #50e7a7);
|
||||
background: rgba(37, 225, 146, 0.1);
|
||||
border: 1px solid rgba(37, 225, 146, 0.22);
|
||||
}
|
||||
|
||||
.pending {
|
||||
color: var(--bg-amber-400, #ffd778);
|
||||
background: rgba(255, 204, 86, 0.1);
|
||||
border: 1px solid rgba(255, 204, 86, 0.25);
|
||||
}
|
||||
|
||||
.none {
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
font-size: 12px;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Gauge } from '@signozhq/icons';
|
||||
import { MetricreductionruletypesGettableReductionRuleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import styles from './VolumeControlBadge.module.scss';
|
||||
|
||||
interface VolumeControlBadgeProps {
|
||||
rule?: MetricreductionruletypesGettableReductionRuleDTO;
|
||||
}
|
||||
|
||||
function VolumeControlBadge({ rule }: VolumeControlBadgeProps): JSX.Element {
|
||||
if (!rule) {
|
||||
return (
|
||||
<span className={styles.none} data-testid="vc-badge-none">
|
||||
—
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={`${styles.badge} ${rule.active ? styles.active : styles.pending}`}
|
||||
data-testid="vc-badge-active"
|
||||
>
|
||||
<Gauge size={11} />
|
||||
{rule.active ? 'Active' : 'Pending'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default VolumeControlBadge;
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { useGetMetricReductionRuleTimeseries } from 'api/generated/services/metrics';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import BarChart from 'container/DashboardContainer/visualization/charts/BarChart/BarChart';
|
||||
import { buildBaseConfig } from 'container/DashboardContainer/visualization/panels/utils/baseConfigBuilder';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useResizeObserver } from 'hooks/useDimensions';
|
||||
import { LegendPosition } from 'lib/uPlotV2/components/types';
|
||||
import { DrawStyle } from 'lib/uPlotV2/config/types';
|
||||
import { getUPlotChartData } from 'lib/uPlotLib/utils/getUplotChartData';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import { useMemo, useRef } from 'react';
|
||||
|
||||
import { buildVolumeChartPayload } from './utils';
|
||||
import styles from './VolumeControlTab.module.scss';
|
||||
|
||||
const COLOR_MAPPING: Record<string, string> = {
|
||||
Ingested: Color.BG_ROBIN_500,
|
||||
Retained: Color.BG_FOREST_500,
|
||||
};
|
||||
|
||||
interface VolumeControlChartProps {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
function VolumeControlChart({ enabled }: VolumeControlChartProps): JSX.Element {
|
||||
const { data } = useGetMetricReductionRuleTimeseries({ query: { enabled } });
|
||||
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const { timezone } = useTimezone();
|
||||
const graphRef = useRef<HTMLDivElement>(null);
|
||||
const dimensions = useResizeObserver(graphRef);
|
||||
|
||||
const payload = useMemo(
|
||||
() => buildVolumeChartPayload(data?.data).payload,
|
||||
[data],
|
||||
);
|
||||
const chartData = useMemo(() => getUPlotChartData(payload), [payload]);
|
||||
|
||||
const config = useMemo(() => {
|
||||
const timestamps = (chartData[0] as number[]) ?? [];
|
||||
const builder = buildBaseConfig({
|
||||
id: 'metric-volume-control',
|
||||
isDarkMode,
|
||||
apiResponse: payload,
|
||||
timezone,
|
||||
panelType: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'short',
|
||||
onDragSelect: (): void => {},
|
||||
minTimeScale: timestamps[0],
|
||||
maxTimeScale: timestamps[timestamps.length - 1],
|
||||
});
|
||||
(payload.data.result ?? []).forEach((series) => {
|
||||
builder.addSeries({
|
||||
scaleKey: 'y',
|
||||
drawStyle: DrawStyle.Bar,
|
||||
label: series.legend ?? series.queryName,
|
||||
colorMapping: COLOR_MAPPING,
|
||||
isDarkMode,
|
||||
});
|
||||
});
|
||||
return builder;
|
||||
}, [payload, chartData, isDarkMode, timezone]);
|
||||
|
||||
return (
|
||||
<div className={styles.chart} data-testid="volume-control-chart">
|
||||
<Typography.Text className={styles.chartTitle}>
|
||||
Series volume over time · ingested vs retained
|
||||
</Typography.Text>
|
||||
<div className={styles.chartBody} ref={graphRef}>
|
||||
{dimensions.width > 0 && (
|
||||
<BarChart
|
||||
config={config}
|
||||
data={chartData}
|
||||
width={dimensions.width}
|
||||
height={dimensions.height}
|
||||
yAxisUnit="short"
|
||||
timezone={timezone}
|
||||
legendConfig={{ position: LegendPosition.BOTTOM }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default VolumeControlChart;
|
||||
@@ -0,0 +1,153 @@
|
||||
.tab {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 16px 0;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--bg-robin-400, #7190f9);
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0 !important;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 13px;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
max-width: 680px;
|
||||
}
|
||||
|
||||
.stats {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.search {
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.chart {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
border: 1px solid var(--bg-slate-400, #1d212d);
|
||||
border-radius: 6px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.chart-title {
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.chart-body {
|
||||
height: 340px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.stats {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.stat {
|
||||
display: flex;
|
||||
flex: 1 1 0;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 150px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--bg-slate-400, #1d212d);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-ink-400, #121317);
|
||||
}
|
||||
|
||||
.stat-hero {
|
||||
border-color: rgba(80, 231, 167, 0.4);
|
||||
background: rgba(80, 231, 167, 0.06);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
color: var(--bg-vanilla-100, #fff);
|
||||
}
|
||||
|
||||
.stat-value-good {
|
||||
color: var(--bg-forest-400, #50e7a7);
|
||||
}
|
||||
|
||||
.stat-delta {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--bg-forest-400, #50e7a7);
|
||||
}
|
||||
|
||||
.stat-unit {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.metric-name {
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: 12.5px;
|
||||
color: var(--bg-vanilla-100, #fff);
|
||||
}
|
||||
|
||||
.attributes {
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-300, #e9e9e9);
|
||||
}
|
||||
|
||||
.muted {
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.reduction {
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--bg-forest-400, #50e7a7);
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 32px 16px;
|
||||
text-align: center;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
|
||||
.unavailable {
|
||||
padding: 48px 16px;
|
||||
text-align: center;
|
||||
color: var(--bg-vanilla-400, #c0c1c3);
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
import { Gauge } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { Input, Table } from 'antd';
|
||||
import type { TableColumnsType, TableProps } from 'antd';
|
||||
import {
|
||||
useGetMetricReductionRuleStats,
|
||||
useListMetricReductionRules,
|
||||
} from 'api/generated/services/metrics';
|
||||
import {
|
||||
ListMetricReductionRulesParams,
|
||||
MetricreductionruletypesGettableReductionRuleDTO,
|
||||
MetricreductionruletypesOrderDTO,
|
||||
MetricreductionruletypesReductionRuleOrderByDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import dayjs from 'dayjs';
|
||||
import { useVolumeControlFeatureGate } from 'hooks/metricsExplorer/useVolumeControlFeatureGate';
|
||||
import useDebounce from 'hooks/useDebounce';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import {
|
||||
formatCompact,
|
||||
formatUsd,
|
||||
} from '../MetricDetails/VolumeControl/configUtils';
|
||||
import {
|
||||
getLabelVerb,
|
||||
getMatchTypeLabel,
|
||||
} from '../MetricDetails/VolumeControl/utils';
|
||||
import VolumeControlConfigDrawer from '../MetricDetails/VolumeControl/VolumeControlConfigDrawer';
|
||||
import VolumeControlBadge from './VolumeControlBadge';
|
||||
import VolumeControlChart from './VolumeControlChart';
|
||||
import styles from './VolumeControlTab.module.scss';
|
||||
|
||||
const OrderBy = MetricreductionruletypesReductionRuleOrderByDTO;
|
||||
const SortOrder = MetricreductionruletypesOrderDTO;
|
||||
const DEFAULT_PAGE_SIZE = 10;
|
||||
|
||||
type VolumeControlTableParams = Required<
|
||||
Omit<ListMetricReductionRulesParams, 'metricName'>
|
||||
>;
|
||||
|
||||
const DEFAULT_PARAMS: VolumeControlTableParams = {
|
||||
orderBy: OrderBy.reduction,
|
||||
order: SortOrder.desc,
|
||||
search: '',
|
||||
offset: 0,
|
||||
limit: DEFAULT_PAGE_SIZE,
|
||||
};
|
||||
|
||||
function VolumeControlTab(): JSX.Element {
|
||||
const { isVolumeControlEnabled, canManageVolumeControl } =
|
||||
useVolumeControlFeatureGate();
|
||||
const [selectedRule, setSelectedRule] =
|
||||
useState<MetricreductionruletypesGettableReductionRuleDTO | null>(null);
|
||||
const [params, setParams] = useState<VolumeControlTableParams>(DEFAULT_PARAMS);
|
||||
|
||||
const [searchInput, setSearchInput] = useState('');
|
||||
const debouncedSearch = useDebounce(searchInput, 400);
|
||||
useEffect(() => {
|
||||
setParams((prev) =>
|
||||
prev.search === debouncedSearch
|
||||
? prev
|
||||
: { ...prev, search: debouncedSearch, offset: 0 },
|
||||
);
|
||||
}, [debouncedSearch]);
|
||||
|
||||
const { data, isLoading } = useListMetricReductionRules(params, {
|
||||
query: { enabled: isVolumeControlEnabled },
|
||||
});
|
||||
|
||||
const { data: statsData } = useGetMetricReductionRuleStats({
|
||||
query: { enabled: isVolumeControlEnabled },
|
||||
});
|
||||
const stats = statsData?.data;
|
||||
const overallReduction =
|
||||
stats && stats.ingestedSeries > 0
|
||||
? Math.round((1 - stats.retainedSeries / stats.ingestedSeries) * 100)
|
||||
: 0;
|
||||
|
||||
const rules = data?.data.rules ?? [];
|
||||
const total = data?.data.total ?? 0;
|
||||
|
||||
const sortOrderFor = useCallback(
|
||||
(
|
||||
key: MetricreductionruletypesReductionRuleOrderByDTO,
|
||||
): 'ascend' | 'descend' | undefined => {
|
||||
if (params.orderBy !== key) {
|
||||
return undefined;
|
||||
}
|
||||
return params.order === SortOrder.desc ? 'descend' : 'ascend';
|
||||
},
|
||||
[params],
|
||||
);
|
||||
|
||||
const columns: TableColumnsType<MetricreductionruletypesGettableReductionRuleDTO> =
|
||||
useMemo(
|
||||
() => [
|
||||
{
|
||||
title: 'METRIC',
|
||||
dataIndex: 'metricName',
|
||||
key: OrderBy.metric,
|
||||
sorter: true,
|
||||
sortOrder: sortOrderFor(OrderBy.metric),
|
||||
render: (metricName: string): JSX.Element => (
|
||||
<span className={styles.metricName}>{metricName}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'STATUS',
|
||||
key: 'status',
|
||||
width: 130,
|
||||
render: (
|
||||
_value: unknown,
|
||||
rule: MetricreductionruletypesGettableReductionRuleDTO,
|
||||
): JSX.Element => <VolumeControlBadge rule={rule} />,
|
||||
},
|
||||
{
|
||||
title: 'MODE',
|
||||
key: 'mode',
|
||||
width: 160,
|
||||
render: (
|
||||
_value: unknown,
|
||||
rule: MetricreductionruletypesGettableReductionRuleDTO,
|
||||
): JSX.Element => <span>{getMatchTypeLabel(rule.matchType)}</span>,
|
||||
},
|
||||
{
|
||||
title: 'ATTRIBUTES',
|
||||
key: 'attributes',
|
||||
render: (
|
||||
_value: unknown,
|
||||
rule: MetricreductionruletypesGettableReductionRuleDTO,
|
||||
): JSX.Element => (
|
||||
<span className={styles.attributes}>
|
||||
{getLabelVerb(rule.matchType)} {(rule.labels ?? []).join(', ') || '—'}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'INGESTED',
|
||||
key: OrderBy.ingested_volume,
|
||||
width: 130,
|
||||
sorter: true,
|
||||
sortOrder: sortOrderFor(OrderBy.ingested_volume),
|
||||
render: (
|
||||
_value: unknown,
|
||||
rule: MetricreductionruletypesGettableReductionRuleDTO,
|
||||
): JSX.Element => (
|
||||
<span className={styles.muted}>{formatCompact(rule.ingestedSeries)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'RETAINED',
|
||||
key: OrderBy.reduced_volume,
|
||||
width: 130,
|
||||
sorter: true,
|
||||
sortOrder: sortOrderFor(OrderBy.reduced_volume),
|
||||
render: (
|
||||
_value: unknown,
|
||||
rule: MetricreductionruletypesGettableReductionRuleDTO,
|
||||
): JSX.Element => <span>{formatCompact(rule.retainedSeries)}</span>,
|
||||
},
|
||||
{
|
||||
title: 'CHANGE',
|
||||
key: OrderBy.reduction,
|
||||
width: 110,
|
||||
sorter: true,
|
||||
sortOrder: sortOrderFor(OrderBy.reduction),
|
||||
render: (
|
||||
_value: unknown,
|
||||
rule: MetricreductionruletypesGettableReductionRuleDTO,
|
||||
): JSX.Element => {
|
||||
if (rule.reductionPercent <= 0) {
|
||||
return <span className={styles.muted}>—</span>;
|
||||
}
|
||||
return (
|
||||
<span className={styles.reduction}>
|
||||
−{Math.round(rule.reductionPercent)}%
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'LAST CONFIGURED',
|
||||
key: OrderBy.last_updated,
|
||||
width: 240,
|
||||
sorter: true,
|
||||
sortOrder: sortOrderFor(OrderBy.last_updated),
|
||||
render: (
|
||||
_value: unknown,
|
||||
rule: MetricreductionruletypesGettableReductionRuleDTO,
|
||||
): JSX.Element => (
|
||||
<span className={styles.muted}>
|
||||
{dayjs(rule.updatedAt).format('MMM D, YYYY · h:mm A')}
|
||||
{rule.updatedBy ? ` · ${rule.updatedBy}` : ''}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
...(canManageVolumeControl
|
||||
? ([
|
||||
{
|
||||
title: '',
|
||||
key: 'action',
|
||||
width: 110,
|
||||
render: (
|
||||
_value: unknown,
|
||||
rule: MetricreductionruletypesGettableReductionRuleDTO,
|
||||
): JSX.Element => (
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
onClick={(): void => setSelectedRule(rule)}
|
||||
data-testid={`vc-manage-${rule.metricName}`}
|
||||
>
|
||||
Manage
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
] as TableColumnsType<MetricreductionruletypesGettableReductionRuleDTO>)
|
||||
: []),
|
||||
],
|
||||
[canManageVolumeControl, sortOrderFor],
|
||||
);
|
||||
|
||||
const handleTableChange: TableProps<MetricreductionruletypesGettableReductionRuleDTO>['onChange'] =
|
||||
(pagination, _filters, sorter): void => {
|
||||
const active = Array.isArray(sorter) ? sorter[0] : sorter;
|
||||
const pageSize = pagination.pageSize ?? DEFAULT_PAGE_SIZE;
|
||||
const current = pagination.current ?? 1;
|
||||
|
||||
setParams((prev) => ({
|
||||
...prev,
|
||||
orderBy: active?.order
|
||||
? (active.columnKey as MetricreductionruletypesReductionRuleOrderByDTO)
|
||||
: DEFAULT_PARAMS.orderBy,
|
||||
order: active?.order === 'descend' ? SortOrder.desc : SortOrder.asc,
|
||||
limit: pageSize,
|
||||
offset: (current - 1) * pageSize,
|
||||
}));
|
||||
};
|
||||
|
||||
if (!isVolumeControlEnabled) {
|
||||
return (
|
||||
<div className={styles.unavailable} data-testid="volume-control-unavailable">
|
||||
<Typography.Text>
|
||||
Volume control is available on enterprise and cloud plans.
|
||||
</Typography.Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.tab} data-testid="volume-control-tab">
|
||||
<div className={styles.header}>
|
||||
<div className={styles.titleRow}>
|
||||
<Gauge size={18} />
|
||||
<Typography.Title level={4} className={styles.title}>
|
||||
Volume Control
|
||||
</Typography.Title>
|
||||
</div>
|
||||
<Typography.Text className={styles.subtitle}>
|
||||
Aggregate away high-cardinality attributes to reduce stored metric volume
|
||||
and cost.
|
||||
</Typography.Text>
|
||||
</div>
|
||||
|
||||
<div className={styles.stats}>
|
||||
<div className={styles.stat}>
|
||||
<span className={styles.statLabel}>Active rules</span>
|
||||
<span className={styles.statValue}>{total}</span>
|
||||
</div>
|
||||
<div className={styles.stat}>
|
||||
<span className={styles.statLabel}>Ingested series</span>
|
||||
<span className={styles.statValue}>
|
||||
{formatCompact(stats?.ingestedSeries ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.stat}>
|
||||
<span className={styles.statLabel}>Retained series</span>
|
||||
<span className={styles.statValue}>
|
||||
{formatCompact(stats?.retainedSeries ?? 0)}
|
||||
{overallReduction > 0 && (
|
||||
<span className={styles.statDelta}>−{overallReduction}%</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className={`${styles.stat} ${styles.statHero}`}>
|
||||
<span className={styles.statLabel}>Est. monthly savings</span>
|
||||
<span className={`${styles.statValue} ${styles.statValueGood}`}>
|
||||
{formatUsd(stats?.estimatedMonthlySavingsUsd ?? 0)}
|
||||
<span className={styles.statUnit}>/mo</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<VolumeControlChart enabled={isVolumeControlEnabled} />
|
||||
|
||||
<div className={styles.toolbar}>
|
||||
<Input
|
||||
className={styles.search}
|
||||
placeholder="Search metrics"
|
||||
allowClear
|
||||
value={searchInput}
|
||||
onChange={(e): void => setSearchInput(e.target.value)}
|
||||
data-testid="volume-control-search"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Table<MetricreductionruletypesGettableReductionRuleDTO>
|
||||
rowKey="metricName"
|
||||
loading={isLoading}
|
||||
dataSource={rules}
|
||||
columns={columns}
|
||||
onChange={handleTableChange}
|
||||
pagination={{
|
||||
current: Math.floor(params.offset / params.limit) + 1,
|
||||
pageSize: params.limit,
|
||||
total,
|
||||
showSizeChanger: false,
|
||||
}}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<div className={styles.empty} data-testid="volume-control-tab-empty">
|
||||
No volume control rules yet. Open a metric and set one up to start
|
||||
reducing its series volume.
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
|
||||
{canManageVolumeControl && selectedRule && (
|
||||
<VolumeControlConfigDrawer
|
||||
metricName={selectedRule.metricName}
|
||||
existingRule={selectedRule}
|
||||
open={!!selectedRule}
|
||||
onClose={(): void => setSelectedRule(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default VolumeControlTab;
|
||||
@@ -0,0 +1,64 @@
|
||||
import {
|
||||
Querybuildertypesv5QueryRangeResponseDTO,
|
||||
Querybuildertypesv5TimeSeriesDataDTO,
|
||||
Querybuildertypesv5TimeSeriesDTO,
|
||||
Querybuildertypesv5TimeSeriesValueDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { SuccessResponse } from 'types/api';
|
||||
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
|
||||
|
||||
function findSeries(
|
||||
series: Querybuildertypesv5TimeSeriesDTO[] | null | undefined,
|
||||
label: string,
|
||||
): Querybuildertypesv5TimeSeriesDTO | undefined {
|
||||
return series?.find((entry) =>
|
||||
(entry.labels ?? []).some((value) => value.value === label),
|
||||
);
|
||||
}
|
||||
|
||||
function toChartValues(
|
||||
points: Querybuildertypesv5TimeSeriesValueDTO[],
|
||||
): [number, string][] {
|
||||
return points.map((point) => [
|
||||
Math.floor((point.timestamp ?? 0) / 1000),
|
||||
String(point.value ?? 0),
|
||||
]);
|
||||
}
|
||||
|
||||
export function buildVolumeChartPayload(
|
||||
response?: Querybuildertypesv5QueryRangeResponseDTO,
|
||||
): SuccessResponse<MetricRangePayloadProps> {
|
||||
const result = response?.data?.results?.[0] as
|
||||
| Querybuildertypesv5TimeSeriesDataDTO
|
||||
| undefined;
|
||||
const series = result?.aggregations?.[0]?.series;
|
||||
|
||||
const ingested = findSeries(series, 'ingested')?.values ?? [];
|
||||
const retained = findSeries(series, 'retained')?.values ?? [];
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
message: 'Success',
|
||||
error: null,
|
||||
payload: {
|
||||
data: {
|
||||
resultType: 'matrix',
|
||||
result: [
|
||||
{
|
||||
queryName: 'ingested',
|
||||
legend: 'Ingested',
|
||||
metric: {},
|
||||
values: toChartValues(ingested),
|
||||
},
|
||||
{
|
||||
queryName: 'retained',
|
||||
legend: 'Retained',
|
||||
metric: {},
|
||||
values: toChartValues(retained),
|
||||
},
|
||||
],
|
||||
newResult: { data: { result: [], resultType: 'matrix' } },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { FeatureKeys } from 'constants/features';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
interface VolumeControlFeatureGate {
|
||||
isVolumeControlEnabled: boolean;
|
||||
canManageVolumeControl: boolean;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function useVolumeControlFeatureGate(): VolumeControlFeatureGate {
|
||||
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
|
||||
const { user, featureFlags, isFetchingActiveLicense, activeLicense } =
|
||||
useAppContext();
|
||||
|
||||
const isMetricsReductionEnabled = Boolean(
|
||||
featureFlags?.find(
|
||||
(flag) => flag.name === FeatureKeys.ENABLE_METRICS_REDUCTION,
|
||||
)?.active,
|
||||
);
|
||||
|
||||
const isVolumeControlEnabled =
|
||||
(isMetricsReductionEnabled && (isCloudUser || isEnterpriseSelfHostedUser)) ||
|
||||
true;
|
||||
const isAdmin = user?.role === USER_ROLES.ADMIN || true;
|
||||
|
||||
return {
|
||||
isVolumeControlEnabled,
|
||||
canManageVolumeControl: isVolumeControlEnabled && isAdmin,
|
||||
isLoading: isFetchingActiveLicense && !activeLicense,
|
||||
};
|
||||
}
|
||||
@@ -3,19 +3,29 @@ import { useLocation } from 'react-use';
|
||||
import RouteTab from 'components/RouteTab';
|
||||
import { TabRoutes } from 'components/RouteTab/types';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useVolumeControlFeatureGate } from 'hooks/metricsExplorer/useVolumeControlFeatureGate';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
|
||||
import history from 'lib/history';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { Explorer, Summary, Views } from './constants';
|
||||
import { Explorer, Summary, Views, VolumeControl } from './constants';
|
||||
|
||||
import './MetricsExplorerPage.styles.scss';
|
||||
|
||||
function MetricsExplorerPage(): JSX.Element {
|
||||
const { pathname } = useLocation();
|
||||
const { isVolumeControlEnabled } = useVolumeControlFeatureGate();
|
||||
|
||||
const routes: TabRoutes[] = [Summary, Explorer, Views];
|
||||
const routes: TabRoutes[] = useMemo(
|
||||
() => [
|
||||
Summary,
|
||||
...(isVolumeControlEnabled ? [VolumeControl] : []),
|
||||
Explorer,
|
||||
Views,
|
||||
],
|
||||
[isVolumeControlEnabled],
|
||||
);
|
||||
|
||||
const { updateAllQueriesOperators } = useQueryBuilder();
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ import { TabRoutes } from 'components/RouteTab/types';
|
||||
import ROUTES from 'constants/routes';
|
||||
import ExplorerPage from 'container/MetricsExplorer/Explorer';
|
||||
import SummaryPage from 'container/MetricsExplorer/Summary';
|
||||
import { BarChart, Compass, TowerControl } from '@signozhq/icons';
|
||||
import VolumeControlTab from 'container/MetricsExplorer/VolumeControlTab/VolumeControlTab';
|
||||
import { BarChart, Compass, Gauge, TowerControl } from '@signozhq/icons';
|
||||
import SaveView from 'pages/SaveView';
|
||||
|
||||
export const Summary: TabRoutes = {
|
||||
@@ -37,3 +38,14 @@ export const Views: TabRoutes = {
|
||||
route: ROUTES.METRICS_EXPLORER_VIEWS,
|
||||
key: ROUTES.METRICS_EXPLORER_VIEWS,
|
||||
};
|
||||
|
||||
export const VolumeControl: TabRoutes = {
|
||||
Component: VolumeControlTab,
|
||||
name: (
|
||||
<div className="tab-item">
|
||||
<Gauge size={16} /> Volume Control
|
||||
</div>
|
||||
),
|
||||
route: ROUTES.METRICS_EXPLORER_VOLUME_CONTROL,
|
||||
key: ROUTES.METRICS_EXPLORER_VOLUME_CONTROL,
|
||||
};
|
||||
|
||||
@@ -123,6 +123,7 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
|
||||
METRICS_EXPLORER: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
METRICS_EXPLORER_EXPLORER: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
METRICS_EXPLORER_VIEWS: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
METRICS_EXPLORER_VOLUME_CONTROL: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
API_MONITORING: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
WORKSPACE_ACCESS_RESTRICTED: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
METRICS_EXPLORER_BASE: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
|
||||
Reference in New Issue
Block a user