Compare commits

..

2 Commits

Author SHA1 Message Date
Vinícius Lourenço
649c3a250c build(web): pin hashed asset names that the immutable cache relies on 2026-11-23 22:46:11 -03:00
Vinícius Lourenço
f7b1383427 perf(web): cache hashed frontend assets as immutable 2026-11-23 22:46:09 -03:00
91 changed files with 306 additions and 5331 deletions

View File

@@ -4523,103 +4523,6 @@ components:
required:
- name
type: object
DashboardtypesDistributionAxes:
properties:
x:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionXAxis'
description: The bucket axis.
"y":
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionYAxis'
description: The count axis.
type: object
DashboardtypesDistributionChartAppearance:
properties:
percentiles:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionPercentiles'
description: Percentile markers drawn across the bucket axis.
stack:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionStackMode'
description: 'How groups combine in a bucket: normal (default) stacks them,
none draws them side by side, percent stacks them as shares of the bucket.'
required:
- stack
type: object
DashboardtypesDistributionPanelSpec:
properties:
axes:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionAxes'
description: The X (bucket) axis range and Y (count) axis scale.
chartAppearance:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionChartAppearance'
description: Stacking and percentile markers.
formatting:
allOf:
- $ref: '#/components/schemas/DashboardtypesPanelFormatting'
description: Unit and decimal precision of the bucket bounds; counts take
no unit.
legend:
allOf:
- $ref: '#/components/schemas/DashboardtypesLegend'
description: Legend placement and series colors.
visualization:
allOf:
- $ref: '#/components/schemas/DashboardtypesBasicVisualization'
description: The time range the bucket counts are summed over.
type: object
DashboardtypesDistributionPercentiles:
properties:
enabled:
description: Whether percentile markers are drawn. Null draws them.
nullable: true
type: boolean
values:
description: The percentiles to mark, each in (0, 100), at most 5, no duplicates.
Null means [50, 90, 99]; [] marks none.
items:
format: double
type: number
nullable: true
type: array
type: object
DashboardtypesDistributionStackMode:
enum:
- none
- normal
- percent
type: string
DashboardtypesDistributionXAxis:
properties:
max:
description: Buckets wholly above this value are hidden. Null shows them
all.
nullable: true
type: number
min:
description: Buckets wholly below this value are hidden. Null shows them
all.
nullable: true
type: number
type: object
DashboardtypesDistributionYAxis:
properties:
scale:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionYScale'
description: 'How counts are spaced: linear (default) or log.'
required:
- scale
type: object
DashboardtypesDistributionYScale:
enum:
- linear
- log
type: string
DashboardtypesDynamicVariableSignal:
enum:
- traces
@@ -5615,7 +5518,6 @@ components:
mapping:
signoz/AreaChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec'
signoz/BarChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
signoz/DistributionPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec'
signoz/GeoMapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
signoz/HeatmapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
signoz/HistogramPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
@@ -5642,7 +5544,6 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec'
type: object
DashboardtypesPanelPluginKind:
enum:
@@ -5659,7 +5560,6 @@ components:
- signoz/ScatterPlotPanel
- signoz/GeoMapPanel
- signoz/TopListPanel
- signoz/DistributionPanel
type: string
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
properties:
@@ -5691,21 +5591,6 @@ components:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec:
properties:
kind:
description: The panel kind.
enum:
- signoz/DistributionPanel
type: string
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesDistributionPanelSpec'
description: The options for this panel kind. {} accepts every default.
required:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec:
properties:
kind:
@@ -5889,9 +5774,9 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPlugin'
description: 'The visualization: kind is one of signoz/TimeSeriesPanel,
signoz/BarChartPanel, signoz/AreaChartPanel, signoz/NumberPanel, signoz/PieChartPanel,
signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel,
signoz/HeatmapPanel or signoz/DistributionPanel, and spec holds that kind''s
options ({} accepts every default).'
signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel
or signoz/HeatmapPanel, and spec holds that kind''s options ({} accepts
every default).'
queries:
description: The queries the panel runs. Use exactly one entry for a data
panel and [] for signoz/TextPanel. To run several named queries or formulas,
@@ -6027,8 +5912,8 @@ components:
- $ref: '#/components/schemas/Querybuildertypesv5RequestType'
description: 'The result shape the panel requests: time_series for time
series, bar, area and histogram panels, scalar for number, table and pie
panels, raw for list panels, heatmap for heatmap panels, distribution
for distribution panels, trace for trace panels.'
panels, raw for list panels, heatmap for heatmap panels, trace for trace
panels.'
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesQuerySpec'
@@ -6185,9 +6070,9 @@ components:
(builder query over AI observability traces), signoz/CompositeQuery (several
named queries and formulas), signoz/Formula, signoz/PromQLQuery, signoz/ClickHouseSQL
or signoz/TraceOperator, and spec holds that kind''s query. Pie and table
panels reject signoz/PromQLQuery; heatmap and distribution panels reject
signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only
signoz/BuilderQuery and signoz/AIBuilderQuery.'
panels reject signoz/PromQLQuery; heatmap panels reject signoz/AIBuilderQuery
and signoz/TraceOperator; list panels accept only signoz/BuilderQuery
and signoz/AIBuilderQuery.'
required:
- plugin
type: object

3
frontend/.gitignore vendored
View File

@@ -1,4 +1,7 @@
# Vite copies public/ unhashed, and the Go server caches /assets/ as immutable
/public/assets/
# Sentry Config File
.env.sentry-build-plugin
.qodo

View File

