mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-03 21:51:22 +00:00
Compare commits
19 Commits
chore/dead
...
fix/distri
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b142756e6f | ||
|
|
c9a5e6fd17 | ||
|
|
eb0f2b243d | ||
|
|
d09cb94875 | ||
|
|
eac4fba13d | ||
|
|
8fa52236ed | ||
|
|
2c1b959b86 | ||
|
|
02edef8406 | ||
|
|
08d7bbc32f | ||
|
|
542fd1432d | ||
|
|
f0b805ce21 | ||
|
|
e802abaf74 | ||
|
|
0cd4b05cc3 | ||
|
|
2733421a05 | ||
|
|
be0baa98fa | ||
|
|
3f4a28f86d | ||
|
|
53887f9788 | ||
|
|
0fef6d1a6f | ||
|
|
5eb5a23269 |
@@ -4523,6 +4523,121 @@ 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.
|
||||
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: 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/DashboardtypesDistributionVisualization'
|
||||
description: The time range the bucket counts are summed over, and how groups
|
||||
stack.
|
||||
type: object
|
||||
DashboardtypesDistributionPercentileValues:
|
||||
items:
|
||||
format: double
|
||||
type: number
|
||||
maxItems: 5
|
||||
type: array
|
||||
uniqueItems: true
|
||||
DashboardtypesDistributionPercentiles:
|
||||
properties:
|
||||
enabled:
|
||||
description: Whether percentile markers are drawn. Null draws them.
|
||||
nullable: true
|
||||
type: boolean
|
||||
values:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesDistributionPercentileValues'
|
||||
description: The percentiles to mark, each greater than 0 and less than
|
||||
100, at most 5, no repeats. Null or omitted marks 50, 90 and 99; [] marks
|
||||
none.
|
||||
required:
|
||||
- values
|
||||
type: object
|
||||
DashboardtypesDistributionStackMode:
|
||||
enum:
|
||||
- normal
|
||||
- none
|
||||
- percent
|
||||
type: string
|
||||
DashboardtypesDistributionVisualization:
|
||||
properties:
|
||||
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.'
|
||||
timePreference:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesTimePreference'
|
||||
description: 'The time range the panel queries: global_time (default) follows
|
||||
the dashboard range; last_5_min, last_15_min, last_30_min, last_1_hr,
|
||||
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
|
||||
fixed window.'
|
||||
required:
|
||||
- stack
|
||||
type: object
|
||||
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
|
||||
@@ -5518,6 +5633,7 @@ 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'
|
||||
@@ -5544,6 +5660,7 @@ components:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpec'
|
||||
type: object
|
||||
DashboardtypesPanelPluginKind:
|
||||
enum:
|
||||
@@ -5560,6 +5677,7 @@ components:
|
||||
- signoz/ScatterPlotPanel
|
||||
- signoz/GeoMapPanel
|
||||
- signoz/TopListPanel
|
||||
- signoz/DistributionPanel
|
||||
type: string
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
|
||||
properties:
|
||||
@@ -5591,6 +5709,21 @@ 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:
|
||||
@@ -5774,9 +5907,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
|
||||
or signoz/HeatmapPanel, and spec holds that kind''s options ({} accepts
|
||||
every default).'
|
||||
signoz/TablePanel, signoz/HistogramPanel, signoz/ListPanel, signoz/TextPanel,
|
||||
signoz/HeatmapPanel or signoz/DistributionPanel, 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,
|
||||
@@ -5912,8 +6045,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, trace for trace
|
||||
panels.'
|
||||
panels, raw for list panels, heatmap for heatmap panels, distribution
|
||||
for distribution panels, trace for trace panels.'
|
||||
spec:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesQuerySpec'
|
||||
@@ -6070,9 +6203,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 panels reject signoz/AIBuilderQuery
|
||||
and signoz/TraceOperator; list panels accept only signoz/BuilderQuery
|
||||
and signoz/AIBuilderQuery.'
|
||||
panels reject signoz/PromQLQuery; heatmap and distribution panels reject
|
||||
signoz/AIBuilderQuery and signoz/TraceOperator; list panels accept only
|
||||
signoz/BuilderQuery and signoz/AIBuilderQuery.'
|
||||
required:
|
||||
- plugin
|
||||
type: object
|
||||
|
||||
@@ -7248,6 +7248,123 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @maxItems 5
|
||||
*/
|
||||
export type DashboardtypesDistributionPercentileValuesDTO = number[];
|
||||
|
||||
export interface DashboardtypesDistributionPercentilesDTO {
|
||||
/**
|
||||
* @type boolean,null
|
||||
* @description Whether percentile markers are drawn. Null draws them.
|
||||
*/
|
||||
enabled?: boolean | null;
|
||||
/**
|
||||
* @description The percentiles to mark, each greater than 0 and less than 100, at most 5, no repeats. Null or omitted marks 50, 90 and 99; [] marks none.
|
||||
*/
|
||||
values: DashboardtypesDistributionPercentileValuesDTO;
|
||||
}
|
||||
|
||||
export interface DashboardtypesDistributionChartAppearanceDTO {
|
||||
/**
|
||||
* @description Percentile markers drawn across the bucket axis.
|
||||
*/
|
||||
percentiles?: DashboardtypesDistributionPercentilesDTO;
|
||||
}
|
||||
|
||||
export enum DashboardtypesDistributionStackModeDTO {
|
||||
normal = 'normal',
|
||||
none = 'none',
|
||||
percent = 'percent',
|
||||
}
|
||||
export interface DashboardtypesDistributionVisualizationDTO {
|
||||
/**
|
||||
* @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;
|
||||
/**
|
||||
* @description The time range the panel queries: global_time (default) follows the dashboard range; last_5_min, last_15_min, last_30_min, last_1_hr, last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a fixed window.
|
||||
*/
|
||||
timePreference?: DashboardtypesTimePreferenceDTO;
|
||||
}
|
||||
|
||||
export interface DashboardtypesDistributionPanelSpecDTO {
|
||||
/**
|
||||
* @description The X (bucket) axis range and Y (count) axis scale.
|
||||
*/
|
||||
axes?: DashboardtypesDistributionAxesDTO;
|
||||
/**
|
||||
* @description 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, and how groups stack.
|
||||
*/
|
||||
visualization?: DashboardtypesDistributionVisualizationDTO;
|
||||
}
|
||||
|
||||
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
|
||||
@@ -7261,7 +7378,8 @@ export type DashboardtypesPanelPluginDTO =
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO;
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTO;
|
||||
|
||||
export enum Querybuildertypesv5RequestTypeDTO {
|
||||
scalar = 'scalar',
|
||||
@@ -7750,14 +7868,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 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 and distribution 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, 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, distribution for distribution panels, trace for trace panels.
|
||||
*/
|
||||
kind: Querybuildertypesv5RequestTypeDTO;
|
||||
/**
|
||||
@@ -7777,7 +7895,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 or signoz/HeatmapPanel, 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, signoz/HeatmapPanel or signoz/DistributionPanel, and spec holds that kind's options ({} accepts every default).
|
||||
*/
|
||||
plugin: DashboardtypesPanelPluginDTO;
|
||||
/**
|
||||
@@ -8550,6 +8668,7 @@ 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.
|
||||
|
||||
@@ -286,7 +286,7 @@ export function createAggregation(
|
||||
];
|
||||
}
|
||||
|
||||
// A heatmap buckets the field the user names; count() would be rejected as one.
|
||||
// A heatmap or distribution 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,
|
||||
|
||||
@@ -292,6 +292,11 @@
|
||||
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
|
||||
&.full-row {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.cm-placeholder {
|
||||
font-size: 12px !important;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ToggleGroup } from '@signozhq/ui/toggle-group';
|
||||
import { Tooltip, TooltipProvider } from '@signozhq/ui/tooltip';
|
||||
import InputWithLabel from 'components/InputWithLabel/InputWithLabel';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
|
||||
import { GroupByFilter } from 'container/QueryBuilder/filters/GroupByFilter/GroupByFilter';
|
||||
import { OrderByFilter } from 'container/QueryBuilder/filters/OrderByFilter/OrderByFilter';
|
||||
import { ReduceToFilter } from 'container/QueryBuilder/filters/ReduceToFilter/ReduceToFilter';
|
||||
@@ -102,7 +103,7 @@ function QueryAddOns({
|
||||
}
|
||||
|
||||
if (
|
||||
panelType === PANEL_TYPES.HEATMAP &&
|
||||
isBucketPanelType(panelType) &&
|
||||
!(
|
||||
query.dataSource === DataSource.METRICS &&
|
||||
HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
|
||||
@@ -201,13 +202,16 @@ function QueryAddOns({
|
||||
initializedRef.current = true;
|
||||
|
||||
// Initial seeding from query values on mount. A disabled field never opens.
|
||||
// Bucket options open even when empty: they are what makes a bucket panel.
|
||||
setSelectedViews(
|
||||
offeredAddOns.filter((addOn) => {
|
||||
const resolved = resolvedFields.get(addOn.key);
|
||||
|
||||
return (
|
||||
resolved?.pinned ||
|
||||
(hasValue(get(query, addOn.queryPath)) && !resolved?.disabled)
|
||||
((hasValue(get(query, addOn.queryPath)) ||
|
||||
addOn.key === QueryBuilderField.BucketOptions) &&
|
||||
!resolved?.disabled)
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -497,7 +501,10 @@ function QueryAddOns({
|
||||
{selectedViews.find(
|
||||
(view) => view.key === QueryBuilderField.BucketOptions,
|
||||
) && (
|
||||
<div className="add-on-content" data-testid="bucket-options-content">
|
||||
<div
|
||||
className="add-on-content full-row"
|
||||
data-testid="bucket-options-content"
|
||||
>
|
||||
<BucketOptions
|
||||
bucketOptions={query.bucketOptions}
|
||||
unit={currentQuery.unit}
|
||||
|
||||
@@ -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 or distribution: the bucket axis is what they plot against,
|
||||
// and no other panel type sends one. A histogram metric brings its own buckets.
|
||||
export const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
|
||||
ATTRIBUTE_TYPES.HISTOGRAM,
|
||||
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,
|
||||
|
||||
@@ -12,7 +12,7 @@ import { toDistributionFieldOptions } from './distributionFieldOptions';
|
||||
|
||||
import Styles from './DistributionFieldSelect.module.scss';
|
||||
|
||||
/** A logs or traces heatmap's aggregation: the one numeric field it buckets. */
|
||||
/** A logs or traces heatmap or distribution's aggregation: the one numeric field it buckets. */
|
||||
export default function DistributionFieldSelect({
|
||||
queryData,
|
||||
onChange,
|
||||
@@ -54,6 +54,8 @@ export default function DistributionFieldSelect({
|
||||
value={selectedField || undefined}
|
||||
onChange={(field): void => onChange?.(field ?? '')}
|
||||
allowClear
|
||||
// Log keys are discovered from ingested data, so a field may not be listed yet.
|
||||
allowCreate={(field): string => `Use "${field}"`}
|
||||
placeholder={getDistributionFieldPlaceholder(queryData.dataSource)}
|
||||
searchInputProps={{
|
||||
placeholder: 'Search numeric fields',
|
||||
|
||||
@@ -125,10 +125,11 @@ describe('DistributionFieldSelect', () => {
|
||||
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
|
||||
});
|
||||
|
||||
it('only offers listed fields: typed text is a filter, not a value', async () => {
|
||||
it('accepts a typed field the keys do not list', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
@@ -137,13 +138,12 @@ describe('DistributionFieldSelect', () => {
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'no_such_field',
|
||||
'attribute.bytes',
|
||||
);
|
||||
await screen.findByTestId('distribution-field-select-create');
|
||||
await user.keyboard('{Enter}');
|
||||
|
||||
await screen.findByText('No numeric fields');
|
||||
expect(
|
||||
screen.queryByTestId('distribution-field-select-item-no_such_field'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(onChange).toHaveBeenCalledWith('attribute.bytes');
|
||||
});
|
||||
|
||||
it('searches the server for typed text, past the listed fields', async () => {
|
||||
|
||||
@@ -38,7 +38,7 @@ export function toDistributionFieldText(key: TelemetryFieldKey): string {
|
||||
|
||||
/**
|
||||
* 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
|
||||
* aggregates, which a heatmap or distribution 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(
|
||||
|
||||
@@ -499,6 +499,23 @@ describe('QueryAddOns', () => {
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is offered on a metrics distribution too', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery({ dataSource: DataSource.METRICS })}
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.DISTRIBUTION}
|
||||
index={0}
|
||||
isForTraceOperator={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByTestId('query-add-on-bucket_options'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is not offered on other panel types', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
@@ -554,12 +571,10 @@ describe('QueryAddOns', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the server default, log at scale 4, without sending it', async () => {
|
||||
const user = userEvent.setup();
|
||||
it('opens empty on the server default, log at scale 4, without sending it', () => {
|
||||
renderHeatmap();
|
||||
|
||||
await user.click(screen.getByTestId('query-add-on-bucket_options'));
|
||||
|
||||
expect(screen.getByTestId('bucket-options-content')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Log' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true',
|
||||
|
||||
@@ -74,6 +74,8 @@ describe('QueryAggregationOptions on a heatmap', () => {
|
||||
it.each([
|
||||
[PANEL_TYPES.HEATMAP, DataSource.TRACES, true],
|
||||
[PANEL_TYPES.HEATMAP, DataSource.METRICS, false],
|
||||
[PANEL_TYPES.DISTRIBUTION, DataSource.LOGS, true],
|
||||
[PANEL_TYPES.DISTRIBUTION, DataSource.METRICS, false],
|
||||
[PANEL_TYPES.TIME_SERIES, DataSource.TRACES, false],
|
||||
])(
|
||||
'%s over %s renders the field picker: %s',
|
||||
|
||||
@@ -34,6 +34,7 @@ export const getComponentForPanelType = (
|
||||
[PANEL_TYPES.HISTOGRAM]: Uplot,
|
||||
// V2-only kind; it renders through the V2 panel registry.
|
||||
[PANEL_TYPES.HEATMAP]: null,
|
||||
[PANEL_TYPES.DISTRIBUTION]: null,
|
||||
[PANEL_TYPES.GEO_MAP]: null,
|
||||
[PANEL_TYPES.TOP_LIST]: null,
|
||||
// Dashboards v2 renders this kind; nothing reaches the V1 chart map for it.
|
||||
|
||||
@@ -313,6 +313,7 @@ export enum PANEL_TYPES {
|
||||
PIE = 'pie',
|
||||
HISTOGRAM = 'histogram',
|
||||
HEATMAP = 'heatmap',
|
||||
DISTRIBUTION = 'distribution',
|
||||
GEO_MAP = 'geo_map',
|
||||
TOP_LIST = 'top_list',
|
||||
TEXT = 'text',
|
||||
|
||||
@@ -528,11 +528,12 @@ export const metricsHistogramSpaceAggregateOperatorOptions: SelectOption<
|
||||
];
|
||||
|
||||
/**
|
||||
* A heatmap's Y axis is the `le` labels themselves, so every percentile draws the grid a
|
||||
* count already draws. Sum is also what the statement builder forces on a histogram
|
||||
* heatmap whatever is asked for, so it is the only honest option to offer.
|
||||
* A bucket panel's (heatmap, distribution) axis is the `le` labels themselves, so every
|
||||
* percentile draws what a count already draws. Sum is also what the statement builder
|
||||
* forces on a histogram bucket panel whatever is asked for, so it is the only honest
|
||||
* option to offer.
|
||||
*/
|
||||
export const metricsHeatmapHistogramSpaceAggregateOperatorOptions: SelectOption<
|
||||
export const metricsBucketHistogramSpaceAggregateOperatorOptions: SelectOption<
|
||||
string,
|
||||
string
|
||||
>[] = [
|
||||
|
||||
@@ -6,7 +6,7 @@ import InputWithLabel from 'components/InputWithLabel/InputWithLabel';
|
||||
import BucketOptions from 'components/QueryBuilderV2/QueryV2/QueryAddOns/BucketOptions/BucketOptions';
|
||||
import { parseLimit, sanitizeLimit } from 'components/QueryBuilderV2/utils';
|
||||
import { LEGEND } from 'constants/global';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
|
||||
// ** Hooks
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
|
||||
@@ -185,9 +185,9 @@ export function Formula({
|
||||
</div>
|
||||
</Col>
|
||||
)}
|
||||
{/* A heatmap draws its one enabled query, which is the formula when its
|
||||
inputs are disabled — so the formula states its own bucket axis. */}
|
||||
{isQBV2 && panelType === PANEL_TYPES.HEATMAP && (
|
||||
{/* A heatmap or distribution draws its one enabled query, which is the formula
|
||||
when its inputs are disabled — so the formula states its own bucket axis. */}
|
||||
{isQBV2 && isBucketPanelType(panelType) && (
|
||||
<Col span={24} className="formula-item">
|
||||
<BucketOptions
|
||||
bucketOptions={formula.bucketOptions}
|
||||
|
||||
@@ -10,7 +10,7 @@ export type OrderByFilterProps = {
|
||||
isRawQuery?: boolean;
|
||||
isNewQueryV2?: boolean;
|
||||
placeholder?: string;
|
||||
/** A logs or traces heatmap aggregates a field, which Order by then offers. */
|
||||
/** A logs or traces heatmap or distribution aggregates a field, which Order by then offers. */
|
||||
panelType?: PANEL_TYPES;
|
||||
};
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ export const PANEL_TYPES_VS_FULL_VIEW_TABLE: PanelTypeAndGraphManagerVisibilityP
|
||||
PIE: false,
|
||||
HISTOGRAM: false,
|
||||
HEATMAP: false,
|
||||
DISTRIBUTION: false,
|
||||
GEO_MAP: false,
|
||||
TOP_LIST: false,
|
||||
TEXT: false,
|
||||
|
||||
@@ -24,6 +24,7 @@ export const PanelTypeVsPanelWrapper = {
|
||||
[PANEL_TYPES.HISTOGRAM]: HistogramPanel,
|
||||
// V2-only kind; it renders through the V2 panel registry.
|
||||
[PANEL_TYPES.HEATMAP]: null,
|
||||
[PANEL_TYPES.DISTRIBUTION]: null,
|
||||
[PANEL_TYPES.GEO_MAP]: null,
|
||||
[PANEL_TYPES.TOP_LIST]: null,
|
||||
};
|
||||
|
||||
@@ -527,5 +527,44 @@ describe('useQueryBuilderOperations - Empty Aggregate Attribute Type', () => {
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps only the switched query on a distribution panel moving to traces', () => {
|
||||
setupMockQueryBuilder('distribution');
|
||||
|
||||
const result = renderHookWithProps({
|
||||
query: { ...defaultMockQuery, queryName: 'B', disabled: true },
|
||||
index: 1,
|
||||
});
|
||||
act(() => {
|
||||
result.current.handleChangeDataSource(DataSource.TRACES);
|
||||
});
|
||||
|
||||
expect(mockHandleSetQueryData).not.toHaveBeenCalled();
|
||||
const [next] = mockRedirectWithQueryBuilderData.mock.calls[0];
|
||||
expect(next.builder.queryFormulas).toStrictEqual([]);
|
||||
expect(next.builder.queryData).toHaveLength(1);
|
||||
expect(next.builder.queryData[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
queryName: 'B',
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps every query on a distribution panel moving to metrics', () => {
|
||||
setupMockQueryBuilder('distribution');
|
||||
|
||||
const result = renderHookWithProps({ index: 1 });
|
||||
act(() => {
|
||||
result.current.handleChangeDataSource(DataSource.METRICS);
|
||||
});
|
||||
|
||||
expect(mockRedirectWithQueryBuilderData).not.toHaveBeenCalled();
|
||||
expect(mockHandleSetQueryData).toHaveBeenLastCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ dataSource: DataSource.METRICS }),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from 'constants/queryBuilder';
|
||||
import {
|
||||
metricsGaugeSpaceAggregateOperatorOptions,
|
||||
metricsHeatmapHistogramSpaceAggregateOperatorOptions,
|
||||
metricsBucketHistogramSpaceAggregateOperatorOptions,
|
||||
metricsHistogramSpaceAggregateOperatorOptions,
|
||||
metricsSumSpaceAggregateOperatorOptions,
|
||||
metricsUnknownSpaceAggregateOperatorOptions,
|
||||
@@ -30,6 +30,7 @@ import { getOperatorsBySourceAndPanelType } from 'lib/newQueryBuilder/getOperato
|
||||
import { findDataTypeOfOperator } from 'lib/query/findDataTypeOfOperator';
|
||||
import {
|
||||
aggregatesDistributionField,
|
||||
isLogsOrTraces,
|
||||
setDistributionField,
|
||||
toDistributionAggregation,
|
||||
} from 'lib/query/distributionField';
|
||||
@@ -59,6 +60,7 @@ import {
|
||||
} from 'types/common/queryBuilder';
|
||||
import { SelectOption } from 'types/common/select';
|
||||
import { getFormatedLegend } from 'utils/getFormatedLegend';
|
||||
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
|
||||
|
||||
export const useQueryOperations: UseQueryOperations = ({
|
||||
query,
|
||||
@@ -181,10 +183,9 @@ export const useQueryOperations: UseQueryOperations = ({
|
||||
(aggregateAttribute?.type as ATTRIBUTE_TYPES) || ATTRIBUTE_TYPES.GAUGE,
|
||||
});
|
||||
|
||||
const histogramSpaceAggregationOptions =
|
||||
panelType === PANEL_TYPES.HEATMAP
|
||||
? metricsHeatmapHistogramSpaceAggregateOperatorOptions
|
||||
: metricsHistogramSpaceAggregateOperatorOptions;
|
||||
const histogramSpaceAggregationOptions = isBucketPanelType(panelType)
|
||||
? metricsBucketHistogramSpaceAggregateOperatorOptions
|
||||
: metricsHistogramSpaceAggregateOperatorOptions;
|
||||
|
||||
switch (aggregateAttribute?.type) {
|
||||
case ATTRIBUTE_TYPES.SUM:
|
||||
@@ -267,13 +268,12 @@ export const useQueryOperations: UseQueryOperations = ({
|
||||
timeAggregation: '',
|
||||
metricName: newQuery.aggregateAttribute?.key || '',
|
||||
temporality: '',
|
||||
// A heatmap cell holds a count of observations per `le` band, which is
|
||||
// the one option the kind offers — a percentile default would sit in the
|
||||
// Heatmap and distribution count observations per `le` band, the one
|
||||
// option those kinds offer — a percentile default would sit in the
|
||||
// selector with nothing behind it.
|
||||
spaceAggregation:
|
||||
panelType === PANEL_TYPES.HEATMAP
|
||||
? MetricAggregateOperator.COUNT
|
||||
: MetricAggregateOperator.P90,
|
||||
spaceAggregation: isBucketPanelType(panelType)
|
||||
? MetricAggregateOperator.COUNT
|
||||
: MetricAggregateOperator.P90,
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
},
|
||||
];
|
||||
@@ -437,17 +437,39 @@ export const useQueryOperations: UseQueryOperations = ({
|
||||
newQueryData = newQueryData ? newQueryData : newQuery;
|
||||
|
||||
setOperators(newOperators);
|
||||
handleSetQueryData(
|
||||
index,
|
||||
aggregatesDistributionField(panelType, newQueryData.dataSource)
|
||||
? toDistributionAggregation(newQueryData)
|
||||
: newQueryData,
|
||||
);
|
||||
const nextQuery = aggregatesDistributionField(
|
||||
panelType,
|
||||
newQueryData.dataSource,
|
||||
)
|
||||
? toDistributionAggregation(newQueryData)
|
||||
: newQueryData;
|
||||
|
||||
// A logs/traces distribution shows one query and no formula (its definition
|
||||
// hides the rest); the request would still carry them, so only the switched
|
||||
// query stays.
|
||||
const { queryData, queryFormulas } = currentQuery.builder;
|
||||
if (
|
||||
panelType === PANEL_TYPES.DISTRIBUTION &&
|
||||
isLogsOrTraces(nextSource) &&
|
||||
(queryData.length > 1 || queryFormulas.length > 0)
|
||||
) {
|
||||
redirectWithQueryBuilderData({
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: [{ ...nextQuery, disabled: false }],
|
||||
queryFormulas: [],
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
handleSetQueryData(index, nextQuery);
|
||||
},
|
||||
[
|
||||
isRawQuery,
|
||||
panelType,
|
||||
query,
|
||||
currentQuery,
|
||||
handleSetQueryData,
|
||||
index,
|
||||
redirectWithQueryBuilderData,
|
||||
|
||||
13
frontend/src/lib/query/__tests__/bucketPanelTypes.test.ts
Normal file
13
frontend/src/lib/query/__tests__/bucketPanelTypes.test.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
import { isBucketPanelType } from '../bucketPanelTypes';
|
||||
|
||||
describe('isBucketPanelType', () => {
|
||||
it('is true for heatmap and distribution only', () => {
|
||||
expect(isBucketPanelType(PANEL_TYPES.HEATMAP)).toBe(true);
|
||||
expect(isBucketPanelType(PANEL_TYPES.DISTRIBUTION)).toBe(true);
|
||||
expect(isBucketPanelType(PANEL_TYPES.HISTOGRAM)).toBe(false);
|
||||
expect(isBucketPanelType(PANEL_TYPES.TIME_SERIES)).toBe(false);
|
||||
expect(isBucketPanelType(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
aggregatesDistributionField,
|
||||
getDistributionFieldPlaceholder,
|
||||
setDistributionField,
|
||||
toDistributionAggregation,
|
||||
@@ -17,6 +18,17 @@ const queryOf = (
|
||||
aggregations: expressions.map((expression) => ({ expression })),
|
||||
});
|
||||
|
||||
describe('aggregatesDistributionField', () => {
|
||||
it.each([
|
||||
[PANEL_TYPES.HEATMAP, DataSource.TRACES, true],
|
||||
[PANEL_TYPES.DISTRIBUTION, DataSource.LOGS, true],
|
||||
[PANEL_TYPES.DISTRIBUTION, DataSource.METRICS, false],
|
||||
[PANEL_TYPES.HISTOGRAM, DataSource.TRACES, false],
|
||||
])('%s over %s → %s', (panelType, dataSource, expected) => {
|
||||
expect(aggregatesDistributionField(panelType, dataSource)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDistributionFieldPlaceholder', () => {
|
||||
it.each([
|
||||
[DataSource.TRACES, 'Numeric field to bucket, e.g. duration_nano'],
|
||||
|
||||
@@ -49,8 +49,23 @@ describe('handleQueryChange bucket options', () => {
|
||||
);
|
||||
});
|
||||
|
||||
// The request rejects an axis on any type but heatmap, so a switch has to shed it
|
||||
// from the query (via the field allowlist) and from the formula (by hand).
|
||||
it('keeps both axes when a heatmap switches to a distribution', () => {
|
||||
const result = handleQueryChange(
|
||||
PANEL_TYPES.DISTRIBUTION,
|
||||
queryWithFormulaAxis(),
|
||||
PANEL_TYPES.HEATMAP,
|
||||
);
|
||||
|
||||
expect(result.builder.queryData[0].bucketOptions).toStrictEqual(
|
||||
bucketOptions,
|
||||
);
|
||||
expect(result.builder.queryFormulas[0].bucketOptions).toStrictEqual(
|
||||
bucketOptions,
|
||||
);
|
||||
});
|
||||
|
||||
// The request rejects an axis on any type but heatmap and distribution, so a switch
|
||||
// has to shed it from the query (via the field allowlist) and from the formula (by hand).
|
||||
it('drops both axes when switching to another panel type', () => {
|
||||
const result = handleQueryChange(
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
@@ -124,16 +139,19 @@ 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,
|
||||
);
|
||||
// A heatmap or distribution request takes one builder query and rejects a trace operator.
|
||||
it.each([PANEL_TYPES.HEATMAP, PANEL_TYPES.DISTRIBUTION] as const)(
|
||||
'drops the trace operator when switching to a %s',
|
||||
(panelType) => {
|
||||
const result = handleQueryChange(
|
||||
panelType,
|
||||
queryWithTraceOperator(),
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
);
|
||||
|
||||
expect(result.builder.queryTraceOperator).toStrictEqual([]);
|
||||
});
|
||||
expect(result.builder.queryTraceOperator).toStrictEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps the trace operator when switching to a table', () => {
|
||||
const result = handleQueryChange(
|
||||
|
||||
@@ -5,7 +5,7 @@ export const unquoteAlias = (alias: string): string =>
|
||||
alias.replace(/^['"]|['"]$/g, '');
|
||||
|
||||
/**
|
||||
* A logs or traces heatmap's aggregation: one field with an optional alias.
|
||||
* A logs or traces heatmap or distribution'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(
|
||||
@@ -26,7 +26,7 @@ export function parseAggregations(
|
||||
'g',
|
||||
);
|
||||
// With no call at all, the whole expression may be the field a logs/traces
|
||||
// heatmap buckets, e.g. "duration_nano"
|
||||
// heatmap or distribution buckets, e.g. "duration_nano"
|
||||
let match =
|
||||
regex.exec(expression) ??
|
||||
(allowDistributionField ? DISTRIBUTION_FIELD.exec(expression) : null);
|
||||
|
||||
14
frontend/src/lib/query/bucketPanelTypes.ts
Normal file
14
frontend/src/lib/query/bucketPanelTypes.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
/**
|
||||
* Panel types whose request counts observations into buckets (`heatmap`,
|
||||
* `distribution`): they share the bucket axis, its query-builder options and the
|
||||
* count aggregation a histogram metric gets.
|
||||
*/
|
||||
export function isBucketPanelType(
|
||||
panelType: string | null | undefined,
|
||||
): boolean {
|
||||
return (
|
||||
panelType === PANEL_TYPES.HEATMAP || panelType === PANEL_TYPES.DISTRIBUTION
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
OrderByPayload,
|
||||
@@ -6,6 +5,8 @@ import type {
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import type { LogAggregation, TraceAggregation } from 'types/api/v5/queryRange';
|
||||
|
||||
import { isBucketPanelType } from './bucketPanelTypes';
|
||||
|
||||
import {
|
||||
ALIAS,
|
||||
DISTRIBUTION_FIELD,
|
||||
@@ -20,7 +21,7 @@ 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. */
|
||||
/** The percentile a field or histogram metric gets when it leaves a heatmap or distribution. */
|
||||
export const DEFAULT_PERCENTILE = 'p90';
|
||||
|
||||
type FieldAggregation = TraceAggregation | LogAggregation;
|
||||
@@ -30,7 +31,7 @@ const fieldAggregations = (query: IBuilderQuery): FieldAggregation[] =>
|
||||
(aggregation): aggregation is FieldAggregation => 'expression' in aggregation,
|
||||
);
|
||||
|
||||
function isLogsOrTraces(
|
||||
export function isLogsOrTraces(
|
||||
dataSource: DataSource,
|
||||
): dataSource is DataSource.LOGS | DataSource.TRACES {
|
||||
return dataSource === DataSource.LOGS || dataSource === DataSource.TRACES;
|
||||
@@ -41,7 +42,7 @@ export function aggregatesDistributionField(
|
||||
panelType: string | null | undefined,
|
||||
dataSource: DataSource,
|
||||
): boolean {
|
||||
return panelType === PANEL_TYPES.HEATMAP && isLogsOrTraces(dataSource);
|
||||
return isBucketPanelType(panelType) && isLogsOrTraces(dataSource);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,7 +79,7 @@ export function getDistributionFieldPlaceholder(
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs and traces heatmaps bucket a field; any function aggregation is
|
||||
* Logs and traces heatmaps and distributions 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.
|
||||
*/
|
||||
@@ -109,7 +110,7 @@ export function toDistributionAggregation(query: IBuilderQuery): IBuilderQuery {
|
||||
);
|
||||
}
|
||||
|
||||
/** Picks `field` as the heatmap's aggregation; a sort on the old field follows it. */
|
||||
/** Picks `field` as the aggregation; a sort on the old field follows it. */
|
||||
export function setDistributionField(
|
||||
query: IBuilderQuery,
|
||||
field: string,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import { cloneDeep, isEqual, set, unset } from 'lodash-es';
|
||||
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
|
||||
import {
|
||||
IBuilderFormula,
|
||||
IBuilderQuery,
|
||||
@@ -99,13 +100,13 @@ export const getIsQueryModified = (
|
||||
/**
|
||||
* Formulas are carried across a panel-type switch whole, not rebuilt from
|
||||
* `panelTypeDataSourceFormValuesMap` the way `queryData` is, so a bucket axis has to be
|
||||
* dropped by hand. The request rejects one on any type but heatmap.
|
||||
* dropped by hand. The request rejects one on any type that does not count buckets.
|
||||
*/
|
||||
const withHeatmapBucketOptions = (
|
||||
const withBucketOptions = (
|
||||
formulas: IBuilderFormula[],
|
||||
newPanelType: keyof PartialPanelTypes,
|
||||
): IBuilderFormula[] => {
|
||||
if (newPanelType === PANEL_TYPES.HEATMAP) {
|
||||
if (isBucketPanelType(newPanelType)) {
|
||||
return formulas;
|
||||
}
|
||||
|
||||
@@ -170,11 +171,11 @@ export function rebuildBuilderForPanelType(
|
||||
|
||||
return tempQuery;
|
||||
}),
|
||||
queryFormulas: withHeatmapBucketOptions(builder.queryFormulas, newPanelType),
|
||||
queryFormulas: withBucketOptions(builder.queryFormulas, newPanelType),
|
||||
queryTraceOperator:
|
||||
newPanelType === PANEL_TYPES.LIST ||
|
||||
newPanelType === PANEL_TYPES.SCATTER ||
|
||||
newPanelType === PANEL_TYPES.HEATMAP
|
||||
isBucketPanelType(newPanelType)
|
||||
? []
|
||||
: builder.queryTraceOperator,
|
||||
};
|
||||
|
||||
@@ -17,6 +17,7 @@ export type PartialPanelTypes = {
|
||||
[PANEL_TYPES.SCATTER]: 'scatter';
|
||||
[PANEL_TYPES.HISTOGRAM]: 'histogram';
|
||||
[PANEL_TYPES.HEATMAP]: 'heatmap';
|
||||
[PANEL_TYPES.DISTRIBUTION]: 'distribution';
|
||||
[PANEL_TYPES.GEO_MAP]: 'geo_map';
|
||||
[PANEL_TYPES.TOP_LIST]: 'top_list';
|
||||
};
|
||||
@@ -149,6 +150,7 @@ export const panelTypeDataSourceFormValuesMap: Record<
|
||||
[PANEL_TYPES.BAR]: bySource(SERIES, SERIES_METRICS),
|
||||
[PANEL_TYPES.HISTOGRAM]: bySource(SERIES, SERIES_METRICS),
|
||||
[PANEL_TYPES.HEATMAP]: bySource(HEATMAP, HEATMAP),
|
||||
[PANEL_TYPES.DISTRIBUTION]: bySource(HEATMAP, HEATMAP),
|
||||
[PANEL_TYPES.TABLE]: bySource(SERIES, SCALAR_METRICS),
|
||||
[PANEL_TYPES.PIE]: bySource(SERIES, SCALAR_METRICS),
|
||||
[PANEL_TYPES.SCATTER]: bySource(SERIES, SCALAR_METRICS),
|
||||
|
||||
@@ -11,8 +11,9 @@ const MARKER_IDLE_ALPHA = 0.55;
|
||||
/** Cap height as a share of the font size. */
|
||||
const CAP_HEIGHT_RATIO = 0.7;
|
||||
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_PADDING_X_PX = 5;
|
||||
const MARKER_BADGE_PADDING_Y_PX = 4;
|
||||
const MARKER_BADGE_RADIUS_PX = 3;
|
||||
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. */
|
||||
@@ -81,21 +82,24 @@ export function layoutMarkerLabels(
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** A square diamond centred on `(x, y)` with half-diagonal `radius`, filled then outlined. */
|
||||
function drawDiamond(
|
||||
/** A rounded rectangle centred on `(x, y)`, filled then outlined. */
|
||||
function drawBadge(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
x: number,
|
||||
y: number,
|
||||
radius: number,
|
||||
halfWidth: number,
|
||||
halfHeight: number,
|
||||
fill: string,
|
||||
stroke: string,
|
||||
): void {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, y - radius);
|
||||
ctx.lineTo(x + radius, y);
|
||||
ctx.lineTo(x, y + radius);
|
||||
ctx.lineTo(x - radius, y);
|
||||
ctx.closePath();
|
||||
ctx.roundRect(
|
||||
x - halfWidth,
|
||||
y - halfHeight,
|
||||
2 * halfWidth,
|
||||
2 * halfHeight,
|
||||
MARKER_BADGE_RADIUS_PX * uPlot.pxRatio,
|
||||
);
|
||||
ctx.fillStyle = fill;
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = stroke;
|
||||
@@ -103,7 +107,7 @@ function drawDiamond(
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashed lines across the plot with a diamond badge at each end naming the
|
||||
* Dashed lines across the plot with a 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.
|
||||
*/
|
||||
@@ -128,33 +132,34 @@ export function drawPercentileMarkers(
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
|
||||
const badgeLabels = markers.map((group) => {
|
||||
// Cap height stands in for the text's height.
|
||||
const halfHeight =
|
||||
(MARKER_FONT_SIZE_PX * pxRatio * CAP_HEIGHT_RATIO) / 2 +
|
||||
MARKER_BADGE_PADDING_Y_PX * pxRatio;
|
||||
const badges = markers.map((group) => {
|
||||
const text = formatPercentileBadge(group);
|
||||
return { text, width: ctx.measureText(text).width };
|
||||
return {
|
||||
text,
|
||||
x: uPlotInstance.valToPos(group[0].axisValue, 'x', true),
|
||||
halfWidth:
|
||||
ctx.measureText(text).width / 2 + MARKER_BADGE_PADDING_X_PX * pxRatio,
|
||||
};
|
||||
});
|
||||
// One square diamond for all, fitting the widest name's box: |dx| + |dy| ≤ radius at
|
||||
// its corners. Cap height stands in for the text's height.
|
||||
const radius =
|
||||
(Math.max(...badgeLabels.map(({ width }) => width)) +
|
||||
MARKER_FONT_SIZE_PX * pxRatio * CAP_HEIGHT_RATIO) /
|
||||
2 +
|
||||
MARKER_BADGE_PADDING_PX * pxRatio;
|
||||
const badges = markers.map((group, index) => ({
|
||||
text: badgeLabels[index].text,
|
||||
x: uPlotInstance.valToPos(group[0].axisValue, 'x', true),
|
||||
}));
|
||||
const rows = layoutMarkerLabels(
|
||||
badges.map(({ x }) => ({ x: x - radius, width: 2 * radius })),
|
||||
badges.map(({ x, halfWidth }) => ({
|
||||
x: x - halfWidth,
|
||||
width: 2 * halfWidth,
|
||||
})),
|
||||
MARKER_BADGE_GAP_PX * pxRatio,
|
||||
);
|
||||
const rowStep = 2 * radius + MARKER_BADGE_GAP_PX * pxRatio;
|
||||
const rowStep = 2 * halfHeight + MARKER_BADGE_GAP_PX * pxRatio;
|
||||
const badgeCentres = (index: number): [number, number] => {
|
||||
const offset = radius + rows[index] * rowStep;
|
||||
const offset = halfHeight + rows[index] * rowStep;
|
||||
return [bbox.top + offset, bottom - offset];
|
||||
};
|
||||
|
||||
const drawMarker = (index: number): void => {
|
||||
const { text, x } = badges[index];
|
||||
const { text, x, halfWidth } = badges[index];
|
||||
const isHovered = index === hovered;
|
||||
|
||||
ctx.globalAlpha = isHovered ? 1 : MARKER_IDLE_ALPHA;
|
||||
@@ -169,7 +174,15 @@ export function drawPercentileMarkers(
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.setLineDash([]);
|
||||
badgeCentres(index).forEach((y) => {
|
||||
drawDiamond(ctx, x, y, radius, isHovered ? color : background, color);
|
||||
drawBadge(
|
||||
ctx,
|
||||
x,
|
||||
y,
|
||||
halfWidth,
|
||||
halfHeight,
|
||||
isHovered ? color : background,
|
||||
color,
|
||||
);
|
||||
ctx.fillStyle = isHovered ? background : color;
|
||||
ctx.fillText(text, x, y);
|
||||
});
|
||||
@@ -179,7 +192,7 @@ export function drawPercentileMarkers(
|
||||
}
|
||||
// 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`;
|
||||
ctx.font = `600 ${MARKER_VALUE_FONT_SIZE_PX * pxRatio}px Inter, sans-serif`;
|
||||
const value = formatPercentileValue(markers[index], formatBound);
|
||||
const pillPaddingX = MARKER_PILL_PADDING_X_PX * pxRatio;
|
||||
const pillPaddingY = MARKER_PILL_PADDING_Y_PX * pxRatio;
|
||||
@@ -200,7 +213,8 @@ export function drawPercentileMarkers(
|
||||
width + 2 * pillPaddingX,
|
||||
height + 2 * pillPaddingY,
|
||||
);
|
||||
ctx.fillStyle = isDarkMode ? Color.BG_SLATE_400 : Color.BG_INK_400;
|
||||
// The hovered badge's colours, so the value reads as part of the same marker.
|
||||
ctx.fillStyle = color;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(left, top, width, height, MARKER_PILL_RADIUS_PX * pxRatio);
|
||||
ctx.moveTo(notchX - pointer, top);
|
||||
@@ -208,7 +222,7 @@ export function drawPercentileMarkers(
|
||||
ctx.lineTo(notchX + pointer, top);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.fillStyle = Color.BG_VANILLA_100;
|
||||
ctx.fillStyle = background;
|
||||
ctx.fillText(value, left + width / 2, top + height / 2);
|
||||
};
|
||||
|
||||
@@ -219,16 +233,16 @@ export function drawPercentileMarkers(
|
||||
}
|
||||
ctx.restore();
|
||||
|
||||
return badges.map(({ x }, index) => {
|
||||
return badges.map(({ x, halfWidth }, 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 - radius, bbox.left),
|
||||
right: toPlot(x + radius, bbox.left),
|
||||
top: toPlot(y - radius, bbox.top),
|
||||
bottom: toPlot(y + radius, bbox.top),
|
||||
left: toPlot(x - halfWidth, bbox.left),
|
||||
right: toPlot(x + halfWidth, bbox.left),
|
||||
top: toPlot(y - halfHeight, bbox.top),
|
||||
bottom: toPlot(y + halfHeight, bbox.top),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ const OPTIONS = [
|
||||
{ kind: 'signoz/BarChartPanel', displayName: 'Bar Chart' },
|
||||
{ kind: 'signoz/AreaChartPanel', displayName: 'Area' },
|
||||
{ kind: 'signoz/PieChartPanel', displayName: 'Pie Chart' },
|
||||
{ kind: 'signoz/HistogramPanel', displayName: 'Histogram' },
|
||||
{ kind: 'signoz/HistogramPanel', displayName: 'Histogram', isRetired: true },
|
||||
{ kind: 'signoz/ListPanel', displayName: 'List' },
|
||||
{ kind: 'signoz/TextPanel', displayName: 'Text' },
|
||||
].map((option) => ({ ...option, icon: (): null => null }));
|
||||
@@ -110,6 +110,22 @@ describe('PanelTypeSwitcher', () => {
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not offer a retired type to a panel of another type', async () => {
|
||||
await renderSwitcher();
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('panel-type-signoz/HistogramPanel'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps a retired type on offer to a panel already of it', async () => {
|
||||
await renderSwitcher({ panelKind: 'signoz/HistogramPanel' });
|
||||
|
||||
expect(
|
||||
screen.getByTestId('panel-type-signoz/HistogramPanel'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disables types whose supported signals exclude the current signal', async () => {
|
||||
const { onChange, user } = await renderSwitcher({
|
||||
signal: TelemetrytypesSignalDTO.metrics,
|
||||
|
||||
@@ -4,11 +4,14 @@ import type { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { PANEL_OPTIONS } from '../../../Panels/registry';
|
||||
import type { PanelKind } from '../../../Panels/types/panelKind';
|
||||
import { isPanelOptionOffered } from '../../../Panels/utils/isPanelOptionOffered';
|
||||
import type { ConfigSelectItem } from '../controls/ConfigSelect/ConfigSelect';
|
||||
|
||||
import { getPanelTypeDisabledReason } from './utils';
|
||||
|
||||
interface UsePanelTypeSelectItemsArgs {
|
||||
/** The panel's kind — the only one a retired kind is still offered to. */
|
||||
panelKind: PanelKind;
|
||||
/** Active query type — a kind that can't be authored in it is disabled. */
|
||||
queryType: EQueryType;
|
||||
/** Current datasource — also gates the disabled rule (List needs logs/traces, not metrics). */
|
||||
@@ -21,12 +24,15 @@ interface UsePanelTypeSelectItemsArgs {
|
||||
* the capabilities guard, the same rule the editor's `PanelTypeSwitcher` applies.
|
||||
*/
|
||||
export function usePanelTypeSelectItems({
|
||||
panelKind,
|
||||
queryType,
|
||||
signal,
|
||||
}: UsePanelTypeSelectItemsArgs): ConfigSelectItem<PanelKind>[] {
|
||||
return useMemo(
|
||||
() =>
|
||||
PANEL_OPTIONS.map(({ kind, displayName, icon: Icon }) => {
|
||||
PANEL_OPTIONS.filter((option) =>
|
||||
isPanelOptionOffered(option, panelKind),
|
||||
).map(({ kind, displayName, icon: Icon }) => {
|
||||
// One reason drives both the disabled flag and the tooltip, so they can't disagree.
|
||||
const disabledReason = getPanelTypeDisabledReason({
|
||||
kind,
|
||||
@@ -42,6 +48,6 @@ export function usePanelTypeSelectItems({
|
||||
tooltip: disabledReason,
|
||||
};
|
||||
}),
|
||||
[queryType, signal],
|
||||
[panelKind, queryType, signal],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,13 @@ export const SWITCH_SKETCHES = {
|
||||
))}
|
||||
</SketchSvg>
|
||||
),
|
||||
percentiles: (
|
||||
<SketchSvg>
|
||||
<path d="M3 19 L9 13 L15 7 L21 9 L27 14 L33 17 L37 19" />
|
||||
<path d="M15 3 V20" strokeDasharray="2 2" />
|
||||
<path d="M29 3 V20" strokeDasharray="2 2" />
|
||||
</SketchSvg>
|
||||
),
|
||||
rank: (
|
||||
<SketchSvg>
|
||||
{[5, 11, 17].map((y, index) => (
|
||||
|
||||
@@ -180,6 +180,22 @@ export const TILE_DRAWINGS = {
|
||||
<rect x={38} y={8} width={11} height={6} {...FILLED} />
|
||||
</TileSvg>
|
||||
),
|
||||
barsSideBySide: (
|
||||
<TileSvg>
|
||||
<rect x={10} y={8} width={7} height={14} {...FILLED} opacity={0.5} />
|
||||
<rect x={18} y={12} width={7} height={10} {...FILLED} />
|
||||
<rect x={36} y={11} width={7} height={11} {...FILLED} opacity={0.5} />
|
||||
<rect x={44} y={6} width={7} height={16} {...FILLED} />
|
||||
</TileSvg>
|
||||
),
|
||||
barsPercent: (
|
||||
<TileSvg>
|
||||
<rect x={14} y={12} width={11} height={10} {...FILLED} opacity={0.5} />
|
||||
<rect x={14} y={2} width={11} height={9} {...FILLED} />
|
||||
<rect x={38} y={8} width={11} height={14} {...FILLED} opacity={0.5} />
|
||||
<rect x={38} y={2} width={11} height={5} {...FILLED} />
|
||||
</TileSvg>
|
||||
),
|
||||
areaOverlap: (
|
||||
<TileSvg>
|
||||
<path d="M4 15 L18 9 L32 13 L46 6 L60 9" />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ComponentType } from 'react';
|
||||
import {
|
||||
type DashboardtypesDistributionAxesDTO,
|
||||
type DashboardtypesGeoMapChartAppearanceDTO,
|
||||
DashboardtypesGeoMapLayerDTO,
|
||||
type DashboardtypesGeoMapLocationDTO,
|
||||
@@ -32,6 +33,7 @@ import BucketsSection from './sections/BucketsSection/BucketsSection';
|
||||
import ChartAppearanceSection from './sections/ChartAppearanceSection/ChartAppearanceSection';
|
||||
import ContextLinksSection from './sections/ContextLinksSection/ContextLinksSection';
|
||||
import DimensionsSection from './sections/DimensionsSection/DimensionsSection';
|
||||
import DistributionAxesSection from './sections/DistributionAxesSection/DistributionAxesSection';
|
||||
import FormattingSection from './sections/FormattingSection/FormattingSection';
|
||||
import LegendSection from './sections/LegendSection/LegendSection';
|
||||
import LocationSection from './sections/LocationSection/LocationSection';
|
||||
@@ -105,6 +107,13 @@ export const SECTION_REGISTRY: {
|
||||
getPluginSlice<DashboardtypesScatterPlotAxesDTO>(spec, 'axes'),
|
||||
update: (spec, axes): PanelSpec => updatePluginSlice(spec, 'axes', axes),
|
||||
},
|
||||
// Same `axes` key again, in Distribution's bucket-range/count-scale shape.
|
||||
[SectionKind.DistributionAxes]: {
|
||||
Component: DistributionAxesSection,
|
||||
get: (spec): DashboardtypesDistributionAxesDTO | undefined =>
|
||||
getPluginSlice<DashboardtypesDistributionAxesDTO>(spec, 'axes'),
|
||||
update: (spec, axes): PanelSpec => updatePluginSlice(spec, 'axes', axes),
|
||||
},
|
||||
[SectionKind.Dimensions]: {
|
||||
Component: DimensionsSection,
|
||||
get: (spec): DashboardtypesScatterPlotDimensionsDTO | undefined =>
|
||||
|
||||
@@ -16,6 +16,7 @@ import { resolveBubbleRadius } from 'pages/DashboardPage/DashboardContainer/Pane
|
||||
|
||||
import ConfigRangeSlider from '../../controls/ConfigRangeSlider/ConfigRangeSlider';
|
||||
import DisconnectValuesField from './DisconnectValuesField';
|
||||
import DistributionPercentilesField from './DistributionPercentilesField';
|
||||
import GeoMapColorsField from './GeoMapColorsField';
|
||||
import HeatmapColorsField from './HeatmapColorsField';
|
||||
import PointsFields from './PointsFields';
|
||||
@@ -43,6 +44,7 @@ const BUBBLE_RADIUS_BOUNDS = { min: 1, max: 64 };
|
||||
*/
|
||||
function ChartAppearanceSection({
|
||||
value,
|
||||
defaultValue,
|
||||
savedValue,
|
||||
controls,
|
||||
onChange,
|
||||
@@ -59,6 +61,15 @@ function ChartAppearanceSection({
|
||||
|
||||
return (
|
||||
<>
|
||||
{controls.percentiles && (
|
||||
<DistributionPercentilesField
|
||||
value={value?.percentiles}
|
||||
defaultValue={defaultValue?.percentiles}
|
||||
savedValue={savedValue?.percentiles}
|
||||
onChange={(percentiles): void => onChange({ ...value, percentiles })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{controls.lineStyle && (
|
||||
<ConfigField label="Line" {...reset('lineStyle')}>
|
||||
<ConfigTiles
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { DashboardtypesDistributionPercentilesDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import ConfigField from '../../controls/ConfigField/ConfigField';
|
||||
import ConfigMultiSelect from '../../controls/ConfigMultiSelect/ConfigMultiSelect';
|
||||
import ConfigSwitch from '../../controls/ConfigSwitch/ConfigSwitch';
|
||||
import { SWITCH_SKETCHES } from '../../controls/drawings/switchSketches';
|
||||
import { createFieldResetter } from '../../utils/changes';
|
||||
import {
|
||||
MAX_PERCENTILE_MARKERS,
|
||||
resolvePercentileItems,
|
||||
} from './percentileOptions';
|
||||
|
||||
interface DistributionPercentilesFieldProps {
|
||||
value: DashboardtypesDistributionPercentilesDTO | undefined;
|
||||
/** The new panel's seed: what the server writes for unset percentiles. */
|
||||
defaultValue?: DashboardtypesDistributionPercentilesDTO;
|
||||
savedValue?: DashboardtypesDistributionPercentilesDTO;
|
||||
onChange: (next: DashboardtypesDistributionPercentilesDTO) => void;
|
||||
}
|
||||
|
||||
/** Edits `chartAppearance.percentiles`. */
|
||||
function DistributionPercentilesField({
|
||||
value,
|
||||
defaultValue,
|
||||
savedValue,
|
||||
onChange,
|
||||
}: DistributionPercentilesFieldProps): JSX.Element {
|
||||
const reset = createFieldResetter(value, savedValue, onChange);
|
||||
const enabled = value?.enabled ?? defaultValue?.enabled ?? false;
|
||||
const values = value?.values ?? defaultValue?.values ?? [];
|
||||
|
||||
return (
|
||||
<>
|
||||
<ConfigSwitch
|
||||
testId="panel-editor-v2-percentile-markers"
|
||||
title="Percentile markers"
|
||||
description="Dashed lines at percentiles estimated from the bucket counts."
|
||||
sketch={SWITCH_SKETCHES.percentiles}
|
||||
changed={reset('enabled').changed}
|
||||
value={enabled}
|
||||
onChange={(next): void => onChange({ enabled: next, values })}
|
||||
/>
|
||||
|
||||
{enabled && (
|
||||
<ConfigField
|
||||
label="Percentiles"
|
||||
help={
|
||||
<span data-testid="panel-editor-v2-percentile-limit">
|
||||
{values.length >= MAX_PERCENTILE_MARKERS
|
||||
? `Limit of ${MAX_PERCENTILE_MARKERS} reached; remove one to pick another.`
|
||||
: `Up to ${MAX_PERCENTILE_MARKERS}.`}
|
||||
</span>
|
||||
}
|
||||
{...reset('values')}
|
||||
>
|
||||
<ConfigMultiSelect
|
||||
testId="panel-editor-v2-percentile-values"
|
||||
placeholder="Pick percentiles"
|
||||
value={values.map(String)}
|
||||
items={resolvePercentileItems(values)}
|
||||
onChange={(picked): void => {
|
||||
if (picked.length <= MAX_PERCENTILE_MARKERS) {
|
||||
onChange({ enabled, values: picked.map(Number) });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</ConfigField>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DistributionPercentilesField;
|
||||
@@ -0,0 +1,127 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import DistributionPercentilesField from '../DistributionPercentilesField';
|
||||
import { resolvePercentileItems } from '../percentileOptions';
|
||||
|
||||
describe('DistributionPercentilesField', () => {
|
||||
it("opens on the new panel's seed, with the values picker shown", () => {
|
||||
render(
|
||||
<DistributionPercentilesField
|
||||
value={undefined}
|
||||
defaultValue={{ enabled: true, values: [50, 90, 99] }}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByTestId('panel-editor-v2-percentile-values'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('turns markers off, keeping the values for when they come back', async () => {
|
||||
const onChange = jest.fn() as jest.MockedFunction<
|
||||
ComponentProps<typeof DistributionPercentilesField>['onChange']
|
||||
>;
|
||||
render(
|
||||
<DistributionPercentilesField
|
||||
value={{ enabled: true, values: [75] }}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await userEvent
|
||||
.setup(NO_DELAY_USER_EVENT)
|
||||
.click(screen.getByTestId('panel-editor-v2-percentile-markers'));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({ enabled: false, values: [75] });
|
||||
});
|
||||
|
||||
it('hides the values picker while markers are off', () => {
|
||||
render(
|
||||
<DistributionPercentilesField
|
||||
value={{ enabled: false, values: [75] }}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('panel-editor-v2-percentile-values'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DistributionPercentilesField limit', () => {
|
||||
it('says when the limit is reached', () => {
|
||||
const { rerender } = render(
|
||||
<DistributionPercentilesField
|
||||
value={{ enabled: true, values: [50, 90, 99] }}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
screen.getByTestId('panel-editor-v2-percentile-limit'),
|
||||
).toHaveTextContent('Up to 5.');
|
||||
|
||||
rerender(
|
||||
<DistributionPercentilesField
|
||||
value={{ enabled: true, values: [50, 75, 90, 95, 99] }}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
screen.getByTestId('panel-editor-v2-percentile-limit'),
|
||||
).toHaveTextContent('Limit of 5 reached; remove one to pick another.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolvePercentileItems', () => {
|
||||
it('adds a saved value missing from the presets, in order', () => {
|
||||
expect(resolvePercentileItems([97]).map(({ label }) => label)).toStrictEqual([
|
||||
'p50',
|
||||
'p75',
|
||||
'p90',
|
||||
'p95',
|
||||
'p97',
|
||||
'p99',
|
||||
'p99.9',
|
||||
]);
|
||||
});
|
||||
|
||||
it('resets cleared percentiles to the saved ones', async () => {
|
||||
const onChange = jest.fn() as jest.MockedFunction<
|
||||
ComponentProps<typeof DistributionPercentilesField>['onChange']
|
||||
>;
|
||||
render(
|
||||
<DistributionPercentilesField
|
||||
value={{ enabled: true, values: [] }}
|
||||
savedValue={{ enabled: true, values: [50, 90, 99] }}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await userEvent.setup().click(screen.getByTestId('config-field-reset'));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
enabled: true,
|
||||
values: [50, 90, 99],
|
||||
});
|
||||
});
|
||||
|
||||
it('offers no Reset when the values match the saved ones', () => {
|
||||
render(
|
||||
<DistributionPercentilesField
|
||||
value={{ enabled: true, values: [50, 90, 99] }}
|
||||
savedValue={{ enabled: true, values: [50, 90, 99] }}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByTestId('config-field-reset')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { ConfigMultiSelectItem } from '../../controls/ConfigMultiSelect/ConfigMultiSelect';
|
||||
|
||||
/** The save API rejects more. */
|
||||
export const MAX_PERCENTILE_MARKERS = 5;
|
||||
|
||||
const PRESET_PERCENTILES = [50, 75, 90, 95, 99, 99.9];
|
||||
|
||||
/** The presets plus any saved value outside them, ascending, so nothing saved is hidden. */
|
||||
export function resolvePercentileItems(
|
||||
values: number[],
|
||||
): ConfigMultiSelectItem[] {
|
||||
return [...new Set([...PRESET_PERCENTILES, ...values])]
|
||||
.sort((a, b) => a - b)
|
||||
.map((percentile) => ({
|
||||
value: String(percentile),
|
||||
label: `p${percentile}`,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
.axes {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.axis + .axis {
|
||||
padding-top: 24px;
|
||||
border-top: 1px solid var(--l1-border);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { SolidAlertCircle } from '@signozhq/icons';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import type {
|
||||
SectionEditorProps,
|
||||
SectionKind,
|
||||
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
|
||||
import { DashboardtypesDistributionYScaleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import ConfigField from '../../controls/ConfigField/ConfigField';
|
||||
import ConfigRangeInput from '../../controls/ConfigRangeInput/ConfigRangeInput';
|
||||
import { isRangeInverted } from '../../controls/ConfigRangeInput/utils';
|
||||
import ConfigTiles from '../../controls/ConfigTiles/ConfigTiles';
|
||||
import { createFieldResetter } from '../../utils/changes';
|
||||
import { Y_SCALE_HELP, Y_SCALE_OPTIONS } from './options';
|
||||
|
||||
import styles from './DistributionAxesSection.module.scss';
|
||||
|
||||
function DistributionAxesSection({
|
||||
value,
|
||||
savedValue,
|
||||
onChange,
|
||||
}: SectionEditorProps<SectionKind.DistributionAxes>): JSX.Element {
|
||||
const reset = createFieldResetter(value, savedValue, onChange);
|
||||
const xMin = value?.x?.min;
|
||||
const xMax = value?.x?.max;
|
||||
const yScale = value?.y?.scale ?? DashboardtypesDistributionYScaleDTO.linear;
|
||||
|
||||
return (
|
||||
<div className={styles.axes}>
|
||||
<div className={styles.axis}>
|
||||
<ConfigField
|
||||
label="X-axis range"
|
||||
help={
|
||||
isRangeInverted(xMin, xMax) ? (
|
||||
<Callout color="danger" size="sm" icon={<SolidAlertCircle />}>
|
||||
Min can't be greater than max.
|
||||
</Callout>
|
||||
) : (
|
||||
'Hides buckets outside the range. Leave empty to show them all.'
|
||||
)
|
||||
}
|
||||
{...reset('x')}
|
||||
>
|
||||
<ConfigRangeInput
|
||||
minTestId="panel-editor-v2-distribution-x-min"
|
||||
maxTestId="panel-editor-v2-distribution-x-max"
|
||||
min={xMin}
|
||||
max={xMax}
|
||||
onChangeMin={(min): void =>
|
||||
onChange({ ...value, x: { ...value?.x, min } })
|
||||
}
|
||||
onChangeMax={(max): void =>
|
||||
onChange({ ...value, x: { ...value?.x, max } })
|
||||
}
|
||||
/>
|
||||
</ConfigField>
|
||||
</div>
|
||||
<div className={styles.axis}>
|
||||
<ConfigField
|
||||
label="Y-axis scale"
|
||||
help={Y_SCALE_HELP[yScale]}
|
||||
{...reset('y')}
|
||||
>
|
||||
<ConfigTiles
|
||||
testId="panel-editor-v2-distribution-y-scale"
|
||||
aria-label="Y-axis scale"
|
||||
value={yScale}
|
||||
items={Y_SCALE_OPTIONS}
|
||||
onChange={(scale): void => onChange({ ...value, y: { scale } })}
|
||||
/>
|
||||
</ConfigField>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default DistributionAxesSection;
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import { DashboardtypesDistributionYScaleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import DistributionAxesSection from '../DistributionAxesSection';
|
||||
|
||||
describe('DistributionAxesSection', () => {
|
||||
it('opens on the defaults the chart draws: every bucket, linear counts', () => {
|
||||
render(<DistributionAxesSection value={undefined} onChange={jest.fn()} />);
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Hides buckets outside the range. Leave empty to show them all.',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Bar heights proportional to counts.'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('writes the x min without dropping the max or the y scale', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onChange = jest.fn() as jest.MockedFunction<
|
||||
ComponentProps<typeof DistributionAxesSection>['onChange']
|
||||
>;
|
||||
render(
|
||||
<DistributionAxesSection
|
||||
value={{
|
||||
x: { max: 100 },
|
||||
y: { scale: DashboardtypesDistributionYScaleDTO.log },
|
||||
}}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('panel-editor-v2-distribution-x-min'));
|
||||
await user.paste('10');
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
x: { min: 10, max: 100 },
|
||||
y: { scale: DashboardtypesDistributionYScaleDTO.log },
|
||||
});
|
||||
});
|
||||
|
||||
it('flags a min above the max', () => {
|
||||
render(
|
||||
<DistributionAxesSection
|
||||
value={{ x: { min: 100, max: 10 } }}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByText("Min can't be greater than max."),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('writes the y scale', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onChange = jest.fn() as jest.MockedFunction<
|
||||
ComponentProps<typeof DistributionAxesSection>['onChange']
|
||||
>;
|
||||
render(<DistributionAxesSection value={undefined} onChange={onChange} />);
|
||||
|
||||
await user.click(
|
||||
screen.getByTestId('panel-editor-v2-distribution-y-scale-log'),
|
||||
);
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
y: { scale: DashboardtypesDistributionYScaleDTO.log },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { DashboardtypesDistributionYScaleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { pickScaleOptions } from '../AxesSection/options';
|
||||
|
||||
export const Y_SCALE_OPTIONS = pickScaleOptions([
|
||||
DashboardtypesDistributionYScaleDTO.linear,
|
||||
DashboardtypesDistributionYScaleDTO.log,
|
||||
] as const);
|
||||
|
||||
export const Y_SCALE_HELP: Record<DashboardtypesDistributionYScaleDTO, string> =
|
||||
{
|
||||
linear: 'Bar heights proportional to counts.',
|
||||
log: 'Keeps small tail buckets visible next to the bulk.',
|
||||
};
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
BAR_LAYOUT_HELP,
|
||||
BAR_LAYOUT_OPTIONS,
|
||||
BarLayout,
|
||||
BUCKET_STACK_HELP,
|
||||
BUCKET_STACK_OPTIONS,
|
||||
STACK_MODE_HELP,
|
||||
STACK_MODE_OPTIONS,
|
||||
} from './options';
|
||||
@@ -35,7 +37,8 @@ type VisualizationSectionProps = SectionEditorProps<SectionKind.Visualization> &
|
||||
/**
|
||||
* Edits the `visualization` slice: the panel-type switcher (`switchPanelKind`, every
|
||||
* kind), the per-panel time preference, bar stacking (`stackedBarChart`, Bar only),
|
||||
* area stacking (`stack`, Area only) and gap filling (`fillSpans`). Each control is
|
||||
* area stacking (`stack`, Area only), bucket stacking (`stack`, Distribution only)
|
||||
* and gap filling (`fillSpans`). Each control is
|
||||
* gated by its `controls` flag, so a kind only renders — and only writes — the fields
|
||||
* its spec supports.
|
||||
*/
|
||||
@@ -137,6 +140,22 @@ function VisualizationSection({
|
||||
/>
|
||||
</ConfigField>
|
||||
)}
|
||||
|
||||
{controls.bucketStack && (
|
||||
<ConfigField
|
||||
label="Groups in a bucket"
|
||||
help={stack && BUCKET_STACK_HELP[stack]}
|
||||
{...reset('stack')}
|
||||
>
|
||||
<ConfigTiles
|
||||
testId="panel-editor-v2-bucket-stack"
|
||||
aria-label="Groups in a bucket"
|
||||
value={stack}
|
||||
items={BUCKET_STACK_OPTIONS}
|
||||
onChange={(next): void => onChange({ ...value, stack: next })}
|
||||
/>
|
||||
</ConfigField>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import {
|
||||
DashboardtypesStackModeDTO,
|
||||
@@ -162,6 +163,43 @@ describe('VisualizationSection', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the bucket stack on the kind's seeded default", () => {
|
||||
render(
|
||||
<VisualizationSection
|
||||
value={undefined}
|
||||
defaultValue={{ stack: DashboardtypesStackModeDTO.normal }}
|
||||
controls={{ switchPanelKind: false, bucketStack: true }}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Groups sit on top of each other, so the height shows the bucket total.',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('writes the chosen bucket stack', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = jest.fn() as jest.MockedFunction<
|
||||
ComponentProps<typeof VisualizationSection>['onChange']
|
||||
>;
|
||||
render(
|
||||
<VisualizationSection
|
||||
value={undefined}
|
||||
controls={{ switchPanelKind: false, bucketStack: true }}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('panel-editor-v2-bucket-stack-none'));
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
stack: DashboardtypesStackModeDTO.none,
|
||||
});
|
||||
});
|
||||
|
||||
it('toggles fill spans through onChange', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = jest.fn();
|
||||
|
||||
@@ -55,3 +55,32 @@ export const STACK_MODE_HELP: Record<DashboardtypesStackModeDTO, string> = {
|
||||
[DashboardtypesStackModeDTO.percent]:
|
||||
'Each series shows its share of the total at every point in time.',
|
||||
};
|
||||
|
||||
/** Distribution's layout of groups within a bucket. */
|
||||
export const BUCKET_STACK_OPTIONS: ConfigTileItem<DashboardtypesStackModeDTO>[] =
|
||||
[
|
||||
{
|
||||
value: DashboardtypesStackModeDTO.normal,
|
||||
label: 'Stacked',
|
||||
drawing: TILE_DRAWINGS.barsStacked,
|
||||
},
|
||||
{
|
||||
value: DashboardtypesStackModeDTO.none,
|
||||
label: 'Side by side',
|
||||
drawing: TILE_DRAWINGS.barsSideBySide,
|
||||
},
|
||||
{
|
||||
value: DashboardtypesStackModeDTO.percent,
|
||||
label: '100%',
|
||||
drawing: TILE_DRAWINGS.barsPercent,
|
||||
},
|
||||
];
|
||||
|
||||
export const BUCKET_STACK_HELP: Record<DashboardtypesStackModeDTO, string> = {
|
||||
[DashboardtypesStackModeDTO.normal]:
|
||||
'Groups sit on top of each other, so the height shows the bucket total.',
|
||||
[DashboardtypesStackModeDTO.none]:
|
||||
'Groups share each bucket side by side; hard to read past a few groups.',
|
||||
[DashboardtypesStackModeDTO.percent]:
|
||||
"Each group's share of the bucket; the y axis becomes a percentage.",
|
||||
};
|
||||
|
||||
@@ -21,9 +21,10 @@ import RunQueryBtn from 'container/QueryBuilder/components/RunQueryBtn/RunQueryB
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useSyncQueryBuilderFields } from 'components/QueryBuilderV2/useSyncQueryBuilderFields';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { DATA_SOURCE_TO_SIGNAL, DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
getQueryBuilderFields,
|
||||
getQueryTypeSignals,
|
||||
isRawRequest,
|
||||
} from '../../Panels/types/panelCapabilities';
|
||||
@@ -44,6 +45,8 @@ interface PanelEditorQueryBuilderProps {
|
||||
onStageRunQuery: () => void;
|
||||
/** Abort the in-flight preview fetch (the button's cancel action). */
|
||||
onCancelQuery: () => void;
|
||||
/** Optional content above the tabs (e.g. Histogram's pointer to Distribution). */
|
||||
banner?: ReactNode;
|
||||
/** Optional content pinned below the builder (e.g. the List columns editor). */
|
||||
footer?: ReactNode;
|
||||
/** Pin the tabs + Run Query row to the top of the scroll area. Off in the View modal, which shares a scroll area with its own header. */
|
||||
@@ -60,6 +63,7 @@ function PanelEditorQueryBuilder({
|
||||
isLoadingQueries,
|
||||
onStageRunQuery,
|
||||
onCancelQuery,
|
||||
banner,
|
||||
footer,
|
||||
stickyHeader = true,
|
||||
}: PanelEditorQueryBuilderProps): JSX.Element {
|
||||
@@ -74,6 +78,16 @@ function PanelEditorQueryBuilder({
|
||||
// operator that combines aggregated trace queries (V1 parity).
|
||||
const isRawQuery = isRawRequest(panelDefinition.queryCapabilities);
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
// Every query of a panel shares a signal, so the first one speaks for all.
|
||||
const signal = currentQuery.builder.queryData[0]?.dataSource;
|
||||
const queryBuilderFields = useMemo(
|
||||
() =>
|
||||
getQueryBuilderFields(
|
||||
panelDefinition,
|
||||
signal ? DATA_SOURCE_TO_SIGNAL[signal] : undefined,
|
||||
),
|
||||
[panelDefinition, signal],
|
||||
);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
useSyncQueryBuilderFields(panelDefinition.syncedQueryBuilderFields);
|
||||
|
||||
@@ -111,7 +125,7 @@ function PanelEditorQueryBuilder({
|
||||
<div className="query-builder-v2-container">
|
||||
<QueryBuilderV2
|
||||
panelType={panelType}
|
||||
fieldsConfig={panelDefinition.queryBuilderFields}
|
||||
fieldsConfig={queryBuilderFields}
|
||||
allowedDataSources={getQueryTypeSignals(
|
||||
panelDefinition.supportedQueryTypesKindMap,
|
||||
EQueryType.QUERY_BUILDER,
|
||||
@@ -187,7 +201,7 @@ function PanelEditorQueryBuilder({
|
||||
// QB wants a null data source and AI pins traces: both mounted, they overwrite each other's provider config in a loop.
|
||||
destroyInactiveTabPane: isBuilderQueryType(queryType),
|
||||
}));
|
||||
}, [panelDefinition, panelType, isDarkMode, isRawQuery]);
|
||||
}, [panelDefinition, queryBuilderFields, panelType, isDarkMode, isRawQuery]);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -197,6 +211,7 @@ function PanelEditorQueryBuilder({
|
||||
role="presentation"
|
||||
>
|
||||
<div className={styles.scrollArea}>
|
||||
{banner}
|
||||
<Tabs
|
||||
type="card"
|
||||
className={cx(styles.tabsContainer, {
|
||||
|
||||
@@ -50,7 +50,7 @@ const mockUseQueryBuilder = useQueryBuilder as unknown as jest.Mock;
|
||||
|
||||
const BUILDER_QUERY = {
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
builder: { queryData: [{ dataSource: 'traces' }] },
|
||||
builder: { queryData: [{ dataSource: 'traces' }], queryFormulas: [] },
|
||||
};
|
||||
const AI_QUERY = {
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import type { DashboardtypesPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
initialClickHouseData,
|
||||
initialFormulaBuilderFormValues,
|
||||
initialQueriesMap,
|
||||
initialQueryAIWithType,
|
||||
initialQueryPromQLData,
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { rebuildBuilderForPanelType } from 'lib/query/panelQuery';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type { MetricAggregation } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { act, renderHook } from 'tests/test-utils';
|
||||
|
||||
import { resolveQueryType } from 'pages/DashboardPage/DashboardContainer/Panels/capabilities';
|
||||
import { getBuilderQueries } from '../../../Panels/utils/getBuilderQueries';
|
||||
@@ -61,6 +68,7 @@ const LIST_QUERIES = [{ id: 'list-q' }] as unknown as NonNullable<
|
||||
DashboardtypesPanelSpecDTO['queries']
|
||||
>;
|
||||
const TRANSFORMED = {
|
||||
queryFormulas: [],
|
||||
queryData: [{ orderBy: [] }],
|
||||
} as unknown as Query['builder'];
|
||||
const CONVERTED = [{ id: 'converted' }] as unknown as NonNullable<
|
||||
@@ -79,6 +87,21 @@ const tracesBuilder = (expression: string): Query['builder'] => ({
|
||||
queryFormulas: [],
|
||||
});
|
||||
|
||||
const builderWithQueries = (
|
||||
queries: (Partial<IBuilderQuery> & { queryName: string; disabled: boolean })[],
|
||||
formulas: { queryName: string; disabled: boolean }[] = [],
|
||||
): Query['builder'] => ({
|
||||
...initialQueriesMap.metrics.builder,
|
||||
queryData: queries.map((query) => ({
|
||||
...initialQueriesMap.metrics.builder.queryData[0],
|
||||
...query,
|
||||
})),
|
||||
queryFormulas: formulas.map((formula) => ({
|
||||
...initialFormulaBuilderFormValues,
|
||||
...formula,
|
||||
})),
|
||||
});
|
||||
|
||||
function makeSpec(
|
||||
kind: string,
|
||||
pluginSpec: unknown,
|
||||
@@ -103,7 +126,13 @@ function fakeQuery(
|
||||
queryType: string,
|
||||
queryData: Record<string, unknown>[] = [],
|
||||
): Query {
|
||||
return { id, queryType, builder: { queryData } } as unknown as Query;
|
||||
return {
|
||||
id,
|
||||
queryType,
|
||||
builder: { queryData },
|
||||
promql: [],
|
||||
clickhouse_sql: [],
|
||||
} as unknown as Query;
|
||||
}
|
||||
|
||||
function builderState(currentQuery: Query): {
|
||||
@@ -275,15 +304,62 @@ describe('usePanelKindChange', () => {
|
||||
expect(persisted.builder.queryTraceOperator).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('keeps one query and drops the formulas when switching to a Heatmap panel', () => {
|
||||
it('keeps the metric queries and formulas, one enabled, when switching to a Heatmap panel', () => {
|
||||
const setSpec = jest.fn();
|
||||
mockUseQueryBuilder.mockReturnValue(
|
||||
builderState(fakeQuery('ts-current', 'builder')),
|
||||
);
|
||||
mockRebuildBuilder.mockReturnValue(
|
||||
builderWithQueries(
|
||||
[
|
||||
{ queryName: 'A', disabled: false },
|
||||
{ queryName: 'B', disabled: false },
|
||||
],
|
||||
[{ queryName: 'F1', disabled: false }],
|
||||
),
|
||||
);
|
||||
|
||||
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.map(({ queryName, disabled }) => ({
|
||||
queryName,
|
||||
disabled,
|
||||
})),
|
||||
).toStrictEqual([
|
||||
{ queryName: 'A', disabled: false },
|
||||
{ queryName: 'B', disabled: true },
|
||||
]);
|
||||
expect(
|
||||
persisted.builder.queryFormulas.map(({ queryName, disabled }) => ({
|
||||
queryName,
|
||||
disabled,
|
||||
})),
|
||||
).toStrictEqual([{ queryName: 'F1', disabled: true }]);
|
||||
});
|
||||
|
||||
it('keeps one traces query and drops the formulas when switching to a Heatmap panel', () => {
|
||||
const setSpec = jest.fn();
|
||||
mockUseQueryBuilder.mockReturnValue(
|
||||
builderState(fakeQuery('ts-current', 'builder')),
|
||||
);
|
||||
const traces = tracesBuilder('count()');
|
||||
mockRebuildBuilder.mockReturnValue({
|
||||
queryData: [{ queryName: 'A' }, { queryName: 'B' }],
|
||||
queryFormulas: [{ queryName: 'F1' }],
|
||||
} as unknown as Query['builder']);
|
||||
...traces,
|
||||
queryData: [
|
||||
{ ...traces.queryData[0], queryName: 'A', disabled: true },
|
||||
{ ...traces.queryData[0], queryName: 'B', disabled: false },
|
||||
],
|
||||
queryFormulas: [{ ...initialFormulaBuilderFormValues, queryName: 'F1' }],
|
||||
});
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePanelKindChange({
|
||||
@@ -296,17 +372,131 @@ describe('usePanelKindChange', () => {
|
||||
|
||||
const [persisted] = mockToPerses.mock.calls[0] as [Query];
|
||||
expect(persisted.builder.queryData.map((qd) => qd.queryName)).toStrictEqual([
|
||||
'A',
|
||||
'B',
|
||||
]);
|
||||
expect(persisted.builder.queryFormulas).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('keeps the field of a traces function aggregation when switching to a Heatmap panel', () => {
|
||||
it.each(['signoz/HeatmapPanel', 'signoz/DistributionPanel'] as const)(
|
||||
'keeps an enabled metric formula as the one output when switching to %s',
|
||||
(kind) => {
|
||||
const setSpec = jest.fn();
|
||||
mockUseQueryBuilder.mockReturnValue(
|
||||
builderState(fakeQuery('ts-current', 'builder')),
|
||||
);
|
||||
mockRebuildBuilder.mockReturnValue(
|
||||
builderWithQueries(
|
||||
[
|
||||
{ queryName: 'A', disabled: true },
|
||||
{ queryName: 'B', disabled: true },
|
||||
],
|
||||
[{ queryName: 'F1', disabled: false }],
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePanelKindChange({
|
||||
spec: makeSpec('signoz/TimeSeriesPanel', {}, TABLE_QUERIES),
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
setSpec,
|
||||
}),
|
||||
);
|
||||
act(() => result.current.onChangePanelKind(kind));
|
||||
|
||||
const [persisted] = mockToPerses.mock.calls[0] as [Query];
|
||||
expect(
|
||||
persisted.builder.queryData.map(({ queryName, disabled }) => ({
|
||||
queryName,
|
||||
disabled,
|
||||
})),
|
||||
).toStrictEqual([
|
||||
{ queryName: 'A', disabled: true },
|
||||
{ queryName: 'B', disabled: true },
|
||||
]);
|
||||
expect(
|
||||
persisted.builder.queryFormulas.map(({ queryName, disabled }) => ({
|
||||
queryName,
|
||||
disabled,
|
||||
})),
|
||||
).toStrictEqual([{ queryName: 'F1', disabled: false }]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['signoz/HeatmapPanel', 'signoz/DistributionPanel'] as const)(
|
||||
'keeps one enabled PromQL and ClickHouse query when switching to %s',
|
||||
(kind) => {
|
||||
mockUseQueryBuilder.mockReturnValue(
|
||||
builderState({
|
||||
...initialQueriesMap.metrics,
|
||||
promql: ['A', 'B', 'C'].map((name) => ({
|
||||
...initialQueryPromQLData,
|
||||
name,
|
||||
disabled: name === 'A',
|
||||
})),
|
||||
clickhouse_sql: ['A', 'B'].map((name) => ({
|
||||
...initialClickHouseData,
|
||||
name,
|
||||
disabled: true,
|
||||
})),
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePanelKindChange({
|
||||
spec: makeSpec('signoz/TimeSeriesPanel', {}, TABLE_QUERIES),
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
setSpec: jest.fn(),
|
||||
}),
|
||||
);
|
||||
act(() => result.current.onChangePanelKind(kind));
|
||||
|
||||
const [persisted] = mockToPerses.mock.calls[0] as [Query];
|
||||
const summarize = (
|
||||
queries: { name: string; disabled: boolean }[],
|
||||
): { name: string; disabled: boolean }[] =>
|
||||
queries.map(({ name, disabled }) => ({ name, disabled }));
|
||||
expect(summarize(persisted.promql)).toStrictEqual([
|
||||
{ name: 'B', disabled: false },
|
||||
]);
|
||||
expect(summarize(persisted.clickhouse_sql)).toStrictEqual([
|
||||
{ name: 'A', disabled: false },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('leaves PromQL queries alone when switching to a non-bucket kind', () => {
|
||||
const promql = ['A', 'B'].map((name) => ({
|
||||
...initialQueryPromQLData,
|
||||
name,
|
||||
}));
|
||||
mockUseQueryBuilder.mockReturnValue(
|
||||
builderState({ ...initialQueriesMap.metrics, promql }),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePanelKindChange({
|
||||
spec: makeSpec('signoz/TimeSeriesPanel', {}, TABLE_QUERIES),
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
setSpec: jest.fn(),
|
||||
}),
|
||||
);
|
||||
act(() => result.current.onChangePanelKind('signoz/BarChartPanel'));
|
||||
|
||||
const [persisted] = mockToPerses.mock.calls[0] as [Query];
|
||||
expect(persisted.promql).toStrictEqual(promql);
|
||||
});
|
||||
|
||||
it('keeps an enabled query enabled ahead of a disabled one', () => {
|
||||
const setSpec = jest.fn();
|
||||
mockUseQueryBuilder.mockReturnValue(
|
||||
builderState(fakeQuery('ts-current', 'builder')),
|
||||
);
|
||||
mockRebuildBuilder.mockReturnValue(tracesBuilder('p99(duration_nano)'));
|
||||
mockRebuildBuilder.mockReturnValue(
|
||||
builderWithQueries([
|
||||
{ queryName: 'A', disabled: true },
|
||||
{ queryName: 'B', disabled: false },
|
||||
]),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePanelKindChange({
|
||||
@@ -315,14 +505,45 @@ describe('usePanelKindChange', () => {
|
||||
setSpec,
|
||||
}),
|
||||
);
|
||||
act(() => result.current.onChangePanelKind('signoz/HeatmapPanel'));
|
||||
act(() => result.current.onChangePanelKind('signoz/DistributionPanel'));
|
||||
|
||||
const [persisted] = mockToPerses.mock.calls[0] as [Query];
|
||||
expect(persisted.builder.queryData[0].aggregations).toMatchObject([
|
||||
{ expression: 'duration_nano' },
|
||||
expect(
|
||||
persisted.builder.queryData.map(({ queryName, disabled }) => ({
|
||||
queryName,
|
||||
disabled,
|
||||
})),
|
||||
).toStrictEqual([
|
||||
{ queryName: 'A', disabled: true },
|
||||
{ queryName: 'B', disabled: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(['signoz/HeatmapPanel', 'signoz/DistributionPanel'] as const)(
|
||||
'keeps the field of a traces function aggregation when switching to %s',
|
||||
(kind) => {
|
||||
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(kind));
|
||||
|
||||
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(
|
||||
@@ -379,6 +600,46 @@ describe('usePanelKindChange', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the percentile of a disabled formula input when switching to a Heatmap panel', () => {
|
||||
const setSpec = jest.fn();
|
||||
mockUseQueryBuilder.mockReturnValue(
|
||||
builderState(fakeQuery('ts-current', 'builder')),
|
||||
);
|
||||
const p90Latency: MetricAggregation = {
|
||||
metricName: 'signoz_latency',
|
||||
temporality: '',
|
||||
timeAggregation: 'avg',
|
||||
spaceAggregation: 'p90',
|
||||
};
|
||||
mockRebuildBuilder.mockReturnValue(
|
||||
builderWithQueries(
|
||||
[
|
||||
{
|
||||
queryName: 'A',
|
||||
disabled: true,
|
||||
spaceAggregation: 'p90',
|
||||
aggregations: [p90Latency],
|
||||
},
|
||||
],
|
||||
[{ queryName: 'F1', disabled: false }],
|
||||
),
|
||||
);
|
||||
|
||||
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];
|
||||
const [queryData] = persisted.builder.queryData;
|
||||
expect(queryData.spaceAggregation).toBe('p90');
|
||||
expect(queryData.aggregations?.[0]).toStrictEqual(p90Latency);
|
||||
});
|
||||
|
||||
it('swaps count back for a percentile when a histogram leaves a Heatmap panel', () => {
|
||||
const setSpec = jest.fn();
|
||||
mockUseQueryBuilder.mockReturnValue(
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
toDistributionAggregation,
|
||||
} from 'lib/query/distributionField';
|
||||
import { rebuildBuilderForPanelType } from 'lib/query/panelQuery';
|
||||
import { isBucketPanelType } from 'lib/query/bucketPanelTypes';
|
||||
import type { PartialPanelTypes } from 'lib/query/panelTypeDataSourceFormValuesMap';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
|
||||
@@ -37,8 +38,9 @@ import {
|
||||
} from '../getSwitchedPluginSpec';
|
||||
import {
|
||||
withPercentileHistogramAggregation,
|
||||
withSingleHeatmapQuery,
|
||||
} from '../utils/heatmapQuery';
|
||||
withSingleBucketQuery,
|
||||
withSingleEnabledQuery,
|
||||
} from '../utils/bucketQuery';
|
||||
|
||||
// V1's panel-type rebuild clears orderBy for lists; re-seed the fresh-list default (timestamp desc).
|
||||
const DEFAULT_LIST_ORDER_BY: OrderByPayload[] = [
|
||||
@@ -186,15 +188,15 @@ export function usePanelKindChange({
|
||||
: transformed,
|
||||
newKind,
|
||||
);
|
||||
const isHeatmap = newKind === 'signoz/HeatmapPanel';
|
||||
const isBucketPanel = isBucketPanelType(newPanelType);
|
||||
const converted = {
|
||||
...ordered,
|
||||
queryData: ordered.queryData.map(
|
||||
isHeatmap ? toDistributionAggregation : fromDistributionAggregation,
|
||||
isBucketPanel ? toDistributionAggregation : fromDistributionAggregation,
|
||||
),
|
||||
};
|
||||
return isHeatmap
|
||||
? withSingleHeatmapQuery(converted)
|
||||
return isBucketPanel
|
||||
? withSingleBucketQuery(converted)
|
||||
: withPercentileHistogramAggregation(converted);
|
||||
};
|
||||
|
||||
@@ -257,6 +259,10 @@ export function usePanelKindChange({
|
||||
...(query.builder_ai_query && {
|
||||
builder_ai_query: rebuildForNewKind(query.builder_ai_query),
|
||||
}),
|
||||
...(isBucketPanelType(newPanelType) && {
|
||||
promql: withSingleEnabledQuery(query.promql),
|
||||
clickhouse_sql: withSingleEnabledQuery(query.clickhouse_sql),
|
||||
}),
|
||||
};
|
||||
const signal = getBuilderQueries(currentSpec.queries)[0]
|
||||
?.signal as TelemetrytypesSignalDTO;
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { ATTRIBUTE_TYPES } from 'constants/queryBuilder';
|
||||
import {
|
||||
DEFAULT_PERCENTILE,
|
||||
isLogsOrTraces,
|
||||
} from 'lib/query/distributionField';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type {
|
||||
MetricAggregation,
|
||||
SpaceAggregation,
|
||||
} from 'types/api/v5/queryRange';
|
||||
|
||||
const PERCENTILE_SPACE_AGGREGATIONS = new Set<SpaceAggregation>([
|
||||
'p50',
|
||||
'p75',
|
||||
'p90',
|
||||
'p95',
|
||||
'p99',
|
||||
]);
|
||||
|
||||
const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
|
||||
ATTRIBUTE_TYPES.HISTOGRAM,
|
||||
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,
|
||||
]);
|
||||
|
||||
/** What a bucket panel's cell or bar holds, and the one space aggregation it offers. */
|
||||
const BUCKET_HISTOGRAM_SPACE_AGGREGATION = 'count';
|
||||
|
||||
/**
|
||||
* A bucket panel (heatmap, distribution) draws against one bucket axis, so the request
|
||||
* takes exactly one enabled output. Metrics keep their queries and formulas, since a
|
||||
* formula over disabled metric queries is a valid output; the first enabled one stays
|
||||
* enabled (the first query when none is). Logs and traces take no formula and one
|
||||
* query, so only the first enabled query survives there. The per-kind cache restores
|
||||
* whatever is dropped here if the panel switches back.
|
||||
*
|
||||
* Percentiles go the same way: a histogram bucket panel takes its axis from the `le`
|
||||
* labels, so a percentile draws what a count already draws, and the statement builder
|
||||
* sums the `le` counts either way.
|
||||
*/
|
||||
export function withSingleBucketQuery(
|
||||
builder: Query['builder'],
|
||||
): Query['builder'] {
|
||||
const { queryData, queryFormulas } = builder;
|
||||
if (!queryData.length) {
|
||||
return builder;
|
||||
}
|
||||
|
||||
if (isLogsOrTraces(queryData[0].dataSource)) {
|
||||
return {
|
||||
...builder,
|
||||
queryData: withSingleEnabledQuery(queryData).map(withBucketCount),
|
||||
queryFormulas: [],
|
||||
};
|
||||
}
|
||||
|
||||
const outputs = [...queryData, ...queryFormulas];
|
||||
const keptIndex = Math.max(
|
||||
0,
|
||||
outputs.findIndex((output) => !output.disabled),
|
||||
);
|
||||
// Only the drawn query takes its axis from `le`; a disabled formula input still
|
||||
// runs as a time series, where its percentile means what it says.
|
||||
return {
|
||||
...builder,
|
||||
queryData: queryData.map((query, index) =>
|
||||
index === keptIndex
|
||||
? withBucketCount({ ...query, disabled: false })
|
||||
: { ...query, disabled: true },
|
||||
),
|
||||
queryFormulas: queryFormulas.map((formula, index) => ({
|
||||
...formula,
|
||||
disabled: queryData.length + index !== keptIndex,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function withBucketCount(query: IBuilderQuery): IBuilderQuery {
|
||||
return {
|
||||
...query,
|
||||
spaceAggregation: withoutPercentile(query.spaceAggregation),
|
||||
aggregations: query.aggregations?.map((aggregation) => ({
|
||||
...aggregation,
|
||||
spaceAggregation: withoutPercentile(
|
||||
(aggregation as MetricAggregation).spaceAggregation,
|
||||
),
|
||||
})) as IBuilderQuery['aggregations'],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A bucket panel takes one enabled query on every tab: the first enabled one (the first
|
||||
* when none is), enabled. The per-kind cache restores the rest.
|
||||
*/
|
||||
export function withSingleEnabledQuery<T extends { disabled: boolean }>(
|
||||
queries: T[],
|
||||
): T[] {
|
||||
const kept = queries.find((query) => !query.disabled) ?? queries[0];
|
||||
return kept ? [{ ...kept, disabled: false }] : queries;
|
||||
}
|
||||
|
||||
/** Cast because the substitute is a `SpaceAggregation` whichever of its callers `T` came from. */
|
||||
function withoutPercentile<T extends string | undefined>(
|
||||
spaceAggregation: T,
|
||||
): T {
|
||||
return (
|
||||
PERCENTILE_SPACE_AGGREGATIONS.has(spaceAggregation as SpaceAggregation)
|
||||
? BUCKET_HISTOGRAM_SPACE_AGGREGATION
|
||||
: spaceAggregation
|
||||
) as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Undoes the count above: every other kind offers a histogram metric percentiles alone,
|
||||
* so a count carried out of a bucket panel would sit in the selector with no option
|
||||
* behind it. Other metric types are left alone — count is a real choice for a sum or a
|
||||
* gauge.
|
||||
*/
|
||||
export function withPercentileHistogramAggregation(
|
||||
builder: Query['builder'],
|
||||
): Query['builder'] {
|
||||
return {
|
||||
...builder,
|
||||
queryData: builder.queryData.map((queryData) => {
|
||||
if (
|
||||
!HISTOGRAM_ATTRIBUTE_TYPES.has(queryData.aggregateAttribute?.type ?? '')
|
||||
) {
|
||||
return queryData;
|
||||
}
|
||||
|
||||
return {
|
||||
...queryData,
|
||||
spaceAggregation: withoutCount(queryData.spaceAggregation),
|
||||
aggregations: queryData.aggregations?.map((aggregation) => ({
|
||||
...aggregation,
|
||||
spaceAggregation: withoutCount(
|
||||
(aggregation as MetricAggregation).spaceAggregation,
|
||||
),
|
||||
})) as IBuilderQuery['aggregations'],
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function withoutCount<T extends string | undefined>(spaceAggregation: T): T {
|
||||
return (
|
||||
spaceAggregation === BUCKET_HISTOGRAM_SPACE_AGGREGATION
|
||||
? DEFAULT_PERCENTILE
|
||||
: spaceAggregation
|
||||
) as T;
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
import { ATTRIBUTE_TYPES } from 'constants/queryBuilder';
|
||||
import { DEFAULT_PERCENTILE } from 'lib/query/distributionField';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type {
|
||||
MetricAggregation,
|
||||
SpaceAggregation,
|
||||
} from 'types/api/v5/queryRange';
|
||||
|
||||
const PERCENTILE_SPACE_AGGREGATIONS = new Set<SpaceAggregation>([
|
||||
'p50',
|
||||
'p75',
|
||||
'p90',
|
||||
'p95',
|
||||
'p99',
|
||||
]);
|
||||
|
||||
const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
|
||||
ATTRIBUTE_TYPES.HISTOGRAM,
|
||||
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,
|
||||
]);
|
||||
|
||||
/** What a heatmap cell holds, and the one space aggregation the kind offers. */
|
||||
const HEATMAP_HISTOGRAM_SPACE_AGGREGATION = 'count';
|
||||
|
||||
/**
|
||||
* A heatmap draws against one bucket axis, so the request takes exactly one enabled
|
||||
* query and refuses a formula over the cells. The per-kind cache restores whatever is
|
||||
* dropped here if the panel switches back.
|
||||
*
|
||||
* Percentiles go the same way: a histogram heatmap takes its axis from the `le` labels,
|
||||
* so a percentile draws the grid a count already draws, and the statement builder sums
|
||||
* the `le` counts either way.
|
||||
*/
|
||||
export function withSingleHeatmapQuery(
|
||||
builder: Query['builder'],
|
||||
): Query['builder'] {
|
||||
const [first] = builder.queryData;
|
||||
if (!first) {
|
||||
return builder;
|
||||
}
|
||||
|
||||
return {
|
||||
...builder,
|
||||
queryData: [
|
||||
{
|
||||
...first,
|
||||
spaceAggregation: withoutPercentile(first.spaceAggregation),
|
||||
aggregations: first.aggregations?.map((aggregation) => ({
|
||||
...aggregation,
|
||||
spaceAggregation: withoutPercentile(
|
||||
(aggregation as MetricAggregation).spaceAggregation,
|
||||
),
|
||||
})) as IBuilderQuery['aggregations'],
|
||||
},
|
||||
],
|
||||
queryFormulas: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** Cast because the substitute is a `SpaceAggregation` whichever of its callers `T` came from. */
|
||||
function withoutPercentile<T extends string | undefined>(
|
||||
spaceAggregation: T,
|
||||
): T {
|
||||
return (
|
||||
PERCENTILE_SPACE_AGGREGATIONS.has(spaceAggregation as SpaceAggregation)
|
||||
? HEATMAP_HISTOGRAM_SPACE_AGGREGATION
|
||||
: spaceAggregation
|
||||
) as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Undoes the count above: every other kind offers a histogram metric percentiles alone,
|
||||
* so a count carried out of a heatmap would sit in the selector with no option behind
|
||||
* it. Other metric types are left alone — count is a real choice for a sum or a gauge.
|
||||
*/
|
||||
export function withPercentileHistogramAggregation(
|
||||
builder: Query['builder'],
|
||||
): Query['builder'] {
|
||||
return {
|
||||
...builder,
|
||||
queryData: builder.queryData.map((queryData) => {
|
||||
if (
|
||||
!HISTOGRAM_ATTRIBUTE_TYPES.has(queryData.aggregateAttribute?.type ?? '')
|
||||
) {
|
||||
return queryData;
|
||||
}
|
||||
|
||||
return {
|
||||
...queryData,
|
||||
spaceAggregation: withoutCount(queryData.spaceAggregation),
|
||||
aggregations: queryData.aggregations?.map((aggregation) => ({
|
||||
...aggregation,
|
||||
spaceAggregation: withoutCount(
|
||||
(aggregation as MetricAggregation).spaceAggregation,
|
||||
),
|
||||
})) as IBuilderQuery['aggregations'],
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function withoutCount<T extends string | undefined>(spaceAggregation: T): T {
|
||||
return (
|
||||
spaceAggregation === HEATMAP_HISTOGRAM_SPACE_AGGREGATION
|
||||
? DEFAULT_PERCENTILE
|
||||
: spaceAggregation
|
||||
) as T;
|
||||
}
|
||||
@@ -8,7 +8,10 @@ import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { UNSUPPORTED_PANEL } from '../kinds/UnsupportedPanel/definition';
|
||||
import { getPanelDefinition, isPanelKindSupported } from '../registry';
|
||||
import type { PanelQueryCapabilities } from '../types/panelCapabilities';
|
||||
import {
|
||||
getQueryBuilderFields,
|
||||
type PanelQueryCapabilities,
|
||||
} from '../types/panelCapabilities';
|
||||
import { NO_PANEL_ACTIONS } from '../types/panelDefinition';
|
||||
import {
|
||||
getQueryPanelDefinition,
|
||||
@@ -24,7 +27,8 @@ import type { PanelKind } from '../types/panelKind';
|
||||
|
||||
const { QUERY_BUILDER, CLICKHOUSE, PROM } = EQueryType;
|
||||
const { logs, traces, metrics } = TelemetrytypesSignalDTO;
|
||||
const { time_series, scalar, raw, heatmap } = Querybuildertypesv5RequestTypeDTO;
|
||||
const { time_series, scalar, raw, heatmap, distribution } =
|
||||
Querybuildertypesv5RequestTypeDTO;
|
||||
|
||||
const EXPECTED_QUERY_TYPES: Record<PanelKind, EQueryType[]> = {
|
||||
'signoz/TimeSeriesPanel': [
|
||||
@@ -58,6 +62,7 @@ const EXPECTED_QUERY_TYPES: Record<PanelKind, EQueryType[]> = {
|
||||
EQueryType.AI_QUERY_BUILDER,
|
||||
],
|
||||
'signoz/HeatmapPanel': [QUERY_BUILDER, CLICKHOUSE, PROM],
|
||||
'signoz/DistributionPanel': [QUERY_BUILDER, CLICKHOUSE, PROM],
|
||||
'signoz/PieChartPanel': [
|
||||
QUERY_BUILDER,
|
||||
CLICKHOUSE,
|
||||
@@ -78,6 +83,7 @@ const EXPECTED_SIGNALS: Record<PanelKind, TelemetrytypesSignalDTO[]> = {
|
||||
'signoz/NumberPanel': [metrics, logs, traces],
|
||||
'signoz/HistogramPanel': [metrics, logs, traces],
|
||||
'signoz/HeatmapPanel': [metrics, logs, traces],
|
||||
'signoz/DistributionPanel': [metrics, logs, traces],
|
||||
'signoz/PieChartPanel': [metrics, logs, traces],
|
||||
'signoz/GeoMapPanel': [metrics, logs, traces],
|
||||
'signoz/TopListPanel': [metrics, logs, traces],
|
||||
@@ -133,6 +139,13 @@ const EXPECTED_QUERY_CAPABILITIES: Partial<
|
||||
orderTiebreaker: false,
|
||||
serverPaginated: false,
|
||||
},
|
||||
'signoz/DistributionPanel': {
|
||||
requestType: distribution,
|
||||
formatTableResultForUI: false,
|
||||
bucketedStepInterval: false,
|
||||
orderTiebreaker: false,
|
||||
serverPaginated: false,
|
||||
},
|
||||
'signoz/NumberPanel': {
|
||||
requestType: scalar,
|
||||
formatTableResultForUI: false,
|
||||
@@ -196,6 +209,7 @@ const HIDES_TRACE_OPERATOR: PanelKind[] = [
|
||||
'signoz/ScatterPlotPanel',
|
||||
'signoz/GeoMapPanel',
|
||||
'signoz/HeatmapPanel',
|
||||
'signoz/DistributionPanel',
|
||||
];
|
||||
|
||||
describe('panel capabilities guard', () => {
|
||||
@@ -218,6 +232,24 @@ describe('panel capabilities guard', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('formula', () => {
|
||||
it.each([
|
||||
[TelemetrytypesSignalDTO.metrics, false],
|
||||
[TelemetrytypesSignalDTO.logs, true],
|
||||
[TelemetrytypesSignalDTO.traces, true],
|
||||
])('a %s distribution hides it: %s', (signal, hidden) => {
|
||||
expect(
|
||||
resolveQueryBuilderField(
|
||||
QueryBuilderField.Formula,
|
||||
getQueryBuilderFields(
|
||||
requireQueryPanelDefinition('signoz/DistributionPanel'),
|
||||
signal,
|
||||
),
|
||||
).hidden,
|
||||
).toBe(hidden);
|
||||
});
|
||||
});
|
||||
|
||||
// A dashboard spec written by a newer SigNoz can name a kind this build has no
|
||||
// definition for. The registry answers with UNSUPPORTED_PANEL rather than nothing, so
|
||||
// every guard below reads it without first proving a definition exists.
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useCallback, useMemo, useRef } from 'react';
|
||||
import type { DashboardtypesDistributionPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import Distribution from 'lib/visualization/charts/Distribution/Distribution';
|
||||
import type { DistributionBarClick } from 'lib/visualization/charts/Distribution/types';
|
||||
import { IRenderTooltipFooterArgs } from 'lib/uPlotV2/components/types';
|
||||
import TooltipFooter from 'lib/visualization/panels/components/TooltipFooter';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useResizeObserver } from 'hooks/useDimensions';
|
||||
import { getDistributionResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
|
||||
|
||||
import NoData from '../../components/NoData/NoData';
|
||||
import PanelStyles from '../../panel.module.scss';
|
||||
import { PanelRendererProps } from '../../types/rendererProps';
|
||||
import {
|
||||
resolveDecimalPrecision,
|
||||
resolveDistributionPercentiles,
|
||||
resolveDistributionYScale,
|
||||
resolveLegendPosition,
|
||||
resolveStackMode,
|
||||
} from '../../utils/chartAppearance/resolvers';
|
||||
import { prepareDistributionClickData } from '../../utils/drilldown/prepareDistributionClickData';
|
||||
import { getBuilderQueries } from '../../utils/getBuilderQueries';
|
||||
import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
|
||||
|
||||
import { prepareDistributionData } from './prepareData';
|
||||
|
||||
function DistributionPanelRenderer({
|
||||
panelId,
|
||||
panel,
|
||||
data,
|
||||
isFetching,
|
||||
refetch,
|
||||
onClick,
|
||||
enableDrillDown,
|
||||
}: PanelRendererProps<'signoz/DistributionPanel'>): JSX.Element {
|
||||
const graphRef = useRef<HTMLDivElement>(null);
|
||||
const containerDimensions = useResizeObserver(graphRef);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
const spec = useMemo<DashboardtypesDistributionPanelSpecDTO>(
|
||||
() => panel.spec.plugin.spec,
|
||||
[panel.spec.plugin.spec],
|
||||
);
|
||||
|
||||
const { buckets, series, queryName } = useMemo(
|
||||
() =>
|
||||
prepareDistributionData({
|
||||
results: getDistributionResults(data.response),
|
||||
legendMap: data.legendMap ?? {},
|
||||
}),
|
||||
[data.response, data.legendMap],
|
||||
);
|
||||
|
||||
const percentiles = useMemo(
|
||||
() => resolveDistributionPercentiles(spec.chartAppearance?.percentiles),
|
||||
[spec.chartAppearance?.percentiles],
|
||||
);
|
||||
|
||||
const decimalPrecision = useMemo(
|
||||
() => resolveDecimalPrecision(spec.formatting?.decimalPrecision),
|
||||
[spec.formatting?.decimalPrecision],
|
||||
);
|
||||
|
||||
const builderQueries = useMemo(
|
||||
() => getBuilderQueries(panel.spec.queries),
|
||||
[panel.spec.queries],
|
||||
);
|
||||
|
||||
const handleBarClick = useCallback(
|
||||
(click: DistributionBarClick): void => {
|
||||
const payload = prepareDistributionClickData({
|
||||
click,
|
||||
queryName,
|
||||
builderQueries,
|
||||
timeRange: getPanelTimeRange(data.requestPayload),
|
||||
});
|
||||
if (payload) {
|
||||
onClick?.(payload);
|
||||
}
|
||||
},
|
||||
[onClick, queryName, builderQueries, data.requestPayload],
|
||||
);
|
||||
|
||||
const renderTooltipFooter = useCallback(
|
||||
({ isPinned, dismiss }: IRenderTooltipFooterArgs) => (
|
||||
<TooltipFooter
|
||||
id={panelId}
|
||||
isPinned={isPinned}
|
||||
canDrilldown={!!enableDrillDown}
|
||||
dismiss={dismiss}
|
||||
/>
|
||||
),
|
||||
[panelId, enableDrillDown],
|
||||
);
|
||||
|
||||
const hasBars = buckets.length > 0 && series.length > 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={graphRef}
|
||||
data-testid="distribution-panel-renderer"
|
||||
className={PanelStyles.panelContainer}
|
||||
>
|
||||
{!hasBars && (
|
||||
<NoData isFetching={isFetching} onRetry={refetch} panel={panel} />
|
||||
)}
|
||||
{hasBars &&
|
||||
containerDimensions.width > 0 &&
|
||||
containerDimensions.height > 0 && (
|
||||
<Distribution
|
||||
key={panelId}
|
||||
id={panelId}
|
||||
buckets={buckets}
|
||||
series={series}
|
||||
xMin={spec.axes?.x?.min ?? undefined}
|
||||
xMax={spec.axes?.x?.max ?? undefined}
|
||||
yScale={resolveDistributionYScale(spec.axes?.y?.scale)}
|
||||
stack={resolveStackMode(spec.visualization?.stack)}
|
||||
xAxisUnit={spec.formatting?.unit}
|
||||
decimalPrecision={decimalPrecision}
|
||||
customColors={spec.legend?.customColors ?? undefined}
|
||||
percentiles={percentiles}
|
||||
canPinTooltip
|
||||
renderTooltipFooter={renderTooltipFooter}
|
||||
onBarClick={enableDrillDown && onClick ? handleBarClick : undefined}
|
||||
legendPosition={resolveLegendPosition(spec.legend?.position)}
|
||||
isDarkMode={isDarkMode}
|
||||
width={containerDimensions.width}
|
||||
height={containerDimensions.height}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default DistributionPanelRenderer;
|
||||
@@ -0,0 +1,152 @@
|
||||
import type {
|
||||
Querybuildertypesv5DistributionDataDTO,
|
||||
Querybuildertypesv5DistributionDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { prepareDistributionData } from '../prepareData';
|
||||
|
||||
function result({
|
||||
queryName = 'A',
|
||||
buckets = [1, 2, 4],
|
||||
distributions = [],
|
||||
}: {
|
||||
queryName?: string;
|
||||
buckets?: number[];
|
||||
distributions?: Querybuildertypesv5DistributionDTO[];
|
||||
} = {}): Querybuildertypesv5DistributionDataDTO {
|
||||
return {
|
||||
queryName,
|
||||
aggregations: [
|
||||
{ alias: '__result_0', index: 0, meta: { buckets }, distributions },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe('prepareDistributionData', () => {
|
||||
it('reads the bucket bounds and one count array per group', () => {
|
||||
const { buckets, series, queryName } = prepareDistributionData({
|
||||
results: [
|
||||
result({
|
||||
distributions: [
|
||||
{
|
||||
labels: [{ key: { name: 'service' }, value: 'redis' }],
|
||||
counts: [5, 12, 3, 1],
|
||||
},
|
||||
{
|
||||
labels: [{ key: { name: 'service' }, value: 'cart' }],
|
||||
counts: [0, 4, 8, 0],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
legendMap: {},
|
||||
});
|
||||
|
||||
expect(buckets).toStrictEqual([1, 2, 4]);
|
||||
expect(queryName).toBe('A');
|
||||
expect(series).toStrictEqual([
|
||||
{
|
||||
label: '{service="redis"}',
|
||||
groupLabels: { service: 'redis' },
|
||||
counts: [5, 12, 3, 1],
|
||||
},
|
||||
{
|
||||
label: '{service="cart"}',
|
||||
groupLabels: { service: 'cart' },
|
||||
counts: [0, 4, 8, 0],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('names an ungrouped distribution after its query', () => {
|
||||
const { series } = prepareDistributionData({
|
||||
results: [result({ distributions: [{ counts: [1, 0, 0, 0] }] })],
|
||||
legendMap: { A: '' },
|
||||
});
|
||||
|
||||
expect(series).toHaveLength(1);
|
||||
expect(series[0].label).toBe('A');
|
||||
});
|
||||
|
||||
it('applies the query legend as the group label template', () => {
|
||||
const { series } = prepareDistributionData({
|
||||
results: [
|
||||
result({
|
||||
distributions: [
|
||||
{
|
||||
labels: [{ key: { name: 'service' }, value: 'redis' }],
|
||||
counts: [1, 0, 0, 0],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
legendMap: { A: '{{service}} latency' },
|
||||
});
|
||||
|
||||
expect(series[0].label).toBe('redis latency');
|
||||
});
|
||||
|
||||
it('pads missing counts with zero and trims extras, keeping the overflow slot', () => {
|
||||
const { series } = prepareDistributionData({
|
||||
results: [
|
||||
result({
|
||||
distributions: [
|
||||
{ counts: [1, 2] },
|
||||
{ counts: [1, 2, 3, 4, 5] },
|
||||
{ counts: null },
|
||||
],
|
||||
}),
|
||||
],
|
||||
legendMap: {},
|
||||
});
|
||||
|
||||
expect(series.map(({ counts }) => counts)).toStrictEqual([
|
||||
[1, 2, 0, 0],
|
||||
[1, 2, 3, 4],
|
||||
[0, 0, 0, 0],
|
||||
]);
|
||||
});
|
||||
|
||||
it('skips aggregations without bounds and reads the first that has them', () => {
|
||||
const { buckets } = prepareDistributionData({
|
||||
results: [
|
||||
{
|
||||
queryName: 'A',
|
||||
aggregations: [
|
||||
{
|
||||
alias: '__result_0',
|
||||
index: 0,
|
||||
meta: {},
|
||||
distributions: [{ counts: [1] }],
|
||||
},
|
||||
{
|
||||
alias: '__result_1',
|
||||
index: 1,
|
||||
meta: { buckets: [10, 20] },
|
||||
distributions: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
legendMap: {},
|
||||
});
|
||||
|
||||
expect(buckets).toStrictEqual([10, 20]);
|
||||
});
|
||||
|
||||
it('returns no buckets when nothing carries bounds', () => {
|
||||
expect(
|
||||
prepareDistributionData({
|
||||
results: [result({ buckets: [] })],
|
||||
legendMap: {},
|
||||
}),
|
||||
).toStrictEqual({ buckets: [], series: [], queryName: '' });
|
||||
expect(prepareDistributionData({ results: [], legendMap: {} })).toStrictEqual(
|
||||
{
|
||||
buckets: [],
|
||||
series: [],
|
||||
queryName: '',
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
DashboardtypesPanelKindDTO,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind as DistributionKind,
|
||||
type DashboardtypesDistributionPanelSpecDTO,
|
||||
type Querybuildertypesv5DistributionDataDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
|
||||
|
||||
import type { PanelOfKind } from '../../../types/rendererProps';
|
||||
import { getDistributionDataWarning } from '../warning';
|
||||
|
||||
function dataWith(buckets: number[], counts: number[][]): PanelQueryData {
|
||||
const result: Querybuildertypesv5DistributionDataDTO = {
|
||||
queryName: 'A',
|
||||
aggregations: [
|
||||
{
|
||||
alias: '__result_0',
|
||||
index: 0,
|
||||
meta: { buckets },
|
||||
distributions: counts.map((entry) => ({ counts: entry })),
|
||||
},
|
||||
],
|
||||
};
|
||||
return {
|
||||
response: {
|
||||
status: 'success',
|
||||
data: {
|
||||
type: Querybuildertypesv5RequestTypeDTO.distribution,
|
||||
data: { results: [result] },
|
||||
},
|
||||
},
|
||||
requestPayload: undefined,
|
||||
legendMap: {},
|
||||
};
|
||||
}
|
||||
|
||||
function panelWith(
|
||||
spec: Partial<DashboardtypesDistributionPanelSpecDTO> = {},
|
||||
): PanelOfKind<'signoz/DistributionPanel'> {
|
||||
return {
|
||||
kind: DashboardtypesPanelKindDTO.Panel,
|
||||
spec: {
|
||||
display: { name: '' },
|
||||
plugin: { kind: DistributionKind['signoz/DistributionPanel'], spec },
|
||||
queries: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('getDistributionDataWarning', () => {
|
||||
it('warns when more than 10% of observations overflow', () => {
|
||||
const warning = getDistributionDataWarning(
|
||||
panelWith({ formatting: { unit: 's' } }),
|
||||
dataWith([1, 10], [[10, 50, 40]]),
|
||||
);
|
||||
|
||||
expect(warning?.message).toMatch(/^40% of observations are above 10/);
|
||||
});
|
||||
|
||||
it('says nothing at or under 10%', () => {
|
||||
expect(
|
||||
getDistributionDataWarning(panelWith(), dataWith([1, 10], [[40, 50, 10]])),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('says nothing without bounds', () => {
|
||||
expect(getDistributionDataWarning(panelWith(), dataWith([], []))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { ChartColumnBig } from '@signozhq/icons';
|
||||
|
||||
import { QueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.types';
|
||||
|
||||
import type { PanelDefinition } from '../../types/panelDefinition';
|
||||
import { QueryTypeKind } from '../../types/panelCapabilities';
|
||||
import QueryBuilderEditorPane from 'pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/QueryBuilderEditorPane';
|
||||
import Renderer from './Renderer';
|
||||
import { sections } from './sections';
|
||||
import { getDistributionDataWarning } from './warning';
|
||||
import {
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
TelemetrytypesSignalDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export const definition: PanelDefinition<'signoz/DistributionPanel'> = {
|
||||
kind: 'signoz/DistributionPanel',
|
||||
displayName: 'Distribution',
|
||||
mode: 'query',
|
||||
icon: ChartColumnBig,
|
||||
Renderer,
|
||||
EditorPane: QueryBuilderEditorPane,
|
||||
sections,
|
||||
supportedQueryTypesKindMap: {
|
||||
// Logs and traces bucket the field named as the aggregation.
|
||||
[EQueryType.QUERY_BUILDER]: {
|
||||
kind: QueryTypeKind.SIGNAL,
|
||||
signals: [
|
||||
TelemetrytypesSignalDTO.metrics,
|
||||
TelemetrytypesSignalDTO.logs,
|
||||
TelemetrytypesSignalDTO.traces,
|
||||
],
|
||||
},
|
||||
[EQueryType.CLICKHOUSE]: { kind: QueryTypeKind.SIGNAL_LESS },
|
||||
[EQueryType.PROM]: { kind: QueryTypeKind.SIGNAL_LESS },
|
||||
},
|
||||
// The request rejects both, as for heatmap: a point is a count per bucket.
|
||||
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' },
|
||||
},
|
||||
// Logs and traces bucket the one field the query names; a formula has none.
|
||||
queryBuilderFieldsBySignal: {
|
||||
[TelemetrytypesSignalDTO.logs]: {
|
||||
[QueryBuilderField.Formula]: { state: 'hidden' },
|
||||
[QueryBuilderField.AdditionalQueries]: { state: 'hidden' },
|
||||
},
|
||||
[TelemetrytypesSignalDTO.traces]: {
|
||||
[QueryBuilderField.Formula]: { state: 'hidden' },
|
||||
[QueryBuilderField.AdditionalQueries]: { state: 'hidden' },
|
||||
},
|
||||
},
|
||||
// No width-derived step: there is no time axis, and a histogram's counts do not
|
||||
// depend on the step.
|
||||
queryCapabilities: {
|
||||
requestType: Querybuildertypesv5RequestTypeDTO.distribution,
|
||||
formatTableResultForUI: false,
|
||||
bucketedStepInterval: false,
|
||||
orderTiebreaker: false,
|
||||
serverPaginated: false,
|
||||
},
|
||||
getDataWarning: getDistributionDataWarning,
|
||||
actions: {
|
||||
view: true,
|
||||
edit: true,
|
||||
clone: true,
|
||||
download: { csv: false, png: true, svg: true },
|
||||
createAlert: false,
|
||||
search: false,
|
||||
drilldown: true,
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
import type {
|
||||
Querybuildertypesv5DistributionDataDTO,
|
||||
Querybuildertypesv5DistributionDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import getLabelName from 'lib/getLabelName';
|
||||
import type { DistributionSeries } from 'lib/visualization/charts/Distribution/types';
|
||||
|
||||
export interface DistributionPanelData {
|
||||
/** Ascending bucket upper bounds shared by every group; empty means no chart. */
|
||||
buckets: number[];
|
||||
series: DistributionSeries[];
|
||||
/** The query the series came from, for drilldown. */
|
||||
queryName: string;
|
||||
}
|
||||
|
||||
const EMPTY_DATA: DistributionPanelData = {
|
||||
buckets: [],
|
||||
series: [],
|
||||
queryName: '',
|
||||
};
|
||||
|
||||
/**
|
||||
* V5 distribution results → the chart's `buckets` + `series`. Only the first
|
||||
* aggregation carrying bounds is read: each has its own bucket axis, and the chart
|
||||
* has one.
|
||||
*/
|
||||
export function prepareDistributionData({
|
||||
results,
|
||||
legendMap,
|
||||
}: {
|
||||
results: Querybuildertypesv5DistributionDataDTO[];
|
||||
legendMap: Record<string, string>;
|
||||
}): DistributionPanelData {
|
||||
for (const result of results) {
|
||||
const { queryName } = result;
|
||||
for (const aggregation of result.aggregations ?? []) {
|
||||
const buckets = aggregation.meta?.buckets;
|
||||
if (!buckets?.length) {
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
buckets,
|
||||
queryName,
|
||||
series: (aggregation.distributions ?? []).map((distribution) =>
|
||||
toDistributionSeries(
|
||||
distribution,
|
||||
buckets.length + 1,
|
||||
queryName,
|
||||
legendMap[queryName] ?? '',
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return EMPTY_DATA;
|
||||
}
|
||||
|
||||
/** Pads or trims to `length` so every series lines up with the bucket axis. */
|
||||
function toDistributionSeries(
|
||||
distribution: Querybuildertypesv5DistributionDTO,
|
||||
length: number,
|
||||
queryName: string,
|
||||
legend: string,
|
||||
): DistributionSeries {
|
||||
const record: Record<string, string> = {};
|
||||
(distribution.labels ?? []).forEach((label) => {
|
||||
if (label.key?.name) {
|
||||
record[label.key.name] = String(label.value);
|
||||
}
|
||||
});
|
||||
|
||||
const counts = distribution.counts ?? [];
|
||||
return {
|
||||
label: getLabelName(record, queryName, legend),
|
||||
groupLabels: record,
|
||||
counts: Array.from({ length }, (_, index) => {
|
||||
const count = counts[index];
|
||||
return Number.isFinite(count) ? count : 0;
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { SectionKind, type SectionConfig } from '../../types/sections';
|
||||
import { resolveDistributionLegendSeries } from '../../utils/legendSeries';
|
||||
|
||||
export const sections: SectionConfig[] = [
|
||||
{
|
||||
kind: SectionKind.Visualization,
|
||||
controls: { switchPanelKind: true, timePreference: true, bucketStack: true },
|
||||
},
|
||||
{
|
||||
kind: SectionKind.ChartAppearance,
|
||||
controls: { percentiles: true },
|
||||
},
|
||||
// Formats the bucket bounds; counts are plain integers and take no unit.
|
||||
{ kind: SectionKind.Formatting, controls: { unit: true, decimals: true } },
|
||||
{ kind: SectionKind.DistributionAxes },
|
||||
{
|
||||
kind: SectionKind.Legend,
|
||||
controls: { position: true, colors: resolveDistributionLegendSeries },
|
||||
},
|
||||
{ kind: SectionKind.ContextLinks },
|
||||
];
|
||||
@@ -0,0 +1,48 @@
|
||||
import { getToolTipValue } from 'components/Graph/yAxisConfig';
|
||||
import type { PanelStatusDetail } from 'pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/types';
|
||||
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
|
||||
import { getDistributionResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
|
||||
|
||||
import type { PanelOfKind } from '../../types/rendererProps';
|
||||
import { prepareDistributionData } from './prepareData';
|
||||
|
||||
/** Above this share in overflow, the bucket bounds probably stop short. */
|
||||
export const OVERFLOW_WARNING_SHARE = 0.1;
|
||||
|
||||
/**
|
||||
* Bounds that stop short, over every group regardless of the legend: too much
|
||||
* landing in overflow.
|
||||
*/
|
||||
export function getDistributionDataWarning(
|
||||
panel: PanelOfKind<'signoz/DistributionPanel'>,
|
||||
data: PanelQueryData,
|
||||
): PanelStatusDetail | null {
|
||||
const { buckets, series } = prepareDistributionData({
|
||||
results: getDistributionResults(data.response),
|
||||
legendMap: data.legendMap ?? {},
|
||||
});
|
||||
if (buckets.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const spec = panel.spec.plugin.spec;
|
||||
const lastBound = buckets[buckets.length - 1];
|
||||
let total = 0;
|
||||
let overflow = 0;
|
||||
series.forEach(({ counts }) => {
|
||||
counts.forEach((count) => {
|
||||
total += count;
|
||||
});
|
||||
overflow += counts[buckets.length] ?? 0;
|
||||
});
|
||||
|
||||
const overflowShare = total > 0 ? overflow / total : 0;
|
||||
if (overflowShare <= OVERFLOW_WARNING_SHARE) {
|
||||
return null;
|
||||
}
|
||||
const bound = getToolTipValue(String(lastBound), spec.formatting?.unit);
|
||||
return {
|
||||
message: `${Math.round(overflowShare * 100)}% of observations are above ${bound}. The bucket bounds may be too low.`,
|
||||
messages: [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
.banner {
|
||||
margin: var(--spacing-4) var(--spacing-6) 0;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { SolidInfoCircle } from '@signozhq/icons';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
|
||||
import type { QueryEditorPaneProps } from '../../types/panelDefinition';
|
||||
import PanelEditorQueryBuilder from '../../../PanelEditor/PanelEditorQueryBuilder/PanelEditorQueryBuilder';
|
||||
|
||||
import styles from './HistogramEditorPane.module.scss';
|
||||
|
||||
/**
|
||||
* Histogram bins the query's values in the browser: percentiles or rates of a
|
||||
* histogram metric, or per-interval aggregates of logs and traces, not the bucket
|
||||
* counts Distribution reads.
|
||||
*/
|
||||
function HistogramEditorPane({
|
||||
panelDefinition,
|
||||
isLoadingQueries,
|
||||
onStageRunQuery,
|
||||
onCancelQuery,
|
||||
stickyHeader,
|
||||
}: QueryEditorPaneProps): JSX.Element {
|
||||
return (
|
||||
<PanelEditorQueryBuilder
|
||||
panelDefinition={panelDefinition}
|
||||
isLoadingQueries={isLoadingQueries}
|
||||
onStageRunQuery={onStageRunQuery}
|
||||
onCancelQuery={onCancelQuery}
|
||||
stickyHeader={stickyHeader}
|
||||
banner={
|
||||
<div className={styles.banner}>
|
||||
<Callout
|
||||
color="primary"
|
||||
size="sm"
|
||||
icon={<SolidInfoCircle />}
|
||||
testId="histogram-distribution-banner"
|
||||
>
|
||||
For bucket counts over the time range, use the Distribution panel.
|
||||
</Callout>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default HistogramEditorPane;
|
||||
@@ -3,7 +3,7 @@ import { BarChart } from '@signozhq/icons';
|
||||
|
||||
import type { PanelDefinition } from '../../types/panelDefinition';
|
||||
import { QueryTypeKind } from '../../types/panelCapabilities';
|
||||
import QueryBuilderEditorPane from 'pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/QueryBuilderEditorPane';
|
||||
import HistogramEditorPane from './HistogramEditorPane';
|
||||
import Renderer from './Renderer';
|
||||
import { sections } from './sections';
|
||||
import {
|
||||
@@ -16,8 +16,9 @@ export const definition: PanelDefinition<'signoz/HistogramPanel'> = {
|
||||
displayName: 'Histogram',
|
||||
mode: 'query',
|
||||
icon: BarChart,
|
||||
isRetired: true,
|
||||
Renderer,
|
||||
EditorPane: QueryBuilderEditorPane,
|
||||
EditorPane: HistogramEditorPane,
|
||||
sections,
|
||||
supportedQueryTypesKindMap: {
|
||||
[EQueryType.QUERY_BUILDER]: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { definition as AreaChart } from './kinds/AreaChartPanel/definition';
|
||||
import { definition as BarChart } from './kinds/BarChartPanel/definition';
|
||||
import { definition as Distribution } from './kinds/DistributionPanel/definition';
|
||||
import { definition as Heatmap } from './kinds/HeatmapPanel/definition';
|
||||
import { definition as Histogram } from './kinds/HistogramPanel/definition';
|
||||
import { definition as NumberValue } from './kinds/NumberPanel/definition';
|
||||
@@ -33,13 +34,14 @@ export const PANELS: PanelRegistry = {
|
||||
[TopList.kind]: TopList,
|
||||
[Histogram.kind]: Histogram,
|
||||
[Heatmap.kind]: Heatmap,
|
||||
[Distribution.kind]: Distribution,
|
||||
[List.kind]: List,
|
||||
[Text.kind]: Text,
|
||||
};
|
||||
|
||||
export type PanelOption = Pick<
|
||||
PanelDefinition,
|
||||
'kind' | 'displayName' | 'icon'
|
||||
'kind' | 'displayName' | 'icon' | 'isRetired'
|
||||
>;
|
||||
|
||||
// Backs both the new-panel picker and the editor's kind switcher; derived from PANELS
|
||||
|
||||
@@ -37,6 +37,9 @@ export type PanelInteractionMap = Record<PanelKind, object> & {
|
||||
'signoz/HeatmapPanel': { onDragSelect?: DragSelect };
|
||||
'signoz/TablePanel': { onClick?: (event: DrilldownClickPayload) => void };
|
||||
'signoz/PieChartPanel': { onClick?: (event: DrilldownClickPayload) => void };
|
||||
'signoz/DistributionPanel': {
|
||||
onClick?: (event: DrilldownClickPayload) => void;
|
||||
};
|
||||
'signoz/TopListPanel': { onClick?: (event: DrilldownClickPayload) => void };
|
||||
'signoz/NumberPanel': { onClick?: (event: DrilldownClickPayload) => void };
|
||||
'signoz/ScatterPlotPanel': {
|
||||
|
||||
@@ -4,7 +4,32 @@ import {
|
||||
type TelemetrytypesSignalDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export type { QueryBuilderFieldsConfig } from 'components/QueryBuilderV2/queryBuilderFields.types';
|
||||
import type { QueryBuilderFieldsConfig } from 'components/QueryBuilderV2/queryBuilderFields.types';
|
||||
import { mergeQueryBuilderFieldsConfig } from 'components/QueryBuilderV2/queryBuilderFields.utils';
|
||||
|
||||
export type { QueryBuilderFieldsConfig };
|
||||
|
||||
/** Narrowing applied over a kind's `queryBuilderFields` while the builder points at that signal. */
|
||||
export type QueryBuilderFieldsBySignal = Partial<
|
||||
Record<TelemetrytypesSignalDTO, QueryBuilderFieldsConfig>
|
||||
>;
|
||||
|
||||
/** A kind's builder narrowing with its `signal` overrides on top. */
|
||||
export function getQueryBuilderFields(
|
||||
{
|
||||
queryBuilderFields,
|
||||
queryBuilderFieldsBySignal,
|
||||
}: {
|
||||
queryBuilderFields: QueryBuilderFieldsConfig;
|
||||
queryBuilderFieldsBySignal?: QueryBuilderFieldsBySignal;
|
||||
},
|
||||
signal?: TelemetrytypesSignalDTO,
|
||||
): QueryBuilderFieldsConfig | undefined {
|
||||
return mergeQueryBuilderFieldsConfig(
|
||||
queryBuilderFields,
|
||||
signal ? queryBuilderFieldsBySignal?.[signal] : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How a kind's query-range request is shaped. Declared per-kind in
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { PanelKind } from './panelKind';
|
||||
import type { SyncedQueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.types';
|
||||
import type {
|
||||
PanelQueryCapabilities,
|
||||
QueryBuilderFieldsBySignal,
|
||||
QueryBuilderFieldsConfig,
|
||||
SupportedQueryTypesKindMap,
|
||||
} from './panelCapabilities';
|
||||
@@ -80,6 +81,8 @@ export interface PanelDefinitionBase<K extends PanelKind = PanelKind> {
|
||||
kind: K;
|
||||
displayName: string;
|
||||
icon: PanelIcon;
|
||||
/** Still renders saved panels, but is offered only to a panel already of this kind. */
|
||||
isRetired?: boolean;
|
||||
sections: SectionConfig[];
|
||||
actions: PanelActionCapabilities;
|
||||
}
|
||||
@@ -128,6 +131,7 @@ export interface QueryPanelDefinition<
|
||||
/** Authoring modes (Query Builder / ClickHouse / PromQL / AI) and the signals each accepts. */
|
||||
supportedQueryTypesKindMap: SupportedQueryTypesKindMap;
|
||||
queryBuilderFields: QueryBuilderFieldsConfig;
|
||||
queryBuilderFieldsBySignal?: QueryBuilderFieldsBySignal;
|
||||
/** How this kind's query-range request is shaped (request type, paging, result formatting). */
|
||||
queryCapabilities: PanelQueryCapabilities;
|
||||
/** Builder fields kept equal across queries: an edit to one query copies to the rest. */
|
||||
|
||||
@@ -29,6 +29,7 @@ export const PANEL_KIND_TO_PANEL_TYPE: Record<PanelKind, PANEL_TYPES> = {
|
||||
'signoz/TopListPanel': PANEL_TYPES.TOP_LIST,
|
||||
'signoz/TextPanel': PANEL_TYPES.TEXT,
|
||||
'signoz/ScatterPlotPanel': PANEL_TYPES.SCATTER,
|
||||
'signoz/DistributionPanel': PANEL_TYPES.DISTRIBUTION,
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,8 @@ import type {
|
||||
DashboardtypesLinkDTO,
|
||||
DashboardtypesAxesDTO,
|
||||
DashboardtypesComparisonThresholdDTO,
|
||||
DashboardtypesDistributionAxesDTO,
|
||||
DashboardtypesDistributionPercentilesDTO,
|
||||
DashboardtypesFillModeDTO,
|
||||
DashboardtypesFillOpacityDTO,
|
||||
DashboardtypesGeoMapBubblesDTO,
|
||||
@@ -78,6 +80,8 @@ export enum SectionKind {
|
||||
Dimensions = 'dimensions',
|
||||
/** Scatter Plot's per-axis `axes` shape; `Axes` is the single y-axis shape. */
|
||||
ScatterAxes = 'scatterAxes',
|
||||
/** Distribution's `axes` shape: the bucket-axis range and count-axis scale. */
|
||||
DistributionAxes = 'distributionAxes',
|
||||
/** Geo Map's placement: what a row is, its columns, the area, the layer and the value columns. */
|
||||
Location = 'location',
|
||||
/** Top List's row display, for a kind with no chart to style. */
|
||||
@@ -129,6 +133,8 @@ export interface PanelChartAppearanceSlice {
|
||||
colors?: DashboardtypesHeatmapColorsDTO & DashboardtypesGeoMapColorsDTO;
|
||||
/** Scatter Plot's dot size and opacity. */
|
||||
points?: DashboardtypesScatterPlotPointsDTO;
|
||||
/** Distribution's percentile markers. */
|
||||
percentiles?: DashboardtypesDistributionPercentilesDTO;
|
||||
/** Geo Map's circle radius range. */
|
||||
bubbles?: DashboardtypesGeoMapBubblesDTO;
|
||||
/** Geo Map's shape names; unset shows them. */
|
||||
@@ -146,7 +152,7 @@ export interface PanelVisualizationSlice {
|
||||
timePreference?: DashboardtypesTimePreferenceDTO;
|
||||
/** Bar stacking; a kind declares this or `stack`, never both. */
|
||||
stackedBarChart?: boolean;
|
||||
/** Area stacking. */
|
||||
/** Area or Distribution stacking; Distribution's wire enum is nominally distinct with the same members. */
|
||||
stack?: DashboardtypesStackModeDTO;
|
||||
fillSpans?: boolean;
|
||||
}
|
||||
@@ -171,6 +177,7 @@ export interface SectionSpecMap {
|
||||
[SectionKind.PanelHeader]: DashboardtypesHeaderOptionsDTO; // spec.plugin.spec.headerOptions (Text)
|
||||
[SectionKind.Dimensions]: DashboardtypesScatterPlotDimensionsDTO; // spec.plugin.spec.dimensions (Scatter Plot)
|
||||
[SectionKind.ScatterAxes]: DashboardtypesScatterPlotAxesDTO; // spec.plugin.spec.axes (Scatter Plot)
|
||||
[SectionKind.DistributionAxes]: DashboardtypesDistributionAxesDTO; // spec.plugin.spec.axes (Distribution)
|
||||
[SectionKind.Location]: GeoMapPlacementSlice; // spec.plugin.spec.location + .map (Geo Map)
|
||||
[SectionKind.Appearance]: DashboardtypesTopListAppearanceDTO; // spec.plugin.spec.appearance (Top List)
|
||||
}
|
||||
@@ -213,6 +220,8 @@ export interface SectionControls {
|
||||
colors?: boolean;
|
||||
/** Scatter Plot's dots: one size, or a min/max range when a size column is bound. */
|
||||
points?: boolean;
|
||||
/** Distribution's percentile markers: on/off and which ones. */
|
||||
percentiles?: boolean;
|
||||
/** Geo Map's value ramp: palette, scale, steps and a value range. */
|
||||
mapColors?: boolean;
|
||||
/** Geo Map's circle radius range. */
|
||||
@@ -227,12 +236,14 @@ export interface SectionControls {
|
||||
};
|
||||
// switchPanelKind → the visualization-type switcher (every kind, so you can switch
|
||||
// away from any panel); stacking → stackedBarChart (Bar); stackMode → stack
|
||||
// (Area); fillSpans → fill gaps with 0 (TimeSeries / Area).
|
||||
// (Area); bucketStack → stack (Distribution); fillSpans → fill gaps with 0
|
||||
// (TimeSeries / Area).
|
||||
[SectionKind.Visualization]: {
|
||||
switchPanelKind: boolean;
|
||||
timePreference?: boolean;
|
||||
stacking?: boolean;
|
||||
stackMode?: boolean;
|
||||
bucketStack?: boolean;
|
||||
fillSpans?: boolean;
|
||||
};
|
||||
// Editor discriminator (not a spec field): which threshold variant a kind edits.
|
||||
@@ -255,6 +266,7 @@ export type AtomicSectionKind =
|
||||
| SectionKind.PanelHeader
|
||||
| SectionKind.Dimensions
|
||||
| SectionKind.ScatterAxes
|
||||
| SectionKind.DistributionAxes
|
||||
| SectionKind.Location;
|
||||
|
||||
/** Predicate to hide a section from the current spec; returning true removes it. */
|
||||
@@ -292,6 +304,7 @@ export const SECTION_METADATA = {
|
||||
[SectionKind.PanelHeader]: { title: 'Panel header', icon: PanelTop },
|
||||
[SectionKind.Dimensions]: { title: 'Dimensions', icon: Crosshair },
|
||||
[SectionKind.ScatterAxes]: { title: 'Axes', icon: Scale3D },
|
||||
[SectionKind.DistributionAxes]: { title: 'Axes', icon: Scale3D },
|
||||
[SectionKind.Location]: { title: 'Location', icon: MapPin },
|
||||
[SectionKind.Appearance]: { title: 'Appearance', icon: Palette },
|
||||
} as const satisfies Record<SectionKind, SectionMetadata>;
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { DEFAULT_BAR_COLOR } from '../../../PanelEditor/ConfigPane/sections/AppearanceSection/barColorOptions';
|
||||
import { defaultColumnsForSignal } from '../../../PanelEditor/ListColumnsEditor/selectFields';
|
||||
import { sections as areaSections } from '../../kinds/AreaChartPanel/sections';
|
||||
import { sections as distributionSections } from '../../kinds/DistributionPanel/sections';
|
||||
import { sections as geoMapSections } from '../../kinds/GeoMapPanel/sections';
|
||||
import { sections as heatmapSections } from '../../kinds/HeatmapPanel/sections';
|
||||
import { sections as listSections } from '../../kinds/ListPanel/sections';
|
||||
@@ -371,6 +372,25 @@ describe('buildPluginSpec', () => {
|
||||
});
|
||||
|
||||
describe('chartAppearance seed', () => {
|
||||
it('seeds a new distribution with the stack and percentiles the server writes', () => {
|
||||
const spec = buildPluginSpec(distributionSections);
|
||||
|
||||
expect(spec.visualization?.stack).toBe(DashboardtypesStackModeDTO.normal);
|
||||
expect(spec.chartAppearance?.percentiles).toStrictEqual({
|
||||
enabled: true,
|
||||
values: [50, 90, 99],
|
||||
});
|
||||
});
|
||||
|
||||
it("carries a distribution's percentiles across a switch", () => {
|
||||
const percentiles = { enabled: false, values: [75] };
|
||||
const spec = buildPluginSpec(distributionSections, {
|
||||
oldSpec: oldSpecWith({ chartAppearance: { percentiles } }),
|
||||
});
|
||||
|
||||
expect(spec.chartAppearance?.percentiles).toStrictEqual(percentiles);
|
||||
});
|
||||
|
||||
it('seeds only the declared defaulting controls', () => {
|
||||
const sections: SectionConfig[] = [
|
||||
{
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import {
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind as DistributionKind,
|
||||
type DashboardtypesPanelSpecDTO,
|
||||
type Querybuildertypesv5DistributionDataDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { resolveSeriesColor } from 'lib/visualization/charts/Distribution/colors';
|
||||
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
|
||||
|
||||
import { resolveDistributionLegendSeries } from '../legendSeries';
|
||||
|
||||
describe('resolveDistributionLegendSeries', () => {
|
||||
it('keys each group by the label and default colour the chart draws it with', () => {
|
||||
const result: Querybuildertypesv5DistributionDataDTO = {
|
||||
queryName: 'A',
|
||||
aggregations: [
|
||||
{
|
||||
alias: '__result_0',
|
||||
index: 0,
|
||||
meta: { buckets: [1] },
|
||||
distributions: [
|
||||
{
|
||||
labels: [{ key: { name: 'service' }, value: 'cart' }],
|
||||
counts: [1, 2],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const data: PanelQueryData = {
|
||||
response: {
|
||||
status: 'success',
|
||||
data: {
|
||||
type: Querybuildertypesv5RequestTypeDTO.distribution,
|
||||
data: { results: [result] },
|
||||
},
|
||||
},
|
||||
requestPayload: undefined,
|
||||
legendMap: { A: '{{service}}' },
|
||||
};
|
||||
const spec: DashboardtypesPanelSpecDTO = {
|
||||
display: { name: '' },
|
||||
plugin: { kind: DistributionKind['signoz/DistributionPanel'], spec: {} },
|
||||
queries: [],
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveDistributionLegendSeries({
|
||||
spec,
|
||||
queries: [],
|
||||
data,
|
||||
isDarkMode: true,
|
||||
}),
|
||||
).toStrictEqual([
|
||||
{ label: 'cart', defaultColor: resolveSeriesColor('cart', true) },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,9 @@ import {
|
||||
import { DEFAULT_BAR_COLOR } from '../../PanelEditor/ConfigPane/sections/AppearanceSection/barColorOptions';
|
||||
import { getTableColumnKeys } from './getTableColumnKeys';
|
||||
|
||||
/** Matches what the server writes for unset `chartAppearance.percentiles.values`. */
|
||||
const DEFAULT_DISTRIBUTION_PERCENTILES = [50, 90, 99];
|
||||
|
||||
/** Cross-section of the per-kind spec union; assigned to `plugin.spec` (unknown) at the boundary. */
|
||||
export interface SeededPluginSpec {
|
||||
visualization?: SectionSpecMap[SectionKind.Visualization];
|
||||
@@ -157,7 +160,7 @@ function translateStackingForKind(
|
||||
}
|
||||
return {};
|
||||
}
|
||||
if (controls.stackMode) {
|
||||
if (controls.stackMode || controls.bucketStack) {
|
||||
if (old?.stack !== undefined) {
|
||||
return { stack: old.stack };
|
||||
}
|
||||
@@ -326,6 +329,7 @@ const SECTION_SEEDS: SectionSeeds = {
|
||||
colors,
|
||||
bubbles,
|
||||
labels,
|
||||
percentiles,
|
||||
} = oldPluginSpec?.chartAppearance ?? {};
|
||||
const appearance: SectionSpecMap[SectionKind.ChartAppearance] = {};
|
||||
if (controls.lineStyle) {
|
||||
@@ -352,6 +356,13 @@ const SECTION_SEEDS: SectionSeeds = {
|
||||
if (controls.spanGaps && spanGaps !== undefined) {
|
||||
appearance.spanGaps = spanGaps;
|
||||
}
|
||||
// The server's default for unset percentiles, so a new panel previews the same.
|
||||
if (controls.percentiles) {
|
||||
appearance.percentiles = percentiles ?? {
|
||||
enabled: true,
|
||||
values: DEFAULT_DISTRIBUTION_PERCENTILES,
|
||||
};
|
||||
}
|
||||
// Seeded so the controls open on the ramp the grid is drawn with; the
|
||||
// count bounds and step count stay unset, which reads as derived.
|
||||
const seededColors = seedColors(controls, colors);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
DashboardtypesAreaFillModeDTO,
|
||||
DashboardtypesDistributionYScaleDTO,
|
||||
DashboardtypesHeatmapColorModeDTO,
|
||||
DashboardtypesHeatmapColorScaleDTO,
|
||||
DashboardtypesHeatmapPaletteDTO,
|
||||
@@ -15,9 +16,12 @@ import {
|
||||
ColorRampPalette,
|
||||
ColorRampScale,
|
||||
} from 'lib/visualization/colorRamp/types';
|
||||
import { DistributionYScale } from 'lib/visualization/charts/Distribution/types';
|
||||
|
||||
import {
|
||||
resolveAreaFillMode,
|
||||
resolveDistributionPercentiles,
|
||||
resolveDistributionYScale,
|
||||
resolveHeatmapAxisScale,
|
||||
resolveHeatmapColors,
|
||||
resolveSpanGaps,
|
||||
@@ -190,3 +194,27 @@ describe('resolveHeatmapColors', () => {
|
||||
expect(resolveHeatmapColors({ steps: 0 })).toStrictEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveDistributionYScale', () => {
|
||||
it('defaults to linear', () => {
|
||||
expect(resolveDistributionYScale(undefined)).toBe(DistributionYScale.Linear);
|
||||
expect(
|
||||
resolveDistributionYScale(DashboardtypesDistributionYScaleDTO.log),
|
||||
).toBe(DistributionYScale.Log);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveDistributionPercentiles', () => {
|
||||
it('marks nothing without percentiles; the server always writes them', () => {
|
||||
expect(resolveDistributionPercentiles(undefined)).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('marks the configured percentiles, or none when turned off', () => {
|
||||
expect(
|
||||
resolveDistributionPercentiles({ enabled: true, values: [75, 99.9] }),
|
||||
).toStrictEqual([75, 99.9]);
|
||||
expect(
|
||||
resolveDistributionPercentiles({ enabled: false, values: [75] }),
|
||||
).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
DashboardtypesAreaFillModeDTO,
|
||||
DashboardtypesDistributionYScaleDTO,
|
||||
DashboardtypesFillModeDTO,
|
||||
DashboardtypesHeatmapColorModeDTO,
|
||||
DashboardtypesHeatmapColorScaleDTO,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
ColorRampPalette,
|
||||
ColorRampScale,
|
||||
} from 'lib/visualization/colorRamp/types';
|
||||
import { DistributionYScale } from 'lib/visualization/charts/Distribution/types';
|
||||
|
||||
/**
|
||||
* Bridges the V2 wire-format enums to the uPlotV2 chart enums. String values
|
||||
@@ -58,7 +60,11 @@ export const AREA_FILL_MODE_MAP: Record<
|
||||
FillMode
|
||||
> = omit(FILL_MODE_MAP, DashboardtypesFillModeDTO.none);
|
||||
|
||||
export const STACK_MODE_MAP: Record<DashboardtypesStackModeDTO, StackMode> = {
|
||||
// Keyed by the wire strings, so Distribution's same-valued enum resolves through it too.
|
||||
export const STACK_MODE_MAP: Record<
|
||||
`${DashboardtypesStackModeDTO}`,
|
||||
StackMode
|
||||
> = {
|
||||
[DashboardtypesStackModeDTO.none]: StackMode.None,
|
||||
[DashboardtypesStackModeDTO.normal]: StackMode.Normal,
|
||||
[DashboardtypesStackModeDTO.percent]: StackMode.Percent,
|
||||
@@ -114,3 +120,11 @@ export const HEATMAP_Y_SCALE_MAP: Record<
|
||||
[DashboardtypesHeatmapYScaleDTO.log]: HeatmapAxisScale.Log,
|
||||
[DashboardtypesHeatmapYScaleDTO.symlog]: HeatmapAxisScale.Symlog,
|
||||
};
|
||||
|
||||
export const DISTRIBUTION_Y_SCALE_MAP: Record<
|
||||
DashboardtypesDistributionYScaleDTO,
|
||||
DistributionYScale
|
||||
> = {
|
||||
[DashboardtypesDistributionYScaleDTO.linear]: DistributionYScale.Linear,
|
||||
[DashboardtypesDistributionYScaleDTO.log]: DistributionYScale.Log,
|
||||
};
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { rangeUtil } from '@grafana/data';
|
||||
import {
|
||||
type DashboardtypesAreaFillModeDTO,
|
||||
type DashboardtypesDistributionPercentilesDTO,
|
||||
type DashboardtypesDistributionStackModeDTO,
|
||||
type DashboardtypesDistributionYScaleDTO,
|
||||
DashboardtypesHeatmapYScaleDTO,
|
||||
DashboardtypesLegendPositionDTO,
|
||||
DashboardtypesPrecisionOptionDTO,
|
||||
@@ -16,9 +19,11 @@ import { FillMode, StackMode } from 'lib/uPlotV2/config/types';
|
||||
import { clampColorSteps } from 'lib/visualization/colorRamp/colorScale';
|
||||
import { HeatmapAxisScale } from 'lib/uPlotV2/plugins/HeatmapPlugin/types';
|
||||
import type { ColorRampOptions } from 'lib/visualization/colorRamp/types';
|
||||
import { DistributionYScale } from 'lib/visualization/charts/Distribution/types';
|
||||
|
||||
import {
|
||||
AREA_FILL_MODE_MAP,
|
||||
DISTRIBUTION_Y_SCALE_MAP,
|
||||
HEATMAP_COLOR_MODE_MAP,
|
||||
HEATMAP_COLOR_SCALE_MAP,
|
||||
HEATMAP_PALETTE_MAP,
|
||||
@@ -96,7 +101,10 @@ export function resolveAreaFillMode(
|
||||
|
||||
/** Missing/unknown falls back to `None` — series drawn independently. */
|
||||
export function resolveStackMode(
|
||||
stack: DashboardtypesStackModeDTO | undefined,
|
||||
stack:
|
||||
| DashboardtypesStackModeDTO
|
||||
| DashboardtypesDistributionStackModeDTO
|
||||
| undefined,
|
||||
): StackMode {
|
||||
if (stack && stack in STACK_MODE_MAP) {
|
||||
return STACK_MODE_MAP[stack];
|
||||
@@ -104,6 +112,23 @@ export function resolveStackMode(
|
||||
return StackMode.None;
|
||||
}
|
||||
|
||||
export function resolveDistributionPercentiles(
|
||||
percentiles: DashboardtypesDistributionPercentilesDTO | undefined,
|
||||
): number[] {
|
||||
if (percentiles?.enabled === false) {
|
||||
return [];
|
||||
}
|
||||
return percentiles?.values ?? [];
|
||||
}
|
||||
|
||||
export function resolveDistributionYScale(
|
||||
scale: DashboardtypesDistributionYScaleDTO | undefined,
|
||||
): DistributionYScale {
|
||||
return scale && scale in DISTRIBUTION_Y_SCALE_MAP
|
||||
? DISTRIBUTION_Y_SCALE_MAP[scale]
|
||||
: DistributionYScale.Linear;
|
||||
}
|
||||
|
||||
/**
|
||||
* Row-height distribution of a heatmap's bucket axis. Missing/unknown resolves to
|
||||
* `auto`, the one option that reads the bucket bounds rather than overriding them.
|
||||
|
||||
@@ -11,6 +11,7 @@ import { buildAggregateData } from '../buildAggregateData';
|
||||
import { stepClickTimeRange } from '../chartClickTimeRange';
|
||||
import { enrichChartClick } from '../enrichChartClick';
|
||||
import { enrichNumberClick } from '../enrichNumberClick';
|
||||
import { prepareDistributionClickData } from '../prepareDistributionClickData';
|
||||
import { enrichPieClick } from '../enrichPieClick';
|
||||
import { enrichTableClick } from '../enrichTableClick';
|
||||
import { getDataLinks } from '../getDataLinks';
|
||||
@@ -416,6 +417,53 @@ describe('enrichPieClick', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('prepareDistributionClickData', () => {
|
||||
const click = {
|
||||
series: {
|
||||
label: 'cart',
|
||||
groupLabels: { 'service.name': 'cart' },
|
||||
counts: [1, 2],
|
||||
},
|
||||
color: '#abc',
|
||||
coordinates: { x: 7, y: 8 },
|
||||
};
|
||||
|
||||
it("filters to the clicked group over the panel's whole window", () => {
|
||||
const payload = prepareDistributionClickData({
|
||||
click,
|
||||
queryName: 'A',
|
||||
builderQueries: [
|
||||
builderQuery({
|
||||
name: 'A',
|
||||
signal: 'metrics',
|
||||
groupBy: [{ name: 'service.name' }],
|
||||
}),
|
||||
],
|
||||
timeRange: { startTime: 1, endTime: 2 },
|
||||
});
|
||||
|
||||
expect(payload).toStrictEqual({
|
||||
coordinates: { x: 7, y: 8 },
|
||||
context: {
|
||||
queryName: 'A',
|
||||
signal: 'metrics',
|
||||
filters: [
|
||||
{ filterKey: 'service.name', filterValue: 'cart', operator: '=' },
|
||||
],
|
||||
timeRange: { startTime: 1, endTime: 2 },
|
||||
label: 'cart',
|
||||
seriesColor: '#abc',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null without a drillable query', () => {
|
||||
expect(
|
||||
prepareDistributionClickData({ click, queryName: '', builderQueries: [] }),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolvePanelContextLinks', () => {
|
||||
it('substitutes the clicked field value (_-prefixed) into the label and URL', () => {
|
||||
const resolved = resolvePanelContextLinks(
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { isValidQueryName } from 'container/QueryTable/Drilldown/drilldownUtils';
|
||||
import type { DistributionBarClick } from 'lib/visualization/charts/Distribution/types';
|
||||
import type { BuilderQuery } from 'types/api/v5/queryRange';
|
||||
|
||||
import type { DrilldownClickPayload } from '../../types/drilldown';
|
||||
|
||||
import { getGroupByFilters } from './getGroupByFilters';
|
||||
import { resolveDrilldownSignal } from './signal';
|
||||
|
||||
interface PrepareDistributionClickDataArgs {
|
||||
click: DistributionBarClick;
|
||||
queryName: string;
|
||||
builderQueries: BuilderQuery[];
|
||||
/** The fetched window: a bar sums the whole range, not one step. */
|
||||
timeRange?: { startTime: number; endTime: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns a bar click into a drilldown payload, filtered to the clicked group. `null`
|
||||
* when the bar has no drillable query.
|
||||
*/
|
||||
export function prepareDistributionClickData({
|
||||
click,
|
||||
queryName,
|
||||
builderQueries,
|
||||
timeRange,
|
||||
}: PrepareDistributionClickDataArgs): DrilldownClickPayload | null {
|
||||
if (!isValidQueryName(queryName)) {
|
||||
return null;
|
||||
}
|
||||
const builderQuery = builderQueries.find((query) => query.name === queryName);
|
||||
|
||||
return {
|
||||
coordinates: click.coordinates,
|
||||
context: {
|
||||
queryName,
|
||||
signal: resolveDrilldownSignal(builderQuery),
|
||||
filters: builderQuery
|
||||
? getGroupByFilters(click.series.groupLabels ?? {}, builderQuery)
|
||||
: [],
|
||||
timeRange,
|
||||
label: click.series.label,
|
||||
seriesColor: click.color,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { PanelOption } from '../registry';
|
||||
import type { PanelKind } from '../types/panelKind';
|
||||
|
||||
/** A retired kind is offered only to the panel already of it, so it can stay put. */
|
||||
export function isPanelOptionOffered(
|
||||
option: PanelOption,
|
||||
currentKind: PanelKind,
|
||||
): boolean {
|
||||
return !option.isRetired || option.kind === currentKind;
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import type {
|
||||
import { themeColors } from 'constants/theme';
|
||||
import getLabelName from 'lib/getLabelName';
|
||||
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
|
||||
import { resolveSeriesColor } from 'lib/visualization/charts/Distribution/colors';
|
||||
import { prepareDistributionData } from '../kinds/DistributionPanel/prepareData';
|
||||
import { preparePieData } from '../kinds/PieChartPanel/prepareData';
|
||||
import { getColorGroupLabels } from '../kinds/ScatterPlotPanel/utils/prepareData';
|
||||
import { getJoinedScalarTable } from './getJoinedScalarTable';
|
||||
@@ -14,6 +16,7 @@ import { prepareScalarTables } from 'pages/DashboardPage/DashboardContainer/quer
|
||||
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
|
||||
import {
|
||||
flattenTimeSeries,
|
||||
getDistributionResults,
|
||||
getScalarResults,
|
||||
getTimeSeriesResults,
|
||||
} from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
|
||||
@@ -59,6 +62,21 @@ function buildLegendSeries(
|
||||
}));
|
||||
}
|
||||
|
||||
/** One entry per group, labelled and coloured as the Distribution chart draws it. */
|
||||
export function resolveDistributionLegendSeries({
|
||||
data,
|
||||
isDarkMode,
|
||||
}: LegendSeriesArgs): LegendSeries[] {
|
||||
const { series } = prepareDistributionData({
|
||||
results: getDistributionResults(data.response),
|
||||
legendMap: data.legendMap ?? {},
|
||||
});
|
||||
return buildLegendSeries(
|
||||
series.map((entry) => entry.label),
|
||||
(label) => resolveSeriesColor(label, isDarkMode),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pie is fed by scalar results, not time series. Reuse the exact slices the renderer
|
||||
* draws (without overrides, so their colors are the defaults) so the color control keys
|
||||
|
||||
@@ -30,7 +30,10 @@ function PanelTypeBrowser({
|
||||
const [query, setQuery] = useState('');
|
||||
const [category, setCategory] = useState<CategoryId>('all');
|
||||
|
||||
const matched = useMemo(() => filterPanelTypeGroups(query), [query]);
|
||||
const matched = useMemo(
|
||||
() => filterPanelTypeGroups(query, selectedKind),
|
||||
[query, selectedKind],
|
||||
);
|
||||
|
||||
const categories = useMemo(
|
||||
() => [
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
type PanelOption,
|
||||
} from '../../../../../Panels/registry';
|
||||
import type { PanelKind } from '../../../../../Panels/types/panelKind';
|
||||
import { isPanelOptionOffered } from '../../../../../Panels/utils/isPanelOptionOffered';
|
||||
|
||||
export type PanelTypeGroupId =
|
||||
| 'trends'
|
||||
@@ -60,13 +61,18 @@ const PANEL_TYPE_META: Record<PanelKind, PanelTypeMeta> = {
|
||||
},
|
||||
'signoz/HistogramPanel': {
|
||||
group: 'distributions',
|
||||
description: 'Distribution of values into buckets',
|
||||
description: 'Bins query results in the browser',
|
||||
},
|
||||
'signoz/HeatmapPanel': {
|
||||
group: 'distributions',
|
||||
description: 'Bucket density over time',
|
||||
isNew: true,
|
||||
},
|
||||
'signoz/DistributionPanel': {
|
||||
group: 'distributions',
|
||||
description: 'Bucket counts over the time range',
|
||||
isNew: true,
|
||||
},
|
||||
'signoz/NumberPanel': {
|
||||
group: 'single',
|
||||
description: 'One aggregate value, large',
|
||||
@@ -92,12 +98,19 @@ export interface PanelTypeGroup {
|
||||
}
|
||||
|
||||
/** Every group with the items matching `query` (name, description or group label); empty groups included. */
|
||||
export function filterPanelTypeGroups(query: string): PanelTypeGroup[] {
|
||||
export function filterPanelTypeGroups(
|
||||
query: string,
|
||||
currentKind: PanelKind,
|
||||
): PanelTypeGroup[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
return PANEL_TYPE_GROUPS.map(({ id, label }) => ({
|
||||
id,
|
||||
label,
|
||||
items: PANEL_OPTIONS.filter(({ kind }) => PANEL_TYPE_META[kind].group === id)
|
||||
items: PANEL_OPTIONS.filter(
|
||||
(option) =>
|
||||
PANEL_TYPE_META[option.kind].group === id &&
|
||||
isPanelOptionOffered(option, currentKind),
|
||||
)
|
||||
.map((option) => ({ ...option, ...PANEL_TYPE_META[option.kind] }))
|
||||
.filter(
|
||||
(item) =>
|
||||
|
||||
@@ -58,6 +58,23 @@ const HEATMAP_CELLS = [
|
||||
[0.4, 0.85, 0.7, 0.2],
|
||||
[0.3, 0.65, 0.9, 0.45],
|
||||
];
|
||||
// `[lower, upper]` heights (0–44) of two stacked groups per bucket, skewed right.
|
||||
const DISTRIBUTION_STACKS = [
|
||||
[6, 3],
|
||||
[14, 6],
|
||||
[26, 10],
|
||||
[20, 12],
|
||||
[12, 9],
|
||||
[7, 6],
|
||||
[4, 3],
|
||||
[2, 2],
|
||||
];
|
||||
const DISTRIBUTION_UPPER = { fill: 'var(--bg-robin-400)', fillOpacity: 0.55 };
|
||||
const PERCENTILE_MARKER = {
|
||||
stroke: 'var(--l1-foreground)',
|
||||
strokeOpacity: 0.6,
|
||||
};
|
||||
|
||||
// Bar lengths (% of the track) for the top-list sketch, longest first.
|
||||
const TOP_LIST_BARS = [100, 76, 54, 34];
|
||||
const TEXT_ROWS = [45, 100, 92, 64].map((width, i) => [
|
||||
@@ -155,6 +172,39 @@ export const PANEL_TYPE_PREVIEWS: Record<PanelKind, JSX.Element> = {
|
||||
)}
|
||||
</svg>
|
||||
),
|
||||
'signoz/DistributionPanel': (
|
||||
<svg viewBox="0 0 120 44" preserveAspectRatio="none" className={styles.svg}>
|
||||
{DISTRIBUTION_STACKS.map(([lower, upper], i) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<g key={i}>
|
||||
<rect
|
||||
x={i * 15 + 1}
|
||||
y={44 - lower}
|
||||
width={13}
|
||||
height={lower}
|
||||
style={AREA_FILL}
|
||||
/>
|
||||
<rect
|
||||
x={i * 15 + 1}
|
||||
y={44 - lower - upper}
|
||||
width={13}
|
||||
height={upper}
|
||||
style={DISTRIBUTION_UPPER}
|
||||
/>
|
||||
</g>
|
||||
))}
|
||||
<line
|
||||
x1={88}
|
||||
x2={88}
|
||||
y1={2}
|
||||
y2={44}
|
||||
strokeWidth={1}
|
||||
strokeDasharray="3 2"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
style={PERCENTILE_MARKER}
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
'signoz/ScatterPlotPanel': (
|
||||
<svg viewBox="0 0 120 44" className={styles.svg}>
|
||||
{SCATTER_DOTS.map(([cx, cy, r]) => (
|
||||
|
||||
@@ -73,6 +73,7 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
|
||||
// Same capabilities-guarded options as the editor's PanelTypeSwitcher, so the two
|
||||
// selectors disable the same kinds (e.g. List under PromQL, metrics-only kinds).
|
||||
const panelTypeItems = usePanelTypeSelectItems({
|
||||
panelKind,
|
||||
queryType: query?.queryType ?? EQueryType.QUERY_BUILDER,
|
||||
signal: query?.signal,
|
||||
});
|
||||
|
||||
@@ -477,25 +477,28 @@ describe('extractLegendMap', () => {
|
||||
});
|
||||
|
||||
describe('hasRunnableQueries', () => {
|
||||
const heatmapQuery = (
|
||||
const bucketQuery = (
|
||||
kind: 'heatmap' | 'distribution',
|
||||
signal: string,
|
||||
aggregations: Record<string, unknown>[],
|
||||
): DashboardtypesQueryDTO[] =>
|
||||
compositeQuery([
|
||||
{ type: 'builder_query', spec: { name: 'A', signal, aggregations } },
|
||||
]).map((query) => ({ ...query, kind: 'heatmap' }) as DashboardtypesQueryDTO);
|
||||
]).map((query) => ({ ...query, kind }) 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,
|
||||
);
|
||||
['heatmap', 'logs', [], false],
|
||||
['heatmap', 'traces', [{ expression: ' ' }], false],
|
||||
['heatmap', 'traces', [{ expression: 'duration_nano' }], true],
|
||||
['heatmap', 'metrics', [{ metricName: 'http_latency' }], true],
|
||||
['distribution', 'logs', [], false],
|
||||
['distribution', 'traces', [{ expression: 'duration_nano' }], true],
|
||||
] as const)(
|
||||
'%s over %s with aggregations %j is runnable: %s',
|
||||
(kind, signal, aggregations, runnable) => {
|
||||
expect(
|
||||
hasRunnableQueries(bucketQuery(kind, signal, [...aggregations])),
|
||||
).toBe(runnable);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -329,7 +329,7 @@ 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.
|
||||
* logs/traces heatmap or distribution names no field to bucket.
|
||||
*/
|
||||
export function hasRunnableQueries(queries: DashboardtypesQueryDTO[]): boolean {
|
||||
const envelopes = toQueryEnvelopes(queries);
|
||||
@@ -342,7 +342,8 @@ export function hasRunnableQueries(queries: DashboardtypesQueryDTO[]): boolean {
|
||||
.map((envelope) => envelope.spec as QuerySpecView);
|
||||
|
||||
if (
|
||||
queries[0].kind === Querybuildertypesv5RequestTypeDTO.heatmap &&
|
||||
(queries[0].kind === Querybuildertypesv5RequestTypeDTO.heatmap ||
|
||||
queries[0].kind === Querybuildertypesv5RequestTypeDTO.distribution) &&
|
||||
builderSpecs.some(
|
||||
(spec) =>
|
||||
!spec.disabled &&
|
||||
|
||||
@@ -123,6 +123,8 @@ export function panelTypeToRequestType(
|
||||
return Querybuildertypesv5RequestTypeDTO.raw;
|
||||
case PANEL_TYPES.HEATMAP:
|
||||
return Querybuildertypesv5RequestTypeDTO.heatmap;
|
||||
case PANEL_TYPES.DISTRIBUTION:
|
||||
return Querybuildertypesv5RequestTypeDTO.distribution;
|
||||
case PANEL_TYPES.TRACE:
|
||||
return Querybuildertypesv5RequestTypeDTO.trace;
|
||||
default:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
Querybuildertypesv5AggregationBucketDTO,
|
||||
Querybuildertypesv5DistributionDataDTO,
|
||||
Querybuildertypesv5ExecStatsDTO,
|
||||
Querybuildertypesv5RawDataDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
@@ -36,6 +37,17 @@ export function getHeatmapResults(
|
||||
[]) as Querybuildertypesv5TimeSeriesDataDTO[];
|
||||
}
|
||||
|
||||
/** One summed count array per group, positional against each aggregation's `meta.buckets`. */
|
||||
export function getDistributionResults(
|
||||
response: QueryRangeV5200 | undefined,
|
||||
): Querybuildertypesv5DistributionDataDTO[] {
|
||||
if (response?.data?.type !== 'distribution') {
|
||||
return [];
|
||||
}
|
||||
return (response.data.data?.results ??
|
||||
[]) as Querybuildertypesv5DistributionDataDTO[];
|
||||
}
|
||||
|
||||
export function getScalarResults(
|
||||
response: QueryRangeV5200 | undefined,
|
||||
): Querybuildertypesv5ScalarDataDTO[] {
|
||||
|
||||
@@ -209,6 +209,12 @@ export const HeatmapTracesField: Story = {
|
||||
play: pickHeatmapTracesField,
|
||||
};
|
||||
|
||||
/** A new distribution panel's config pane, every section expanded. */
|
||||
export const ConfigDistribution: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'distribution' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
/** A new list panel's config pane, every section expanded. */
|
||||
export const ConfigList: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'list' },
|
||||
|
||||
@@ -33,6 +33,7 @@ export const NEW_PANEL_KINDS = [
|
||||
'pie-chart',
|
||||
'histogram',
|
||||
'heatmap',
|
||||
'distribution',
|
||||
'list',
|
||||
'text',
|
||||
'top-list',
|
||||
@@ -49,6 +50,7 @@ const KIND_BY_OPTION: Record<NewPanelKind, PanelKind> = {
|
||||
table: 'signoz/TablePanel',
|
||||
histogram: 'signoz/HistogramPanel',
|
||||
heatmap: 'signoz/HeatmapPanel',
|
||||
distribution: 'signoz/DistributionPanel',
|
||||
list: 'signoz/ListPanel',
|
||||
text: 'signoz/TextPanel',
|
||||
'top-list': 'signoz/TopListPanel',
|
||||
|
||||
@@ -27,15 +27,17 @@ import { publicDashboardMeta } from '../__story_mockdata__/publicDashboard';
|
||||
|
||||
import {
|
||||
BUCKET_WIDTHS,
|
||||
DISTRIBUTION_OVERFLOWS,
|
||||
DISTRIBUTION_X_RANGES,
|
||||
GAPS,
|
||||
HEATMAP_COUNT_RANGES,
|
||||
HEATMAP_FIXED_COUNTS,
|
||||
HEATMAP_PALETTES,
|
||||
HEATMAP_SOURCES,
|
||||
BUCKET_SOURCES,
|
||||
HEATMAP_Y_SCALES,
|
||||
LEGEND_POSITIONS,
|
||||
LINE_STYLES,
|
||||
MAX_SERIES,
|
||||
MAX_SERIES_CONTROL,
|
||||
PANEL_KINDS,
|
||||
PANEL_RESULTS,
|
||||
PANELS_DASHBOARD_ID,
|
||||
@@ -60,9 +62,11 @@ import {
|
||||
} from './__story_mockdata__/panelResponses';
|
||||
import type {
|
||||
BucketWidth,
|
||||
DistributionOverflow,
|
||||
DistributionXRange,
|
||||
Gaps,
|
||||
HeatmapCountRange,
|
||||
HeatmapSource,
|
||||
BucketSource,
|
||||
PanelArgs,
|
||||
PanelKind,
|
||||
PanelResult,
|
||||
@@ -115,7 +119,7 @@ export const panelsMocks = defineStoryMocks({
|
||||
stack: choiceControl<StackMode>('Stack', {
|
||||
group: PANEL,
|
||||
description:
|
||||
'Area stacks `normal` or to `percent`; Bar stacks on anything but `none`. No effect on other kinds.',
|
||||
'Area and Distribution stack `normal` or to `percent`, and Distribution draws `none` side by side; Bar stacks on anything but `none`. No effect on other kinds.',
|
||||
options: STACK_MODES,
|
||||
value: StackMode.none,
|
||||
}),
|
||||
@@ -137,11 +141,27 @@ export const panelsMocks = defineStoryMocks({
|
||||
options: HEATMAP_COUNT_RANGES,
|
||||
value: 'auto',
|
||||
}),
|
||||
heatmapSource: choiceControl<HeatmapSource>('Heatmap source', {
|
||||
distributionXRange: choiceControl<DistributionXRange>(
|
||||
'Distribution x range',
|
||||
{
|
||||
group: PANEL,
|
||||
description:
|
||||
'Bucket axis range: `all` shows every bucket, `clamped` hides those outside 10–1000.',
|
||||
options: DISTRIBUTION_X_RANGES,
|
||||
value: 'all',
|
||||
},
|
||||
),
|
||||
percentiles: toggleControl('Distribution percentiles', {
|
||||
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,
|
||||
'Dashed p50, p90 and p99 markers across the Distribution panel.',
|
||||
value: true,
|
||||
}),
|
||||
bucketSource: choiceControl<BucketSource>('Bucket source', {
|
||||
group: PANEL,
|
||||
description:
|
||||
'The signal the Heatmap and Distribution panels bucket: 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: BUCKET_SOURCES,
|
||||
value: 'metrics',
|
||||
}),
|
||||
bucketWidth: choiceControl<BucketWidth>('Histogram bucket width', {
|
||||
@@ -171,7 +191,8 @@ export const panelsMocks = defineStoryMocks({
|
||||
}),
|
||||
yScale: choiceControl<YScale>('Y scale', {
|
||||
group: PANEL,
|
||||
description: 'The y axis of Time Series, Bar and Area.',
|
||||
description:
|
||||
'The y axis of Time Series, Bar and Area, and the count axis of Distribution.',
|
||||
options: Y_SCALES,
|
||||
value: 'linear',
|
||||
}),
|
||||
@@ -228,9 +249,9 @@ export const panelsMocks = defineStoryMocks({
|
||||
series: countControl('Series', {
|
||||
group: DATA,
|
||||
description:
|
||||
'Series on the charts, groups on the heatmap, slices on the pie, rows on the table and the top list.',
|
||||
'Series on the charts, groups on the heatmap and distribution, slices on the pie, rows on the table and the top list. Side by side, a distribution draws at most 10 and sums the rest into Other.',
|
||||
value: 4,
|
||||
max: MAX_SERIES,
|
||||
max: MAX_SERIES_CONTROL,
|
||||
}),
|
||||
pieSlices: choiceControl<PieSlices>('Pie slices', {
|
||||
group: DATA,
|
||||
@@ -246,6 +267,13 @@ export const panelsMocks = defineStoryMocks({
|
||||
options: GAPS,
|
||||
value: 'none',
|
||||
}),
|
||||
overflow: choiceControl<DistributionOverflow>('Distribution overflow', {
|
||||
group: DATA,
|
||||
description:
|
||||
'Observations past the last bucket bound: `low` 2%, `high` 25%, which the panel header flags.',
|
||||
options: DISTRIBUTION_OVERFLOWS,
|
||||
value: 'low',
|
||||
}),
|
||||
listRows: countControl('List rows', {
|
||||
group: DATA,
|
||||
description:
|
||||
@@ -315,6 +343,7 @@ export const panelsMocks = defineStoryMocks({
|
||||
listWideRows: values.listWideRows,
|
||||
gaps: values.gaps,
|
||||
pieSlices: values.pieSlices,
|
||||
overflow: values.overflow,
|
||||
});
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -16,6 +16,7 @@ import DashboardPage from '../../DashboardPage';
|
||||
|
||||
import { panelsMocks } from './Panels.stories.mocks';
|
||||
import {
|
||||
playDistributionTooltip,
|
||||
playLegendRight,
|
||||
playListJsonBody,
|
||||
playListPaginated,
|
||||
@@ -114,19 +115,19 @@ export const HeatmapLog: Story = {
|
||||
|
||||
/** A traces heatmap bucketing each span's `duration_nano`. */
|
||||
export const HeatmapTraces: Story = {
|
||||
args: { kind: 'Heatmap', heatmapSource: 'traces' },
|
||||
args: { kind: 'Heatmap', bucketSource: 'traces' },
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/** A logs heatmap bucketing the `attribute.queue_depth` log field. */
|
||||
export const HeatmapLogs: Story = {
|
||||
args: { kind: 'Heatmap', heatmapSource: 'logs' },
|
||||
args: { kind: 'Heatmap', bucketSource: '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' },
|
||||
args: { kind: 'Heatmap', bucketSource: 'no field' },
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
@@ -136,6 +137,97 @@ export const HeatmapCountRange: Story = {
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/**
|
||||
* Latency bucket counts over the whole range, one stacked bar per bucket on a log
|
||||
* bucket axis, with p50, p90 and p99 marked and the overflow bucket hatched.
|
||||
*/
|
||||
export const Distribution: Story = {
|
||||
args: { kind: 'Distribution', stack: StackMode.normal },
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/** Each bucket split between the services, their bars side by side. */
|
||||
export const DistributionSideBySide: Story = {
|
||||
args: { kind: 'Distribution', stack: StackMode.none },
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/** Each bucket stacked to 100%, every band its service's share of that bucket. */
|
||||
export const DistributionPercent: Story = {
|
||||
args: { kind: 'Distribution', stack: StackMode.percent },
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/** Buckets outside 10–1000 hidden, counts on a log axis. */
|
||||
export const DistributionClampedLog: Story = {
|
||||
args: {
|
||||
kind: 'Distribution',
|
||||
stack: StackMode.normal,
|
||||
distributionXRange: 'clamped',
|
||||
yScale: 'log',
|
||||
},
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/** A traces distribution bucketing each span's `duration_nano`. */
|
||||
export const DistributionTraces: Story = {
|
||||
args: {
|
||||
kind: 'Distribution',
|
||||
stack: StackMode.normal,
|
||||
bucketSource: 'traces',
|
||||
},
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/** A logs distribution bucketing the `attribute.queue_depth` log field. */
|
||||
export const DistributionLogs: Story = {
|
||||
args: { kind: 'Distribution', stack: StackMode.normal, bucketSource: 'logs' },
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/** A traces distribution with no field to bucket: the panel waits for one instead of querying. */
|
||||
export const DistributionNoField: Story = {
|
||||
args: {
|
||||
kind: 'Distribution',
|
||||
stack: StackMode.normal,
|
||||
bucketSource: 'no field',
|
||||
},
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/**
|
||||
* The tooltip over a bucket: its total, then each service's count and share of its
|
||||
* own total.
|
||||
*/
|
||||
export const DistributionTooltip: Story = {
|
||||
args: { kind: 'Distribution', stack: StackMode.normal },
|
||||
play: playDistributionTooltip,
|
||||
};
|
||||
|
||||
/** Fourteen services stacked: every one drawn, with no Other. */
|
||||
export const DistributionManyGroups: Story = {
|
||||
args: { kind: 'Distribution', stack: StackMode.normal, series: 14 },
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/**
|
||||
* Fourteen services side by side: as many as keep every bar 3 px wide in the
|
||||
* narrowest bucket are drawn, and the rest summed into Other.
|
||||
*/
|
||||
export const DistributionSideBySideOther: Story = {
|
||||
args: { kind: 'Distribution', stack: StackMode.none, series: 14 },
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/**
|
||||
* A quarter of observations past the last bound: the overflow bar dominates, p99
|
||||
* reads `> 5 s`, and the header warns that the bounds may be too low.
|
||||
*/
|
||||
export const DistributionOverflow: Story = {
|
||||
args: { kind: 'Distribution', stack: StackMode.normal, overflow: 'high' },
|
||||
play: playPanel,
|
||||
};
|
||||
|
||||
/** Each service's share of traffic as a donut, with the total in the middle. */
|
||||
export const Pie: Story = {
|
||||
args: { kind: 'Pie' },
|
||||
|
||||
@@ -25,6 +25,7 @@ export const PANEL_KINDS = [
|
||||
'Area',
|
||||
'Histogram',
|
||||
'Heatmap',
|
||||
'Distribution',
|
||||
'Pie',
|
||||
'Number',
|
||||
'Table',
|
||||
@@ -54,15 +55,15 @@ export const HEATMAP_Y_SCALES = Object.values(HeatmapYScale);
|
||||
|
||||
export const HEATMAP_COUNT_RANGES = ['auto', 'fixed'] as const;
|
||||
|
||||
export const HEATMAP_SOURCES = [
|
||||
export const BUCKET_SOURCES = [
|
||||
'metrics',
|
||||
'logs',
|
||||
'traces',
|
||||
'no field',
|
||||
] as const;
|
||||
|
||||
/** The field a logs or traces heatmap buckets. */
|
||||
export const HEATMAP_FIELDS = {
|
||||
/** The field a logs or traces heatmap or distribution buckets. */
|
||||
export const BUCKET_FIELDS = {
|
||||
logs: 'attribute.queue_depth',
|
||||
traces: 'duration_nano',
|
||||
} as const;
|
||||
@@ -101,6 +102,7 @@ export const PANEL_NAME: Record<PanelKind, string> = {
|
||||
Area: 'Request rate by service',
|
||||
Histogram: 'Latency distribution',
|
||||
Heatmap: 'Latency heatmap',
|
||||
Distribution: 'Latency buckets',
|
||||
Pie: 'Traffic share',
|
||||
Number: 'p99 latency',
|
||||
Table: 'Calls by service',
|
||||
@@ -144,6 +146,21 @@ export const HEATMAP_BUCKETS = [
|
||||
|
||||
export const HEATMAP_COLUMNS = 30;
|
||||
|
||||
/** Exponential, as a latency histogram's `le` bounds are, so `auto` picks log. */
|
||||
export const DISTRIBUTION_BUCKETS = [
|
||||
5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000,
|
||||
];
|
||||
|
||||
/** `clamped` hides buckets outside 10–1000. */
|
||||
export const DISTRIBUTION_X_RANGES = ['all', 'clamped'] as const;
|
||||
export const DISTRIBUTION_CLAMP = { min: 10, max: 1000 };
|
||||
|
||||
/** `high` puts a quarter of each group past the last bound, over the warning's 10%. */
|
||||
export const DISTRIBUTION_OVERFLOWS = ['low', 'high'] as const;
|
||||
|
||||
/** Groups the series control allows: past the 10 a side-by-side distribution draws. */
|
||||
export const MAX_SERIES_CONTROL = 14;
|
||||
|
||||
export const SERVICES = [
|
||||
'checkout',
|
||||
'payments',
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
import {
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpecDTOKind as AreaChartKind,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTOKind as BarChartKind,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDistributionPanelSpecDTOKind as DistributionKind,
|
||||
DashboardtypesDistributionYScaleDTO as DistributionYScale,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTOKind as HeatmapKind,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpecDTOKind as HistogramKind,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpecDTOKind as ListKind,
|
||||
@@ -16,6 +18,7 @@ import {
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTOKind as TimeSeriesKind,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind as TopListKind,
|
||||
MetrictypesSpaceAggregationDTO as SpaceAggregation,
|
||||
DashboardtypesDistributionStackModeDTO as DistributionStackMode,
|
||||
DashboardtypesStackModeDTO as StackMode,
|
||||
DashboardtypesTextModeDTO as TextMode,
|
||||
Querybuildertypesv5RequestTypeDTO as RequestType,
|
||||
@@ -24,6 +27,7 @@ import {
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import {
|
||||
DISTRIBUTION_CLAMP,
|
||||
HEATMAP_FIXED_COUNTS,
|
||||
TABLE_SECOND_COLUMN,
|
||||
TABLE_THRESHOLD_VALUE,
|
||||
@@ -33,7 +37,7 @@ import {
|
||||
import {
|
||||
comparisonThresholds,
|
||||
labelThresholds,
|
||||
eventHeatmapQuery,
|
||||
bucketQuery,
|
||||
logQuery,
|
||||
metricQuery,
|
||||
tableThresholds,
|
||||
@@ -133,9 +137,39 @@ export const panelShape = (args: PanelArgs): PanelShape => {
|
||||
},
|
||||
},
|
||||
queries: [
|
||||
args.heatmapSource === 'metrics'
|
||||
? metricQuery(RequestType.heatmap, { grouped: true, heatmap: true })
|
||||
: eventHeatmapQuery(args.heatmapSource),
|
||||
bucketQuery(args.bucketSource, RequestType.heatmap, {
|
||||
grouped: true,
|
||||
heatmap: true,
|
||||
}),
|
||||
],
|
||||
};
|
||||
case 'Distribution':
|
||||
return {
|
||||
plugin: {
|
||||
kind: DistributionKind['signoz/DistributionPanel'],
|
||||
spec: {
|
||||
visualization: { stack: DistributionStackMode[args.stack] },
|
||||
formatting,
|
||||
legend,
|
||||
axes: {
|
||||
x: args.distributionXRange === 'clamped' ? DISTRIBUTION_CLAMP : {},
|
||||
y: {
|
||||
scale:
|
||||
args.yScale === 'log'
|
||||
? DistributionYScale.log
|
||||
: DistributionYScale.linear,
|
||||
},
|
||||
},
|
||||
chartAppearance: {
|
||||
percentiles: { enabled: args.percentiles, values: [50, 90, 99] },
|
||||
},
|
||||
},
|
||||
},
|
||||
queries: [
|
||||
bucketQuery(args.bucketSource, RequestType.distribution, {
|
||||
grouped: true,
|
||||
histogram: true,
|
||||
}),
|
||||
],
|
||||
};
|
||||
case 'Pie':
|
||||
|
||||
@@ -26,14 +26,14 @@ import {
|
||||
|
||||
import {
|
||||
CHART_THRESHOLD_VALUE,
|
||||
HEATMAP_FIELDS,
|
||||
BUCKET_FIELDS,
|
||||
NUMBER_THRESHOLD_VALUE,
|
||||
QUERY_NAME,
|
||||
TABLE_THRESHOLD_VALUE,
|
||||
TABLE_VALUE_COLUMN,
|
||||
THRESHOLD_COLOR,
|
||||
} from './constants';
|
||||
import type { HeatmapSource, TextSample } from './types';
|
||||
import type { BucketSource, TextSample } from './types';
|
||||
|
||||
export const labelThresholds = (
|
||||
on: boolean,
|
||||
@@ -93,6 +93,8 @@ export const TEXT_BODIES: Record<TextSample, string> = {
|
||||
interface MetricQueryOptions {
|
||||
grouped: boolean;
|
||||
heatmap?: boolean;
|
||||
/** A histogram metric, whose `le` bounds are the bucket axis: no bucket options. */
|
||||
histogram?: boolean;
|
||||
name?: string;
|
||||
metricName?: string;
|
||||
spaceAggregation?: SpaceAggregation;
|
||||
@@ -103,6 +105,7 @@ export const metricQuery = (
|
||||
{
|
||||
grouped,
|
||||
heatmap,
|
||||
histogram,
|
||||
name = QUERY_NAME,
|
||||
metricName = 'signoz_latency',
|
||||
spaceAggregation = SpaceAggregation.p99,
|
||||
@@ -113,9 +116,10 @@ export const metricQuery = (
|
||||
signal: MetricSignal.metrics,
|
||||
aggregations: [
|
||||
{
|
||||
metricName: heatmap ? `${metricName}_bucket` : metricName,
|
||||
spaceAggregation: heatmap ? undefined : spaceAggregation,
|
||||
timeAggregation: heatmap ? TimeAggregation.increase : TimeAggregation.avg,
|
||||
metricName: heatmap || histogram ? `${metricName}_bucket` : metricName,
|
||||
spaceAggregation: heatmap || histogram ? undefined : spaceAggregation,
|
||||
timeAggregation:
|
||||
heatmap || histogram ? TimeAggregation.increase : TimeAggregation.avg,
|
||||
},
|
||||
],
|
||||
groupBy: grouped ? [{ name: 'service.name' }] : undefined,
|
||||
@@ -153,9 +157,10 @@ 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'>,
|
||||
/** `no field` is a traces query whose field was cleared: it saves with no aggregation. */
|
||||
export const eventBucketQuery = (
|
||||
source: Exclude<BucketSource, 'metrics'>,
|
||||
requestType: typeof RequestType.heatmap | typeof RequestType.distribution,
|
||||
): DashboardtypesQueryDTO => {
|
||||
const groupBy = [{ name: 'service.name' }];
|
||||
const legend = '{{service.name}}';
|
||||
@@ -168,7 +173,7 @@ export const eventHeatmapQuery = (
|
||||
? {
|
||||
name: QUERY_NAME,
|
||||
signal: LogSignal.logs,
|
||||
aggregations: [{ expression: HEATMAP_FIELDS.logs }],
|
||||
aggregations: [{ expression: BUCKET_FIELDS.logs }],
|
||||
groupBy,
|
||||
legend,
|
||||
bucketOptions,
|
||||
@@ -177,17 +182,27 @@ export const eventHeatmapQuery = (
|
||||
name: QUERY_NAME,
|
||||
signal: TraceSignal.traces,
|
||||
aggregations:
|
||||
source === 'traces' ? [{ expression: HEATMAP_FIELDS.traces }] : [],
|
||||
source === 'traces' ? [{ expression: BUCKET_FIELDS.traces }] : [],
|
||||
groupBy,
|
||||
legend,
|
||||
bucketOptions,
|
||||
};
|
||||
|
||||
return {
|
||||
kind: RequestType.heatmap,
|
||||
kind: requestType,
|
||||
spec: {
|
||||
name: QUERY_NAME,
|
||||
plugin: { kind: BuilderQueryKind['signoz/BuilderQuery'], spec },
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** A heatmap or distribution query over the chosen source. */
|
||||
export const bucketQuery = (
|
||||
source: BucketSource,
|
||||
requestType: typeof RequestType.heatmap | typeof RequestType.distribution,
|
||||
metricOptions: MetricQueryOptions,
|
||||
): DashboardtypesQueryDTO =>
|
||||
source === 'metrics'
|
||||
? metricQuery(requestType, metricOptions)
|
||||
: eventBucketQuery(source, requestType);
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { Warning } from 'types/api';
|
||||
import type { MetricRangePayloadV5, RawRow } from 'types/api/v5/queryRange';
|
||||
|
||||
import {
|
||||
queryRangeV5DistributionResponse,
|
||||
queryRangeV5EmptyResponse,
|
||||
queryRangeV5HeatmapResponse,
|
||||
queryRangeV5RawResponse,
|
||||
@@ -23,17 +24,25 @@ import {
|
||||
} from '../../__story_mockdata__/panelData';
|
||||
|
||||
import {
|
||||
DISTRIBUTION_BUCKETS,
|
||||
HEATMAP_BUCKETS,
|
||||
HEATMAP_COLUMNS,
|
||||
HOLE,
|
||||
LONG_TAIL_SLICES,
|
||||
MAX_SERIES,
|
||||
MAX_SERIES_CONTROL,
|
||||
NUMBER_VALUE,
|
||||
QUERY_NAME,
|
||||
SERVICES,
|
||||
TABLE_SECOND_COLUMN,
|
||||
} from './constants';
|
||||
import type { Gaps, PanelRequest, PanelResponseArgs, PieSlices } from './types';
|
||||
import type {
|
||||
DistributionOverflow,
|
||||
Gaps,
|
||||
PanelRequest,
|
||||
PanelResponseArgs,
|
||||
PieSlices,
|
||||
} from './types';
|
||||
|
||||
export const serviceAt = (index: number): string =>
|
||||
index < SERVICES.length
|
||||
@@ -86,7 +95,7 @@ export const latencyPoints = (
|
||||
|
||||
/** The series index a service label was generated from. */
|
||||
export const serviceIndex = (label: string): number =>
|
||||
Array.from({ length: MAX_SERIES }, (_unused, index) =>
|
||||
Array.from({ length: MAX_SERIES_CONTROL }, (_unused, index) =>
|
||||
serviceAt(index),
|
||||
).indexOf(label);
|
||||
|
||||
@@ -194,6 +203,38 @@ const wideAttributes = (index: number): Record<string, string> =>
|
||||
]),
|
||||
);
|
||||
|
||||
/**
|
||||
* A latency-shaped hump per group, peaking a bucket further right every third
|
||||
* group, plus the overflow count `overflow` asks for.
|
||||
*/
|
||||
export const distributionCounts = (
|
||||
group: number,
|
||||
overflow: DistributionOverflow,
|
||||
): number[] => {
|
||||
const peak = 3 + (group % 3);
|
||||
const scale = 1 + (group % 4) * 0.4;
|
||||
const finite = DISTRIBUTION_BUCKETS.map((_bound, index) =>
|
||||
Math.round(scale * 120 * Math.exp(-((index - peak) ** 2) / 3)),
|
||||
);
|
||||
const total = finite.reduce((sum, count) => sum + count, 0);
|
||||
const share = overflow === 'high' ? 0.25 : 0.02;
|
||||
return [...finite, Math.round((total * share) / (1 - share))];
|
||||
};
|
||||
|
||||
const distributionResponse = (
|
||||
count: number,
|
||||
overflow: DistributionOverflow,
|
||||
warning: Warning | undefined,
|
||||
): QueryRangeV5200 =>
|
||||
queryRangeV5DistributionResponse({
|
||||
buckets: DISTRIBUTION_BUCKETS,
|
||||
warning,
|
||||
distributions: Array.from({ length: count }, (_unused, group) => ({
|
||||
labels: [{ key: { name: 'service.name' }, value: serviceAt(group) }],
|
||||
counts: distributionCounts(group, overflow),
|
||||
})),
|
||||
});
|
||||
|
||||
/** Spaced by the window, newest first, as the `timestamp desc` order asks for. */
|
||||
const logRows = (
|
||||
{ start, end }: PanelWindow,
|
||||
@@ -237,6 +278,7 @@ export const panelQueryResponse = ({
|
||||
listWideRows,
|
||||
gaps,
|
||||
pieSlices,
|
||||
overflow,
|
||||
window,
|
||||
offset,
|
||||
limit,
|
||||
@@ -250,6 +292,8 @@ export const panelQueryResponse = ({
|
||||
switch (kind) {
|
||||
case 'Heatmap':
|
||||
return heatmapResponse(window, series, warning);
|
||||
case 'Distribution':
|
||||
return distributionResponse(series, overflow, warning);
|
||||
case 'Pie':
|
||||
return queryRangeV5ScalarTableResponse({
|
||||
groupBy: ['service.name'],
|
||||
|
||||
@@ -16,9 +16,11 @@ import type { PanelWindow } from '../../__story_mockdata__/panelData';
|
||||
|
||||
import type {
|
||||
BUCKET_WIDTHS,
|
||||
DISTRIBUTION_OVERFLOWS,
|
||||
DISTRIBUTION_X_RANGES,
|
||||
GAPS,
|
||||
HEATMAP_COUNT_RANGES,
|
||||
HEATMAP_SOURCES,
|
||||
BUCKET_SOURCES,
|
||||
PANEL_KINDS,
|
||||
PANEL_RESULTS,
|
||||
PIE_SLICES,
|
||||
@@ -37,7 +39,7 @@ export type PanelUnit = (typeof UNITS)[number];
|
||||
|
||||
export type HeatmapCountRange = (typeof HEATMAP_COUNT_RANGES)[number];
|
||||
|
||||
export type HeatmapSource = (typeof HEATMAP_SOURCES)[number];
|
||||
export type BucketSource = (typeof BUCKET_SOURCES)[number];
|
||||
|
||||
export type BucketWidth = (typeof BUCKET_WIDTHS)[number];
|
||||
|
||||
@@ -52,6 +54,9 @@ export type SpanGaps = (typeof SPAN_GAPS)[number];
|
||||
export type TopListAggregation = (typeof TOP_LIST_AGGREGATIONS)[number];
|
||||
|
||||
export type PieSlices = (typeof PIE_SLICES)[number];
|
||||
export type DistributionOverflow = (typeof DISTRIBUTION_OVERFLOWS)[number];
|
||||
|
||||
export type DistributionXRange = (typeof DISTRIBUTION_X_RANGES)[number];
|
||||
|
||||
/** The controls that shape the dashboard document. */
|
||||
export interface PanelArgs {
|
||||
@@ -63,7 +68,7 @@ export interface PanelArgs {
|
||||
palette: HeatmapPalette;
|
||||
heatmapScale: HeatmapYScale;
|
||||
heatmapCounts: HeatmapCountRange;
|
||||
heatmapSource: HeatmapSource;
|
||||
bucketSource: BucketSource;
|
||||
bucketWidth: BucketWidth;
|
||||
textSample: TextSample;
|
||||
textAlign: TextAlign;
|
||||
@@ -73,6 +78,8 @@ export interface PanelArgs {
|
||||
showPoints: boolean;
|
||||
spanGaps: SpanGaps;
|
||||
columnUnits: boolean;
|
||||
distributionXRange: DistributionXRange;
|
||||
percentiles: boolean;
|
||||
showRank: boolean;
|
||||
showShare: boolean;
|
||||
topListAggregation: TopListAggregation;
|
||||
@@ -94,4 +101,5 @@ export interface PanelResponseArgs extends PanelRequest {
|
||||
listWideRows: boolean;
|
||||
gaps: Gaps;
|
||||
pieSlices: PieSlices;
|
||||
overflow: DistributionOverflow;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { DashboardtypesHeatmapYScaleDTO as HeatmapYScale } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
|
||||
DashboardtypesStackModeDTO as StackMode,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { MAX_SIDE_BY_SIDE_GROUPS } from 'lib/visualization/charts/Distribution/topGroups';
|
||||
import {
|
||||
DEFAULT_COLOR_RAMP_OPTIONS,
|
||||
getRampBottom,
|
||||
@@ -10,12 +14,16 @@ import { expect, waitFor, within } from 'storybook/test';
|
||||
import type uPlot from 'uplot';
|
||||
|
||||
import {
|
||||
DISTRIBUTION_BUCKETS,
|
||||
HEATMAP_BUCKETS,
|
||||
HEATMAP_FIXED_COUNTS,
|
||||
} from '../__story_mockdata__/constants';
|
||||
import { heatmapCellCounts } from '../__story_mockdata__/panelResponses';
|
||||
import {
|
||||
distributionCounts,
|
||||
heatmapCellCounts,
|
||||
} from '../__story_mockdata__/panelResponses';
|
||||
|
||||
import { PANEL_LOAD, type PanelPlayArgs } from './args';
|
||||
import { hasData, PANEL_LOAD, type PanelPlayArgs } from './args';
|
||||
import { findPlot, toRgb, waitForPlot } from './plot';
|
||||
|
||||
const isMultipleOf = (value: number, width: number): boolean =>
|
||||
@@ -98,3 +106,166 @@ export const expectHeatmap = async (
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const expectDistribution = async (
|
||||
root: HTMLElement,
|
||||
args: PanelPlayArgs,
|
||||
): Promise<void> => {
|
||||
const isStacked = args.stack !== StackMode.none;
|
||||
let plot: uPlot | undefined;
|
||||
await waitFor(async () => {
|
||||
plot = findPlot(root);
|
||||
await expect(plot).toBeDefined();
|
||||
}, PANEL_LOAD);
|
||||
const drawn = plot as uPlot;
|
||||
|
||||
// A stack draws every group. Side by side fits as many as the panel's width allows,
|
||||
// up to the cap, and sums the rest into Other.
|
||||
const notice = within(root).queryByTestId('distribution-other-notice');
|
||||
if (isStacked) {
|
||||
await expect(notice).not.toBeInTheDocument();
|
||||
await expect(drawn.series.length - 1).toBe(args.series);
|
||||
} else {
|
||||
if (args.series > MAX_SIDE_BY_SIDE_GROUPS) {
|
||||
await expect(notice).toHaveTextContent(
|
||||
`of ${args.series} groups; the rest are summed into Other.`,
|
||||
);
|
||||
}
|
||||
await expect(drawn.series.length - 1).toBeLessThanOrEqual(
|
||||
MAX_SIDE_BY_SIDE_GROUPS,
|
||||
);
|
||||
}
|
||||
|
||||
// One slot a bucket. Clamped to 10–1000: (10, 25] is slot 2, (500, 1000] slot 7.
|
||||
if (args.distributionXRange === 'clamped') {
|
||||
await expect(drawn.scales.x.min).toBe(2);
|
||||
await expect(drawn.scales.x.max).toBe(8);
|
||||
} else {
|
||||
await expect(drawn.scales.x.max ?? 0).toBeLessThanOrEqual(
|
||||
DISTRIBUTION_BUCKETS.length + 1,
|
||||
);
|
||||
}
|
||||
|
||||
if (args.stack === StackMode.percent) {
|
||||
await expect(drawn.scales.y.max ?? 0).toBeGreaterThanOrEqual(100);
|
||||
} else {
|
||||
await expect(drawn.scales.y.distr).toBe(args.yScale === 'log' ? 3 : 1);
|
||||
}
|
||||
};
|
||||
|
||||
/** Rows the tooltip list's 300 px window always holds. */
|
||||
const TOOLTIP_ROWS_IN_VIEW = 7;
|
||||
|
||||
/** Moves uPlot's cursor over `bucket`, low in its column, as a real pointer would. */
|
||||
const hoverBucket = (plot: uPlot, bucket: number): void => {
|
||||
const rect = plot.over.getBoundingClientRect();
|
||||
const init = {
|
||||
bubbles: true,
|
||||
clientX: rect.left + plot.valToPos(bucket + 0.5, 'x'),
|
||||
clientY: rect.top + rect.height - 2,
|
||||
};
|
||||
plot.over.dispatchEvent(new MouseEvent('mouseenter', init));
|
||||
plot.over.dispatchEvent(new MouseEvent('mousemove', init));
|
||||
};
|
||||
|
||||
const bucketCounts = (args: PanelPlayArgs, bucket: number): number[] =>
|
||||
Array.from(
|
||||
{ length: args.series },
|
||||
(_, group) => distributionCounts(group, args.overflow)[bucket],
|
||||
);
|
||||
|
||||
const expectTooltipFor = async (
|
||||
plot: uPlot,
|
||||
args: PanelPlayArgs,
|
||||
bucket: number,
|
||||
): Promise<void> => {
|
||||
const drawnGroups = plot.series.length - 1;
|
||||
hoverBucket(plot, bucket);
|
||||
const total = bucketCounts(args, bucket).reduce(
|
||||
(sum, count) => sum + count,
|
||||
0,
|
||||
);
|
||||
|
||||
const tooltip = await within(document.body).findByTestId(
|
||||
'distribution-tooltip',
|
||||
{},
|
||||
PANEL_LOAD,
|
||||
);
|
||||
await waitFor(
|
||||
async () =>
|
||||
expect(
|
||||
within(tooltip).getByTestId('distribution-tooltip-total'),
|
||||
).toHaveTextContent(total.toLocaleString()),
|
||||
PANEL_LOAD,
|
||||
);
|
||||
// The hovered group sits above the divider. The list below runs largest first, one row
|
||||
// a drawn group, or over Other the groups Other sums.
|
||||
const active = within(tooltip).getByTestId('distribution-tooltip-active');
|
||||
const isOverOther = (active.textContent ?? '').startsWith('Other');
|
||||
// A lone group collapses into the row above the divider, as in the time-series tooltip.
|
||||
const list = within(tooltip).queryByTestId('uplot-tooltip-list');
|
||||
if (!list) {
|
||||
await expect(drawnGroups).toBe(1);
|
||||
return;
|
||||
}
|
||||
const listed = isOverOther ? args.series - (drawnGroups - 1) : drawnGroups;
|
||||
// The list renders only the rows in view, so a longer one is checked in part.
|
||||
const isWhollyRendered = listed <= TOOLTIP_ROWS_IN_VIEW;
|
||||
// Virtuoso draws one row, measures it, then the rest.
|
||||
let rows: HTMLElement[] = [];
|
||||
await waitFor(async () => {
|
||||
rows = within(list).getAllByTestId('uplot-tooltip-item-content');
|
||||
if (isWhollyRendered) {
|
||||
await expect(rows).toHaveLength(listed);
|
||||
}
|
||||
}, PANEL_LOAD);
|
||||
// The label span carries the full label as its title; the count follows it.
|
||||
const rowLabels = rows.map(
|
||||
(row) => row.querySelector('[title]')?.getAttribute('title') ?? '',
|
||||
);
|
||||
const rowCounts = rows.map((row, index) =>
|
||||
Number(
|
||||
(row.textContent ?? '').slice(rowLabels[index].length).replace(/,/g, ''),
|
||||
),
|
||||
);
|
||||
await expect(rowCounts).toStrictEqual([...rowCounts].sort((a, b) => b - a));
|
||||
// Rows carry each series' full label, as the legend and time-series tooltip do.
|
||||
if (isWhollyRendered && !isOverOther) {
|
||||
await expect([...rowLabels].sort()).toStrictEqual(
|
||||
plot.series
|
||||
.slice(1)
|
||||
.map((series) => String(series.label))
|
||||
.sort(),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Hovers the (100 ms, 250 ms] bucket, then the overflow one. Only a drawn
|
||||
* Distribution has a tooltip to check.
|
||||
*/
|
||||
export const expectDistributionTooltip = async (
|
||||
root: HTMLElement,
|
||||
args: PanelPlayArgs,
|
||||
): Promise<void> => {
|
||||
if (
|
||||
args.kind !== 'Distribution' ||
|
||||
args.dataState !== 'loaded' ||
|
||||
args.bucketSource === 'no field' ||
|
||||
!hasData(args)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let plot: uPlot | undefined;
|
||||
await waitFor(async () => {
|
||||
plot = findPlot(root);
|
||||
await expect(plot).toBeDefined();
|
||||
}, PANEL_LOAD);
|
||||
const drawn = plot as uPlot;
|
||||
|
||||
await expectTooltipFor(drawn, args, DISTRIBUTION_BUCKETS.indexOf(250));
|
||||
// A clamped range ends at 1000 ms, before the overflow bucket.
|
||||
if (args.distributionXRange !== 'clamped') {
|
||||
await expectTooltipFor(drawn, args, DISTRIBUTION_BUCKETS.length);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,7 +3,11 @@ import { expect, within } from 'storybook/test';
|
||||
import { PANEL_NAME } from '../__story_mockdata__/constants';
|
||||
|
||||
import { hasData, PANEL_LOAD, type PanelPlayArgs } from './args';
|
||||
import { expectHeatmap, expectHistogram } from './distributions';
|
||||
import {
|
||||
expectDistribution,
|
||||
expectHeatmap,
|
||||
expectHistogram,
|
||||
} from './distributions';
|
||||
import { expectLineChart } from './lineChart';
|
||||
import { expectListPage } from './list';
|
||||
import { findPlot } from './plot';
|
||||
@@ -32,6 +36,7 @@ const KIND_EXPECTATIONS: Record<
|
||||
Area: expectLineChart,
|
||||
Histogram: expectHistogram,
|
||||
Heatmap: expectHeatmap,
|
||||
Distribution: expectDistribution,
|
||||
Pie: expectPie,
|
||||
Number: expectNumber,
|
||||
Table: expectTable,
|
||||
@@ -58,7 +63,10 @@ export const expectPanel = async (
|
||||
|
||||
await within(root).findByText(PANEL_NAME[args.kind], {}, PANEL_LOAD);
|
||||
|
||||
if (args.kind === 'Heatmap' && args.heatmapSource === 'no field') {
|
||||
if (
|
||||
(args.kind === 'Heatmap' || args.kind === 'Distribution') &&
|
||||
args.bucketSource === 'no field'
|
||||
) {
|
||||
await within(root).findByTestId('panel-no-query', {}, PANEL_LOAD);
|
||||
await expect(findPlot(root)).toBeUndefined();
|
||||
return;
|
||||
@@ -81,7 +89,11 @@ export const expectPanel = async (
|
||||
within(root).queryByTestId('panel-status-warning'),
|
||||
).not.toBeInTheDocument();
|
||||
}
|
||||
// The panel's own read of the data, apart from the response's warning.
|
||||
await expect(
|
||||
Boolean(within(root).queryByTestId('panel-status-data-warning')),
|
||||
).toBe(expectsTopListWarning(args));
|
||||
).toBe(
|
||||
expectsTopListWarning(args) ||
|
||||
(args.kind === 'Distribution' && args.overflow === 'high'),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { expect, within } from 'storybook/test';
|
||||
|
||||
import type { PanelPlayArgs } from './args';
|
||||
import { expectDistributionTooltip } from './distributions';
|
||||
import { expectPanel } from './expectPanel';
|
||||
import { filterLegend, searchTable } from './interactions';
|
||||
import { walkListPages } from './list';
|
||||
@@ -40,3 +41,11 @@ export const playLegendRight: PanelPlay = async ({ canvasElement, args }) => {
|
||||
await expectPanel(canvasElement, args);
|
||||
await filterLegend(canvasElement, args);
|
||||
};
|
||||
|
||||
export const playDistributionTooltip: PanelPlay = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}) => {
|
||||
await expectPanel(canvasElement, args);
|
||||
await expectDistributionTooltip(canvasElement, args);
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type QueryRangeV5200,
|
||||
type Querybuildertypesv5DistributionDTO,
|
||||
type Querybuildertypesv5ColumnDescriptorDTO,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
type Querybuildertypesv5TimeSeriesDTO,
|
||||
@@ -17,6 +18,7 @@ import type { Warning } from 'types/api';
|
||||
import type {
|
||||
ColumnDescriptor,
|
||||
MetricRangePayloadV5,
|
||||
RawRow,
|
||||
RequestType,
|
||||
TimeSeries,
|
||||
TimeSeriesValue,
|
||||
@@ -134,7 +136,7 @@ export const queryRangeV5EmptyResponse = (
|
||||
},
|
||||
});
|
||||
|
||||
export const queryRangeV5RawResponse = <T>(
|
||||
export const queryRangeV5RawResponse = <T extends RawRow['data']>(
|
||||
rows: Array<{ timestamp: string; data: T }>,
|
||||
options: ResponseOptions & {
|
||||
hasMore?: boolean;
|
||||
@@ -325,6 +327,37 @@ export const queryRangeV5HeatmapResponse = ({
|
||||
},
|
||||
});
|
||||
|
||||
interface DistributionResponseSpec {
|
||||
/** Ascending bucket upper bounds; each distribution carries one count per bound plus the overflow. */
|
||||
buckets: number[];
|
||||
distributions: Querybuildertypesv5DistributionDTO[];
|
||||
queryName?: string;
|
||||
warning?: Warning;
|
||||
}
|
||||
|
||||
/** A distribution panel's answer: per-group counts summed over the range. */
|
||||
export const queryRangeV5DistributionResponse = ({
|
||||
buckets,
|
||||
distributions,
|
||||
queryName = 'A',
|
||||
warning,
|
||||
}: DistributionResponseSpec): QueryRangeV5200 => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
warning,
|
||||
type: Querybuildertypesv5RequestTypeDTO.distribution,
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
queryName,
|
||||
aggregations: [{ index: 0, meta: { buckets }, distributions }],
|
||||
},
|
||||
],
|
||||
},
|
||||
meta: { rowsScanned: 0, bytesScanned: 0, durationMs: 0 },
|
||||
},
|
||||
});
|
||||
|
||||
/** The v5 request's builder queries and formulas in the shape `keysFor` reads them. */
|
||||
const v5QueryShapes = (
|
||||
body: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
|
||||
@@ -82,6 +82,7 @@ export const panelTypeToExplorerView: Record<PANEL_TYPES, ExplorerViews> = {
|
||||
[PANEL_TYPES.PIE]: ExplorerViews.TIMESERIES,
|
||||
[PANEL_TYPES.HISTOGRAM]: ExplorerViews.TIMESERIES,
|
||||
[PANEL_TYPES.HEATMAP]: ExplorerViews.TIMESERIES,
|
||||
[PANEL_TYPES.DISTRIBUTION]: ExplorerViews.TIMESERIES,
|
||||
[PANEL_TYPES.GEO_MAP]: ExplorerViews.TABLE,
|
||||
[PANEL_TYPES.TOP_LIST]: ExplorerViews.TABLE,
|
||||
// Dashboard-only visualisation; explorers never offer it.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user