@@ -11,7 +11,7 @@ const config: Config.InitialOptions = {
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
collectCoverageFrom: ['src/**/*.{ts,tsx}'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
modulePathIgnorePatterns: ['<rootDir>/dist/'],
modulePathIgnorePatterns: ['dist'],
moduleNameMapper: {
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$':
'<rootDir>/__mocks__/fileMock.ts',

View File

@@ -7248,112 +7248,6 @@ export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDa
spec: DashboardtypesTopListPanelSpecDTO;
}
/**
* The panel kind.
*/
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind {
'signoz/DistributionPanel' = 'signoz/DistributionPanel',
}
export interface DashboardtypesDistributionXAxisDTO {
/**
* @type number,null
* @description Buckets wholly above this value are hidden. Null shows them all.
*/
max?: number | null;
/**
* @type number,null
* @description Buckets wholly below this value are hidden. Null shows them all.
*/
min?: number | null;
}
export enum DashboardtypesDistributionYScaleDTO {
linear = 'linear',
log = 'log',
}
export interface DashboardtypesDistributionYAxisDTO {
/**
* @description How counts are spaced: linear (default) or log.
*/
scale: DashboardtypesDistributionYScaleDTO;
}
export interface DashboardtypesDistributionAxesDTO {
/**
* @description The bucket axis.
*/
x?: DashboardtypesDistributionXAxisDTO;
/**
* @description The count axis.
*/
y?: DashboardtypesDistributionYAxisDTO;
}
export interface DashboardtypesDistributionPercentilesDTO {
/**
* @type boolean,null
* @description Whether percentile markers are drawn. Null draws them.
*/
enabled?: boolean | null;
/**
* @type array,null
* @description The percentiles to mark, each in (0, 100), at most 5, no duplicates. Null means [50, 90, 99]; [] marks none.
*/
values?: number[] | null;
}
export enum DashboardtypesDistributionStackModeDTO {
none = 'none',
normal = 'normal',
percent = 'percent',
}
export interface DashboardtypesDistributionChartAppearanceDTO {
/**
* @description Percentile markers drawn across the bucket axis.
*/
percentiles?: DashboardtypesDistributionPercentilesDTO;
/**
* @description How groups combine in a bucket: normal (default) stacks them, none draws them side by side, percent stacks them as shares of the bucket.
*/
stack: DashboardtypesDistributionStackModeDTO;
}
export interface DashboardtypesDistributionPanelSpecDTO {
/**
* @description The X (bucket) axis range and Y (count) axis scale.
*/
axes?: DashboardtypesDistributionAxesDTO;
/**
* @description Stacking and percentile markers.
*/
chartAppearance?: DashboardtypesDistributionChartAppearanceDTO;
/**
* @description Unit and decimal precision of the bucket bounds; counts take no unit.
*/
formatting?: DashboardtypesPanelFormattingDTO;
/**
* @description Legend placement and series colors.
*/
legend?: DashboardtypesLegendDTO;
/**
* @description The time range the bucket counts are summed over.
*/
visualization?: DashboardtypesBasicVisualizationDTO;
}
export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTO {
/**
* @enum signoz/DistributionPanel
* @type string
* @description The panel kind.
*/
kind: DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind;
/**
* @description The options for this panel kind. {} accepts every default.
*/
spec: DashboardtypesDistributionPanelSpecDTO;
}
export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTO
@@ -7367,8 +7261,7 @@ export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTO;
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO;
export enum Querybuildertypesv5RequestTypeDTO {
scalar = 'scalar',
@@ -7857,14 +7750,14 @@ export interface DashboardtypesQuerySpecDTO {
*/
name?: string;
/**
* @description The query: kind is one of signoz/BuilderQuery, signoz/AIBuilderQuery (builder query over AI observability traces), signoz/CompositeQuery (several named queries and formulas), signoz/Formula, signoz/PromQLQuery, signoz/ClickHouseSQL or signoz/TraceOperator, and spec holds that kind's query. Pie and table panels reject signoz/PromQLQuery; heatmap and distribution panels reject signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only signoz/BuilderQuery and signoz/AIBuilderQuery.
* @description The query: kind is one of signoz/BuilderQuery, signoz/AIBuilderQuery (builder query over AI observability traces), signoz/CompositeQuery (several named queries and formulas), signoz/Formula, signoz/PromQLQuery, signoz/ClickHouseSQL or signoz/TraceOperator, and spec holds that kind's query. Pie and table panels reject signoz/PromQLQuery; heatmap panels reject signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only signoz/BuilderQuery and signoz/AIBuilderQuery.
*/
plugin: DashboardtypesQueryPluginDTO;
}
export interface DashboardtypesQueryDTO {
/**
* @description The result shape the panel requests: time_series for time series, bar, area and histogram panels, scalar for number, table and pie panels, raw for list panels, heatmap for heatmap panels, distribution for distribution panels, trace for trace panels.
* @description The result shape the panel requests: time_series for time series, bar, area and histogram panels, scalar for number, table and pie panels, raw for list panels, heatmap for heatmap panels, trace for trace panels.
*/
kind: Querybuildertypesv5RequestTypeDTO;
/**
@@ -7884,7 +7777,7 @@ export interface DashboardtypesPanelSpecDTO {
*/
links?: DashboardtypesLinkDTO[] | null;
/**
* @description The visualization: kind is one of signoz/TimeSeriesPanel, signoz/BarChartPanel, signoz/AreaChartPanel, signoz/NumberPanel, signoz/PieChartPanel, signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel, signoz/HeatmapPanel or signoz/DistributionPanel, and spec holds that kind's options ({} accepts every default).
* @description The visualization: kind is one of signoz/TimeSeriesPanel, signoz/BarChartPanel, signoz/AreaChartPanel, signoz/NumberPanel, signoz/PieChartPanel, signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel or signoz/HeatmapPanel, and spec holds that kind's options ({} accepts every default).
*/
plugin: DashboardtypesPanelPluginDTO;
/**
@@ -8657,7 +8550,6 @@ export enum DashboardtypesPanelPluginKindDTO {
'signoz/ScatterPlotPanel' = 'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
'signoz/TopListPanel' = 'signoz/TopListPanel',
'signoz/DistributionPanel' = 'signoz/DistributionPanel',
}
/**
* The RFC 6902 operations, applied in order against the dashboard's postable shape.

View File

@@ -21,7 +21,6 @@ import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import {
convertBuilderQueriesToV5,
createAggregation,
mapPanelTypeToRequestType,
prepareQueryRangePayloadV5,
} from './prepareQueryRangePayloadV5';
@@ -1016,47 +1015,3 @@ describe('convertBuilderQueriesToV5 builder query type', () => {
expect(buildEnvelope(builderQueryType, 'trace').type).toBe('builder_query');
});
});
describe('createAggregation fallback', () => {
const logsQuery = (expression: string): Partial<IBuilderQuery> => ({
dataSource: DataSource.LOGS,
aggregations: [{ expression }],
});
it('sends no aggregation for a heatmap with no field', () => {
expect(createAggregation(logsQuery(''), PANEL_TYPES.HEATMAP)).toStrictEqual(
[],
);
});
it('reads a field on a heatmap and turns it into count() elsewhere', () => {
expect(
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.HEATMAP),
).toStrictEqual([{ expression: 'duration_nano' }]);
expect(
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.TIME_SERIES),
).toStrictEqual([{ expression: 'count()' }]);
});
it('still defaults other panels to count()', () => {
expect(
createAggregation(logsQuery(''), PANEL_TYPES.TIME_SERIES),
).toStrictEqual([{ expression: 'count()' }]);
});
it('sends the field of a logs heatmap query', () => {
const [envelope] = convertBuilderQueriesToV5(
{
A: {
...logsQuery('duration_nano'),
queryName: 'A',
} as IBuilderQuery,
},
mapPanelTypeToRequestType(PANEL_TYPES.HEATMAP),
PANEL_TYPES.HEATMAP,
);
expect((envelope.spec as LogBuilderQuery).aggregations).toStrictEqual([
{ expression: 'duration_nano' },
]);
});
});

View File

@@ -5,8 +5,6 @@ import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { foldAISlot } from 'lib/query/builderSlot';
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
import { parseAggregations } from 'lib/query/aggregationExpression';
import { aggregatesDistributionField } from 'lib/query/distributionField';
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
import { isEmpty } from 'lodash-es';
import { DynamicVariableSuggestion } from 'providers/Dashboard/store/dynamicVariableSuggestions';
@@ -242,6 +240,32 @@ function createBaseSpec(
};
}
// Utility to parse aggregation expressions with optional alias
export function parseAggregations(
expression: string,
availableAlias?: string,
): { expression: string; alias?: string }[] {
const result: { expression: string; alias?: string }[] = [];
// Matches function calls like "count()" or "sum(field)" with optional alias like "as 'alias'"
// Handles quoted ('alias'), dash-separated (field-name), and unquoted values after "as" keyword
const regex =
/([a-zA-Z0-9_]+\([^)]*\))(?:\s*as\s+((?:'[^']*'|"[^"]*"|[a-zA-Z0-9_-]+)))?/g;
let match = regex.exec(expression);
while (match !== null) {
const expr = match[1];
let alias = match[2] || availableAlias; // Use provided alias or availableAlias if not matched
if (alias) {
// Remove quotes if present
alias = alias.replace(/^['"]|['"]$/g, '');
result.push({ expression: expr, alias });
} else {
result.push({ expression: expr });
}
match = regex.exec(expression);
}
return result;
}
export function createAggregation(
queryData: any,
panelType?: PANEL_TYPES,
@@ -286,28 +310,18 @@ export function createAggregation(
];
}
// A heatmap buckets the field the user names; count() would be rejected as one.
// Elsewhere a field is not an aggregation, so it falls back to count().
const isDistributionField = aggregatesDistributionField(
panelType,
queryData.dataSource,
);
const fallback = isDistributionField ? [] : [{ expression: 'count()' }];
if (queryData.aggregations?.length > 0) {
return queryData.aggregations.flatMap(
(agg: { expression: string; alias?: string }) => {
const parsedAggregations = parseAggregations(
agg.expression,
agg?.alias,
isDistributionField,
);
return isEmpty(parsedAggregations) ? fallback : parsedAggregations;
const parsedAggregations = parseAggregations(agg.expression, agg?.alias);
return isEmpty(parsedAggregations)
? [{ expression: 'count()' }]
: parsedAggregations;
},
);
}
return fallback;
return [{ expression: 'count()' }];
}
/**

View File

@@ -106,10 +106,8 @@ function QueryAddOns({
if (
panelType === PANEL_TYPES.HEATMAP &&
!(
query.dataSource === DataSource.METRICS &&
HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
)
query.dataSource === DataSource.METRICS &&
!HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
) {
addOns = [...addOns, BUCKET_OPTIONS];
}
@@ -438,7 +436,6 @@ function QueryAddOns({
onChange={handleChangeOrderByKeys}
isRawQuery={isRawQuery}
isNewQueryV2
panelType={panelType ?? undefined}
placeholder={placeholderOf(QueryBuilderField.OrderBy)}
/>
</div>

View File

@@ -107,8 +107,8 @@ export const BASE_ADD_ONS = (
export const REDUCE_TO = toAddOn(QueryBuilderField.ReduceTo);
// Offered only by a heatmap: the bucket axis is what a heatmap plots against, and no
// other panel type sends one. A histogram metric brings its own buckets.
// Offered only by a heatmap over metrics: the bucket axis is what a heatmap plots
// against, and no other panel type sends one. A histogram brings its own buckets.
export const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
ATTRIBUTE_TYPES.HISTOGRAM,
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,

View File

@@ -1,5 +0,0 @@
// Fills the row like the filter and Group By boxes.
.select {
flex: 1;
min-width: 400px;
}

View File

@@ -1,69 +0,0 @@
import { useMemo, useState } from 'react';
import { Combobox } from '@signozhq/ui/combobox';
import { TelemetrytypesFieldDataTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
import useDebounce from 'hooks/useDebounce';
import { getDistributionFieldPlaceholder } from 'lib/query/distributionField';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { DATA_SOURCE_TO_SIGNAL } from 'types/common/queryBuilder';
import { toDistributionFieldOptions } from './distributionFieldOptions';
import Styles from './DistributionFieldSelect.module.scss';
/** A logs or traces heatmap's aggregation: the one numeric field it buckets. */
export default function DistributionFieldSelect({
queryData,
onChange,
}: {
queryData: IBuilderQuery;
onChange?: (field: string) => void;
}): JSX.Element {
const [search, setSearch] = useState('');
const searchText = useDebounce(search, DEBOUNCE_DELAY);
// The keys API caps its answer, so a field past the cap is reached by searching.
const {
data: fieldKeys,
isLoading,
isFetching,
} = useFieldKeysSuggestion(
{
signal: DATA_SOURCE_TO_SIGNAL[queryData.dataSource],
searchText,
fieldDataType: TelemetrytypesFieldDataTypeDTO.number,
},
queryData.builderQueryType,
{ keepPreviousData: true },
);
const [aggregation] = queryData.aggregations ?? [];
const selectedField =
aggregation && 'expression' in aggregation ? aggregation.expression : '';
const items = useMemo(
() => toDistributionFieldOptions(fieldKeys ?? [], selectedField),
[fieldKeys, selectedField],
);
return (
<div className={Styles.select}>
<Combobox
items={items}
value={selectedField || undefined}
onChange={(field): void => onChange?.(field ?? '')}
allowClear
placeholder={getDistributionFieldPlaceholder(queryData.dataSource)}
searchInputProps={{
placeholder: 'Search numeric fields',
loading: isFetching,
onChange: setSearch,
}}
loading={isLoading}
noContent="No numeric fields"
testId="distribution-field-select"
/>
</div>
);
}

View File

@@ -6,7 +6,6 @@ import {
IBuilderQuery,
IBuilderTraceOperator,
} from 'types/api/queryBuilder/queryBuilderData';
import { aggregatesDistributionField } from 'lib/query/distributionField';
import { DataSource } from 'types/common/queryBuilder';
import {
@@ -20,7 +19,6 @@ import {
} from '../../queryBuilderFields.utils';
import { isScalarPanelType } from '../panelTypes';
import DistributionFieldSelect from './DistributionFieldSelect';
import QueryAggregationSelect from './QueryAggregationSelect';
import './QueryAggregation.styles.scss';
@@ -65,21 +63,17 @@ function QueryAggregationOptions({
data-testid="query-aggregation-container"
>
<div className="aggregation-container">
{aggregatesDistributionField(panelType, dataSource) ? (
<DistributionFieldSelect queryData={queryData} onChange={onChange} />
) : (
<QueryAggregationSelect
onChange={onChange}
queryData={queryData}
maxAggregations={
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.TOP_LIST
? 1
: undefined
}
/>
)}
<QueryAggregationSelect
onChange={onChange}
queryData={queryData}
maxAggregations={
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.TOP_LIST
? 1
: undefined
}
/>
{!stepInterval.hidden && (
<div className="query-aggregation-interval">

View File

@@ -1,163 +0,0 @@
import {
TelemetrytypesFieldContextDTO,
TelemetrytypesFieldDataTypeDTO,
TelemetrytypesSignalDTO,
type GetFieldsKeys200,
} from 'api/generated/services/sigNoz.schemas';
import { ENVIRONMENT } from 'constants/env';
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
import { initialQueriesMap } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import DistributionFieldSelect from '../DistributionFieldSelect';
const keysResponse: GetFieldsKeys200 = {
status: 'success',
data: {
complete: true,
keys: {
duration_nano: [
{
name: 'duration_nano',
fieldContext: TelemetrytypesFieldContextDTO.span,
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
signal: TelemetrytypesSignalDTO.traces,
},
],
quantity: [
{
name: 'quantity',
fieldContext: TelemetrytypesFieldContextDTO.attribute,
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
signal: TelemetrytypesSignalDTO.traces,
},
],
},
},
};
const tracesQuery = (expression: string): IBuilderQuery => ({
...(initialQueriesMap.traces.builder.queryData[0] as IBuilderQuery),
aggregations: [{ expression }],
});
describe('DistributionFieldSelect', () => {
const requests: URLSearchParams[] = [];
afterEach(() => {
jest.useRealTimers();
});
beforeEach(() => {
requests.length = 0;
server.use(
rest.get(`${ENVIRONMENT.baseURL}/api/v1/fields/keys`, (req, res, ctx) => {
requests.push(req.url.searchParams);
return res(ctx.status(200), ctx.json(keysResponse));
}),
);
});
it('shows the saved field', () => {
render(
<DistributionFieldSelect
queryData={tracesQuery('duration_nano')}
onChange={jest.fn()}
/>,
);
expect(screen.getByTestId('distribution-field-select')).toHaveTextContent(
'duration_nano',
);
});
it('picks a numeric field, keeping its context', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
render(
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
);
await user.click(screen.getByTestId('distribution-field-select'));
await screen.findByTestId(
'distribution-field-select-item-attribute.quantity',
);
await user.type(
screen.getByTestId('distribution-field-select-search'),
'attribute.quantity{Enter}',
);
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
expect(requests[0].get('fieldDataType')).toBe(
TelemetrytypesFieldDataTypeDTO.number,
);
expect(requests[0].get('signal')).toBe('traces');
});
it('replaces the saved field with the newly picked one', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
render(
<DistributionFieldSelect
queryData={tracesQuery('duration_nano')}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId('distribution-field-select'));
await screen.findByTestId(
'distribution-field-select-item-attribute.quantity',
);
await user.type(
screen.getByTestId('distribution-field-select-search'),
'attribute.quantity{Enter}',
);
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
});
it('only offers listed fields: typed text is a filter, not a value', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
render(
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
);
await user.click(screen.getByTestId('distribution-field-select'));
await screen.findByTestId(
'distribution-field-select-item-attribute.quantity',
);
await user.type(
screen.getByTestId('distribution-field-select-search'),
'no_such_field',
);
await screen.findByText('No numeric fields');
expect(
screen.queryByTestId('distribution-field-select-item-no_such_field'),
).not.toBeInTheDocument();
});
it('searches the server for typed text, past the listed fields', async () => {
jest.useFakeTimers();
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
pointerEventsCheck: 0,
});
render(
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
);
await user.click(screen.getByTestId('distribution-field-select'));
await user.type(
await screen.findByTestId('distribution-field-select-search'),
'queue',
);
act(() => {
jest.advanceTimersByTime(DEBOUNCE_DELAY);
});
await waitFor(() => expect(requests.at(-1)?.get('searchText')).toBe('queue'));
});
});

View File

@@ -1,84 +0,0 @@
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
import {
toDistributionFieldOptions,
toDistributionFieldText,
} from '../distributionFieldOptions';
const key = (
name: string,
fieldContext: FieldContext,
): { name: string; fieldContext: FieldContext } => ({ name, fieldContext });
const KEYS = [
key('quantity', FieldContext.resource),
key('duration_nano', FieldContext.span),
key('quantity', FieldContext.attribute),
key('total_tokens', FieldContext.trace),
key('latency', FieldContext.body),
key('duration_nano', FieldContext.span),
];
describe('toDistributionFieldText', () => {
it.each([
[key('duration_nano', FieldContext.span), 'duration_nano'],
[key('severity_number', FieldContext.log), 'severity_number'],
[
key('http.status_code', FieldContext.attribute),
'attribute.http.status_code',
],
[key('latency', FieldContext.body), 'body.latency'],
])('%j → %s', (fieldKey, text) => {
expect(toDistributionFieldText(fieldKey)).toBe(text);
});
});
const item = (
text: string,
): { type: 'item'; label: string; value: string } => ({
type: 'item',
label: text,
value: text,
});
describe('toDistributionFieldOptions', () => {
it('groups columns first, keeps contexts apart, drops trace keys and repeats', () => {
expect(toDistributionFieldOptions(KEYS, 'duration_nano')).toStrictEqual([
{
type: 'group',
label: 'Columns',
value: 'column',
items: [item('duration_nano')],
},
{
type: 'group',
label: 'Attribute',
value: 'attribute',
items: [item('attribute.quantity')],
},
{
type: 'group',
label: 'Resource',
value: 'resource',
items: [item('resource.quantity')],
},
{
type: 'group',
label: 'Body',
value: 'body',
items: [item('body.latency')],
},
]);
});
it('leads with a saved field the keys do not carry', () => {
const options = toDistributionFieldOptions(KEYS, 'queue-depth');
expect(options[0]).toStrictEqual(item('queue-depth'));
expect(options).toHaveLength(5);
});
it('adds nothing for an empty or listed field', () => {
expect(toDistributionFieldOptions(KEYS, '')).toHaveLength(4);
expect(toDistributionFieldOptions(KEYS, 'body.latency')).toHaveLength(4);
});
});

View File

@@ -1,81 +0,0 @@
import type {
ComboboxItemType,
ComboboxOptionItemType,
} from '@signozhq/ui/combobox';
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
import { upperFirst } from 'lodash-es';
import type { TelemetryFieldKey } from 'types/api/v5/queryRange';
// Span and log columns are read by their name alone; anything else keeps its
// context so `attribute.quantity` and `resource.quantity` stay apart.
const COLUMN_CONTEXTS = new Set<string | undefined>([
FieldContext.span,
FieldContext.log,
FieldContext[''],
]);
const GROUP_ORDER: string[] = [
'column',
FieldContext.attribute,
FieldContext.resource,
];
const headingOf = (group: string): string =>
group === 'column' ? 'Columns' : upperFirst(group);
const toItem = (text: string): ComboboxOptionItemType => ({
type: 'item',
label: text,
value: text,
});
/** The key text the querier parses back into this key (`GetFieldKeyFromKeyText`). */
export function toDistributionFieldText(key: TelemetryFieldKey): string {
return COLUMN_CONTEXTS.has(key.fieldContext)
? key.name
: `${key.fieldContext}.${key.name}`;
}
/**
* Numeric keys grouped by context, each one once. `trace.*` keys are per-trace
* aggregates, which a heatmap cannot bucket. A saved field the keys do not carry
* leads as its own item, so the combobox can still show it.
*/
export function toDistributionFieldOptions(
keys: TelemetryFieldKey[],
selectedField: string,
): ComboboxItemType[] {
const byGroup = new Map<string, Set<string>>();
keys
.filter((key) => key.fieldContext !== FieldContext.trace)
.forEach((key) => {
const group = COLUMN_CONTEXTS.has(key.fieldContext)
? 'column'
: String(key.fieldContext);
byGroup.set(
group,
(byGroup.get(group) ?? new Set()).add(toDistributionFieldText(key)),
);
});
const isSelectedListed = [...byGroup.values()].some((texts) =>
texts.has(selectedField),
);
const rank = (group: string): number => {
const index = GROUP_ORDER.indexOf(group);
return index === -1 ? GROUP_ORDER.length : index;
};
const groups = [...byGroup.entries()]
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
.map(([group, texts]): ComboboxItemType => ({
type: 'group',
label: headingOf(group),
value: group,
items: [...texts].map(toItem),
}));
return selectedField && !isSelectedListed
? [toItem(selectedField), ...groups]
: groups;
}

View File

@@ -506,7 +506,7 @@ describe('QueryAddOns', () => {
);
}
it('is offered on a metrics heatmap', () => {
it('is offered on a metrics heatmap only', () => {
renderHeatmap();
expect(
@@ -532,16 +532,23 @@ describe('QueryAddOns', () => {
).not.toBeInTheDocument();
});
it.each([DataSource.LOGS, DataSource.TRACES])(
'is offered on a %s heatmap',
(dataSource) => {
renderHeatmap({ dataSource });
it('is not offered on a heatmap over another signal', () => {
render(
<QueryAddOns
query={baseQuery({ dataSource: DataSource.LOGS })}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.HEATMAP}
index={0}
isForTraceOperator={false}
/>,
);
expect(
screen.getByTestId('query-add-on-bucket_options'),
).toBeInTheDocument();
},
);
expect(
screen.queryByTestId('query-add-on-bucket_options'),
).not.toBeInTheDocument();
});
it.each([ATTRIBUTE_TYPES.HISTOGRAM, ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM])(
'is not offered for a %s metric, which carries its own buckets',

View File

@@ -8,7 +8,7 @@ import QueryAggregationOptions from '../QueryV2/QueryAggregation/QueryAggregatio
jest.mock('../QueryV2/QueryAggregation/QueryAggregationSelect', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="aggregation-select" />,
default: (): null => null,
}));
const queryData = initialQueriesMap.traces.builder
@@ -69,18 +69,3 @@ describe('QueryAggregationOptions step interval', () => {
expect(screen.getByText('every')).toBeInTheDocument();
});
});
describe('QueryAggregationOptions on a heatmap', () => {
it.each([
[PANEL_TYPES.HEATMAP, DataSource.TRACES, true],
[PANEL_TYPES.HEATMAP, DataSource.METRICS, false],
[PANEL_TYPES.TIME_SERIES, DataSource.TRACES, false],
])(
'%s over %s renders the field picker: %s',
(panelType, dataSource, picker) => {
renderFor(panelType, dataSource);
expect(!!screen.queryByTestId('distribution-field-select')).toBe(picker);
expect(!!screen.queryByTestId('aggregation-select')).toBe(!picker);
},
);
});

View File

@@ -1,4 +1,3 @@
import type { PANEL_TYPES } from 'constants/queryBuilder';
import {
IBuilderQuery,
OrderByPayload,
@@ -11,8 +10,6 @@ export type OrderByFilterProps = {
entityVersion?: string;
isNewQueryV2?: boolean;
placeholder?: string;
/** A logs or traces heatmap aggregates a field, which Order by then offers. */
panelType?: PANEL_TYPES;
};
export type OrderByFilterValue = {

View File

@@ -23,7 +23,6 @@ export function OrderByFilter({
entityVersion,
isNewQueryV2 = false,
placeholder,
panelType,
}: OrderByFilterProps): JSX.Element {
const getPopupContainer = useSelectPopupContainer();
const {
@@ -53,9 +52,8 @@ export function OrderByFilter({
// Get parsed aggregation options using createAggregation only for QueryV2
const parsedAggregationOptions = useMemo(
() =>
isNewQueryV2 ? getParsedAggregationOptionsForOrderBy(query, panelType) : [],
[query, isNewQueryV2, panelType],
() => (isNewQueryV2 ? getParsedAggregationOptionsForOrderBy(query) : []),
[query, isNewQueryV2],
);
const optionsData = useMemo(() => {

View File

@@ -433,57 +433,4 @@ describe('useQueryBuilderOperations - Empty Aggregate Attribute Type', () => {
);
});
});
describe('handleChangeQueryData on a heatmap', () => {
it('moves the sort on the old field to the new one', () => {
setupMockQueryBuilder('heatmap');
const result = renderHookWithProps({
entityVersion: ENTITY_VERSION_V5,
query: {
...defaultMockQuery,
dataSource: DataSource.TRACES,
aggregations: [{ expression: 'duration_nano' }],
orderBy: [{ columnName: 'duration_nano', order: 'desc' }],
},
});
act(() => {
result.current.handleChangeQueryData('aggregations', [
{ expression: 'attribute.quantity' },
]);
});
expect(mockHandleSetQueryData).toHaveBeenLastCalledWith(
0,
expect.objectContaining({
aggregations: [{ expression: 'attribute.quantity' }],
orderBy: [{ columnName: 'attribute.quantity', order: 'desc' }],
}),
);
});
});
describe('handleChangeDataSource', () => {
it.each([
['heatmap', ''],
['time_series', 'count() '],
])(
'seeds the traces aggregation on a %s panel with %j',
(panelType, expression) => {
setupMockQueryBuilder(panelType);
const result = renderHookWithProps({ entityVersion: ENTITY_VERSION_V5 });
act(() => {
result.current.handleChangeDataSource(DataSource.TRACES);
});
expect(mockHandleSetQueryData).toHaveBeenLastCalledWith(
0,
expect.objectContaining({
dataSource: DataSource.TRACES,
aggregations: [{ expression }],
}),
);
},
);
});
});

View File

@@ -29,11 +29,6 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getMetricsOperatorsByAttributeType } from 'lib/newQueryBuilder/getMetricsOperatorsByAttributeType';
import { getOperatorsBySourceAndPanelType } from 'lib/newQueryBuilder/getOperatorsBySourceAndPanelType';
import { findDataTypeOfOperator } from 'lib/query/findDataTypeOfOperator';
import {
aggregatesDistributionField,
setDistributionField,
toDistributionAggregation,
} from 'lib/query/distributionField';
import { isEmpty, isEqual } from 'lodash-es';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import {
@@ -481,12 +476,7 @@ export const useQueryOperations: UseQueryOperations = ({
newQueryData = newQueryData ? newQueryData : newQuery;
setOperators(newOperators);
handleSetQueryData(
index,
aggregatesDistributionField(panelType, newQueryData.dataSource)
? toDistributionAggregation(newQueryData)
: newQueryData,
);
handleSetQueryData(index, newQueryData);
},
[
isRawQuery,
@@ -516,18 +506,13 @@ export const useQueryOperations: UseQueryOperations = ({
const handleChangeQueryData: HandleChangeQueryData | HandleChangeQueryDataV5 =
useCallback(
(key: string, value: any) => {
// A heatmap's sort names its field, so it follows a field change.
const newQuery =
key === 'aggregations' &&
aggregatesDistributionField(panelType, query.dataSource)
? setDistributionField(query, value?.[0]?.expression ?? '')
: {
...query,
[key]:
key === LEGEND && typeof value === 'string'
? getFormatedLegend(value)
: value,
};
const newQuery = {
...query,
[key]:
key === LEGEND && typeof value === 'string'
? getFormatedLegend(value)
: value,
};
if (isForTraceOperator) {
handleSetTraceOperatorData(index, newQuery);
@@ -538,7 +523,6 @@ export const useQueryOperations: UseQueryOperations = ({
[
query,
index,
panelType,
handleSetQueryData,
handleSetTraceOperatorData,
isForTraceOperator,

View File

@@ -1,27 +0,0 @@
import { parseAggregations } from '../aggregationExpression';
describe('parseAggregations', () => {
it.each([
['duration_nano', [{ expression: 'duration_nano' }]],
['attribute.queue_depth', [{ expression: 'attribute.queue_depth' }]],
['attribute.queue-depth', [{ expression: 'attribute.queue-depth' }]],
['body.latency as lat', [{ expression: 'body.latency', alias: 'lat' }]],
[
"count() as 'total' avg(code.lineno)",
[
{ expression: 'count()', alias: 'total' },
{ expression: 'avg(code.lineno)' },
],
],
// Words beside a call are not aggregations of their own.
['count() AS total', [{ expression: 'count()' }]],
['p99(duration_nano) by service', [{ expression: 'p99(duration_nano)' }]],
['sum(a', []],
])('parses %s', (input, expected) => {
expect(parseAggregations(input, undefined, true)).toStrictEqual(expected);
});
it('leaves a field out unless asked to read one', () => {
expect(parseAggregations('duration_nano')).toStrictEqual([]);
});
});

View File

@@ -1,193 +0,0 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import {
getDistributionFieldPlaceholder,
setDistributionField,
toDistributionAggregation,
fromDistributionAggregation,
} from '../distributionField';
const queryOf = (
dataSource: DataSource,
expressions: string[],
): IBuilderQuery => ({
...(initialQueriesMap[dataSource].builder.queryData[0] as IBuilderQuery),
aggregations: expressions.map((expression) => ({ expression })),
});
describe('getDistributionFieldPlaceholder', () => {
it.each([
[DataSource.TRACES, 'Numeric field to bucket, e.g. duration_nano'],
[DataSource.LOGS, 'Numeric field to bucket'],
])('%s → %s', (dataSource, expected) => {
expect(getDistributionFieldPlaceholder(dataSource)).toBe(expected);
});
});
describe('toDistributionAggregation', () => {
it.each([DataSource.TRACES, DataSource.LOGS])(
'clears a %s count() for the user to pick a field',
(dataSource) => {
expect(
toDistributionAggregation(queryOf(dataSource, ['count()'])).aggregations,
).toStrictEqual([{ expression: '' }]);
},
);
it.each(['attribute.batch_size', 'attribute.queue-depth'])(
'keeps the bare field %s',
(field) => {
const query = queryOf(DataSource.LOGS, [field]);
expect(toDistributionAggregation(query)).toBe(query);
},
);
it('keeps the field of a one-argument call', () => {
expect(
toDistributionAggregation(
queryOf(DataSource.LOGS, ['avg(attribute.latency)']),
).aggregations,
).toStrictEqual([{ expression: 'attribute.latency' }]);
});
it.each(['count_distinct(service.name)', 'countIf(status>=500)'])(
'clears the field rather than bucket the argument of %s',
(expression) => {
expect(
toDistributionAggregation(queryOf(DataSource.TRACES, [expression]))
.aggregations,
).toStrictEqual([{ expression: '' }]);
},
);
it('keeps a field with an alias', () => {
const query = queryOf(DataSource.LOGS, ['body.latency as lat']);
expect(toDistributionAggregation(query)).toBe(query);
});
it('renames an order on the aggregation alias to the field', () => {
const query = {
...queryOf(DataSource.TRACES, []),
aggregations: [{ expression: 'p99(duration_nano)', alias: 'lat' }],
orderBy: [{ columnName: 'lat', order: 'desc' }],
};
expect(toDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'duration_nano', order: 'desc' },
]);
});
it('keeps the field of an inline-aliased call and moves the order on its alias', () => {
const query = {
...queryOf(DataSource.TRACES, ["p99(duration_nano) as 'lat'"]),
orderBy: [{ columnName: 'lat', order: 'desc' }],
};
const next = toDistributionAggregation(query);
expect(next.aggregations).toStrictEqual([{ expression: 'duration_nano' }]);
expect(next.orderBy).toStrictEqual([
{ columnName: 'duration_nano', order: 'desc' },
]);
});
it('drops the order on an aggregation it clears', () => {
const query = {
...queryOf(DataSource.LOGS, ['count()']),
orderBy: [
{ columnName: 'count()', order: 'desc' },
{ columnName: 'timestamp', order: 'asc' },
],
};
expect(toDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'timestamp', order: 'asc' },
]);
});
it('drops orders on every aggregation it clears', () => {
const query = {
...queryOf(DataSource.TRACES, [
'avg(duration_nano) max(attribute.quantity)',
'count() as total',
]),
orderBy: [
{ columnName: 'max(attribute.quantity)', order: 'desc' },
{ columnName: 'total', order: 'asc' },
{ columnName: 'timestamp', order: 'asc' },
],
};
expect(toDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'timestamp', order: 'asc' },
]);
});
it('renames an order on the aggregation to the field', () => {
const query = {
...queryOf(DataSource.TRACES, ['p99(duration_nano)']),
orderBy: [{ columnName: 'p99(duration_nano)', order: 'desc' }],
};
expect(toDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'duration_nano', order: 'desc' },
]);
});
it('leaves a metrics query alone', () => {
const query = initialQueriesMap.metrics.builder.queryData[0];
expect(toDistributionAggregation(query)).toBe(query);
});
});
describe('fromDistributionAggregation', () => {
it.each([
['duration_nano', 'p90(duration_nano)'],
['', 'count()'],
])('turns the field %j into %s', (field, expression) => {
expect(
fromDistributionAggregation(queryOf(DataSource.TRACES, [field]))
.aggregations,
).toStrictEqual([{ expression }]);
});
it('drops the alias out of the field', () => {
expect(
fromDistributionAggregation(
queryOf(DataSource.LOGS, ['body.latency as lat']),
).aggregations,
).toStrictEqual([{ expression: 'p90(body.latency)' }]);
});
it('renames an order on the field to the new aggregation', () => {
const query = {
...queryOf(DataSource.TRACES, ['duration_nano']),
orderBy: [{ columnName: 'duration_nano', order: 'asc' }],
};
expect(fromDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'p90(duration_nano)', order: 'asc' },
]);
});
it.each([['count()'], ['count()', 'avg(x)']])(
'leaves function aggregations %j alone',
(...expressions) => {
const query = queryOf(DataSource.LOGS, expressions);
expect(fromDistributionAggregation(query)).toBe(query);
},
);
});
describe('setDistributionField', () => {
const sorted = {
...queryOf(DataSource.TRACES, ['duration_nano']),
orderBy: [{ columnName: 'duration_nano', order: 'desc' }],
};
it('moves the sort on the old field to the new one', () => {
expect(setDistributionField(sorted, 'attribute.quantity')).toMatchObject({
aggregations: [{ expression: 'attribute.quantity' }],
orderBy: [{ columnName: 'attribute.quantity', order: 'desc' }],
});
});
it('drops the sort when the field is cleared', () => {
expect(setDistributionField(sorted, '').orderBy).toStrictEqual([]);
});
});

View File

@@ -62,28 +62,6 @@ describe('handleQueryChange bucket options', () => {
expect(result.builder.queryFormulas[0].bucketOptions).toBeUndefined();
});
it.each([DataSource.LOGS, DataSource.TRACES])(
'keeps the axis of a %s query that stays a heatmap',
(dataSource) => {
const base = initialQueriesMap[dataSource];
const result = handleQueryChange(
PANEL_TYPES.HEATMAP,
{
...base,
builder: {
...base.builder,
queryData: [{ ...base.builder.queryData[0], bucketOptions }],
},
},
PANEL_TYPES.HEATMAP,
);
expect(result.builder.queryData[0].bucketOptions).toStrictEqual(
bucketOptions,
);
},
);
it('leaves the rest of the formula intact', () => {
const result = handleQueryChange(
PANEL_TYPES.TIME_SERIES,
@@ -124,17 +102,6 @@ describe('handleQueryChange trace operator', () => {
expect(result.builder.queryTraceOperator).toStrictEqual([]);
});
// A heatmap request takes one builder query and rejects a trace operator.
it('drops the trace operator when switching to a heatmap', () => {
const result = handleQueryChange(
PANEL_TYPES.HEATMAP,
queryWithTraceOperator(),
PANEL_TYPES.TIME_SERIES,
);
expect(result.builder.queryTraceOperator).toStrictEqual([]);
});
it('keeps the trace operator when switching to a table', () => {
const result = handleQueryChange(
PANEL_TYPES.TABLE,

View File

@@ -1,46 +0,0 @@
/** An `as` alias: quoted, or an unquoted word that may carry dashes. */
export const ALIAS = `(?:'[^']*'|"[^"]*"|[a-zA-Z0-9_-]+)`;
export const unquoteAlias = (alias: string): string =>
alias.replace(/^['"]|['"]$/g, '');
/**
* A logs or traces heatmap's aggregation: one field with an optional alias.
* The field mirrors the querier's HeatmapAggregationField: no call, no whitespace.
*/
export const DISTRIBUTION_FIELD = new RegExp(
`^\\s*([^\\s()]+)(?:\\s+as\\s+(${ALIAS}))?\\s*$`,
);
// Utility to parse aggregation expressions with optional alias
export function parseAggregations(
expression: string,
availableAlias?: string,
allowDistributionField = false,
): { expression: string; alias?: string }[] {
const result: { expression: string; alias?: string }[] = [];
// Matches function calls like "count()" or "sum(field)" with optional alias like "as 'alias'"
// Handles quoted ('alias'), dash-separated (field-name), and unquoted values after "as" keyword
const regex = new RegExp(
`([a-zA-Z0-9_]+\\([^)]*\\))(?:\\s*as\\s+(${ALIAS}))?`,
'g',
);
// With no call at all, the whole expression may be the field a logs/traces
// heatmap buckets, e.g. "duration_nano"
let match =
regex.exec(expression) ??
(allowDistributionField ? DISTRIBUTION_FIELD.exec(expression) : null);
while (match !== null) {
const expr = match[1];
let alias = match[2] || availableAlias; // Use provided alias or availableAlias if not matched
if (alias) {
// Remove quotes if present
alias = unquoteAlias(alias);
result.push({ expression: expr, alias });
} else {
result.push({ expression: expr });
}
match = regex.exec(expression);
}
return result;
}

View File

@@ -1,140 +0,0 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import type {
IBuilderQuery,
OrderByPayload,
} from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import type { LogAggregation, TraceAggregation } from 'types/api/v5/queryRange';
import {
ALIAS,
DISTRIBUTION_FIELD,
parseAggregations,
unquoteAlias,
} from './aggregationExpression';
// A numeric one-argument call such as `p99(duration_nano) as lat`; group 1 is the
// field, group 2 the inline alias. Other functions (`count_distinct`, `countIf`)
// take text or a condition.
const NUMERIC_FIELD_CALL = new RegExp(
`^\\s*(?:avg|sum|min|max|p\\d{2})\\(\\s*([^\\s(),]+)\\s*\\)(?:\\s+as\\s+(${ALIAS}))?\\s*$`,
);
/** The percentile a field or histogram metric gets when it leaves a heatmap. */
export const DEFAULT_PERCENTILE = 'p90';
type FieldAggregation = TraceAggregation | LogAggregation;
const fieldAggregations = (query: IBuilderQuery): FieldAggregation[] =>
(query.aggregations ?? []).filter(
(aggregation): aggregation is FieldAggregation => 'expression' in aggregation,
);
function isLogsOrTraces(
dataSource: DataSource,
): dataSource is DataSource.LOGS | DataSource.TRACES {
return dataSource === DataSource.LOGS || dataSource === DataSource.TRACES;
}
/** Whether the query's aggregation is a field rather than a function call. */
export function aggregatesDistributionField(
panelType: string | null | undefined,
dataSource: DataSource,
): boolean {
return panelType === PANEL_TYPES.HEATMAP && isLogsOrTraces(dataSource);
}
/**
* Replaces every aggregation with `to`. Order-by names an aggregation by its alias
* when it has one, else its expression: the order on `from` moves to `to`, or is
* dropped when `to` is empty, and orders on `removedKeys` go.
*/
function replaceAggregation(
query: IBuilderQuery,
from: Partial<FieldAggregation> | undefined,
to: string,
removedKeys: string[] = [],
): IBuilderQuery {
const fromKey = from?.alias || from?.expression;
const isFrom = (order: OrderByPayload): boolean =>
Boolean(fromKey) && order.columnName === fromKey;
return {
...query,
aggregations: [{ expression: to }],
orderBy: query.orderBy
?.filter((order) =>
isFrom(order) ? Boolean(to) : !removedKeys.includes(order.columnName),
)
.map((order) => (isFrom(order) ? { ...order, columnName: to } : order)),
};
}
export function getDistributionFieldPlaceholder(
dataSource: DataSource,
): string {
return dataSource === DataSource.TRACES
? 'Numeric field to bucket, e.g. duration_nano'
: 'Numeric field to bucket';
}
/**
* Logs and traces heatmaps bucket a field; any function aggregation is
* rejected, so a numeric `fn(field)` keeps its field and anything else leaves
* the field for the user to pick.
*/
export function toDistributionAggregation(query: IBuilderQuery): IBuilderQuery {
if (!isLogsOrTraces(query.dataSource)) {
return query;
}
const aggregations = fieldAggregations(query);
const [first] = aggregations;
const hasOneAggregation = aggregations.length === 1;
if (hasOneAggregation && DISTRIBUTION_FIELD.test(first.expression ?? '')) {
return query;
}
const fieldCall = hasOneAggregation
? NUMERIC_FIELD_CALL.exec(first.expression ?? '')
: null;
const inlineAlias = fieldCall?.[2] && unquoteAlias(fieldCall[2]);
const removedKeys = aggregations
.flatMap(({ expression, alias }) =>
parseAggregations(expression ?? '', alias),
)
.map(({ expression, alias }) => alias || expression);
return replaceAggregation(
query,
{ ...first, alias: first?.alias || inlineAlias },
fieldCall?.[1] ?? '',
removedKeys,
);
}
/** Picks `field` as the heatmap's aggregation; a sort on the old field follows it. */
export function setDistributionField(
query: IBuilderQuery,
field: string,
): IBuilderQuery {
const [first] = fieldAggregations(query);
return replaceAggregation(query, first, field);
}
/** Inverse of `toDistributionAggregation`: every other panel needs a function aggregation. */
export function fromDistributionAggregation(
query: IBuilderQuery,
): IBuilderQuery {
const aggregations = fieldAggregations(query);
if (!isLogsOrTraces(query.dataSource) || aggregations.length !== 1) {
return query;
}
const [first] = aggregations;
const expression = first.expression?.trim() ?? '';
const field = DISTRIBUTION_FIELD.exec(expression)?.[1];
if (expression && !field) {
return query;
}
return replaceAggregation(
query,
{ alias: first.alias, expression: field },
field ? `${DEFAULT_PERCENTILE}(${field})` : 'count()',
);
}

View File

@@ -175,9 +175,7 @@ export function rebuildBuilderForPanelType(
}),
queryFormulas: withHeatmapBucketOptions(builder.queryFormulas, newPanelType),
queryTraceOperator:
newPanelType === PANEL_TYPES.LIST ||
newPanelType === PANEL_TYPES.SCATTER ||
newPanelType === PANEL_TYPES.HEATMAP
newPanelType === PANEL_TYPES.LIST || newPanelType === PANEL_TYPES.SCATTER
? []
: builder.queryTraceOperator,
};

View File

@@ -122,10 +122,12 @@ const RAW_ROWS_METRICS: readonly BuilderField[] = omit(
// `functions` and `having` are dropped rather than carried: the heatmap request
// rejects both. Logs and traces keep the metrics aggregations too, because the map is
// keyed by the query's own signal, which a switch can still be holding.
const HEATMAP: readonly BuilderField[] = [
...omit(SERIES_METRICS, 'functions', 'having'),
'bucketOptions',
];
const HEATMAP: readonly BuilderField[] = omit(
SERIES_METRICS,
'functions',
'having',
);
const HEATMAP_METRICS: readonly BuilderField[] = [...HEATMAP, 'bucketOptions'];
/** Each cell gets its own copy; a shared instance would let cells contaminate
* each other. */
@@ -148,7 +150,7 @@ export const panelTypeDataSourceFormValuesMap: Record<
[PANEL_TYPES.AREA]: bySource(SERIES, SERIES_METRICS),
[PANEL_TYPES.BAR]: bySource(SERIES, SERIES_METRICS),
[PANEL_TYPES.HISTOGRAM]: bySource(SERIES, SERIES_METRICS),
[PANEL_TYPES.HEATMAP]: bySource(HEATMAP, HEATMAP),
[PANEL_TYPES.HEATMAP]: bySource(HEATMAP, HEATMAP_METRICS),
[PANEL_TYPES.TABLE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.PIE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.SCATTER]: bySource(SERIES, SCALAR_METRICS),

View File

@@ -52,14 +52,6 @@
font-variant-numeric: tabular-nums;
}
.bucketLabel {
padding: var(--spacing-2) var(--gutter) 0;
font-family: var(--font-mono);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
overflow-wrap: anywhere;
}
.filter {
display: flex;
align-items: center;

View File

@@ -38,7 +38,6 @@ export default function HeatmapTooltip({
series,
visibleGroups,
groupColor,
bucketLabel,
yAxisUnit,
decimalPrecision,
timezone,
@@ -140,15 +139,6 @@ export default function HeatmapTooltip({
{isPinned && <TooltipPinnedBadge />}
</div>
{bucketLabel && (
<div
className={Styles.bucketLabel}
data-testid="heatmap-tooltip-bucket-label"
>
{bucketLabel}
</div>
)}
{filterLabel && (
<div
className={Styles.filter}

View File

@@ -112,22 +112,6 @@ describe('HeatmapTooltip — cell identity', () => {
expect(screen.getByTestId('heatmap-tooltip-count')).toHaveTextContent('455');
});
it('names what the grid measures when the panel supplies it', () => {
renderTooltip({ bucketLabel: 'Traces · duration_nano' });
expect(screen.getByTestId('heatmap-tooltip-bucket-label')).toHaveTextContent(
'Traces · duration_nano',
);
});
it('leaves the bucket label out when there is none', () => {
renderTooltip();
expect(
screen.queryByTestId('heatmap-tooltip-bucket-label'),
).not.toBeInTheDocument();
});
it('marks the surface as pinned so the border picks up the ring', () => {
renderTooltip({ isPinned: true });

View File

@@ -121,8 +121,6 @@ export interface HeatmapTooltipProps
visibleGroups: string[];
/** Same colour the legend and the densest cells use. */
groupColor: string;
/** What the bucket axis measures, e.g. `Traces · duration_nano`. */
bucketLabel?: string;
}
export interface ScatterTooltipProps

View File

@@ -1,139 +0,0 @@
import type uPlot from 'uplot';
import { createVariableWidthBarsPathBuilder } from '../variableWidthBars';
class FakePath2D {
rects: number[][] = [];
rect(x: number, y: number, width: number, height: number): void {
this.rects.push([x, y, width, height]);
}
}
/** 10 px per unit on both axes; y grows downward from 100. */
const fakePlot: Partial<uPlot> = {
valToPos: (value: number, scaleKey: string): number =>
scaleKey === 'x' ? value * 10 : 100 - value * 10,
ctx: {} as CanvasRenderingContext2D,
};
const plot = fakePlot as uPlot;
type Fills = Map<CanvasRenderingContext2D['fillStyle'], Path2D>;
function fillsOf(paths: ReturnType<uPlot.Series.PathBuilder>): Fills {
const fill = paths?.fill;
if (!(fill instanceof Map)) {
throw new Error('expected a fill per style');
}
return fill;
}
function rectsOf(path: Path2D | undefined): number[][] {
if (!(path instanceof FakePath2D)) {
throw new Error('expected a FakePath2D');
}
return path.rects;
}
describe('createVariableWidthBarsPathBuilder', () => {
const originalPath2D = globalThis.Path2D;
beforeAll(() => {
Object.defineProperty(globalThis, 'Path2D', {
value: FakePath2D,
configurable: true,
});
});
afterAll(() => {
Object.defineProperty(globalThis, 'Path2D', {
value: originalPath2D,
configurable: true,
});
});
function build(
pattern: CanvasPattern | null = null,
): ReturnType<uPlot.Series.PathBuilder> {
return createVariableWidthBarsPathBuilder({
getBars: () => [
{ x0: 0, x1: 1, y0: 0, y1: 2, hatched: false },
{ x0: 1, x1: 4, y0: 0, y1: 5, hatched: false },
{ x0: 4, x1: 6, y0: 1, y1: 3, hatched: true },
],
fill: '#ff0000',
hatchedFill: '#ff000066',
getHatchPattern: () => pattern,
gapPx: 2,
})(plot, 1, 0, 0);
}
it('draws each bar at its own width, inset by half the gap', () => {
const fills = fillsOf(build());
expect(rectsOf(fills.get('#ff0000'))).toStrictEqual([
[1, 80, 8, 20],
[11, 50, 28, 50],
]);
});
it('draws hatched bars in their own fill, with the pattern on top', () => {
const pattern = {} as CanvasPattern;
const fills = fillsOf(build(pattern));
expect([...fills.keys()]).toStrictEqual(['#ff0000', '#ff000066', pattern]);
expect(rectsOf(fills.get(pattern))).toStrictEqual([[41, 70, 18, 20]]);
});
it('reads a fill callback on every draw', () => {
let fill = '#ff0000';
const builder = createVariableWidthBarsPathBuilder({
getBars: () => [{ x0: 0, x1: 1, y0: 0, y1: 1, hatched: false }],
fill: () => fill,
hatchedFill: '#00ff00',
getHatchPattern: () => null,
gapPx: 0,
});
const first = fillsOf(builder(plot, 1, 0, 0));
fill = '#0000ff';
const second = fillsOf(builder(plot, 1, 0, 0));
expect([...first.keys()]).toStrictEqual(['#ff0000']);
expect([...second.keys()]).toStrictEqual(['#0000ff']);
});
it('keeps solid bars when the hatched fill is the same colour', () => {
const fills = fillsOf(
createVariableWidthBarsPathBuilder({
getBars: () => [
{ x0: 0, x1: 1, y0: 0, y1: 1, hatched: false },
{ x0: 1, x1: 2, y0: 0, y1: 1, hatched: true },
],
fill: 'red',
hatchedFill: 'red',
getHatchPattern: () => null,
gapPx: 0,
})(plot, 1, 0, 0),
);
expect(rectsOf(fills.get('red'))).toHaveLength(2);
});
it('hatches only overflow bars when both fills are the same colour', () => {
const pattern = {} as CanvasPattern;
const fills = fillsOf(
createVariableWidthBarsPathBuilder({
getBars: () => [
{ x0: 0, x1: 1, y0: 0, y1: 1, hatched: false },
{ x0: 1, x1: 2, y0: 0, y1: 1, hatched: true },
],
fill: 'red',
hatchedFill: 'red',
getHatchPattern: () => pattern,
gapPx: 0,
})(plot, 1, 0, 0),
);
expect(rectsOf(fills.get(pattern))).toStrictEqual([[10, 90, 10, 10]]);
});
});

View File

@@ -1,88 +0,0 @@
import uPlot from 'uplot';
/** A bar in scale space. Unlike uPlot's own bars, each one carries its own width. */
export interface VariableWidthBar {
x0: number;
x1: number;
y0: number;
y1: number;
/** Drawn in `hatchedFill` with the hatch pattern on top. */
hatched: boolean;
}
/** A fill, or one read on every draw (e.g. to dim a series on hover). */
type BarFill = string | (() => string);
/** Bars narrower than this, in CSS pixels, keep no gap between them. */
const MIN_WIDTH_FOR_GAP_PX = 3;
/**
* Draws `[x0, x1] × [y0, y1]` rects on the `x` and `y` scales. uPlot's bar builder
* assumes one width for every bar, which a bucket axis with uneven bounds breaks.
*
* `getBars` runs on every redraw, so a caller can derive the bars from the plot's
* current state (e.g. which series are shown).
*/
export function createVariableWidthBarsPathBuilder({
getBars,
fill,
hatchedFill,
getHatchPattern,
gapPx,
}: {
getBars: (u: uPlot, seriesIdx: number) => VariableWidthBar[];
fill: BarFill;
hatchedFill: BarFill;
getHatchPattern: (ctx: CanvasRenderingContext2D) => CanvasPattern | null;
/** Space between neighbouring bars, in CSS pixels. */
gapPx: number;
}): uPlot.Series.PathBuilder {
return (u, seriesIdx): uPlot.Series.Paths => {
const solidFill = resolveFill(fill);
const overflowFill = resolveFill(hatchedFill);
const solidPath = new Path2D();
// The hatch overlays only overflow bars, so they keep a path of their own even
// when one colour fill covers both (a Map keyed by fill holds one path a fill).
const hatchedPath = new Path2D();
const isSharedFill = overflowFill === solidFill;
const inset = (gapPx * uPlot.pxRatio) / 2;
const minWidthForGap = MIN_WIDTH_FOR_GAP_PX * uPlot.pxRatio;
let hasHatched = false;
getBars(u, seriesIdx).forEach((bar) => {
const left = u.valToPos(bar.x0, 'x', true);
const right = u.valToPos(bar.x1, 'x', true);
const top = u.valToPos(bar.y1, 'y', true);
const bottom = u.valToPos(bar.y0, 'y', true);
const width = right - left;
const gap = width > minWidthForGap ? inset : 0;
const rect = [left + gap, top, width - 2 * gap, bottom - top] as const;
if (!bar.hatched || isSharedFill) {
solidPath.rect(...rect);
}
if (bar.hatched) {
hatchedPath.rect(...rect);
hasHatched = true;
}
});
const fills = new Map<CanvasRenderingContext2D['fillStyle'], Path2D>([
[solidFill, solidPath],
]);
if (hasHatched) {
if (!isSharedFill) {
fills.set(overflowFill, hatchedPath);
}
const pattern = getHatchPattern(u.ctx);
if (pattern) {
fills.set(pattern, hatchedPath);
}
}
return { stroke: null, fill: fills, clip: null, band: null, flags: 0 };
};
}
function resolveFill(fill: BarFill): string {
return typeof fill === 'function' ? fill() : fill;
}

View File

@@ -1,5 +0,0 @@
.notice {
padding: var(--spacing-2) var(--spacing-4);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
}

View File

@@ -1,279 +0,0 @@
import { useCallback, useMemo } from 'react';
import Legend from 'lib/uPlotV2/components/Legend/Legend';
import {
LegendPosition,
type TooltipRenderArgs,
} from 'lib/uPlotV2/components/types';
import type { LegendItem } from 'lib/uPlotV2/config/types';
import { StackMode } from 'lib/uPlotV2/config/types';
import ChartWrapper from 'lib/visualization/charts/ChartWrapper/ChartWrapper';
import { resolveBoundaryPrecision } from 'lib/visualization/charts/Heatmap/utils';
import { DistributionChartProps } from 'lib/visualization/charts/types';
import { useLegendVisibility } from 'lib/visualization/hooks/useLegendVisibility';
import type { LegendLayout } from 'lib/visualization/layout/ChartLayout/ChartLayout';
import { resolveOtherColor, resolveSeriesColor } from './colors';
import DistributionTooltip from './components/DistributionTooltip/DistributionTooltip';
import { buildDistributionConfig } from './config';
import {
clampDistributionXAxis,
cropDistributionXAxis,
resolveDistributionBars,
resolveDistributionXAxis,
sumVisibleCounts,
} from './layout';
import { computeDistributionPercentiles } from './percentiles';
import { groupIntoOther, resolveMaxDrawnGroups } from './topGroups';
import { DistributionYScale } from './types';
import { useDistributionBarClick } from './useDistributionBarClick';
import styles from './Distribution.module.scss';
import { createBoundFormatter, prepareDistributionChartData } from './utils';
/** Rough share of the panel width the plot gets, for fitting side-by-side bars. */
const PLOT_SHARE = 0.9;
const PLOT_SHARE_WITH_RIGHT_LEGEND = 0.65;
/** Vertical space the Other notice takes out of the container. */
const NOTICE_HEIGHT = 20;
const NO_PERCENTILES: readonly number[] = Object.freeze([]);
export default function Distribution({
id,
buckets,
series,
width,
height,
isDarkMode,
xMin,
xMax,
yScale = DistributionYScale.Linear,
stack = StackMode.Normal,
xAxisUnit,
decimalPrecision,
customColors,
percentiles = NO_PERCENTILES,
onBarClick,
showLegend = true,
legendPosition = LegendPosition.BOTTOM,
showTooltip = true,
canPinTooltip = false,
renderTooltipFooter,
tooltipPortalRoot,
layoutChildren,
'data-testid': testId,
}: DistributionChartProps): JSX.Element {
const labels = useMemo(() => series.map((entry) => entry.label), [series]);
const counts = useMemo(() => series.map((entry) => entry.counts), [series]);
const { visibleKeys, focusedSeriesIndex, onLegendAction } =
useLegendVisibility({ keys: labels, indexOffset: 1, id });
const visible = useMemo(
() => labels.map((label) => visibleKeys.includes(label)),
[labels, visibleKeys],
);
const colors = useMemo(
() =>
labels.map((label) => resolveSeriesColor(label, isDarkMode, customColors)),
[labels, isDarkMode, customColors],
);
const { xAxis, totals } = useMemo(() => {
const full = resolveDistributionXAxis(buckets);
const visibleTotals = sumVisibleCounts(counts, visible, full.rows.length);
// An explicit max may reach past the last occupied bucket; only auto-crop without one.
const fitted =
xMax === undefined ? cropDistributionXAxis(full, visibleTotals) : full;
return {
xAxis: clampDistributionXAxis(fitted, xMin, xMax),
totals: visibleTotals,
};
}, [buckets, xMin, xMax, counts, visible]);
// Over the visible groups combined, so a legend toggle moves them without a refetch.
const markers = useMemo(
() => computeDistributionPercentiles({ xAxis, totals, percentiles }),
[xAxis, totals, percentiles],
);
const isLogY =
yScale === DistributionYScale.Log && stack !== StackMode.Percent;
// The legend lists every group; the plot draws the largest and sums the rest into
// Other, so a toggle re-ranks without a refetch.
const drawn = useMemo(
() =>
groupIntoOther({
labels,
counts,
colors,
visible,
maxGroups: resolveMaxDrawnGroups({
stack,
xAxis,
plotWidth:
width *
(legendPosition === LegendPosition.RIGHT
? PLOT_SHARE_WITH_RIGHT_LEGEND
: PLOT_SHARE),
}),
otherColor: resolveOtherColor(isDarkMode),
}),
[
labels,
counts,
colors,
visible,
stack,
xAxis,
width,
legendPosition,
isDarkMode,
],
);
const layout = useMemo(
() =>
resolveDistributionBars({
xAxis,
counts: drawn.counts,
stack,
isLogY,
}),
[xAxis, drawn, stack, isLogY],
);
const boundaryPrecision = useMemo(
() =>
resolveBoundaryPrecision({
yAxis: xAxis,
yAxisUnit: xAxisUnit,
decimalPrecision,
}),
[xAxis, xAxisUnit, decimalPrecision],
);
const formatBound = useMemo(
() => createBoundFormatter(xAxisUnit, boundaryPrecision),
[xAxisUnit, boundaryPrecision],
);
const config = useMemo(
() =>
buildDistributionConfig({
id,
xAxis,
layout,
labels: drawn.labels,
colors: drawn.colors,
stack,
isLogY,
isDarkMode,
markers,
xAxisUnit,
decimalPrecision: boundaryPrecision,
}),
[
id,
xAxis,
layout,
drawn,
stack,
isLogY,
isDarkMode,
markers,
xAxisUnit,
boundaryPrecision,
],
);
const renderTooltip = useCallback(
(args: TooltipRenderArgs): React.ReactNode => (
<DistributionTooltip
uPlotInstance={args.uPlotInstance}
isPinned={args.isPinned}
dismiss={args.dismiss}
xAxis={xAxis}
layout={layout}
labels={drawn.labels}
colors={drawn.colors}
counts={drawn.counts}
formatBound={formatBound}
renderTooltipFooter={renderTooltipFooter}
/>
),
[xAxis, layout, drawn, formatBound, renderTooltipFooter],
);
const handleClick = useDistributionBarClick({
xAxis,
layout,
drawn,
series,
onBarClick,
});
const data = useMemo(
() => prepareDistributionChartData(xAxis, drawn.counts),
[xAxis, drawn],
);
const legendItems = useMemo<LegendItem[]>(
() =>
labels.map((label, index) => ({
seriesIndex: index + 1,
label,
color: colors[index],
show: visible[index],
})),
[labels, colors, visible],
);
const groupLegend = useCallback(
({ averageLegendWidth, showSearch }: LegendLayout): React.ReactNode => (
<Legend
items={legendItems}
position={legendPosition}
averageLegendWidth={averageLegendWidth}
showSearch={showSearch}
itemLabel="groups"
focusedSeriesIndex={focusedSeriesIndex}
onAction={onLegendAction}
/>
),
[legendItems, legendPosition, focusedSeriesIndex, onLegendAction],
);
return (
<ChartWrapper
config={config}
data={data}
width={width}
height={
drawn.otherGroupCount > 0 ? Math.max(0, height - NOTICE_HEIGHT) : height
}
legendConfig={{ position: legendPosition }}
showLegend={showLegend}
customLegend={groupLegend}
legendLabels={labels}
showTooltip={showTooltip}
canPinTooltip={canPinTooltip}
decimalPrecision={decimalPrecision}
customTooltip={renderTooltip}
onClick={handleClick}
contentFooter={
drawn.otherGroupCount > 0 && (
<div className={styles.notice} data-testid="distribution-other-notice">
Showing top {drawn.labels.length - 1} of {drawn.visibleGroupCount} groups;
the rest are summed into Other.
</div>
)
}
renderTooltipFooter={renderTooltipFooter}
tooltipPortalRoot={tooltipPortalRoot}
layoutChildren={layoutChildren}
data-testid={testId}
/>
);
}

View File

@@ -1,115 +0,0 @@
import type React from 'react';
import type { LegendItem } from 'lib/uPlotV2/config/types';
import { render, screen, userEvent } from 'tests/test-utils';
import Distribution from '../Distribution';
import type { DistributionSeries } from '../types';
// The shared Legend virtualises its items; render them all so they are queryable.
jest.mock('react-virtuoso', () => ({
VirtuosoGrid: ({
data,
itemContent,
}: {
data: LegendItem[];
itemContent: (index: number, item: LegendItem) => React.ReactNode;
}): JSX.Element => (
<div>
{data.map((item, index) => (
<div key={item.seriesIndex}>{itemContent(index, item)}</div>
))}
</div>
),
}));
const BUCKETS = [5, 10, 100, 1000];
const SERIES: DistributionSeries[] = [
{ label: 'service.name=cart', counts: [3, 40, 12, 1, 0] },
{ label: 'service.name=checkout', counts: [1, 10, 30, 6, 2] },
];
function renderDistribution(
props: Partial<React.ComponentProps<typeof Distribution>> = {},
): ReturnType<typeof render> {
return render(
<Distribution
id="panel-1"
buckets={BUCKETS}
series={SERIES}
width={800}
height={400}
isDarkMode
data-testid="distribution"
{...props}
/>,
);
}
describe('Distribution', () => {
// Legend items count from 1, as uPlot's data series do.
const CART = 1;
const CHECKOUT = 2;
// The selection persists under the panel id, which every case here shares.
beforeEach(() => localStorage.clear());
function legendItem(seriesIndex: number): HTMLElement {
return screen.getByTestId(`legend-item-${seriesIndex}`);
}
it('renders the plot container', () => {
renderDistribution();
expect(screen.getByTestId('distribution')).toBeInTheDocument();
});
it('lists every group in the legend, all shown', () => {
renderDistribution();
expect(legendItem(CART)).toHaveAttribute('aria-checked', 'true');
expect(legendItem(CHECKOUT)).toHaveAttribute('aria-checked', 'true');
});
it('isolates a group when its row is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDistribution();
await user.click(legendItem(CART));
expect(legendItem(CART)).toHaveAttribute('aria-checked', 'true');
expect(legendItem(CHECKOUT)).toHaveAttribute('aria-checked', 'false');
});
it('hides only that group when its marker is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDistribution();
await user.click(screen.getByTestId(`legend-marker-${CHECKOUT}`));
expect(legendItem(CHECKOUT)).toHaveAttribute('aria-checked', 'false');
expect(legendItem(CART)).toHaveAttribute('aria-checked', 'true');
});
it('sums groups past the stacked cap into Other, with a notice', () => {
renderDistribution({
series: Array.from({ length: 12 }, (_, index) => ({
label: `group-${index}`,
counts: [index, 1, 1, 0, 0],
})),
});
expect(screen.getByTestId('distribution-other-notice')).toHaveTextContent(
'Showing top 9 of 12 groups; the rest are summed into Other.',
);
// The legend still lists every group, so any can be isolated.
expect(legendItem(1)).toHaveAttribute('aria-label', 'group-0');
});
it('shows no notice when every group fits', () => {
renderDistribution();
expect(
screen.queryByTestId('distribution-other-notice'),
).not.toBeInTheDocument();
});
});

View File

@@ -1,126 +0,0 @@
import { StackMode } from 'lib/uPlotV2/config/types';
import type uPlot from 'uplot';
import { resolveDistributionBars, resolveDistributionXAxis } from '../layout';
import { buildDistributionConfig } from '../config';
// Buckets ≤ 10, (10, 20], (20, 40], > 40 in slots [0, 1] … [3, 4]. Only (10, 20] is occupied.
const xAxis = resolveDistributionXAxis([10, 20, 40]);
const counts = [
[0, 4, 0, 0],
[0, 6, 0, 0],
];
function setCursorHook(drawnCounts = counts): (u: uPlot) => void {
const config = buildDistributionConfig({
id: 'panel-1',
xAxis,
layout: resolveDistributionBars({
xAxis,
counts: drawnCounts,
stack: StackMode.Normal,
isLogY: false,
}),
labels: drawnCounts.map((_, index) => `group-${index}`),
colors: drawnCounts.map(() => '#ff0000'),
stack: StackMode.Normal,
isLogY: false,
isDarkMode: true,
markers: [],
}).getConfig();
const [hook] = config.hooks?.setCursor ?? [];
return hook as (u: uPlot) => void;
}
/** Pixels are values, so the cursor sits at `(left, top)` in scale space. */
function plotAt(
left: number,
top: number,
): { u: uPlot; setSeries: jest.Mock; redraw: jest.Mock } {
const setSeries = jest.fn();
const redraw = jest.fn();
const plot: Partial<uPlot> = {
cursor: { left, top },
posToVal: (position: number) => position,
setSeries,
redraw,
};
return { u: plot as uPlot, setSeries, redraw };
}
describe('buildDistributionConfig cursor', () => {
it('turns off drag-to-zoom', () => {
const config = buildDistributionConfig({
id: 'panel-1',
xAxis,
layout: resolveDistributionBars({
xAxis,
counts,
stack: StackMode.Normal,
isLogY: false,
}),
labels: ['group-0', 'group-1'],
colors: ['#ff0000', '#ff0000'],
stack: StackMode.Normal,
isLogY: false,
isDarkMode: true,
markers: [],
}).getConfig();
expect(config.cursor?.drag).toMatchObject({ x: false, y: false });
});
});
describe('buildDistributionConfig setCursor', () => {
// TooltipPlugin only shows a tooltip for a focused series.
it('focuses the group under the cursor, 1-based as uPlot counts series', () => {
const { u, setSeries, redraw } = plotAt(1.5, 8);
setCursorHook()(u);
expect(setSeries).toHaveBeenCalledWith(2, { focus: true });
expect(redraw).toHaveBeenCalledWith(true, false);
});
it('focuses the nearest group above the stack, dimming the rest', () => {
const { u, setSeries, redraw } = plotAt(1.5, 50);
setCursorHook()(u);
expect(setSeries).toHaveBeenCalledWith(2, { focus: true });
expect(redraw).toHaveBeenCalledWith(true, false);
});
it('keeps a tooltip over an empty bucket without dimming any group', () => {
const hook = setCursorHook();
const { u, setSeries, redraw } = plotAt(1.5, 8);
hook(u);
redraw.mockClear();
u.cursor.left = 2.5;
u.cursor.top = 1;
hook(u);
expect(setSeries).toHaveBeenLastCalledWith(1, { focus: true });
expect(redraw).toHaveBeenCalledWith(true, false);
});
it('focuses nothing off the plot', () => {
const hook = setCursorHook();
const { u, setSeries } = plotAt(1.5, 8);
hook(u);
u.cursor.left = -1;
hook(u);
expect(setSeries).toHaveBeenLastCalledWith(null, { focus: true });
});
it('focuses nothing over an empty bucket when every group is hidden', () => {
const { u, setSeries } = plotAt(2.5, 1);
setCursorHook([])(u);
expect(setSeries).not.toHaveBeenCalled();
});
});

View File

@@ -1,58 +0,0 @@
import {
layoutMarkerLabels,
resolveHoveredMarker,
} from '../drawPercentileMarkers';
describe('resolveHoveredMarker', () => {
const areas = [
{
x: 100,
badges: [
{ left: 92, right: 108, top: 0, bottom: 16 },
{ left: 92, right: 108, top: 184, bottom: 200 },
],
},
{
x: 120,
badges: [{ left: 112, right: 128, top: 18, bottom: 34 }],
},
];
it('picks the line nearest x within the tolerance', () => {
expect(resolveHoveredMarker(areas, 103, 100, 4)).toBe(0);
expect(resolveHoveredMarker(areas, 117, 100, 4)).toBe(1);
expect(resolveHoveredMarker(areas, 110, 100, 4)).toBeNull();
});
it('picks the marker whose badge is under the cursor', () => {
expect(resolveHoveredMarker(areas, 107, 190, 4)).toBe(0);
expect(resolveHoveredMarker(areas, 126, 20, 4)).toBe(1);
});
});
describe('layoutMarkerLabels', () => {
it('keeps labels that fit on the first row', () => {
expect(
layoutMarkerLabels(
[
{ x: 0, width: 20 },
{ x: 40, width: 20 },
],
4,
),
).toStrictEqual([0, 0]);
});
it('drops a label that would overlap to the next free row', () => {
expect(
layoutMarkerLabels(
[
{ x: 30, width: 20 },
{ x: 0, width: 20 },
{ x: 10, width: 20 },
],
4,
),
).toStrictEqual([0, 0, 1]);
});
});

View File

@@ -1,286 +0,0 @@
import { StackMode } from 'lib/uPlotV2/config/types';
import {
clampDistributionXAxis,
cropDistributionXAxis,
LOG_Y_BASE,
resolveDistributionBars,
resolveDistributionXAxis,
resolveNearestSeries,
sumVisibleCounts,
thinLabelledSplits,
} from '../layout';
function widths(edges: number[]): number[] {
return edges.slice(1).map((edge, index) => edge - edges[index]);
}
describe('resolveDistributionXAxis', () => {
it('lays N bounds out as N + 1 buckets, overflow last', () => {
const axis = resolveDistributionXAxis([10, 20, 30]);
expect(axis.rows).toHaveLength(4);
expect(axis.rows[0].isUnderflow).toBe(true);
expect(axis.rows[3]).toMatchObject({ lower: 30, isOverflow: true });
expect(axis.edges).toHaveLength(5);
});
it('gives every bucket the same width, ticks on the bounds', () => {
const axis = resolveDistributionXAxis([0, 5, 10, 25, 1000]);
expect(widths(axis.edges)).toStrictEqual([1, 1, 1, 1, 1, 1]);
expect(axis.splits).toStrictEqual([1, 2, 3, 4, 5]);
expect(axis.overflowSplit).toBe(6);
expect(axis.toBucketValue(3.5)).toBe(17.5);
});
});
describe('cropDistributionXAxis', () => {
it('stops one bucket past the last occupied one', () => {
const axis = resolveDistributionXAxis([1, 2, 3, 4]);
const cropped = cropDistributionXAxis(axis, [1, 5, 0, 0, 0]);
expect(cropped.max).toBe(3);
expect(cropped.overflowSplit).toBeNull();
});
});
describe('clampDistributionXAxis', () => {
// Buckets ≤ 10, (10, 20], (20, 40], (40, 80], > 80 in slots [0, 1] … [4, 5].
const axis = resolveDistributionXAxis([10, 20, 40, 80]);
it('keeps every bucket without a range', () => {
expect(clampDistributionXAxis(axis)).toStrictEqual(axis);
});
it('hides buckets wholly outside the range, keeping straddling ones whole', () => {
const clamped = clampDistributionXAxis(axis, 20, 50);
expect([clamped.min, clamped.max]).toStrictEqual([2, 4]);
expect(clamped.overflowSplit).toBeNull();
});
it('keeps the overflow tick while the overflow bucket shows', () => {
const clamped = clampDistributionXAxis(axis, 15);
expect([clamped.min, clamped.max]).toStrictEqual([1, 5]);
expect(clamped.overflowSplit).toBe(5);
});
it('keeps one bucket when the range misses them all', () => {
const clamped = clampDistributionXAxis(axis, 1000);
expect([clamped.min, clamped.max]).toStrictEqual([4, 5]);
});
it('narrows an already cropped axis, never widening it', () => {
const cropped = cropDistributionXAxis(axis, [1, 5, 0, 0, 0]);
expect(clampDistributionXAxis(cropped, 15).max).toBe(cropped.max);
});
});
describe('sumVisibleCounts', () => {
it('adds only the visible series', () => {
expect(
sumVisibleCounts(
[
[1, 2],
[10, 20],
[100, 200],
],
[true, false, true],
2,
),
).toStrictEqual([101, 202]);
});
});
describe('resolveDistributionBars', () => {
const xAxis = resolveDistributionXAxis([1, 2]);
const counts = [
[4, 6, 0],
[1, 3, 2],
];
it('sizes the count axis by the buckets left in the window', () => {
// Buckets ≤ 1, (1, 2], > 2; a max of 1 keeps only the first.
const { yMax } = resolveDistributionBars({
xAxis: clampDistributionXAxis(xAxis, undefined, 1),
counts: [[4, 1000, 0]],
stack: StackMode.Normal,
isLogY: false,
});
expect(yMax).toBe(4);
});
it('stacks series in each bucket under normal', () => {
const { rects, yMax } = resolveDistributionBars({
xAxis,
counts,
stack: StackMode.Normal,
isLogY: false,
});
expect(rects[0].map(({ y0, y1 }) => [y0, y1])).toStrictEqual([
[0, 4],
[0, 6],
]);
expect(rects[1].map(({ y0, y1 }) => [y0, y1])).toStrictEqual([
[4, 5],
[6, 9],
[0, 2],
]);
expect(yMax).toBe(9);
});
it('marks the overflow bucket hatched', () => {
const { rects } = resolveDistributionBars({
xAxis,
counts,
stack: StackMode.Normal,
isLogY: false,
});
expect(rects[1].map(({ hatched }) => hatched)).toStrictEqual([
false,
false,
true,
]);
});
it('stacks shares of each bucket under percent', () => {
const { rects, yMax } = resolveDistributionBars({
xAxis,
counts,
stack: StackMode.Percent,
isLogY: false,
});
expect(rects[0][0]).toMatchObject({ y0: 0, y1: 80 });
expect(rects[1][0]).toMatchObject({ y0: 80, y1: 100 });
expect(yMax).toBe(100);
});
it('splits the bucket width between series under none', () => {
const { rects, yMax } = resolveDistributionBars({
xAxis,
counts,
stack: StackMode.None,
isLogY: false,
});
expect(rects[0][0]).toMatchObject({ x0: 0, x1: 0.5, y0: 0, y1: 4 });
expect(rects[1][0]).toMatchObject({ x0: 0.5, x1: 1, y0: 0, y1: 1 });
expect(yMax).toBe(6);
});
it('starts bars at the log base and skips zero counts', () => {
const { rects } = resolveDistributionBars({
xAxis,
counts,
stack: StackMode.Normal,
isLogY: true,
});
expect(rects[0].map(({ y0 }) => y0)).toStrictEqual([LOG_Y_BASE, LOG_Y_BASE]);
expect(rects[0].map(({ bucketIndex }) => bucketIndex)).toStrictEqual([0, 1]);
});
it('skips bars whose top stays under the log base, never inverting one', () => {
const fractional = [
[0.5, 3, 0],
[0.25, 0.5, 2],
];
const stacked = resolveDistributionBars({
xAxis,
counts: fractional,
stack: StackMode.Normal,
isLogY: true,
});
const sideBySide = resolveDistributionBars({
xAxis,
counts: fractional,
stack: StackMode.None,
isLogY: true,
});
expect(
stacked.rects.map((rects) => rects.map(({ y0, y1 }) => [y0, y1])),
).toStrictEqual([
[[LOG_Y_BASE, 3]],
[
[3, 3.5],
[LOG_Y_BASE, 2],
],
]);
expect(
sideBySide.rects.map((rects) => rects.map(({ bucketIndex }) => bucketIndex)),
).toStrictEqual([[1], [2]]);
});
});
describe('thinLabelledSplits', () => {
it('keeps labels that clear each other by the gap', () => {
expect(
thinLabelledSplits({
positions: [0, 50, 100],
widths: [20, 20, 20],
gap: 10,
}),
).toStrictEqual([0, 1, 2]);
});
it('drops a wide label that would touch its neighbour, keeping the rightmost', () => {
// 16.67 mins-wide labels 60 px apart: each needs 70 px of centre distance.
expect(
thinLabelledSplits({
positions: [0, 60, 120, 180],
widths: [60, 60, 60, 60],
gap: 10,
}),
).toStrictEqual([1, 3]);
});
});
describe('resolveNearestSeries', () => {
// Buckets ≤ 10, (10, 20], (20, 40], > 40 in slots [0, 1] … [3, 4].
const xAxis = resolveDistributionXAxis([10, 20, 40]);
const counts = [
[0, 4, 0, 0],
[0, 6, 0, 0],
];
const stacked = resolveDistributionBars({
xAxis,
counts,
stack: StackMode.Normal,
isLogY: false,
});
it('names the group whose bar is under the point', () => {
expect(resolveNearestSeries(stacked, 1, 1.5, 2)).toBe(0);
expect(resolveNearestSeries(stacked, 1, 1.5, 8)).toBe(1);
});
it('takes the vertically nearest group off the bars, as a bar chart does', () => {
expect(resolveNearestSeries(stacked, 1, 1.5, 50)).toBe(1);
});
it('is null over an empty bucket', () => {
expect(resolveNearestSeries(stacked, 2, 2.5, 1)).toBeNull();
});
it('picks the sub-bar under the cursor side by side', () => {
const sideBySide = resolveDistributionBars({
xAxis,
counts,
stack: StackMode.None,
isLogY: false,
});
expect(resolveNearestSeries(sideBySide, 1, 1.25, 50)).toBe(0);
expect(resolveNearestSeries(sideBySide, 1, 1.75, 1)).toBe(1);
});
});

View File

@@ -1,97 +0,0 @@
import { resolveDistributionXAxis } from '../layout';
import {
computeDistributionPercentiles,
formatPercentileBadge,
formatPercentileName,
formatPercentileValue,
groupPercentileMarkers,
} from '../percentiles';
// Buckets ≤ 10, (10, 20], (20, 40], > 40 in slots [0, 1] … [3, 4].
const xAxis = resolveDistributionXAxis([10, 20, 40]);
describe('computeDistributionPercentiles', () => {
it('interpolates inside the bucket holding the rank, as histogram_quantile does', () => {
const markers = computeDistributionPercentiles({
xAxis,
totals: [10, 20, 10, 0],
percentiles: [50, 90],
});
expect(markers.map(({ value }) => value)).toStrictEqual([15, 32]);
expect(markers.every(({ isOverflow }) => !isOverflow)).toBe(true);
});
it('places the marker the same fraction across the bucket on the axis', () => {
const [p50] = computeDistributionPercentiles({
xAxis,
totals: [10, 20, 10, 0],
percentiles: [50],
});
expect(p50.axisValue).toBe(1.5);
});
it('starts the lowest bucket at zero', () => {
const [p10] = computeDistributionPercentiles({
xAxis,
totals: [10, 20, 10, 0],
percentiles: [10],
});
expect(p10.value).toBe(4);
});
it('reports a percentile in overflow as above the last bound, at its left edge', () => {
const [p99] = computeDistributionPercentiles({
xAxis,
totals: [0, 0, 10, 10],
percentiles: [99],
});
expect(p99).toMatchObject({ value: 40, axisValue: 3, isOverflow: true });
});
it('marks nothing when every count is zero', () => {
expect(
computeDistributionPercentiles({
xAxis,
totals: [0, 0, 0, 0],
percentiles: [50],
}),
).toStrictEqual([]);
});
});
describe('formatPercentileName', () => {
it('keeps fractional percentile names short', () => {
expect(formatPercentileName(99.9)).toBe('p99.9');
expect(formatPercentileName(50)).toBe('p50');
});
});
describe('percentile marker groups', () => {
const formatBound = (value: number): string => `${value} ms`;
const p50 = { percentile: 50, value: 15, axisValue: 1.5, isOverflow: false };
const p99 = { percentile: 99, value: 40, axisValue: 3, isOverflow: true };
const p90 = { percentile: 90, value: 40, axisValue: 3, isOverflow: true };
it('groups markers on the same spot, lowest percentile first', () => {
expect(groupPercentileMarkers([p50, p99, p90])).toStrictEqual([
[p50],
[p90, p99],
]);
});
it('names a group by its lowest percentile', () => {
expect(formatPercentileBadge([p50])).toBe('p50');
expect(formatPercentileBadge([p90, p99])).toBe('p90+');
});
it('shows the estimate, or the overflow bound once for the group', () => {
expect(formatPercentileValue([p50], formatBound)).toBe('p50 ≈ 15 ms');
expect(formatPercentileValue([p90, p99], formatBound)).toBe(
'p90, p99 > 40 ms',
);
});
});

View File

@@ -1,126 +0,0 @@
import { StackMode } from 'lib/uPlotV2/config/types';
import { resolveDistributionXAxis } from '../layout';
import {
groupIntoOther,
resolveClickedGroup,
MAX_STACKED_GROUPS,
OTHER_GROUP_LABEL,
resolveMaxDrawnGroups,
} from '../topGroups';
describe('resolveMaxDrawnGroups', () => {
// Four equal buckets plus underflow and overflow: six slots of one unit each.
const xAxis = resolveDistributionXAxis([1, 2, 3, 4, 5]);
it('caps stacked and percent at the fixed limit', () => {
expect(
resolveMaxDrawnGroups({ stack: StackMode.Normal, xAxis, plotWidth: 60 }),
).toBe(MAX_STACKED_GROUPS);
expect(
resolveMaxDrawnGroups({ stack: StackMode.Percent, xAxis, plotWidth: 60 }),
).toBe(MAX_STACKED_GROUPS);
});
it('fits side by side so the narrowest bar stays 3 px wide', () => {
// 120 px over six slots: 20 px a bucket, six 3 px bars.
expect(
resolveMaxDrawnGroups({ stack: StackMode.None, xAxis, plotWidth: 120 }),
).toBe(6);
expect(
resolveMaxDrawnGroups({ stack: StackMode.None, xAxis, plotWidth: 6 }),
).toBe(1);
});
});
describe('groupIntoOther', () => {
const args = {
labels: ['a', 'b', 'c', 'd'],
counts: [
[1, 1],
[5, 5],
[2, 0],
[3, 3],
],
colors: ['#a', '#b', '#c', '#d'],
visible: [true, true, true, true],
otherColor: '#999',
};
it('draws every visible group when they fit', () => {
const drawn = groupIntoOther({ ...args, maxGroups: 4 });
expect(drawn.labels).toStrictEqual(['a', 'b', 'c', 'd']);
expect(drawn.otherGroupCount).toBe(0);
});
it('keeps the largest, in legend order, and sums the rest exactly', () => {
const drawn = groupIntoOther({ ...args, maxGroups: 3 });
expect(drawn.labels).toStrictEqual(['b', 'd', OTHER_GROUP_LABEL]);
expect(drawn.sourceIndexes).toStrictEqual([1, 3, null]);
expect(drawn.counts[2]).toStrictEqual([3, 1]);
expect(drawn.colors[2]).toBe('#999');
expect(drawn).toMatchObject({ otherGroupCount: 2, visibleGroupCount: 4 });
});
it('re-ranks without hidden groups, which never reach Other', () => {
const drawn = groupIntoOther({
...args,
visible: [true, false, true, true],
maxGroups: 2,
});
expect(drawn.labels).toStrictEqual(['d', OTHER_GROUP_LABEL]);
expect(drawn.sourceIndexes).toStrictEqual([3, null]);
expect(drawn.counts[1]).toStrictEqual([3, 1]);
expect(drawn.visibleGroupCount).toBe(3);
});
});
describe('resolveClickedGroup', () => {
const series = ['a', 'b', 'c'].map((label) => ({
label,
counts: [label === 'a' ? 5 : 1],
}));
const drawn = groupIntoOther({
labels: ['a', 'b', 'c'],
counts: series.map(({ counts }) => counts),
colors: ['#a', '#b', '#c'],
visible: [true, true, true],
maxGroups: 2,
otherColor: '#999',
});
it('maps a drawn bar back to its source group and colour', () => {
expect(resolveClickedGroup(drawn, 0, series)).toStrictEqual({
series: series[0],
color: '#a',
});
});
it('refuses Other and empty space', () => {
expect(resolveClickedGroup(drawn, 1, series)).toBeNull();
expect(resolveClickedGroup(drawn, null, series)).toBeNull();
});
it('maps by source index, not label, when groups share a legend', () => {
const twins = [
{ label: 'Other', groupLabels: { pod: 'a' }, counts: [1] },
{ label: 'Other', groupLabels: { pod: 'b' }, counts: [2] },
];
const drawnTwins = groupIntoOther({
labels: twins.map(({ label }) => label),
counts: twins.map(({ counts }) => counts),
colors: ['#a', '#b'],
visible: [true, true],
maxGroups: 2,
otherColor: '#999',
});
expect(resolveClickedGroup(drawnTwins, 1, twins)).toStrictEqual({
series: twins[1],
color: '#b',
});
});
});

View File

@@ -1,29 +0,0 @@
import { Color } from '@signozhq/design-tokens';
import { themeColors } from 'constants/theme';
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
import { toAlphaHex } from 'lib/uPlotV2/utils/fillOpacity';
const HEX_COLOR = /^#[0-9a-f]{6}$/i;
export function withOpacity(color: string, opacity: number): string {
return HEX_COLOR.test(color) ? `${color}${toAlphaHex(opacity)}` : color;
}
/** Neutral, so the summed remainder never reads as one more group. */
export function resolveOtherColor(isDarkMode: boolean): string {
return isDarkMode ? Color.BG_VANILLA_400 : Color.BG_SLATE_50;
}
export function resolveSeriesColor(
label: string,
isDarkMode: boolean,
customColors?: Record<string, string>,
): string {
return (
customColors?.[label] ??
generateColor(
label,
isDarkMode ? themeColors.chartcolors : themeColors.lightModeColor,
)
);
}

View File

@@ -1,116 +0,0 @@
@use '../../../../../../styles/scrollbar' as *;
// Same surface as the shared and heatmap tooltips.
.container {
--gutter: 14px;
--row-inset: 6px;
font-family: 'Inter';
font-size: 12px;
background: var(--l2-background);
-webkit-font-smoothing: antialiased;
color: var(--l2-foreground);
border-radius: 6px;
border: 1px solid var(--l2-border);
display: flex;
flex-direction: column;
min-width: 240px;
&.pinned {
border-color: var(--ring);
}
}
.divider {
display: block;
width: 100%;
height: 1px;
background-color: var(--l2-border);
}
// Same as the heatmap tooltip's bucket row.
.title {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--spacing-2);
padding: var(--spacing-6) var(--gutter);
}
.titleBucket,
.titleCount {
font-family: var(--font-mono);
font-size: var(--font-size-xs);
font-weight: 700;
letter-spacing: -0.01em;
color: var(--popover-foreground);
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.titleSeparator {
flex: 1;
border-width: 0.5px;
border-style: dashed;
border-color: currentColor;
min-width: 24px;
opacity: 0.5;
}
// One grid for the heading and every row, so their columns line up.
.rows {
display: grid;
grid-template-columns: 12px minmax(0, 1fr) repeat(3, auto);
column-gap: var(--spacing-6);
row-gap: var(--spacing-1);
align-content: start;
padding: var(--spacing-4) var(--spacing-4) var(--spacing-6);
max-height: 320px;
overflow-y: auto;
@include custom-scrollbar;
}
.columnHeader,
.rows .row {
grid-column: 1 / -1;
display: grid;
grid-template-columns: subgrid;
// The shared item's own `gap` would otherwise shift the subgrid off the parent.
column-gap: var(--spacing-6);
align-items: center;
}
.columnHeader {
padding: 0 6px var(--spacing-2);
font-family: var(--font-mono);
font-size: 10px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--muted-foreground);
> span:nth-child(n + 2) {
text-align: right;
}
}
.columnLabel {
grid-column: 1 / 3;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rows .row {
border-radius: var(--radius);
font-variant-numeric: tabular-nums;
&[data-is-active='true'] {
background: var(--l3-background);
}
> :nth-child(n + 3) {
text-align: right;
}
}

View File

@@ -1,154 +0,0 @@
import { useMemo } from 'react';
import cx from 'classnames';
import {
formatRowLabel,
resolveRowIndex,
} from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
import TooltipPinnedBadge from 'lib/uPlotV2/components/Tooltip/components/TooltipPinnedBadge/TooltipPinnedBadge';
import ItemStyles from 'lib/uPlotV2/components/Tooltip/components/TooltipItem/TooltipItem.module.scss';
import { resolveNearestSeries } from '../../layout';
import {
buildDistributionTooltipRows,
formatPercent,
resolveGroupColumn,
} from './distributionTooltipContent';
import { DistributionTooltipProps } from './types';
import Styles from './DistributionTooltip.module.scss';
/**
* The bucket comes from the live cursor, not uPlot's `cursor.idx`: that snaps to the
* nearest bucket centre, which on uneven widths is often the neighbour.
*/
export default function DistributionTooltip({
uPlotInstance,
xAxis,
layout,
labels,
colors,
counts,
formatBound,
isPinned,
dismiss,
renderTooltipFooter,
}: DistributionTooltipProps): JSX.Element | null {
// Read outside the memo: uPlot mutates the same instance on every move.
const { left = -10, top = -10 } = uPlotInstance.cursor;
const hover = useMemo(() => {
if (left < 0 || top < 0) {
return null;
}
const x = uPlotInstance.posToVal(left, 'x');
const bucket = resolveRowIndex(xAxis.edges, x);
if (bucket === null) {
return null;
}
return {
bucket,
series: resolveNearestSeries(
layout,
bucket,
x,
uPlotInstance.posToVal(top, 'y'),
),
};
}, [left, top, uPlotInstance, xAxis, layout]);
const groupColumn = useMemo(() => resolveGroupColumn(labels), [labels]);
const rows = useMemo(
() =>
hover
? buildDistributionTooltipRows({
labels,
colors,
counts,
bucket: hover.bucket,
hoveredSeries: hover.series,
formatLabel: groupColumn.format,
})
: [],
[hover, labels, colors, counts, groupColumn],
);
if (!hover) {
return null;
}
const bucket = xAxis.rows[hover.bucket];
const bucketTotal = rows.reduce((sum, row) => sum + row.count, 0);
return (
<div
className={cx(Styles.container, { [Styles.pinned]: isPinned })}
data-pinned={isPinned}
data-testid="distribution-tooltip"
>
<div className={Styles.title}>
<span
className={Styles.titleBucket}
data-testid="distribution-tooltip-range"
>
{formatRowLabel(bucket, formatBound)}
</span>
<span className={Styles.titleSeparator} />
<span
className={Styles.titleCount}
data-testid="distribution-tooltip-total"
>
{bucketTotal.toLocaleString()}
</span>
{isPinned && <TooltipPinnedBadge />}
</div>
<span className={Styles.divider} />
<div className={Styles.rows}>
<div className={Styles.columnHeader}>
<span
className={Styles.columnLabel}
title={groupColumn.heading}
data-testid="distribution-tooltip-group-heading"
>
{groupColumn.heading}
</span>
<span>Count</span>
<span>% Total</span>
<span data-testid="distribution-tooltip-cumulative-heading">
{bucket.isOverflow ? 'All' : `≤ ${formatBound(bucket.upper)}`}
</span>
</div>
{rows.map((row) => (
<div
key={row.seriesIndex}
className={cx(ItemStyles.uplotTooltipItem, Styles.row)}
data-is-active={row.isHovered}
data-testid="distribution-tooltip-row"
data-hovered={row.isHovered}
>
<span
className={ItemStyles.uplotTooltipItemMarker}
style={{ borderColor: row.color, backgroundColor: row.color }}
/>
<span className={ItemStyles.uplotTooltipItemLabel} title={row.label}>
{row.label}
</span>
<span className={ItemStyles.uplotTooltipItemValue}>
{row.count.toLocaleString()}
</span>
<span className={ItemStyles.uplotTooltipItemValue}>
{formatPercent(row.share)}
</span>
<span className={ItemStyles.uplotTooltipItemValue}>
{formatPercent(row.cumulativeShare)}
</span>
</div>
))}
</div>
{renderTooltipFooter?.({ isPinned, dismiss })}
</div>
);
}

View File

@@ -1,88 +0,0 @@
import { StackMode } from 'lib/uPlotV2/config/types';
import {
resolveDistributionBars,
resolveDistributionXAxis,
} from 'lib/visualization/charts/Distribution/layout';
import { render, screen } from 'tests/test-utils';
import type uPlot from 'uplot';
import DistributionTooltip from '../DistributionTooltip';
// Buckets ≤ 10, (10, 20], (20, 40], > 40 in slots [0, 1] … [3, 4].
const xAxis = resolveDistributionXAxis([10, 20, 40]);
const counts = [
[1, 4, 2, 0],
[0, 6, 1, 1],
];
const layout = resolveDistributionBars({
xAxis,
counts,
stack: StackMode.Normal,
isLogY: false,
});
/** Pixels are values: the cursor at (1.5, 2) is over the first group in (10, 20]. */
function plotAt(left: number, top: number): uPlot {
const plot: Partial<uPlot> = {
cursor: { left, top },
posToVal: (position: number) => position,
};
return plot as uPlot;
}
function renderTooltip(uPlotInstance: uPlot): void {
render(
<DistributionTooltip
uPlotInstance={uPlotInstance}
isPinned={false}
dismiss={jest.fn()}
xAxis={xAxis}
layout={layout}
labels={['{service.name="cart"}', '{service.name="checkout"}']}
colors={['#f00', '#0f0']}
counts={counts}
formatBound={(value): string => `${value} ms`}
/>,
);
}
describe('DistributionTooltip', () => {
it('names the bucket under the cursor and its total', () => {
renderTooltip(plotAt(1.5, 2));
expect(screen.getByTestId('distribution-tooltip-range')).toHaveTextContent(
'10 ms – 20 ms',
);
expect(screen.getByTestId('distribution-tooltip-total')).toHaveTextContent(
'10',
);
});
it('heads the columns with the group-by key and the bucket bound', () => {
renderTooltip(plotAt(1.5, 2));
expect(
screen.getByTestId('distribution-tooltip-group-heading'),
).toHaveTextContent('service.name');
expect(
screen.getByTestId('distribution-tooltip-cumulative-heading'),
).toHaveTextContent('≤ 20 ms');
});
it('lists every group in legend order, the hovered one active', () => {
renderTooltip(plotAt(1.5, 2));
const rows = screen.getAllByTestId('distribution-tooltip-row');
expect(rows).toHaveLength(2);
expect(rows[0]).toHaveTextContent('cart457%71%');
expect(rows[0]).toHaveAttribute('data-is-active', 'true');
expect(rows[1]).toHaveTextContent('checkout675%75%');
expect(rows[1]).toHaveAttribute('data-is-active', 'false');
});
it('renders nothing off the plot', () => {
renderTooltip(plotAt(-1, -1));
expect(screen.queryByTestId('distribution-tooltip')).not.toBeInTheDocument();
});
});

View File

@@ -1,73 +0,0 @@
import {
buildDistributionTooltipRows,
formatPercent,
resolveGroupColumn,
} from '../distributionTooltipContent';
describe('formatPercent', () => {
it('rounds, and never shows a real share as 0%', () => {
expect(formatPercent(0.256)).toBe('26%');
expect(formatPercent(0.004)).toBe('<1%');
expect(formatPercent(0)).toBe('0%');
});
});
describe('resolveGroupColumn', () => {
it('names the column after a shared single key and shows its values', () => {
const column = resolveGroupColumn([
'{service.name="cart"}',
'{service.name="checkout"}',
]);
expect(column.heading).toBe('service.name');
expect(column.format('{service.name="cart"}')).toBe('cart');
});
it('keeps full labels for several keys or mixed labels', () => {
const several = resolveGroupColumn(['{env="prod", service.name="cart"}']);
const mixed = resolveGroupColumn(['{service.name="cart"}', 'Other']);
expect(several.heading).toBe('Group');
expect(several.format('{env="prod", service.name="cart"}')).toBe(
'{env="prod", service.name="cart"}',
);
expect(mixed.heading).toBe('Group');
});
});
describe('buildDistributionTooltipRows', () => {
it('gives each drawn group, in legend order, its count, share and cumulative share', () => {
const rows = buildDistributionTooltipRows({
labels: ['cart', 'checkout'],
colors: ['#f00', '#0f0'],
counts: [
[2, 6, 2],
[5, 0, 5],
],
bucket: 1,
hoveredSeries: 0,
formatLabel: (label) => label.toUpperCase(),
});
expect(rows).toStrictEqual([
{
seriesIndex: 0,
label: 'CART',
color: '#f00',
count: 6,
share: 0.6,
cumulativeShare: 0.8,
isHovered: true,
},
{
seriesIndex: 1,
label: 'CHECKOUT',
color: '#0f0',
count: 0,
share: 0,
cumulativeShare: 0.5,
isHovered: false,
},
]);
});
});

View File

@@ -1,70 +0,0 @@
import { DistributionGroupColumn, DistributionTooltipRow } from './types';
const SINGLE_LABEL = /^\{([^=,]+)="([^"]*)"\}$/;
/** `<1%` rather than `0%`, so a share that exists never reads as none. */
export function formatPercent(share: number): string {
if (share > 0 && share < 0.01) {
return '<1%';
}
return `${Math.round(share * 100)}%`;
}
/**
* Names the group column after the one group-by key every label shares, showing just
* its values; anything else (several keys, Other) keeps the full labels.
*/
export function resolveGroupColumn(labels: string[]): DistributionGroupColumn {
const keys = new Set<string>();
labels.forEach((label) => {
keys.add(SINGLE_LABEL.exec(label)?.[1] ?? '');
});
const [key] = [...keys];
if (keys.size !== 1 || !key) {
return { heading: 'Group', format: (label) => label };
}
return {
heading: key,
format: (label) => SINGLE_LABEL.exec(label)?.[2] ?? label,
};
}
/** One row per drawn group, in legend order, with its count in `bucket`. */
export function buildDistributionTooltipRows({
labels,
colors,
counts,
bucket,
hoveredSeries,
formatLabel,
}: {
labels: string[];
colors: string[];
/** `counts[series][bucket]`. */
counts: number[][];
bucket: number;
hoveredSeries: number | null;
formatLabel: (label: string) => string;
}): DistributionTooltipRow[] {
return labels.map((label, series) => {
const seriesCounts = counts[series] ?? [];
let total = 0;
let atOrBelow = 0;
seriesCounts.forEach((count, index) => {
total += count;
if (index <= bucket) {
atOrBelow += count;
}
});
const count = seriesCounts[bucket] ?? 0;
return {
seriesIndex: series,
label: formatLabel(label),
color: colors[series],
count,
share: total > 0 ? count / total : 0,
cumulativeShare: total > 0 ? atOrBelow / total : 0,
isHovered: series === hoveredSeries,
};
});
}

View File

@@ -1,39 +0,0 @@
import type {
IRenderTooltipFooterArgs,
TooltipRenderArgs,
} from 'lib/uPlotV2/components/types';
import type { DistributionBarsLayout } from '../../layout';
import type { DistributionXAxis } from '../../types';
export interface DistributionTooltipRow {
/** Index among the drawn series. */
seriesIndex: number;
label: string;
color: string;
count: number;
/** Of the group's own total over the range. */
share: number;
/** Of the group's total, at or below this bucket. */
cumulativeShare: number;
isHovered: boolean;
}
export interface DistributionGroupColumn {
heading: string;
format: (label: string) => string;
}
export interface DistributionTooltipProps extends Pick<
TooltipRenderArgs,
'uPlotInstance' | 'isPinned' | 'dismiss'
> {
xAxis: DistributionXAxis;
layout: DistributionBarsLayout;
labels: string[];
colors: string[];
/** `counts[series][bucket]`. */
counts: number[][];
formatBound: (value: number) => string;
renderTooltipFooter?: (args: IRenderTooltipFooterArgs) => React.ReactNode;
}

View File

@@ -1,288 +0,0 @@
import { PrecisionOption } from 'components/Graph/types';
import {
DistributionType,
DrawStyle,
StackMode,
} from 'lib/uPlotV2/config/types';
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
import { createVariableWidthBarsPathBuilder } from 'lib/uPlotV2/paths/variableWidthBars';
import { resolveRowIndex } from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
import { createHatchPattern } from 'lib/uPlotV2/plugins/HeatmapPlugin/paint';
import uPlot from 'uplot';
import { withOpacity } from './colors';
import {
drawPercentileMarkers,
MARKER_HIT_PX,
PercentileMarkerHitArea,
resolveHoveredMarker,
} from './drawPercentileMarkers';
import {
DistributionBarsLayout,
LOG_Y_BASE,
resolveNearestSeries,
thinLabelledSplits,
} from './layout';
import { DistributionPercentile, groupPercentileMarkers } from './percentiles';
import { DistributionXAxis } from './types';
import { createBoundFormatter } from './utils';
/** Minimum space between two x tick labels, in CSS pixels. */
const X_LABEL_GAP_PX = 12;
const BAR_GAP_PX = 1;
const BAR_OPACITY = 0.85;
const OVERFLOW_BAR_OPACITY = 0.4;
/** Every group but the hovered one fades to this. */
const DIMMED_BAR_OPACITY = 0.25;
const DIMMED_OVERFLOW_BAR_OPACITY = 0.12;
const OVERFLOW_AXIS_LABEL = '∞';
/** Headroom above the tallest bar: a fraction on linear, a factor on log. Marker
* labels sit at the top of the plot, so they take more. */
const LINEAR_HEADROOM = 1.1;
const LINEAR_HEADROOM_WITH_MARKERS = 1.3;
const LOG_HEADROOM = 2;
const LOG_HEADROOM_WITH_MARKERS = 6;
function resolveYRange({
yMax,
isLogY,
stack,
hasMarkers,
}: {
yMax: number;
isLogY: boolean;
stack: StackMode;
hasMarkers: boolean;
}): [number, number] {
if (stack === StackMode.Percent) {
return [0, hasMarkers ? 100 * LINEAR_HEADROOM_WITH_MARKERS : 100];
}
if (isLogY) {
const headroom = hasMarkers ? LOG_HEADROOM_WITH_MARKERS : LOG_HEADROOM;
return [LOG_Y_BASE, Math.max(yMax, LOG_Y_BASE) * headroom];
}
const headroom = hasMarkers ? LINEAR_HEADROOM_WITH_MARKERS : LINEAR_HEADROOM;
return [0, yMax > 0 ? yMax * headroom : 1];
}
export interface BuildDistributionConfigArgs {
id: string;
xAxis: DistributionXAxis;
layout: DistributionBarsLayout;
labels: string[];
colors: string[];
stack: StackMode;
isLogY: boolean;
isDarkMode: boolean;
/** Drawn across the plot, labelled at the top. */
markers: DistributionPercentile[];
/** Unit of the bucket bounds; counts take none. */
xAxisUnit?: string;
decimalPrecision?: PrecisionOption;
}
export function buildDistributionConfig({
id,
xAxis,
layout,
labels,
colors,
stack,
isLogY,
isDarkMode,
markers,
xAxisUnit,
decimalPrecision,
}: BuildDistributionConfigArgs): UPlotConfigBuilder {
const builder = new UPlotConfigBuilder({ id });
// uPlot's focus picks the series nearest in value, meaningless for stacked bars; the
// setCursor hook focuses the one under the cursor itself. Alpha 1 leaves the
// dimming to the bar fills.
builder.setFocus({ alpha: 1 });
// The x range is pinned to the buckets, so a drag-zoom would only flash a box.
builder.setCursor({
focus: { prox: -1 },
points: { show: false },
drag: { x: false, y: false },
});
const formatBound = createBoundFormatter(xAxisUnit, decimalPrecision);
builder.addScale({
scaleKey: 'x',
time: false,
auto: false,
range: (): [number, number] => [xAxis.min, xAxis.max],
});
const yRange = resolveYRange({
yMax: layout.yMax,
isLogY,
stack,
hasMarkers: markers.length > 0,
});
builder.addScale({
scaleKey: 'y',
time: false,
auto: false,
distribution: isLogY ? DistributionType.Logarithmic : DistributionType.Linear,
range: (): [number, number] => yRange,
});
const axisSplits =
xAxis.overflowSplit === null
? xAxis.splits
: [...xAxis.splits, xAxis.overflowSplit];
const splitLabels = new Map<number, string>();
xAxis.splits.forEach((split, index) => {
splitLabels.set(split, formatBound(xAxis.rows[index].upper));
});
if (xAxis.overflowSplit !== null) {
splitLabels.set(xAxis.overflowSplit, OVERFLOW_AXIS_LABEL);
}
const labelOf = (split: number): string =>
splitLabels.get(split) ?? formatBound(xAxis.toBucketValue(split));
builder.addAxis({
scaleKey: 'x',
side: 2,
isDarkMode,
// Thinned by each label's own width: bound labels run from `5 s` to
// `16.67 mins`, so no fixed spacing keeps them apart.
splits: (self, axisIdx): number[] => {
const visible = axisSplits.filter(
(split) => split >= xAxis.min && split <= xAxis.max,
);
const font = self.axes[axisIdx]?.font?.[0];
if (font) {
self.ctx.font = font;
}
const kept = thinLabelledSplits({
positions: visible.map((split) => self.valToPos(split, 'x')),
widths: visible.map(
(split) => self.ctx.measureText(labelOf(split)).width / uPlot.pxRatio,
),
gap: X_LABEL_GAP_PX,
});
return kept.map((index) => visible[index]);
},
values: (_, splits): string[] => splits.map(labelOf),
});
builder.addAxis({
scaleKey: 'y',
side: 3,
isDarkMode,
yAxisUnit: stack === StackMode.Percent ? 'percent' : 'short',
// The marker headroom runs a share axis past 100%, which labels nothing real.
...(stack === StackMode.Percent && {
filter: (_self: uPlot, splits: number[]): Array<number | null> =>
splits.map((split) => (split <= 100 ? split : null)),
}),
});
let hatchPattern: CanvasPattern | null | undefined;
const getHatchPattern = (
ctx: CanvasRenderingContext2D,
): CanvasPattern | null => {
hatchPattern ??= createHatchPattern(ctx, isDarkMode);
return hatchPattern;
};
// Read by every series' fill on each draw; a change redraws the paths.
const hover: {
series: number | null;
focused: number | null;
marker: number | null;
} = { series: null, focused: null, marker: null };
const plotMarkers = groupPercentileMarkers(
markers.filter(
({ axisValue }) => axisValue >= xAxis.min && axisValue <= xAxis.max,
),
);
let markerHitAreas: PercentileMarkerHitArea[] = [];
const isDimmed = (seriesIndex: number): boolean =>
hover.series !== null && hover.series !== seriesIndex;
labels.forEach((label, seriesIndex) => {
const color = colors[seriesIndex];
builder.addSeries({
scaleKey: 'y',
label,
drawStyle: DrawStyle.Bar,
pathBuilder: createVariableWidthBarsPathBuilder({
getBars: () => layout.rects[seriesIndex] ?? [],
fill: () =>
withOpacity(
color,
isDimmed(seriesIndex) ? DIMMED_BAR_OPACITY : BAR_OPACITY,
),
hatchedFill: () =>
withOpacity(
color,
isDimmed(seriesIndex)
? DIMMED_OVERFLOW_BAR_OPACITY
: OVERFLOW_BAR_OPACITY,
),
getHatchPattern,
gapPx: BAR_GAP_PX,
}),
lineColor: color,
lineWidth: 0,
colorMapping: {},
isDarkMode,
showPoints: false,
spanGaps: false,
});
});
builder.addHook('draw', (u: uPlot): void => {
markerHitAreas = drawPercentileMarkers(
u,
plotMarkers,
formatBound,
isDarkMode,
hover.marker,
);
});
// Registered as a hook, not a plugin, so it runs before TooltipPlugin's: the tooltip
// only shows for a focused series, and must find it focused when it positions.
builder.addHook('setCursor', (u: uPlot): void => {
const { left = -1, top = -1 } = u.cursor;
const isOnPlot = left >= 0 && top >= 0;
const x = isOnPlot ? u.posToVal(left, 'x') : Number.NaN;
const bucket = isOnPlot ? resolveRowIndex(xAxis.edges, x) : null;
const marker = isOnPlot
? resolveHoveredMarker(markerHitAreas, left, top, MARKER_HIT_PX)
: null;
// Over a marker, the bars neither dim nor show their tooltip.
const hovered =
bucket === null || marker !== null
? null
: resolveNearestSeries(layout, bucket, x, u.posToVal(top, 'y'));
// An empty bucket still gets a tooltip, as a bar chart's zero column does; with no
// nearest group to name, the first stands in.
const isEmptyBucket = bucket !== null && marker === null && hovered === null;
const focused = isEmptyBucket && labels.length > 0 ? 0 : hovered;
if (focused !== hover.focused) {
hover.focused = focused;
u.setSeries(focused === null ? null : focused + 1, { focus: true });
}
if (marker !== hover.marker) {
// The crosshair would cut through the marker's badges.
u.root
.querySelectorAll<HTMLElement>('.u-cursor-x, .u-cursor-y')
.forEach((line) => {
line.style.visibility = marker === null ? '' : 'hidden';
});
}
if (hovered !== hover.series || marker !== hover.marker) {
hover.series = hovered;
hover.marker = marker;
u.redraw(true, false);
}
});
return builder;
}

View File

@@ -1,242 +0,0 @@
import { Color } from '@signozhq/design-tokens';
import { themeColors } from 'constants/theme';
import uPlot from 'uplot';
import {
DistributionPercentile,
formatPercentileBadge,
formatPercentileValue,
} from './percentiles';
const MARKER_DASH: [number, number] = [3, 3];
const MARKER_FONT_SIZE_PX = 9;
/** Space between a badge's name and its diamond's edges. */
const MARKER_BADGE_PADDING_PX = 2;
const MARKER_BADGE_GAP_PX = 2;
const MARKER_VALUE_FONT_SIZE_PX = 11;
/** How far from a marker line the cursor still hovers it, in CSS pixels. */
export const MARKER_HIT_PX = 4;
const MARKER_PILL_PADDING_X_PX = 6;
const MARKER_PILL_PADDING_Y_PX = 3;
const MARKER_PILL_RADIUS_PX = 4;
/** Height of the pill's notch pointing up at the line; also its gap from the axis. */
const MARKER_PILL_POINTER_PX = 4;
interface HitRect {
left: number;
right: number;
top: number;
bottom: number;
}
/** A drawn marker's hover targets, in CSS pixels relative to the plot. */
export interface PercentileMarkerHitArea {
x: number;
badges: HitRect[];
}
/**
* The marker under `(x, y)`: one whose badge it is over, else the line nearest
* `x` within `tolerance`. `null` when none is.
*/
export function resolveHoveredMarker(
areas: PercentileMarkerHitArea[],
x: number,
y: number,
tolerance: number,
): number | null {
const overBadge = areas.findIndex(({ badges }) =>
badges.some(
(badge) =>
x >= badge.left && x <= badge.right && y >= badge.top && y <= badge.bottom,
),
);
if (overBadge !== -1) {
return overBadge;
}
let nearest: number | null = null;
let nearestDistance = tolerance;
areas.forEach((area, index) => {
const distance = Math.abs(area.x - x);
if (distance <= nearestDistance) {
nearest = index;
nearestDistance = distance;
}
});
return nearest;
}
/**
* Stacks marker badges into rows so none overlap: each goes in the first row whose
* last badge ends before it starts. Input and output are in the same pixel space.
*/
export function layoutMarkerLabels(
labels: Array<{ x: number; width: number }>,
gap: number,
): number[] {
const rowEnds: number[] = [];
const order = labels
.map((label, index) => ({ ...label, index }))
.sort((a, b) => a.x - b.x);
const rows = new Array<number>(labels.length).fill(0);
order.forEach(({ x, width, index }) => {
let row = rowEnds.findIndex((end) => x >= end + gap);
if (row === -1) {
row = rowEnds.length;
rowEnds.push(0);
}
rowEnds[row] = x + width;
rows[index] = row;
});
return rows;
}
/** A square diamond centred on `(x, y)` with half-diagonal `r`, filled then outlined. */
function drawDiamond(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
r: number,
fill: string,
stroke: string,
): void {
ctx.beginPath();
ctx.moveTo(x, y - r);
ctx.lineTo(x + r, y);
ctx.lineTo(x, y + r);
ctx.lineTo(x - r, y);
ctx.closePath();
ctx.fillStyle = fill;
ctx.fill();
ctx.strokeStyle = stroke;
ctx.stroke();
}
/**
* Dashed lines across the plot with a diamond badge at each end naming the
* percentile, one per group on the same spot; badges stack into rows so none overlap. The hovered marker is
* emphasised and shows its value on the x axis. Returns each marker's hover targets.
*/
export function drawPercentileMarkers(
u: uPlot,
markers: DistributionPercentile[][],
formatBound: (value: number) => string,
isDarkMode: boolean,
hovered: number | null,
): PercentileMarkerHitArea[] {
if (markers.length === 0) {
return [];
}
const { ctx, bbox } = u;
const { pxRatio } = uPlot;
const color = isDarkMode ? themeColors.white : themeColors.black;
const background = isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100;
const bottom = bbox.top + bbox.height;
ctx.save();
ctx.font = `600 ${MARKER_FONT_SIZE_PX * pxRatio}px Inter, sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const named = markers.map((group) => {
const text = formatPercentileBadge(group);
return { text, width: ctx.measureText(text).width };
});
// One square diamond for all, fitting the widest name's box: |dx| + |dy| ≤ r at
// its corners. Cap height stands in for the text's height.
const r =
(Math.max(...named.map(({ width }) => width)) +
MARKER_FONT_SIZE_PX * pxRatio * 0.7) /
2 +
MARKER_BADGE_PADDING_PX * pxRatio;
const badges = markers.map((group, index) => ({
text: named[index].text,
x: u.valToPos(group[0].axisValue, 'x', true),
}));
const rows = layoutMarkerLabels(
badges.map(({ x }) => ({ x: x - r, width: 2 * r })),
MARKER_BADGE_GAP_PX * pxRatio,
);
const rowStep = 2 * r + MARKER_BADGE_GAP_PX * pxRatio;
const badgeCentres = (index: number): [number, number] => {
const offset = r + rows[index] * rowStep;
return [bbox.top + offset, bottom - offset];
};
const drawMarker = (index: number): void => {
const { text, x } = badges[index];
const isHovered = index === hovered;
ctx.globalAlpha = isHovered ? 1 : 0.55;
ctx.strokeStyle = color;
ctx.lineWidth = pxRatio;
ctx.setLineDash(MARKER_DASH.map((dash) => dash * pxRatio));
ctx.beginPath();
ctx.moveTo(x, bbox.top);
ctx.lineTo(x, bottom);
ctx.stroke();
ctx.globalAlpha = 1;
ctx.setLineDash([]);
badgeCentres(index).forEach((y) => {
drawDiamond(ctx, x, y, r, isHovered ? color : background, color);
ctx.fillStyle = isHovered ? background : color;
ctx.fillText(text, x, y);
});
if (!isHovered) {
return;
}
// The value sits on the x axis under the line, over the tick labels, in a pill
// whose notch points up at the line.
ctx.font = `500 ${MARKER_VALUE_FONT_SIZE_PX * pxRatio}px Inter, sans-serif`;
const value = formatPercentileValue(markers[index], formatBound);
const padX = MARKER_PILL_PADDING_X_PX * pxRatio;
const padY = MARKER_PILL_PADDING_Y_PX * pxRatio;
const pointer = MARKER_PILL_POINTER_PX * pxRatio;
const width = ctx.measureText(value).width + 2 * padX;
const height = MARKER_VALUE_FONT_SIZE_PX * pxRatio + 2 * padY;
const left = Math.min(Math.max(x - width / 2, 0), ctx.canvas.width - width);
const top = bottom + 2 * pointer;
const notchX = Math.min(
Math.max(x, left + pointer + MARKER_PILL_RADIUS_PX * pxRatio),
left + width - pointer - MARKER_PILL_RADIUS_PX * pxRatio,
);
// A halo in the chart's background hides the tick labels it overlaps.
ctx.fillStyle = background;
ctx.fillRect(left - padX, top, width + 2 * padX, height + 2 * padY);
ctx.fillStyle = isDarkMode ? Color.BG_SLATE_400 : Color.BG_INK_400;
ctx.beginPath();
ctx.roundRect(left, top, width, height, MARKER_PILL_RADIUS_PX * pxRatio);
ctx.moveTo(notchX - pointer, top);
ctx.lineTo(notchX, top - pointer);
ctx.lineTo(notchX + pointer, top);
ctx.closePath();
ctx.fill();
ctx.fillStyle = Color.BG_VANILLA_100;
ctx.fillText(value, left + width / 2, top + height / 2);
};
// The hovered one last, so it draws over its neighbours.
badges.forEach((_, index) => index !== hovered && drawMarker(index));
if (hovered !== null && hovered < badges.length) {
drawMarker(hovered);
}
ctx.restore();
return badges.map(({ x }, index) => {
const toPlot = (value: number, origin: number): number =>
(value - origin) / pxRatio;
return {
x: toPlot(x, bbox.left),
badges: badgeCentres(index).map((y) => ({
left: toPlot(x - r, bbox.left),
right: toPlot(x + r, bbox.left),
top: toPlot(y - r, bbox.top),
bottom: toPlot(y + r, bbox.top),
})),
};
});
}

View File

@@ -1,232 +0,0 @@
import { StackMode } from 'lib/uPlotV2/config/types';
import {
cropHeatmapYAxis,
resolveHeatmapYAxis,
} from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
import { HeatmapAxisScale } from 'lib/uPlotV2/plugins/HeatmapPlugin/types';
import { DistributionBarRect, DistributionXAxis } from './types';
/** Bottom of a log count axis: a bar has to start somewhere above zero. */
export const LOG_Y_BASE = 1;
/**
* N bounds give N + 1 buckets: `≤ first`, the finite ones, and `> last`. Every bucket
* is equally wide: bucket `i` spans `[i, i + 1]`, and ticks still name the bounds.
*/
export function resolveDistributionXAxis(buckets: number[]): DistributionXAxis {
const { rows, overflowSplit } = resolveHeatmapYAxis(
buckets,
HeatmapAxisScale.Linear,
);
const edges = rows.map((_, index) => index).concat(rows.length);
return {
rows,
edges,
splits: rows.slice(0, -1).map((_, index) => index + 1),
overflowSplit: overflowSplit === null ? null : rows.length,
toBucketValue: (axisValue: number): number => {
const index = Math.min(rows.length - 1, Math.max(0, Math.floor(axisValue)));
const row = rows[index];
return row.lower + (axisValue - index) * (row.upper - row.lower);
},
min: 0,
max: rows.length,
};
}
/** Sum of each bucket across the visible series. */
export function sumVisibleCounts(
counts: number[][],
visible: boolean[],
bucketCount: number,
): number[] {
const totals = new Array<number>(bucketCount).fill(0);
counts.forEach((seriesCounts, seriesIndex) => {
if (!visible[seriesIndex]) {
return;
}
for (let bucket = 0; bucket < bucketCount; bucket += 1) {
totals[bucket] += seriesCounts[bucket] ?? 0;
}
});
return totals;
}
/** Drops empty buckets past the last occupied one, as the heatmap does. */
export function cropDistributionXAxis(
axis: DistributionXAxis,
totals: number[],
): DistributionXAxis {
return cropHeatmapYAxis(
axis,
totals.map((total) => [total]),
);
}
/**
* Narrows the axis window to the buckets overlapping `[min, max]`, never below one.
* A bucket straddling a bound stays whole: cutting it would misstate its count.
*/
export function clampDistributionXAxis(
axis: DistributionXAxis,
min?: number,
max?: number,
): DistributionXAxis {
const { rows, edges } = axis;
let first = edges.indexOf(axis.min);
let last = edges.indexOf(axis.max) - 1;
while (min !== undefined && first < last && rows[first].upper <= min) {
first += 1;
}
while (max !== undefined && last > first && rows[last].lower >= max) {
last -= 1;
}
return {
...axis,
overflowSplit: rows[last].isOverflow ? axis.overflowSplit : null,
min: edges[first],
max: edges[last + 1],
};
}
export interface DistributionBarsLayout {
/** One list per series, in series order. */
rects: DistributionBarRect[][];
/** Top of the tallest bar inside the axis window, for the count axis range. */
yMax: number;
}
/**
* Every bar, in scale space. `normal` stacks the series in each bucket, `percent`
* stacks their shares of it, `none` splits the bucket width between them.
*/
export function resolveDistributionBars({
xAxis,
counts,
stack,
isLogY,
}: {
xAxis: DistributionXAxis;
/** `counts[series][bucket]`. */
counts: number[][];
stack: StackMode;
isLogY: boolean;
}): DistributionBarsLayout {
const { rows, edges } = xAxis;
const rects: DistributionBarRect[][] = counts.map(() => []);
const base = isLogY ? LOG_Y_BASE : 0;
let yMax = 0;
rows.forEach((row, bucketIndex) => {
const x0 = edges[bucketIndex];
const x1 = edges[bucketIndex + 1];
// Buckets outside the window are off the plot and mustn't set its height.
const isInWindow = x0 >= xAxis.min && x1 <= xAxis.max;
const total = counts.reduce(
(sum, seriesCounts) => sum + (seriesCounts[bucketIndex] ?? 0),
0,
);
let cumulative = 0;
counts.forEach((seriesCounts, seriesIndex) => {
const count = seriesCounts[bucketIndex] ?? 0;
if (count <= 0) {
return;
}
const bar = { bucketIndex, hatched: row.isOverflow };
if (stack === StackMode.None) {
// Below the log base a bar would draw downwards from the axis.
if (count <= base) {
return;
}
const width = (x1 - x0) / counts.length;
rects[seriesIndex].push({
...bar,
x0: x0 + seriesIndex * width,
x1: x0 + (seriesIndex + 1) * width,
y0: base,
y1: count,
});
if (isInWindow) {
yMax = Math.max(yMax, count);
}
return;
}
const scale = stack === StackMode.Percent ? 100 / total : 1;
const y0 = cumulative * scale;
cumulative += count;
const y1 = cumulative * scale;
if (y1 <= base) {
return;
}
rects[seriesIndex].push({
...bar,
x0,
x1,
y0: Math.max(y0, base),
y1,
});
if (isInWindow) {
yMax = Math.max(yMax, y1);
}
});
});
return { rects, yMax };
}
/**
* The group nearest `(x, y)` vertically in `bucket`, as uPlot focuses bar series;
* side by side, only the sub-bar under `x` competes. `null` over an empty bucket.
*/
export function resolveNearestSeries(
layout: DistributionBarsLayout,
bucket: number,
x: number,
y: number,
): number | null {
const candidates = layout.rects.flatMap((rects, series) =>
rects
.filter((rect) => rect.bucketIndex === bucket)
.map((rect) => ({ rect, series })),
);
const underX = candidates.filter(({ rect }) => x >= rect.x0 && x < rect.x1);
let nearest: number | null = null;
let nearestDistance = Number.POSITIVE_INFINITY;
(underX.length > 0 ? underX : candidates).forEach(({ rect, series }) => {
const distance = Math.max(rect.y0 - y, y - rect.y1, 0);
if (distance < nearestDistance) {
nearest = series;
nearestDistance = distance;
}
});
return nearest;
}
/**
* Indexes of the ticks whose centred labels fit without touching, walking from the
* right so the `∞` edge survives. Positions and widths share one pixel space.
*/
export function thinLabelledSplits({
positions,
widths,
gap,
}: {
positions: number[];
widths: number[];
gap: number;
}): number[] {
const kept: number[] = [];
let leftEdge = Number.POSITIVE_INFINITY;
for (let index = positions.length - 1; index >= 0; index -= 1) {
const half = widths[index] / 2;
if (positions[index] + half + gap <= leftEdge) {
kept.push(index);
leftEdge = positions[index] - half;
}
}
return kept.reverse();
}

View File

@@ -1,110 +0,0 @@
import { DistributionXAxis } from './types';
export interface DistributionPercentile {
/** 0–100, as configured. */
percentile: number;
/** The estimate; in overflow, the last finite bound it is known to exceed. */
value: number;
/** Where the marker is drawn, in x-scale space. */
axisValue: number;
isOverflow: boolean;
}
/**
* Percentiles of the summed counts, by `histogram_quantile`'s method: find the bucket
* holding the target rank and interpolate linearly inside it, with the lowest bucket
* starting at zero. So the values match a time-series panel's percentiles.
*/
export function computeDistributionPercentiles({
xAxis,
totals,
percentiles,
}: {
xAxis: DistributionXAxis;
/** Summed visible counts per bucket. */
totals: number[];
percentiles: readonly number[];
}): DistributionPercentile[] {
const { rows, edges } = xAxis;
const total = totals.reduce((sum, count) => sum + count, 0);
if (total <= 0 || rows.length === 0) {
return [];
}
return percentiles.flatMap<DistributionPercentile>((percentile) => {
const rank = (percentile / 100) * total;
let below = 0;
for (let index = 0; index < rows.length; index += 1) {
const count = totals[index] ?? 0;
if (count > 0 && below + count >= rank) {
const row = rows[index];
if (row.isOverflow) {
return [
{
percentile,
value: row.lower,
axisValue: edges[index],
isOverflow: true,
},
];
}
const fraction = (rank - below) / count;
const lower = row.isUnderflow ? Math.min(0, row.upper) : row.lower;
return [
{
percentile,
value: lower + fraction * (row.upper - lower),
axisValue: edges[index] + fraction * (edges[index + 1] - edges[index]),
isOverflow: false,
},
];
}
below += count;
}
return [];
});
}
export function formatPercentileName(percentile: number): string {
return `p${Number(percentile.toFixed(3))}`;
}
/**
* Markers that fall on the same spot, sharing one badge: the percentiles landing
* in overflow all sit on its edge. Each group is in ascending percentile order.
*/
export function groupPercentileMarkers(
markers: DistributionPercentile[],
): DistributionPercentile[][] {
const groups = new Map<number, DistributionPercentile[]>();
markers.forEach((marker) => {
groups.set(marker.axisValue, [
...(groups.get(marker.axisValue) ?? []),
marker,
]);
});
return [...groups.values()].map((group) =>
[...group].sort((a, b) => a.percentile - b.percentile),
);
}
/** `p90` for one marker; `p90+` for a group, starting at its lowest percentile. */
export function formatPercentileBadge(group: DistributionPercentile[]): string {
const name = formatPercentileName(group[0].percentile);
return group.length > 1 ? `${name}+` : name;
}
/**
* `p99 ≈ 412 ms` for an estimate; `p90, p99 > 5 s` where only the overflow bound is
* known. A group shares one spot, so one value and overflow flag.
*/
export function formatPercentileValue(
group: DistributionPercentile[],
formatBound: (value: number) => string,
): string {
const names = group
.map(({ percentile }) => formatPercentileName(percentile))
.join(', ');
const [{ value, isOverflow }] = group;
return `${names} ${isOverflow ? '>' : '≈'} ${formatBound(value)}`;
}

View File

@@ -1,133 +0,0 @@
import { StackMode } from 'lib/uPlotV2/config/types';
import { DistributionSeries, DistributionXAxis } from './types';
/** Colours stop being told apart past this many stacked groups. */
export const MAX_STACKED_GROUPS = 10;
/** Narrowest a side-by-side bar may get, in CSS pixels. */
const MIN_SIDE_BY_SIDE_BAR_PX = 3;
export const OTHER_GROUP_LABEL = 'Other';
/**
* How many series fit: a fixed cap when stacked, and side by side as many as keep
* every bar in the narrowest bucket at least `MIN_SIDE_BY_SIDE_BAR_PX` wide.
*/
export function resolveMaxDrawnGroups({
stack,
xAxis,
plotWidth,
}: {
stack: StackMode;
xAxis: DistributionXAxis;
/** Approximate width of the plotting area, in CSS pixels. */
plotWidth: number;
}): number {
if (stack !== StackMode.None) {
return MAX_STACKED_GROUPS;
}
const span = xAxis.max - xAxis.min;
let narrowest = Number.POSITIVE_INFINITY;
for (let index = 0; index + 1 < xAxis.edges.length; index += 1) {
if (xAxis.edges[index] < xAxis.max) {
narrowest = Math.min(narrowest, xAxis.edges[index + 1] - xAxis.edges[index]);
}
}
if (!(span > 0) || !Number.isFinite(narrowest)) {
return MAX_STACKED_GROUPS;
}
const narrowestPx = (plotWidth * narrowest) / span;
return Math.min(
MAX_STACKED_GROUPS,
Math.max(1, Math.floor(narrowestPx / MIN_SIDE_BY_SIDE_BAR_PX)),
);
}
export interface DrawnGroups {
labels: string[];
counts: number[][];
colors: string[];
/** Each drawn group's index among the source series; `null` for Other. */
sourceIndexes: (number | null)[];
/** Visible groups summed into the Other series; 0 when none were. */
otherGroupCount: number;
/** Visible groups in all, drawn or folded. */
visibleGroupCount: number;
}
function sum(counts: number[]): number {
return counts.reduce((total, count) => total + count, 0);
}
/**
* The visible groups to draw: all of them when they fit, else the largest by total
* and one Other series summing the rest. Exact, because bucket counts add. Drawn
* groups keep legend order.
*/
export function groupIntoOther({
labels,
counts,
colors,
visible,
maxGroups,
otherColor,
}: {
labels: string[];
counts: number[][];
colors: string[];
visible: boolean[];
maxGroups: number;
otherColor: string;
}): DrawnGroups {
const visibleIndexes = labels
.map((_, index) => index)
.filter((index) => visible[index]);
if (visibleIndexes.length <= maxGroups) {
return {
labels: visibleIndexes.map((index) => labels[index]),
counts: visibleIndexes.map((index) => counts[index]),
colors: visibleIndexes.map((index) => colors[index]),
sourceIndexes: visibleIndexes,
otherGroupCount: 0,
visibleGroupCount: visibleIndexes.length,
};
}
const keep = new Set(
[...visibleIndexes]
.sort((a, b) => sum(counts[b]) - sum(counts[a]) || a - b)
.slice(0, Math.max(0, maxGroups - 1)),
);
const kept = visibleIndexes.filter((index) => keep.has(index));
const folded = visibleIndexes.filter((index) => !keep.has(index));
const bucketCount = Math.max(...folded.map((index) => counts[index].length));
const other = Array.from({ length: bucketCount }, (_, bucket) =>
folded.reduce((total, index) => total + (counts[index][bucket] ?? 0), 0),
);
return {
labels: [...kept.map((index) => labels[index]), OTHER_GROUP_LABEL],
counts: [...kept.map((index) => counts[index]), other],
colors: [...kept.map((index) => colors[index]), otherColor],
sourceIndexes: [...kept, null],
otherGroupCount: folded.length,
visibleGroupCount: visibleIndexes.length,
};
}
/**
* The drawn group at `drawnIndex` as a source series and its colour; `null` for Other,
* which sums several groups no single filter can name.
*/
export function resolveClickedGroup(
drawn: DrawnGroups,
drawnIndex: number | null,
series: DistributionSeries[],
): { series: DistributionSeries; color: string } | null {
const source =
drawnIndex === null ? null : (drawn.sourceIndexes[drawnIndex] ?? null);
if (drawnIndex === null || source === null) {
return null;
}
return { series: series[source], color: drawn.colors[drawnIndex] };
}

View File

@@ -1,31 +0,0 @@
import type { VariableWidthBar } from 'lib/uPlotV2/paths/variableWidthBars';
import type { HeatmapYAxis } from 'lib/uPlotV2/plugins/HeatmapPlugin/types';
export interface DistributionSeries {
label: string;
/** Group-by key → value, for drilling into this group. Empty when ungrouped. */
groupLabels?: Record<string, string>;
/** One count per bucket bound plus the trailing overflow, summed over the range. */
counts: number[];
}
/** A click on a group's bar; never on Other, which no filter can name. */
export interface DistributionBarClick {
series: DistributionSeries;
color: string;
/** Viewport coordinates of the click. */
coordinates: { x: number; y: number };
}
export enum DistributionYScale {
Linear = 'linear',
Log = 'log',
}
/** The bucket axis in x-scale space. The heatmap's row axis, laid sideways. */
export type DistributionXAxis = HeatmapYAxis;
/** `x` in bucket-axis units, `y` in counts (or percent); the overflow bucket is hatched. */
export interface DistributionBarRect extends VariableWidthBar {
bucketIndex: number;
}

View File

@@ -1,56 +0,0 @@
import { useCallback, useRef } from 'react';
import { resolveRowIndex } from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
import type { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
import { type DistributionBarsLayout, resolveNearestSeries } from './layout';
import { type DrawnGroups, resolveClickedGroup } from './topGroups';
import type {
DistributionBarClick,
DistributionSeries,
DistributionXAxis,
} from './types';
/** Resolves a plot click to the group under it; Other and empty buckets report none. */
export function useDistributionBarClick({
xAxis,
layout,
drawn,
series,
onBarClick,
}: {
xAxis: DistributionXAxis;
layout: DistributionBarsLayout;
drawn: DrawnGroups;
series: DistributionSeries[];
onBarClick?: (click: DistributionBarClick) => void;
}): ((data: ChartClickData) => void) | undefined {
const onBarClickRef = useRef(onBarClick);
onBarClickRef.current = onBarClick;
const handleClick = useCallback(
({
xValue,
yValue,
absoluteMouseX,
absoluteMouseY,
}: ChartClickData): void => {
const bucket = resolveRowIndex(xAxis.edges, xValue);
const clicked = resolveClickedGroup(
drawn,
bucket === null
? null
: resolveNearestSeries(layout, bucket, xValue, yValue),
series,
);
if (clicked) {
onBarClickRef.current?.({
...clicked,
coordinates: { x: absoluteMouseX, y: absoluteMouseY },
});
}
},
[xAxis, layout, drawn, series],
);
return onBarClick ? handleClick : undefined;
}

View File

@@ -1,32 +0,0 @@
import { PrecisionOption } from 'components/Graph/types';
import { getToolTipValue } from 'components/Graph/yAxisConfig';
import uPlot from 'uplot';
import { DistributionXAxis } from './types';
export function createBoundFormatter(
unit?: string,
decimalPrecision?: PrecisionOption,
): (value: number) => string {
return (value: number): string =>
getToolTipValue(String(value), unit, decimalPrecision);
}
/**
* `[bucket centres, ...counts per series]`. The series draw from the layout, so the
* data only feeds uPlot's cursor and tooltip.
*/
export function prepareDistributionChartData(
xAxis: DistributionXAxis,
counts: number[][],
): uPlot.AlignedData {
const centres = xAxis.rows.map(
(_, index) => (xAxis.edges[index] + xAxis.edges[index + 1]) / 2,
);
return [
centres,
...counts.map((seriesCounts) =>
centres.map((_, index) => seriesCounts[index] ?? 0),
),
] as unknown as uPlot.AlignedData;
}

View File

@@ -68,7 +68,6 @@ export default function Heatmap(props: HeatmapChartProps): JSX.Element {
yAxisUnit,
decimalPrecision,
timezone,
bucketLabel,
showVisualMap = true,
showLegend = true,
legendPosition = LegendPosition.BOTTOM,
@@ -254,7 +253,6 @@ export default function Heatmap(props: HeatmapChartProps): JSX.Element {
yAxisUnit={yAxisUnit}
decimalPrecision={boundaryPrecision}
timezone={timezone}
bucketLabel={bucketLabel}
canPinTooltip={canPinTooltip}
renderTooltipFooter={renderTooltipFooter}
/>
@@ -269,7 +267,6 @@ export default function Heatmap(props: HeatmapChartProps): JSX.Element {
yAxisUnit,
boundaryPrecision,
timezone,
bucketLabel,
canPinTooltip,
renderTooltipFooter,
],

View File

@@ -26,11 +26,6 @@ import {
} from 'lib/uPlotV2/plugins/TooltipPlugin/types';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import type { StackMode } from 'lib/uPlotV2/config/types';
import type {
DistributionBarClick,
DistributionSeries,
DistributionYScale,
} from 'lib/visualization/charts/Distribution/types';
interface BaseChartProps {
width: number;
@@ -147,8 +142,6 @@ export interface HeatmapChartProps {
yAxisUnit?: string;
decimalPrecision?: PrecisionOption;
timezone?: Timezone;
/** What the bucket axis measures, shown in the tooltip header, e.g. `Traces · duration_nano`. */
bucketLabel?: string;
/** Colour bar below the grid. Default true. */
showVisualMap?: boolean;
/** Default true; hidden anyway when there is only one group. The label isolates
@@ -174,48 +167,6 @@ export interface HeatmapChartProps {
'data-testid'?: string;
}
/**
* Whole-range bucket counts, one series per group, drawn as bars whose widths follow
* the bucket bounds. Builds its own config, since `buckets` fully determines the x
* axis. `buckets` and `series` must be referentially stable: a new identity rebuilds
* the plot.
*/
export interface DistributionChartProps {
/** Widget id; the group selection persists under it. */
id: string;
/** Ascending. N boundaries describe N+1 buckets, the last one overflow. */
buckets: number[];
series: DistributionSeries[];
width: number;
height: number;
isDarkMode: boolean;
/** Buckets wholly below it are hidden. */
xMin?: number;
/** Buckets wholly above it are hidden; unset crops trailing empty buckets. */
xMax?: number;
/** Default linear. Ignored under `percent`, whose axis is a share. */
yScale?: DistributionYScale;
/** Default normal. `none` draws the groups side by side. */
stack?: StackMode;
/** Unit of the bucket bounds; counts are always plain numbers. */
xAxisUnit?: string;
decimalPrecision?: PrecisionOption;
/** Hex colours keyed by group label, overriding the automatic palette. */
customColors?: Record<string, string>;
/** 0–100. Marked across the plot, over the visible groups combined. */
percentiles?: readonly number[];
/** Fires for a click on a group's bar; not on Other or empty space. */
onBarClick?: (click: DistributionBarClick) => void;
showLegend?: boolean;
legendPosition?: LegendPosition;
showTooltip?: boolean;
canPinTooltip?: boolean;
renderTooltipFooter?: (args: IRenderTooltipFooterArgs) => React.ReactNode;
tooltipPortalRoot?: HTMLElement | null;
layoutChildren?: React.ReactNode;
'data-testid'?: string;
}
/**
* One resolved pie/donut slice: a display label, its (already parsed) positive
* numeric value, and the colour used for the arc + legend swatch.

View File

@@ -87,9 +87,9 @@ describe('Dashboard settings - default time range', () => {
await user.click(await screen.findByTestId('dashboard-default-time-range'));
await expect(
screen.findByRole('option', { name: 'Default (Last 30 minutes)' }),
).resolves.toBeInTheDocument();
expect(
await screen.findByRole('option', { name: 'Default (Last 30 minutes)' }),
).toBeInTheDocument();
expect(
screen.queryByRole('option', { name: 'Last 30 minutes', exact: true }),
).not.toBeInTheDocument();

View File

@@ -304,7 +304,6 @@ describe('PanelEditorQueryBuilder field visibility (driven by the capabilities g
expect(lastQueryBuilderProps().fieldsConfig).toStrictEqual({
functions: { state: 'hidden' },
having: { state: 'hidden' },
trace_operator: { state: 'hidden' },
});
});
@@ -328,14 +327,10 @@ describe('PanelEditorQueryBuilder signal dropdown (driven by the capabilities gu
});
});
it('offers every signal for the Heatmap kind', () => {
it('offers metrics alone for the Heatmap kind — the only signal with a bucket axis', () => {
renderBuilder('signoz/HeatmapPanel');
expect(lastQueryBuilderProps().allowedDataSources).toStrictEqual([
'metrics',
'logs',
'traces',
]);
expect(lastQueryBuilderProps().allowedDataSources).toStrictEqual(['metrics']);
});
it('offers logs and traces for the List kind, which reads raw rows', () => {

View File

@@ -68,17 +68,6 @@ const CONVERTED = [{ id: 'converted' }] as unknown as NonNullable<
>;
const SWITCHED_SPEC = { switched: true } as unknown;
const tracesBuilder = (expression: string): Query['builder'] => ({
...initialQueriesMap.traces.builder,
queryData: [
{
...initialQueriesMap.traces.builder.queryData[0],
aggregations: [{ expression }],
},
],
queryFormulas: [],
});
function makeSpec(
kind: string,
pluginSpec: unknown,
@@ -301,50 +290,6 @@ describe('usePanelKindChange', () => {
expect(persisted.builder.queryFormulas).toStrictEqual([]);
});
it('keeps the field of a traces function aggregation when switching to a Heatmap panel', () => {
const setSpec = jest.fn();
mockUseQueryBuilder.mockReturnValue(
builderState(fakeQuery('ts-current', 'builder')),
);
mockRebuildBuilder.mockReturnValue(tracesBuilder('p99(duration_nano)'));
const { result } = renderHook(() =>
usePanelKindChange({
spec: makeSpec('signoz/TimeSeriesPanel', {}, TABLE_QUERIES),
panelType: PANEL_TYPES.TIME_SERIES,
setSpec,
}),
);
act(() => result.current.onChangePanelKind('signoz/HeatmapPanel'));
const [persisted] = mockToPerses.mock.calls[0] as [Query];
expect(persisted.builder.queryData[0].aggregations).toMatchObject([
{ expression: 'duration_nano' },
]);
});
it('wraps a traces heatmap field in a function when switching to a TimeSeries panel', () => {
const setSpec = jest.fn();
mockUseQueryBuilder.mockReturnValue(
builderState(fakeQuery('heatmap-current', 'builder')),
);
mockRebuildBuilder.mockReturnValue(tracesBuilder('duration_nano'));
const { result } = renderHook(() =>
usePanelKindChange({
spec: makeSpec('signoz/HeatmapPanel', {}, TABLE_QUERIES),
panelType: PANEL_TYPES.HEATMAP,
setSpec,
}),
);
act(() => result.current.onChangePanelKind('signoz/TimeSeriesPanel'));
const [persisted] = mockToPerses.mock.calls[0] as [Query];
expect(persisted.builder.queryData[0].aggregations).toMatchObject([
{ expression: 'p90(duration_nano)' },
]);
});
it('swaps a percentile spatial aggregation for count when switching to a Heatmap panel', () => {
const setSpec = jest.fn();
mockUseQueryBuilder.mockReturnValue(

View File

@@ -9,10 +9,6 @@ import type {
import type { PANEL_TYPES } from 'constants/queryBuilder';
import { QueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.types';
import { resolveQueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.utils';
import {
fromDistributionAggregation,
toDistributionAggregation,
} from 'lib/query/distributionField';
import { rebuildBuilderForPanelType } from 'lib/query/panelQuery';
import type { PartialPanelTypes } from 'lib/query/panelTypeDataSourceFormValuesMap';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
@@ -186,16 +182,9 @@ export function usePanelKindChange({
: transformed,
newKind,
);
const isHeatmap = newKind === 'signoz/HeatmapPanel';
const converted = {
...ordered,
queryData: ordered.queryData.map(
isHeatmap ? toDistributionAggregation : fromDistributionAggregation,
),
};
return isHeatmap
? withSingleHeatmapQuery(converted)
: withPercentileHistogramAggregation(converted);
return newKind === 'signoz/HeatmapPanel'
? withSingleHeatmapQuery(ordered)
: withPercentileHistogramAggregation(ordered);
};
// Revisit → restore the stash (the reversibility path) on the tab in use, an AI

View File

@@ -1,5 +1,4 @@
import { ATTRIBUTE_TYPES } from 'constants/queryBuilder';
import { DEFAULT_PERCENTILE } from 'lib/query/distributionField';
import type {
IBuilderQuery,
Query,
@@ -22,6 +21,8 @@ const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,
]);
const DEFAULT_HISTOGRAM_SPACE_AGGREGATION = 'p90';
/** What a heatmap cell holds, and the one space aggregation the kind offers. */
const HEATMAP_HISTOGRAM_SPACE_AGGREGATION = 'count';
@@ -105,7 +106,7 @@ export function withPercentileHistogramAggregation(
function withoutCount<T extends string | undefined>(spaceAggregation: T): T {
return (
spaceAggregation === HEATMAP_HISTOGRAM_SPACE_AGGREGATION
? DEFAULT_PERCENTILE
? DEFAULT_HISTOGRAM_SPACE_AGGREGATION
: spaceAggregation
) as T;
}

View File

@@ -77,7 +77,8 @@ const EXPECTED_SIGNALS: Record<PanelKind, TelemetrytypesSignalDTO[]> = {
'signoz/AreaChartPanel': [metrics, logs, traces],
'signoz/NumberPanel': [metrics, logs, traces],
'signoz/HistogramPanel': [metrics, logs, traces],
'signoz/HeatmapPanel': [metrics, logs, traces],
// A heatmap needs a bucket axis, which only a metric carries.
'signoz/HeatmapPanel': [metrics],
'signoz/PieChartPanel': [metrics, logs, traces],
'signoz/GeoMapPanel': [metrics, logs, traces],
'signoz/TopListPanel': [metrics, logs, traces],
@@ -195,7 +196,6 @@ const ALL_KINDS = Object.keys(EXPECTED_QUERY_TYPES) as PanelKind[];
const HIDES_TRACE_OPERATOR: PanelKind[] = [
'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel',
'signoz/HeatmapPanel',
];
describe('panel capabilities guard', () => {

View File

@@ -25,7 +25,6 @@ import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
import {
prepareHeatmapData,
resolveHeatmapStep,
resolveBucketLabel,
resolveRequestedBucketKind,
} from './prepareData';
@@ -87,11 +86,6 @@ function HeatmapPanelRenderer({
[spec.axes?.y?.scale, data.requestPayload],
);
const bucketLabel = useMemo(
() => resolveBucketLabel(data.requestPayload),
[data.requestPayload],
);
const decimalPrecision = useMemo(
() => resolveDecimalPrecision(spec.formatting?.decimalPrecision),
[spec.formatting?.decimalPrecision],
@@ -138,7 +132,6 @@ function HeatmapPanelRenderer({
axisScale={axisScale}
yAxisUnit={spec.formatting?.unit}
decimalPrecision={decimalPrecision}
bucketLabel={bucketLabel}
legendPosition={legendPosition}
timezone={timezone}
isDarkMode={isDarkMode}

View File

@@ -12,7 +12,6 @@ import {
FALLBACK_STEP_SECONDS,
prepareHeatmapData,
resolveHeatmapStep,
resolveBucketLabel,
resolveRequestedBucketKind,
} from '../prepareData';
@@ -157,12 +156,14 @@ describe('resolveHeatmapStep', () => {
});
});
const request = (queries: unknown[]): Querybuildertypesv5QueryRangeRequestDTO =>
({
compositeQuery: { queries },
}) as Querybuildertypesv5QueryRangeRequestDTO;
describe('resolveRequestedBucketKind', () => {
const request = (
queries: unknown[],
): Querybuildertypesv5QueryRangeRequestDTO =>
({
compositeQuery: { queries },
}) as Querybuildertypesv5QueryRangeRequestDTO;
it('reads the kind off the query that carries a bucket axis', () => {
expect(
resolveRequestedBucketKind(
@@ -204,49 +205,3 @@ describe('resolveRequestedBucketKind', () => {
expect(resolveRequestedBucketKind(undefined)).toBeUndefined();
});
});
describe('resolveBucketLabel', () => {
it.each([
[
'a metric',
[
{
spec: {
signal: 'metrics',
aggregations: [{ metricName: 'http_latency' }],
},
},
],
'Metrics · http_latency',
],
[
'a traces field',
[
{
spec: {
signal: 'traces',
aggregations: [{ expression: 'duration_nano' }],
},
},
],
'Traces · duration_nano',
],
[
'the enabled query, past a disabled one',
[
{
spec: {
signal: 'logs',
disabled: true,
aggregations: [{ expression: 'code.lineno' }],
},
},
{ spec: { signal: 'logs', aggregations: [{ expression: 'quantity' }] } },
],
'Logs · quantity',
],
['nothing for ClickHouse', [{ spec: { query: 'SELECT 1' } }], undefined],
])('names %s', (_label, queries, expected) => {
expect(resolveBucketLabel(request(queries))).toBe(expected);
});
});

View File

@@ -22,14 +22,10 @@ export const definition: PanelDefinition<'signoz/HeatmapPanel'> = {
EditorPane: QueryBuilderEditorPane,
sections,
supportedQueryTypesKindMap: {
// Logs and traces bucket the field named as the aggregation.
// Only metrics carry a bucket axis; the request rejects the other signals.
[EQueryType.QUERY_BUILDER]: {
kind: QueryTypeKind.SIGNAL,
signals: [
TelemetrytypesSignalDTO.metrics,
TelemetrytypesSignalDTO.logs,
TelemetrytypesSignalDTO.traces,
],
signals: [TelemetrytypesSignalDTO.metrics],
},
[EQueryType.CLICKHOUSE]: { kind: QueryTypeKind.SIGNAL_LESS },
[EQueryType.PROM]: { kind: QueryTypeKind.SIGNAL_LESS },
@@ -38,8 +34,6 @@ export const definition: PanelDefinition<'signoz/HeatmapPanel'> = {
queryBuilderFields: {
[QueryBuilderField.Functions]: { state: 'hidden' },
[QueryBuilderField.Having]: { state: 'hidden' },
// The request takes one builder query and has no case for a trace operator.
[QueryBuilderField.TraceOperator]: { state: 'hidden' },
},
// Every timestamp is a full column of cells, so the request asks for a step interval
// wide enough to keep the grid legible: at raw resolution a multi-day range is tens of

View File

@@ -5,13 +5,11 @@ import type {
Querybuildertypesv5TimeSeriesDTO,
} from 'api/generated/services/sigNoz.schemas';
import getLabelName from 'lib/getLabelName';
import { upperFirst } from 'lodash-es';
import type {
HeatmapSeries,
HeatmapSeriesLabel,
HeatmapSeriesPoint,
} from 'lib/uPlotV2/plugins/HeatmapPlugin/types';
import type { QuerySpecView } from 'pages/DashboardPage/DashboardContainer/queryV5/buildQueryRangeRequest';
const MS_PER_SECOND = 1000;
@@ -84,25 +82,6 @@ export function resolveRequestedBucketKind(
return undefined;
}
/**
* What the grid buckets, named for the tooltip: `<Signal> · <metric or field>`, off
* the first enabled builder query. `undefined` for ClickHouse and PromQL, which name
* neither.
*/
export function resolveBucketLabel(
request: Querybuildertypesv5QueryRangeRequestDTO | undefined,
): string | undefined {
for (const envelope of request?.compositeQuery?.queries ?? []) {
const spec = envelope.spec as QuerySpecView | undefined;
const [aggregation] = spec?.aggregations ?? [];
const bucketed = aggregation?.metricName || aggregation?.expression;
if (spec?.signal && !spec.disabled && bucketed) {
return `${upperFirst(spec.signal)} · ${bucketed}`;
}
}
return undefined;
}
/**
* Column width in seconds. The server's effective step is authoritative — the
* last column has no successor to infer a width from — so the timestamp delta is

View File

@@ -477,47 +477,6 @@ describe('extractLegendMap', () => {
});
describe('hasRunnableQueries', () => {
const heatmapQuery = (
signal: string,
aggregations: Record<string, unknown>[],
): DashboardtypesQueryDTO[] =>
compositeQuery([
{ type: 'builder_query', spec: { name: 'A', signal, aggregations } },
]).map((query) => ({ ...query, kind: 'heatmap' }) as DashboardtypesQueryDTO);
it.each([
['logs', [], false],
['traces', [{ expression: ' ' }], false],
['traces', [{ expression: 'duration_nano' }], true],
['metrics', [{ metricName: 'http_latency' }], true],
])(
'%s heatmap with aggregations %j is runnable: %s',
(signal, aggregations, runnable) => {
expect(hasRunnableQueries(heatmapQuery(signal, aggregations))).toBe(
runnable,
);
},
);
it('ignores a disabled heatmap query with no field', () => {
const queries = compositeQuery([
{
type: 'builder_query',
spec: {
name: 'A',
signal: 'traces',
aggregations: [{ expression: 'duration_nano' }],
},
},
{
type: 'builder_query',
spec: { name: 'B', signal: 'logs', aggregations: [], disabled: true },
},
]).map((query) => ({ ...query, kind: 'heatmap' }) as DashboardtypesQueryDTO);
expect(hasRunnableQueries(queries)).toBe(true);
});
it('false when the panel has no queries', () => {
expect(hasRunnableQueries([])).toBe(false);
});

View File

@@ -16,7 +16,6 @@ import {
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeClickHouseSQLDTOType,
Querybuildertypesv5QueryEnvelopePromQLDTOType,
Querybuildertypesv5RequestTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelQueryCapabilities } from '../Panels/types/panelCapabilities';
@@ -27,13 +26,12 @@ import {
// Narrow view over the envelope spec variants. Orval erases envelope `spec` to `unknown`, so
// shared fields are read through this view with a localized cast at the envelope boundary.
export interface QuerySpecView {
interface QuerySpecView {
name?: string;
legend?: string;
signal?: string;
stepInterval?: number | string;
disabled?: boolean;
aggregations?: { metricName?: string; expression?: string }[];
aggregations?: { metricName?: string }[];
order?: Querybuildertypesv5OrderByDTO[];
}
@@ -327,9 +325,8 @@ export function extractLegendMap(
}
/**
* Fetch gate. False with no queries, when every metrics builder query lacks a metric name —
* skipping a guaranteed 400 (V1 parity: `validateMetricNameForMetricsDataSource`) — or when a
* logs/traces heatmap names no field to bucket.
* Fetch gate. False with no queries, or when every metrics builder query lacks a metric name —
* skipping a guaranteed 400 (V1 parity: `validateMetricNameForMetricsDataSource`).
*/
export function hasRunnableQueries(queries: DashboardtypesQueryDTO[]): boolean {
const envelopes = toQueryEnvelopes(queries);
@@ -337,23 +334,10 @@ export function hasRunnableQueries(queries: DashboardtypesQueryDTO[]): boolean {
return false;
}
const builderSpecs = envelopes
const metricsSpecs = envelopes
.filter(isBuilderEnvelope)
.map((envelope) => envelope.spec as QuerySpecView);
if (
queries[0].kind === Querybuildertypesv5RequestTypeDTO.heatmap &&
builderSpecs.some(
(spec) =>
!spec.disabled &&
spec.signal !== 'metrics' &&
!spec.aggregations?.[0]?.expression?.trim(),
)
) {
return false;
}
const metricsSpecs = builderSpecs.filter((spec) => spec.signal === 'metrics');
.map((envelope) => envelope.spec as QuerySpecView)
.filter((spec) => spec.signal === 'metrics');
if (metricsSpecs.length === 0) {
return true;

View File

@@ -56,7 +56,6 @@ import {
EDITOR_METRICS,
NEW_PANEL_KINDS,
newPanelKindOf,
numericFieldKeysResponse,
type NewPanelKind,
} from './__story_mockdata__/panelEditor';
@@ -193,11 +192,7 @@ export const panelEditorMocks = defineStoryMocks({
rest.get(
'http://localhost/api/v1/fields/keys',
response.json((req) =>
req.url.searchParams.get('fieldDataType') === 'number'
? numericFieldKeysResponse()
: fieldKeysResponse(EDITOR_FIELD_KEYS),
),
response.json(() => fieldKeysResponse(EDITOR_FIELD_KEYS)),
),
rest.get(

View File

@@ -15,7 +15,6 @@ import {
openClickHouseQuery,
openPanelTypeSwitcher,
openPromQLQuery,
pickHeatmapTracesField,
saveAndExpectToast,
} from './__story_mockdata__/panelEditor.play';
@@ -189,15 +188,6 @@ export const ConfigHeatmap: Story = {
play: expandConfigSections,
};
/**
* A new heatmap switched to traces: the aggregation becomes a picker of the
* signal's numeric fields.
*/
export const HeatmapTracesField: Story = {
args: { panel: 'new', newPanelKind: 'heatmap' },
play: pickHeatmapTracesField,
};
/** A new list panel's config pane, every section expanded. */
export const ConfigList: Story = {
args: { panel: 'new', newPanelKind: 'list' },

View File

@@ -10,7 +10,6 @@ import {
hasClickHouseTab,
hasDisconnectValues,
hasPromQLTab,
openConfigSelect,
type PanelEditorArgs,
pickSegment,
savePanel,
@@ -115,25 +114,6 @@ export const openAIQueryBuilder = async ({
}
};
/** Switches a new heatmap to traces and opens its field picker. */
export const pickHeatmapTracesField = async ({
args,
}: Pick<PlayContext, 'args'>): Promise<void> => {
await openConfigSelect('query-data-source-selector-0');
await userEvent.click(await screen.findByTitle('Traces'));
await userEvent.click(
await screen.findByTestId('distribution-field-select', {}, EDITOR_LOAD),
);
if (args.dataState === 'loaded') {
await screen.findByTestId(
'distribution-field-select-item-attribute.retry.count',
{},
EDITOR_LOAD,
);
}
};
export const openClickHouseQuery = async ({
canvasElement,
args,

View File

@@ -4,15 +4,10 @@
*/
import {
type GetFieldsKeys200,
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
TelemetrytypesFieldContextDTO,
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
import { fieldKeysResponse } from '@/storybook/msw/__story_mockdata__/fields';
import {
metricSeed,
type MetricSeed,
@@ -109,21 +104,3 @@ export const EDITOR_METRICS: MetricSeed[] = [
MetrictypesTemporalityDTO.unspecified,
),
];
/** The numeric keys a logs or traces heatmap's field picker asks for. */
export const numericFieldKeysResponse = (): GetFieldsKeys200 => {
const signal = TelemetrytypesSignalDTO.traces;
const span = fieldKeysResponse(['duration_nano'], {
signal,
fieldContext: TelemetrytypesFieldContextDTO.span,
});
const attribute = fieldKeysResponse(['retry.count', 'http.response.size'], {
signal,
fieldContext: TelemetrytypesFieldContextDTO.attribute,
});
return {
...span,
data: { ...span.data, keys: { ...span.data.keys, ...attribute.data.keys } },
};
};

View File

@@ -31,7 +31,6 @@ import {
HEATMAP_COUNT_RANGES,
HEATMAP_FIXED_COUNTS,
HEATMAP_PALETTES,
HEATMAP_SOURCES,
HEATMAP_Y_SCALES,
LEGEND_POSITIONS,
LINE_STYLES,
@@ -62,7 +61,6 @@ import type {
BucketWidth,
Gaps,
HeatmapCountRange,
HeatmapSource,
PanelArgs,
PanelKind,
PanelResult,
@@ -137,13 +135,6 @@ export const panelsMocks = defineStoryMocks({
options: HEATMAP_COUNT_RANGES,
value: 'auto',
}),
heatmapSource: choiceControl<HeatmapSource>('Heatmap source', {
group: PANEL,
description:
'The signal the heatmap buckets: a metric, a log field (`attribute.queue_depth`), a span field (`duration_nano`), or a traces query whose field was cleared, which the panel does not run.',
options: HEATMAP_SOURCES,
value: 'metrics',
}),
bucketWidth: choiceControl<BucketWidth>('Histogram bucket width', {
group: PANEL,
description:

View File

@@ -112,24 +112,6 @@ export const HeatmapLog: Story = {
play: playPanel,
};
/** A traces heatmap bucketing each span's `duration_nano`. */
export const HeatmapTraces: Story = {
args: { kind: 'Heatmap', heatmapSource: 'traces' },
play: playPanel,
};
/** A logs heatmap bucketing the `attribute.queue_depth` log field. */
export const HeatmapLogs: Story = {
args: { kind: 'Heatmap', heatmapSource: 'logs' },
play: playPanel,
};
/** A traces heatmap with no field to bucket: the panel waits for one instead of querying. */
export const HeatmapNoField: Story = {
args: { kind: 'Heatmap', heatmapSource: 'no field' },
play: playPanel,
};
/** The heatmap's colour bar pinned to a fixed 5–250 count range. */
export const HeatmapCountRange: Story = {
args: { kind: 'Heatmap', heatmapCounts: 'fixed' },

View File

@@ -54,19 +54,6 @@ export const HEATMAP_Y_SCALES = Object.values(HeatmapYScale);
export const HEATMAP_COUNT_RANGES = ['auto', 'fixed'] as const;
export const HEATMAP_SOURCES = [
'metrics',
'logs',
'traces',
'no field',
] as const;
/** The field a logs or traces heatmap buckets. */
export const HEATMAP_FIELDS = {
logs: 'attribute.queue_depth',
traces: 'duration_nano',
} as const;
/** The colour bar's bounds under the `fixed` count range. */
export const HEATMAP_FIXED_COUNTS = { min: 5, max: 250 };

View File

@@ -33,7 +33,6 @@ import {
import {
comparisonThresholds,
labelThresholds,
eventHeatmapQuery,
logQuery,
metricQuery,
tableThresholds,
@@ -133,9 +132,7 @@ export const panelShape = (args: PanelArgs): PanelShape => {
},
},
queries: [
args.heatmapSource === 'metrics'
? metricQuery(RequestType.heatmap, { grouped: true, heatmap: true })
: eventHeatmapQuery(args.heatmapSource),
metricQuery(RequestType.heatmap, { grouped: true, heatmap: true }),
],
};
case 'Pie':

View File

@@ -13,7 +13,6 @@ import {
Querybuildertypesv5OrderDirectionDTO as OrderDirection,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTOSignal as LogSignal,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal as TraceSignal,
Querybuildertypesv5RequestTypeDTO as RequestType,
type DashboardtypesComparisonThresholdDTO,
type DashboardtypesQueryDTO,
@@ -21,19 +20,17 @@ import {
type DashboardtypesThresholdWithLabelDTO,
type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTO as LogBuilderQuery,
type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTO as MetricBuilderQuery,
type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTO as TraceBuilderQuery,
} from 'api/generated/services/sigNoz.schemas';
import {
CHART_THRESHOLD_VALUE,
HEATMAP_FIELDS,
NUMBER_THRESHOLD_VALUE,
QUERY_NAME,
TABLE_THRESHOLD_VALUE,
TABLE_VALUE_COLUMN,
THRESHOLD_COLOR,
} from './constants';
import type { HeatmapSource, TextSample } from './types';
import type { TextSample } from './types';
export const labelThresholds = (
on: boolean,
@@ -152,42 +149,3 @@ export const logQuery = (): DashboardtypesQueryDTO => {
},
};
};
/** `no field` is a traces heatmap whose field was cleared: it saves with no aggregation. */
export const eventHeatmapQuery = (
source: Exclude<HeatmapSource, 'metrics'>,
): DashboardtypesQueryDTO => {
const groupBy = [{ name: 'service.name' }];
const legend = '{{service.name}}';
const bucketOptions = {
kind: LinearBuckets.linear,
spec: { maxValue: 1000, numBuckets: 10 },
};
const spec: LogBuilderQuery | TraceBuilderQuery =
source === 'logs'
? {
name: QUERY_NAME,
signal: LogSignal.logs,
aggregations: [{ expression: HEATMAP_FIELDS.logs }],
groupBy,
legend,
bucketOptions,
}
: {
name: QUERY_NAME,
signal: TraceSignal.traces,
aggregations:
source === 'traces' ? [{ expression: HEATMAP_FIELDS.traces }] : [],
groupBy,
legend,
bucketOptions,
};
return {
kind: RequestType.heatmap,
spec: {
name: QUERY_NAME,
plugin: { kind: BuilderQueryKind['signoz/BuilderQuery'], spec },
},
};
};

View File

@@ -18,7 +18,6 @@ import type {
BUCKET_WIDTHS,
GAPS,
HEATMAP_COUNT_RANGES,
HEATMAP_SOURCES,
PANEL_KINDS,
PANEL_RESULTS,
PIE_SLICES,
@@ -37,8 +36,6 @@ export type PanelUnit = (typeof UNITS)[number];
export type HeatmapCountRange = (typeof HEATMAP_COUNT_RANGES)[number];
export type HeatmapSource = (typeof HEATMAP_SOURCES)[number];
export type BucketWidth = (typeof BUCKET_WIDTHS)[number];
export type TextSample = (typeof TEXT_SAMPLES)[number];
@@ -63,7 +60,6 @@ export interface PanelArgs {
palette: HeatmapPalette;
heatmapScale: HeatmapYScale;
heatmapCounts: HeatmapCountRange;
heatmapSource: HeatmapSource;
bucketWidth: BucketWidth;
textSample: TextSample;
textAlign: TextAlign;

View File

@@ -58,12 +58,6 @@ export const expectPanel = async (
await within(root).findByText(PANEL_NAME[args.kind], {}, PANEL_LOAD);
if (args.kind === 'Heatmap' && args.heatmapSource === 'no field') {
await within(root).findByTestId('panel-no-query', {}, PANEL_LOAD);
await expect(findPlot(root)).toBeUndefined();
return;
}
if (!hasData(args)) {
await expectNoData(root, args);
return;

View File

@@ -8,7 +8,6 @@ import {
MetricAggregation,
TraceAggregation,
} from 'types/api/v5/queryRange';
import type { PANEL_TYPES } from 'constants/queryBuilder';
import { DataSource } from 'types/common/queryBuilder';
import { v4 as uuid } from 'uuid';
@@ -105,19 +104,16 @@ export function getAggregationOptionsForOrderBy(query: {
* Enhanced function that uses createAggregation to parse aggregations first
* then converts them to BaseAutocompleteData format for OrderByFilter
*/
export function getParsedAggregationOptionsForOrderBy(
query: {
aggregations?: TraceAggregation[] | LogAggregation[] | MetricAggregation[];
dataSource: DataSource;
aggregateAttribute?: { key: string };
spaceAggregation?: string;
timeAggregation?: string;
temporality?: string;
},
panelType?: PANEL_TYPES,
): BaseAutocompleteData[] {
export function getParsedAggregationOptionsForOrderBy(query: {
aggregations?: TraceAggregation[] | LogAggregation[] | MetricAggregation[];
dataSource: DataSource;
aggregateAttribute?: { key: string };
spaceAggregation?: string;
timeAggregation?: string;
temporality?: string;
}): BaseAutocompleteData[] {
// First, use createAggregation to parse the aggregations
const parsedAggregations = createAggregation(query, panelType);
const parsedAggregations = createAggregation(query);
// Then convert the parsed aggregations to BaseAutocompleteData format
return convertAggregationsToBaseAutocompleteData(

View File

@@ -188,6 +188,15 @@ export default defineConfig(({ mode }): UserConfig => {
sourcemap: true,
outDir: 'build',
cssMinify: 'esbuild',
// The Go server caches /assets/ as immutable, so every file there must carry a content hash.
assetsDir: 'assets',
rolldownOptions: {
output: {
entryFileNames: 'assets/[name]-[hash].js',
chunkFileNames: 'assets/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash].[ext]',
},
},
},
server: {
open: true,

View File

@@ -669,233 +669,6 @@ func TestValidateHeatmapDashboard(t *testing.T) {
assert.Equal(t, request, rereadRequest)
}
func TestValidateDistributionDashboard(t *testing.T) {
data, err := os.ReadFile("testdata/perses_distribution_panel.json")
require.NoError(t, err, "reading example file")
spec, err := unmarshalDashboard(data)
require.NoError(t, err, "unmarshal and validate failed")
require.IsType(t, &DistributionPanelSpec{}, spec.Panels["p1"].Spec.Plugin.Spec)
panelSpec := spec.Panels["p1"].Spec.Plugin.Spec.(*DistributionPanelSpec)
require.NotNil(t, panelSpec.Axes.X.Min)
assert.Equal(t, 10.0, *panelSpec.Axes.X.Min)
assert.Nil(t, panelSpec.Axes.X.Max)
assert.Equal(t, "log", panelSpec.Axes.Y.Scale.ValueOrDefault())
assert.Equal(t, "none", panelSpec.ChartAppearance.Stack.ValueOrDefault())
require.NotNil(t, panelSpec.ChartAppearance.Percentiles.Enabled)
assert.True(t, *panelSpec.ChartAppearance.Percentiles.Enabled)
assert.Equal(t, []float64{75, 99.9}, panelSpec.ChartAppearance.Percentiles.Values)
dashboard := &DashboardV2{Spec: *spec}
request, err := dashboard.GetPanelQuery(1, 2, "p1")
require.NoError(t, err, "building the panel's query failed")
assert.Equal(t, qb.RequestTypeDistribution, request.RequestType)
require.NoError(t, request.Validate(), "the request built from the panel is not a valid distribution request")
stored, err := json.Marshal(spec)
require.NoError(t, err, "marshal dashboard failed")
reread, err := unmarshalDashboard(stored)
require.NoError(t, err, "the stored dashboard does not validate")
assert.Equal(t, panelSpec, reread.Panels["p1"].Spec.Plugin.Spec)
}
func TestDistributionPanelSpecDefaults(t *testing.T) {
testCases := []struct {
name string
spec string
}{
{name: "EmptySpec", spec: `{}`},
{name: "EmptyChartAppearance", spec: `{"chartAppearance": {}}`},
{name: "EmptyPercentiles", spec: `{"chartAppearance": {"percentiles": {}}}`},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var plugin PanelPlugin
require.NoError(t, json.Unmarshal([]byte(`{"kind": "signoz/DistributionPanel", "spec": `+testCase.spec+`}`), &plugin))
spec := plugin.Spec.(*DistributionPanelSpec)
assert.Nil(t, spec.Axes.X.Min)
assert.Nil(t, spec.Axes.X.Max)
assert.Equal(t, "linear", spec.Axes.Y.Scale.ValueOrDefault())
assert.Equal(t, "normal", spec.ChartAppearance.Stack.ValueOrDefault())
assert.Nil(t, spec.ChartAppearance.Percentiles.Enabled)
assert.Nil(t, spec.ChartAppearance.Percentiles.Values)
stored, err := json.Marshal(spec.ChartAppearance)
require.NoError(t, err)
assert.Equal(t, `{"stack":"normal","percentiles":{"enabled":null,"values":null}}`, string(stored))
})
}
}
func TestDistributionPanelSpecPercentileValues(t *testing.T) {
testCases := []struct {
name string
spec string
expectedPercentilesJSON string
}{
{name: "Disabled_ValuesStayNull", spec: `{"chartAppearance": {"percentiles": {"enabled": false}}}`, expectedPercentilesJSON: `{"enabled":false,"values":null}`},
{name: "EmptyValues_MarksNone", spec: `{"chartAppearance": {"percentiles": {"values": []}}}`, expectedPercentilesJSON: `{"enabled":null,"values":[]}`},
{name: "NullValues_Accepted", spec: `{"chartAppearance": {"percentiles": {"enabled": null, "values": null}}}`, expectedPercentilesJSON: `{"enabled":null,"values":null}`},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var plugin PanelPlugin
require.NoError(t, json.Unmarshal([]byte(`{"kind": "signoz/DistributionPanel", "spec": `+testCase.spec+`}`), &plugin))
spec := plugin.Spec.(*DistributionPanelSpec)
stored, err := json.Marshal(spec.ChartAppearance.Percentiles)
require.NoError(t, err)
assert.Equal(t, testCase.expectedPercentilesJSON, string(stored))
})
}
}
func TestDistributionPanelSpecXMinEqualsMax(t *testing.T) {
var plugin PanelPlugin
require.NoError(t, json.Unmarshal([]byte(`{"kind": "signoz/DistributionPanel", "spec": {"axes": {"x": {"min": 10, "max": 10}}}}`), &plugin))
spec := plugin.Spec.(*DistributionPanelSpec)
require.NotNil(t, spec.Axes.X.Min)
require.NotNil(t, spec.Axes.X.Max)
assert.Equal(t, 10.0, *spec.Axes.X.Min)
assert.Equal(t, 10.0, *spec.Axes.X.Max)
}
func TestDistributionPanelSpecRejections(t *testing.T) {
testCases := []struct {
name string
spec string
expectedMessage string
}{
{
name: "XMin_AboveMax",
spec: `{"axes": {"x": {"min": 20, "max": 10}}}`,
expectedMessage: "axes.x.min 20 is greater than axes.x.max 10",
},
{
name: "YScale_Unknown",
spec: `{"axes": {"y": {"scale": "symlog"}}}`,
expectedMessage: "invalid distribution y scale",
},
{
name: "UnknownField",
spec: `{"axes": {"y": {"softMax": 10}}}`,
expectedMessage: "unknown field \"softMax\"",
},
{
name: "Percentile_Zero",
spec: `{"chartAppearance": {"percentiles": {"values": [0, 50]}}}`,
expectedMessage: "0 is not in (0, 100)",
},
{
name: "Percentile_Hundred",
spec: `{"chartAppearance": {"percentiles": {"values": [100]}}}`,
expectedMessage: "100 is not in (0, 100)",
},
{
name: "Percentile_Duplicate",
spec: `{"chartAppearance": {"percentiles": {"values": [90, 90]}}}`,
expectedMessage: "90 is listed more than once",
},
{
name: "Stack_Empty",
spec: `{"chartAppearance": {"stack": ""}}`,
expectedMessage: "invalid distribution stack mode",
},
{
name: "Percentiles_UnknownField",
spec: `{"chartAppearance": {"percentiles": {"show": true}}}`,
expectedMessage: "unknown field \"show\"",
},
{
name: "XAxis_UnknownField",
spec: `{"axes": {"x": {"softMin": 0}}}`,
expectedMessage: "unknown field \"softMin\"",
},
{
name: "Percentiles_MoreThanFive",
spec: `{"chartAppearance": {"percentiles": {"values": [10, 25, 50, 75, 90, 99]}}}`,
expectedMessage: "at most 5 percentiles",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var plugin PanelPlugin
err := json.Unmarshal([]byte(`{"kind": "signoz/DistributionPanel", "spec": `+testCase.spec+`}`), &plugin)
require.Error(t, err)
assert.Contains(t, err.Error(), testCase.expectedMessage)
})
}
}
func TestDistributionPanelQueryKinds(t *testing.T) {
testCases := []struct {
name string
queryPluginKind string
queryPluginSpec string
expectedAllowed bool
}{
{
name: "PromQL_Allowed",
queryPluginKind: "signoz/PromQLQuery",
queryPluginSpec: `{"name": "A", "query": "sum by (le) (increase(signoz_latency_bucket[5m]))"}`,
expectedAllowed: true,
},
{
name: "ClickHouseSQL_Allowed",
queryPluginKind: "signoz/ClickHouseSQL",
queryPluginSpec: `{"name": "A", "query": "SELECT ts, bucket, value FROM cells"}`,
expectedAllowed: true,
},
{
name: "TraceOperator_Refused",
queryPluginKind: "signoz/TraceOperator",
queryPluginSpec: `{"name": "T1", "expression": "A => B"}`,
expectedAllowed: false,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
data := fmt.Sprintf(`{
"variables": [],
"panels": {
"p1": {
"kind": "Panel",
"spec": {
"links": [],
"plugin": {"kind": "signoz/DistributionPanel", "spec": {}},
"queries": [{
"kind": "distribution",
"spec": {
"plugin": {"kind": %q, "spec": %s}
}
}]
}
}
},
"links": [],
"layouts": []
}`, testCase.queryPluginKind, testCase.queryPluginSpec)
_, err := unmarshalDashboard([]byte(data))
if testCase.expectedAllowed {
require.NoError(t, err)
return
}
require.Error(t, err)
assert.Contains(t, err.Error(), "is not supported by panel kind")
})
}
}
func TestInvalidateOneInvalidPanel(t *testing.T) {
data := []byte(`{
"variables": [],

View File

@@ -28,20 +28,19 @@ type PanelPlugin struct {
// (and strips the duplicate parent properties) after reflection.
func (PanelPlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
return markDiscriminator(s, "kind", map[string]string{
string(PanelKindTimeSeries): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec"),
string(PanelKindBarChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec"),
string(PanelKindAreaChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec"),
string(PanelKindNumber): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpec"),
string(PanelKindPieChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesPieChartPanelSpec"),
string(PanelKindTable): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec"),
string(PanelKindHistogram): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec"),
string(PanelKindList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec"),
string(PanelKindText): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec"),
string(PanelKindHeatmap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec"),
string(PanelKindScatterPlot): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec"),
string(PanelKindGeoMap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec"),
string(PanelKindTopList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec"),
string(PanelKindDistribution): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec"),
string(PanelKindTimeSeries): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec"),
string(PanelKindBarChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec"),
string(PanelKindAreaChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec"),
string(PanelKindNumber): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpec"),
string(PanelKindPieChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesPieChartPanelSpec"),
string(PanelKindTable): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec"),
string(PanelKindHistogram): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec"),
string(PanelKindList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec"),
string(PanelKindText): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec"),
string(PanelKindHeatmap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec"),
string(PanelKindScatterPlot): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec"),
string(PanelKindGeoMap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec"),
string(PanelKindTopList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec"),
})
}
@@ -78,7 +77,6 @@ func (PanelPlugin) JSONSchemaOneOf() []any {
PanelPluginVariant[ScatterPlotPanelSpec]{Kind: string(PanelKindScatterPlot)},
PanelPluginVariant[GeoMapPanelSpec]{Kind: string(PanelKindGeoMap)},
PanelPluginVariant[TopListPanelSpec]{Kind: string(PanelKindTopList)},
PanelPluginVariant[DistributionPanelSpec]{Kind: string(PanelKindDistribution)},
}
}
@@ -242,20 +240,19 @@ func (v VariablePluginVariant[S]) PrepareJSONSchema(s *jsonschema.Schema) error
var (
panelPluginSpecs = map[PanelPluginKind]func() any{
PanelKindTimeSeries: func() any { return new(TimeSeriesPanelSpec) },
PanelKindBarChart: func() any { return new(BarChartPanelSpec) },
PanelKindAreaChart: func() any { return new(AreaChartPanelSpec) },
PanelKindNumber: func() any { return new(NumberPanelSpec) },
PanelKindPieChart: func() any { return new(PieChartPanelSpec) },
PanelKindTable: func() any { return new(TablePanelSpec) },
PanelKindHistogram: func() any { return new(HistogramPanelSpec) },
PanelKindList: func() any { return new(ListPanelSpec) },
PanelKindText: func() any { return new(TextPanelSpec) },
PanelKindHeatmap: func() any { return new(HeatmapPanelSpec) },
PanelKindScatterPlot: func() any { return new(ScatterPlotPanelSpec) },
PanelKindGeoMap: func() any { return new(GeoMapPanelSpec) },
PanelKindTopList: func() any { return new(TopListPanelSpec) },
PanelKindDistribution: func() any { return new(DistributionPanelSpec) },
PanelKindTimeSeries: func() any { return new(TimeSeriesPanelSpec) },
PanelKindBarChart: func() any { return new(BarChartPanelSpec) },
PanelKindAreaChart: func() any { return new(AreaChartPanelSpec) },
PanelKindNumber: func() any { return new(NumberPanelSpec) },
PanelKindPieChart: func() any { return new(PieChartPanelSpec) },
PanelKindTable: func() any { return new(TablePanelSpec) },
PanelKindHistogram: func() any { return new(HistogramPanelSpec) },
PanelKindList: func() any { return new(ListPanelSpec) },
PanelKindText: func() any { return new(TextPanelSpec) },
PanelKindHeatmap: func() any { return new(HeatmapPanelSpec) },
PanelKindScatterPlot: func() any { return new(ScatterPlotPanelSpec) },
PanelKindGeoMap: func() any { return new(GeoMapPanelSpec) },
PanelKindTopList: func() any { return new(TopListPanelSpec) },
}
queryPluginSpecs = map[QueryPluginKind]func() any{
QueryKindBuilder: func() any { return new(BuilderQuerySpec) },
@@ -272,20 +269,19 @@ var (
VariableKindCustom: func() any { return new(CustomVariableSpec) },
}
allowedQueryKinds = map[PanelPluginKind][]QueryPluginKind{
PanelKindTimeSeries: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindBarChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindAreaChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindNumber: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindHistogram: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindPieChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindTable: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindList: {QueryKindBuilder, QueryKindAIBuilder},
PanelKindText: {},
PanelKindHeatmap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindScatterPlot: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindGeoMap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindTopList: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindDistribution: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindTimeSeries: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindBarChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindAreaChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindNumber: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindHistogram: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindPieChart: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindTable: {QueryKindBuilder, QueryKindAIBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
PanelKindList: {QueryKindBuilder, QueryKindAIBuilder},
PanelKindText: {},
PanelKindHeatmap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindScatterPlot: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindGeoMap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindTopList: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
}
)

View File

@@ -70,7 +70,7 @@ func (k *PanelKind) UnmarshalJSON(data []byte) error {
type PanelSpec struct {
Display Display `json:"display" required:"true" description:"The panel title and description."`
Plugin PanelPlugin `json:"plugin" required:"true" description:"The visualization: kind is one of signoz/TimeSeriesPanel, signoz/BarChartPanel, signoz/AreaChartPanel, signoz/NumberPanel, signoz/PieChartPanel, signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel, signoz/HeatmapPanel or signoz/DistributionPanel, and spec holds that kind's options ({} accepts every default)."`
Plugin PanelPlugin `json:"plugin" required:"true" description:"The visualization: kind is one of signoz/TimeSeriesPanel, signoz/BarChartPanel, signoz/AreaChartPanel, signoz/NumberPanel, signoz/PieChartPanel, signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel or signoz/HeatmapPanel, and spec holds that kind's options ({} accepts every default)."`
Queries []Query `json:"queries" required:"true" nullable:"false" description:"The queries the panel runs. Use exactly one entry for a data panel and [] for signoz/TextPanel. To run several named queries or formulas, use one entry whose spec.plugin.kind is signoz/CompositeQuery and put the constituent queries in its plugin spec."`
Links []Link `json:"links,omitzero" description:"Context links offered in the data point drilldown menu of the panel, with dashboard variables resolved in the URL."`
}
@@ -92,13 +92,13 @@ type Link struct {
// ══════════════════════════════════════════════
type Query struct {
Kind qb.RequestType `json:"kind" required:"true" description:"The result shape the panel requests: time_series for time series, bar, area and histogram panels, scalar for number, table and pie panels, raw for list panels, heatmap for heatmap panels, distribution for distribution panels, trace for trace panels."`
Kind qb.RequestType `json:"kind" required:"true" description:"The result shape the panel requests: time_series for time series, bar, area and histogram panels, scalar for number, table and pie panels, raw for list panels, heatmap for heatmap panels, trace for trace panels."`
Spec QuerySpec `json:"spec" required:"true" description:"The query content: an optional name and the query plugin."`
}
type QuerySpec struct {
Name string `json:"name,omitempty" description:"An optional label for the query. The name queries refer to each other by lives in the plugin spec."`
Plugin QueryPlugin `json:"plugin" required:"true" description:"The query: kind is one of signoz/BuilderQuery, signoz/AIBuilderQuery (builder query over AI observability traces), signoz/CompositeQuery (several named queries and formulas), signoz/Formula, signoz/PromQLQuery, signoz/ClickHouseSQL or signoz/TraceOperator, and spec holds that kind's query. Pie and table panels reject signoz/PromQLQuery; heatmap and distribution panels reject signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only signoz/BuilderQuery and signoz/AIBuilderQuery."`
Plugin QueryPlugin `json:"plugin" required:"true" description:"The query: kind is one of signoz/BuilderQuery, signoz/AIBuilderQuery (builder query over AI observability traces), signoz/CompositeQuery (several named queries and formulas), signoz/Formula, signoz/PromQLQuery, signoz/ClickHouseSQL or signoz/TraceOperator, and spec holds that kind's query. Pie and table panels reject signoz/PromQLQuery; heatmap panels reject signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only signoz/BuilderQuery and signoz/AIBuilderQuery."`
}
// ══════════════════════════════════════════════

View File

@@ -190,24 +190,23 @@ func (AIBuilderQuerySpec) PrepareJSONSchema(s *jsonschema.Schema) error {
type PanelPluginKind string
const (
PanelKindTimeSeries PanelPluginKind = "signoz/TimeSeriesPanel"
PanelKindBarChart PanelPluginKind = "signoz/BarChartPanel"
PanelKindAreaChart PanelPluginKind = "signoz/AreaChartPanel"
PanelKindNumber PanelPluginKind = "signoz/NumberPanel"
PanelKindPieChart PanelPluginKind = "signoz/PieChartPanel"
PanelKindTable PanelPluginKind = "signoz/TablePanel"
PanelKindHistogram PanelPluginKind = "signoz/HistogramPanel"
PanelKindList PanelPluginKind = "signoz/ListPanel"
PanelKindText PanelPluginKind = "signoz/TextPanel"
PanelKindHeatmap PanelPluginKind = "signoz/HeatmapPanel"
PanelKindScatterPlot PanelPluginKind = "signoz/ScatterPlotPanel"
PanelKindGeoMap PanelPluginKind = "signoz/GeoMapPanel"
PanelKindTopList PanelPluginKind = "signoz/TopListPanel"
PanelKindDistribution PanelPluginKind = "signoz/DistributionPanel"
PanelKindTimeSeries PanelPluginKind = "signoz/TimeSeriesPanel"
PanelKindBarChart PanelPluginKind = "signoz/BarChartPanel"
PanelKindAreaChart PanelPluginKind = "signoz/AreaChartPanel"
PanelKindNumber PanelPluginKind = "signoz/NumberPanel"
PanelKindPieChart PanelPluginKind = "signoz/PieChartPanel"
PanelKindTable PanelPluginKind = "signoz/TablePanel"
PanelKindHistogram PanelPluginKind = "signoz/HistogramPanel"
PanelKindList PanelPluginKind = "signoz/ListPanel"
PanelKindText PanelPluginKind = "signoz/TextPanel"
PanelKindHeatmap PanelPluginKind = "signoz/HeatmapPanel"
PanelKindScatterPlot PanelPluginKind = "signoz/ScatterPlotPanel"
PanelKindGeoMap PanelPluginKind = "signoz/GeoMapPanel"
PanelKindTopList PanelPluginKind = "signoz/TopListPanel"
)
func (PanelPluginKind) Enum() []any {
return []any{PanelKindTimeSeries, PanelKindBarChart, PanelKindAreaChart, PanelKindNumber, PanelKindPieChart, PanelKindTable, PanelKindHistogram, PanelKindList, PanelKindText, PanelKindHeatmap, PanelKindScatterPlot, PanelKindGeoMap, PanelKindTopList, PanelKindDistribution}
return []any{PanelKindTimeSeries, PanelKindBarChart, PanelKindAreaChart, PanelKindNumber, PanelKindPieChart, PanelKindTable, PanelKindHistogram, PanelKindList, PanelKindText, PanelKindHeatmap, PanelKindScatterPlot, PanelKindGeoMap, PanelKindTopList}
}
func (k PanelPluginKind) rendersWithoutQuery() bool {
@@ -397,89 +396,6 @@ func (c HeatmapColors) validate() error {
return nil
}
type DistributionPanelSpec struct {
Visualization BasicVisualization `json:"visualization" description:"The time range the bucket counts are summed over."`
Formatting PanelFormatting `json:"formatting" description:"Unit and decimal precision of the bucket bounds; counts take no unit."`
Axes DistributionAxes `json:"axes" description:"The X (bucket) axis range and Y (count) axis scale."`
Legend Legend `json:"legend" description:"Legend placement and series colors."`
ChartAppearance DistributionChartAppearance `json:"chartAppearance" description:"Stacking and percentile markers."`
}
type DistributionAxes struct {
X DistributionXAxis `json:"x" description:"The bucket axis."`
Y DistributionYAxis `json:"y" description:"The count axis."`
}
// DistributionXAxis draws every bucket equally wide, whatever its bounds.
type DistributionXAxis struct {
Min *float64 `json:"min" description:"Buckets wholly below this value are hidden. Null shows them all."`
Max *float64 `json:"max" description:"Buckets wholly above this value are hidden. Null shows them all."`
}
func (axis *DistributionXAxis) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
type alias DistributionXAxis
var tmp alias
if err := dec.Decode(&tmp); err != nil {
return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid axes.x")
}
*axis = DistributionXAxis(tmp)
return axis.validate()
}
func (axis DistributionXAxis) validate() error {
if axis.Min != nil && axis.Max != nil && *axis.Min > *axis.Max {
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "axes.x.min %v is greater than axes.x.max %v", *axis.Min, *axis.Max)
}
return nil
}
type DistributionYAxis struct {
Scale DistributionYScale `json:"scale" required:"true" description:"How counts are spaced: linear (default) or log."`
}
type DistributionChartAppearance struct {
Stack DistributionStackMode `json:"stack" required:"true" description:"How groups combine in a bucket: normal (default) stacks them, none draws them side by side, percent stacks them as shares of the bucket."`
Percentiles DistributionPercentiles `json:"percentiles" description:"Percentile markers drawn across the bucket axis."`
}
const maxDistributionPercentiles = 5
type DistributionPercentiles struct {
Enabled *bool `json:"enabled" description:"Whether percentile markers are drawn. Null draws them."`
Values []float64 `json:"values" description:"The percentiles to mark, each in (0, 100), at most 5, no duplicates. Null means [50, 90, 99]; [] marks none."`
}
func (percentiles *DistributionPercentiles) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
type alias DistributionPercentiles
var tmp alias
if err := dec.Decode(&tmp); err != nil {
return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid chartAppearance.percentiles")
}
*percentiles = DistributionPercentiles(tmp)
return percentiles.validate()
}
func (percentiles DistributionPercentiles) validate() error {
if len(percentiles.Values) > maxDistributionPercentiles {
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "chartAppearance.percentiles.values: at most %d percentiles, got %d", maxDistributionPercentiles, len(percentiles.Values))
}
seen := make(map[float64]struct{}, len(percentiles.Values))
for _, value := range percentiles.Values {
if value <= 0 || value >= 100 {
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "chartAppearance.percentiles.values: %v is not in (0, 100)", value)
}
if _, ok := seen[value]; ok {
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "chartAppearance.percentiles.values: %v is listed more than once", value)
}
seen[value] = struct{}{}
}
return nil
}
type TextPanelSpec struct {
Mode TextMode `json:"mode" description:"How text is interpreted. Only markdown is supported."`
Text string `json:"text" description:"The content to render."`
@@ -1767,81 +1683,6 @@ func (s *HeatmapYScale) UnmarshalJSON(data []byte) error {
}
}
type DistributionYScale struct{ valuer.String }
var (
DistributionYScaleLinear = DistributionYScale{valuer.NewString("linear")} // default
DistributionYScaleLog = DistributionYScale{valuer.NewString("log")}
)
func (DistributionYScale) Enum() []any {
return []any{DistributionYScaleLinear, DistributionYScaleLog}
}
func (scale DistributionYScale) ValueOrDefault() string {
if scale.IsZero() {
return DistributionYScaleLinear.StringValue()
}
return scale.StringValue()
}
func (scale DistributionYScale) MarshalJSON() ([]byte, error) {
return json.Marshal(scale.ValueOrDefault())
}
func (scale *DistributionYScale) UnmarshalJSON(data []byte) error {
var v string
if err := json.Unmarshal(data, &v); err != nil {
return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid distribution y scale: must be a string, one of `linear` or `log`")
}
parsed := DistributionYScale{valuer.NewString(v)}
switch parsed {
case DistributionYScaleLinear, DistributionYScaleLog:
*scale = parsed
return nil
default:
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "invalid distribution y scale %q: must be `linear` or `log`", v)
}
}
type DistributionStackMode struct{ valuer.String }
var (
DistributionStackModeNone = DistributionStackMode{valuer.NewString("none")}
DistributionStackModeNormal = DistributionStackMode{valuer.NewString("normal")} // default
DistributionStackModePercent = DistributionStackMode{valuer.NewString("percent")}
)
func (DistributionStackMode) Enum() []any {
return []any{DistributionStackModeNone, DistributionStackModeNormal, DistributionStackModePercent}
}
func (mode DistributionStackMode) ValueOrDefault() string {
if mode.IsZero() {
return DistributionStackModeNormal.StringValue()
}
return mode.StringValue()
}
func (mode DistributionStackMode) MarshalJSON() ([]byte, error) {
return json.Marshal(mode.ValueOrDefault())
}
func (mode *DistributionStackMode) UnmarshalJSON(data []byte) error {
var v string
if err := json.Unmarshal(data, &v); err != nil {
return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid distribution stack mode: must be a string, one of `none`, `normal`, or `percent`")
}
parsed := DistributionStackMode{valuer.NewString(v)}
switch parsed {
case DistributionStackModeNone, DistributionStackModeNormal, DistributionStackModePercent:
*mode = parsed
return nil
default:
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "invalid distribution stack mode %q: must be `none`, `normal`, or `percent`", v)
}
}
type HeatmapColorScale struct{ valuer.String }
var (

View File

@@ -1,95 +0,0 @@
{
"display": {
"name": "latency",
"description": "how request duration is distributed over the range"
},
"variables": [],
"panels": {
"p1": {
"kind": "Panel",
"spec": {
"display": {
"name": "request duration",
"description": ""
},
"plugin": {
"kind": "signoz/DistributionPanel",
"spec": {
"visualization": {
"timePreference": "global_time"
},
"formatting": {
"unit": "s",
"decimalPrecision": "3"
},
"axes": {
"x": {
"min": 10
},
"y": {
"scale": "log"
}
},
"legend": {
"position": "right",
"mode": "list"
},
"chartAppearance": {
"stack": "none",
"percentiles": {
"enabled": true,
"values": [75, 99.9]
}
}
}
},
"links": [],
"queries": [
{
"kind": "distribution",
"spec": {
"plugin": {
"kind": "signoz/BuilderQuery",
"spec": {
"name": "A",
"signal": "metrics",
"aggregations": [
{
"metricName": "http.server.request.duration",
"timeAggregation": "increase",
"spaceAggregation": "sum"
}
],
"groupBy": [
{
"name": "service.name"
}
]
}
}
}
}
]
}
}
},
"links": [],
"layouts": [
{
"kind": "Grid",
"spec": {
"items": [
{
"x": 0,
"y": 0,
"width": 12,
"height": 8,
"content": {
"$ref": "#/spec/panels/p1"
}
}
]
}
}
]
}

View File

@@ -6,7 +6,9 @@ import (
"html/template"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
@@ -16,6 +18,11 @@ import (
"github.com/gorilla/mux"
)
const (
assetsPathPrefix = "/assets/"
immutableCacheControl = "public, max-age=31536000, immutable"
)
type provider struct {
config web.Config
indexContents []byte
@@ -78,10 +85,10 @@ func (provider *provider) AddToRouter(router *mux.Router) error {
func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Join internally call path.Clean to prevent directory traversal
path := filepath.Join(provider.config.Directory, req.URL.Path)
filePath := filepath.Join(provider.config.Directory, req.URL.Path)
// check whether a file exists or is a directory at the given path
fi, err := os.Stat(path)
fi, err := os.Stat(filePath)
if err != nil {
// if the file doesn't exist, serve index.html
if os.IsNotExist(err) {
@@ -101,6 +108,12 @@ func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
return
}
// files under /assets/ are content-hashed, so their URL changes with their content.
// A non-canonical URL can name a file outside /assets/ or get a redirect.
if req.URL.Path == path.Clean(req.URL.Path) && strings.HasPrefix(req.URL.Path, assetsPathPrefix) {
rw.Header().Set("Cache-Control", immutableCacheControl)
}
// otherwise, use http.FileServer to serve the static file
provider.fileHandler.ServeHTTP(rw, req)
}

View File

@@ -6,6 +6,7 @@ import (
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
@@ -251,3 +252,87 @@ func TestServeStaticFilesUnchanged(t *testing.T) {
assert.Equal(t, string(expected), httpGet(t, base+"/assets/style.css"))
}
func TestServeCacheControl(t *testing.T) {
t.Parallel()
directory := t.TempDir()
files := map[string]string{
"index.html": "<html>index</html>",
"assets/x.js": "console.log('x')",
"assets/nested/y.css": "body{}",
"assets-legacy/z.js": "console.log('z')",
"favicon.ico": "icon",
"css/uPlot.min.css": ".uplot{}",
"locales/en/main.json": "{}",
}
for name, content := range files {
require.NoError(t, os.MkdirAll(filepath.Join(directory, filepath.Dir(name)), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(directory, name), []byte(content), 0o644))
}
testCases := []struct {
name string
basePath string
path string
expectedStatus int
expectedBody string
expectedCC string
}{
{name: "ExistingAsset_Immutable", path: "/assets/x.js", expectedBody: files["assets/x.js"], expectedCC: "public, max-age=31536000, immutable"},
{name: "ExistingNestedAsset_Immutable", path: "/assets/nested/y.css", expectedBody: files["assets/nested/y.css"], expectedCC: "public, max-age=31536000, immutable"},
{name: "MissingAsset_ServesIndex_NoCache", path: "/assets/missing-AAAA.js", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "AssetsDirectory_ServesIndex_NoCache", path: "/assets/nested/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "Root_ServesIndex_NoCache", path: "/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "UnknownRoute_ServesIndex_NoCache", path: "/does-not-exist", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "NonAssetFile_NoCache", path: "/favicon.ico", expectedBody: files["favicon.ico"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "NonAssetNestedFile_NoCache", path: "/css/uPlot.min.css", expectedBody: files["css/uPlot.min.css"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "LocaleFile_NoCache", path: "/locales/en/main.json", expectedBody: files["locales/en/main.json"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "AssetsPrefixLookalike_NoCache", path: "/assets-legacy/z.js", expectedBody: files["assets-legacy/z.js"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "BasePath_ExistingAsset_Immutable", basePath: "/signoz", path: "/assets/x.js", expectedBody: files["assets/x.js"], expectedCC: "public, max-age=31536000, immutable"},
{name: "BasePath_MissingAsset_ServesIndex_NoCache", basePath: "/signoz", path: "/assets/missing-AAAA.js", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "BasePath_NonAssetFile_NoCache", basePath: "/signoz", path: "/favicon.ico", expectedBody: files["favicon.ico"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "AssetTrailingSlash_Redirects_NoCache", path: "/assets/x.js/", expectedStatus: http.StatusMovedPermanently, expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "EncodedDotDotOutOfAssets_NoCache", path: "/assets/%2e%2e/locales/en/main.json", expectedBody: files["locales/en/main.json"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "BasePath_Root_ServesIndex_NoCache", basePath: "/signoz", path: "/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
routerWeb, err := New(
context.Background(),
factorytest.NewSettings(),
web.Config{Index: "index.html", Directory: directory},
global.Config{ExternalURL: &url.URL{Path: testCase.basePath}},
)
require.NoError(t, err)
router := mux.NewRouter().UseEncodedPath()
require.NoError(t, routerWeb.AddToRouter(router))
var handler http.Handler = router
if testCase.basePath != "" {
handler = http.StripPrefix(testCase.basePath, router)
}
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
res, err := client.Get(server.URL + testCase.basePath + testCase.path)
require.NoError(t, err)
defer func() { _ = res.Body.Close() }()
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
expectedStatus := testCase.expectedStatus
if expectedStatus == 0 {
expectedStatus = http.StatusOK
}
assert.Equal(t, expectedStatus, res.StatusCode)
assert.Equal(t, testCase.expectedCC, res.Header.Get("Cache-Control"))
assert.Equal(t, testCase.expectedBody, string(body))
})
}
}

View File

@@ -29,7 +29,6 @@ const QUERIES = {
const ALL = ['group_by', 'having', 'order_by', 'limit', 'legend_format'];
const NO_HAVING = ['group_by', 'order_by', 'limit', 'legend_format'];
const METRICS = ['having', 'order_by', 'limit', 'legend_format'];
const HEATMAP = [...NO_HAVING, 'bucket_options'];
/**
* Add-on toggles each panel kind offers per signal. Metrics group by lives in
@@ -45,7 +44,7 @@ const ADD_ONS: Record<
[PanelKind.Table]: ALL,
[PanelKind.PieChart]: ALL,
[PanelKind.Number]: ['legend_format'],
[PanelKind.Heatmap]: HEATMAP,
[PanelKind.Heatmap]: NO_HAVING,
},
traces: {
[PanelKind.TimeSeries]: ALL,
@@ -53,7 +52,7 @@ const ADD_ONS: Record<
[PanelKind.Table]: ALL,
[PanelKind.PieChart]: ALL,
[PanelKind.Number]: ['legend_format'],
[PanelKind.Heatmap]: HEATMAP,
[PanelKind.Heatmap]: NO_HAVING,
},
metrics: {
[PanelKind.TimeSeries]: METRICS,