Compare commits

..

14 Commits

Author SHA1 Message Date
Aditya Singh
043cb3f64d chore(storybook): answer the services list and home stories from query_range v5 2026-11-17 23:50:14 +05:30
Aditya Singh
2e7b42e734 test(services): cover the span-metrics list and home widget on query_range v5 2026-11-17 23:49:36 +05:30
Aditya Singh
934866ab9d fix(service-details): show the span-metrics latency card in ms
The latency card used ns for both sources, but span metrics store latency
in ms, so the axis read µs.
2026-11-17 23:49:08 +05:30
Aditya Singh
91900ea04e fix(home): load the span-metrics services widget from query_range v5 and show p99 in ms
The home P99 column divided by 1e6 for both sources, but span metrics store
latency in ms, so it always read 0.00. The column now picks the unit by
source, like the services list.
2026-11-17 23:48:29 +05:30
Aditya Singh
7ccc4bff6b fix(services): load the span-metrics services list from query_range v5
The v4 reader looked for newResult, which table responses never carry, so
every P99, error rate and ops/s cell read 0.00.
2026-11-17 23:33:16 +05:30
Aditya Singh
11f6f7b0e1 chore(storybook): move the service details download menu play into the mocks 2026-11-17 18:12:18 +05:30
Aditya Singh
5c2c814e8a Merge remote-tracking branch 'origin/main' into feat/service-details-v5 2026-11-17 17:57:41 +05:30
Aditya Singh
0c1560514d test(service-details): pin the services list step and set the resource filter through the route 2026-11-17 13:25:09 +05:30
Aditya Singh
47e2486639 refactor(service-details): drop the unused traces apdex query builder 2026-11-17 13:25:06 +05:30
Aditya Singh
fdd4d8d078 chore(storybook): add the span-metrics service details story 2026-11-17 13:24:58 +05:30
Aditya Singh
079ce982c6 fix(service-details): let v5 pick the step interval for the metrics graphs 2026-11-17 12:42:47 +05:30
Aditya Singh
de1edd1f2d chore(storybook): answer the service details story on query_range v5 with a source control 2026-11-17 01:17:11 +05:30
Aditya Singh
6429c7a3ea feat(service-details): move the graphs and the span-metrics key operations to query_range v5 2026-11-17 01:13:00 +05:30
Aditya Singh
82d7243ad9 feat(query-builder): send the histogram comparison param on v5 metric aggregations 2026-11-16 23:31:25 +05:30
122 changed files with 1170 additions and 5442 deletions

View File

@@ -18,9 +18,7 @@ tag <diff> <tag> <story-id>... # what the reviewer should look at
export <diff> --out <dir> # a static site, hostable
```
`<storybook>` is a running dev server (`http://localhost:6006`), a build directory holding `index.json`, or a project directory with `.storybook/`. **Capture from a build**: `pnpm storybook:build` in `frontend` (about 2 minutes) writes `storybook-static/`. A dev server serves the preview module by module, which adds 5 to 10 seconds to every story and, with several stories at once, ends in `page.goto: Timeout 30000ms exceeded` retries.
Pass `--globals 'a11y.manual:!true'` to every `capture`. The a11y addon otherwise runs axe after every story, about 2 seconds each, and nothing it does shows in a shot.
`<storybook>` is a running dev server (`http://localhost:6006`), a build directory holding `index.json`, or a project directory with `.storybook/`. The frontend has **no `build-storybook` script**, only `storybook dev -p 6006`, so point `capture` at a dev server.
## Cover the change with stories first
@@ -32,7 +30,7 @@ Then confirm it worked: the two runs' story counts should differ by exactly the
## Rules that are not optional
**One freshly started Storybook per ref.** Never start one server and switch git branches under it. Vite's HMR reloads the page, but some modules do not re-initialise, so the shot differs silently from a clean boot and the difference looks like a real change. Settle time does not fix this and is not the variable. Use one worktree and one port per ref, and stop each server before the next. A build made in each ref's worktree has none of this.
**One freshly started Storybook per ref.** Never start one server and switch git branches under it. Vite's HMR reloads the page, but some modules do not re-initialise, so the shot differs silently from a clean boot and the difference looks like a real change. Settle time does not fix this and is not the variable. Use one worktree and one port per ref, and stop each server before the next.
**Capture both themes: `--theme dark,light`.** Without it sbshot shoots the story's own default and everything lands in a single `default/` folder, so every regression in the other theme is invisible. Themes double the shot count, so scope with `--stories` or `--title`, never by dropping a theme.

View File

@@ -364,7 +364,7 @@ tokenizer:
interval: 1h
token:
# The maximum number of tokens a user can have. This limits the number of concurrent sessions a user can have.
max_per_user: 20
max_per_user: 5
##################### Flagger #####################
flagger:

View File

@@ -5527,7 +5527,6 @@ components:
signoz/TablePanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec'
signoz/TextPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec'
signoz/TimeSeriesPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
signoz/TopListPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
propertyName: kind
oneOf:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
@@ -5542,7 +5541,6 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec'
type: object
DashboardtypesPanelPluginKind:
enum:
@@ -5558,7 +5556,6 @@ components:
- signoz/HeatmapPanel
- signoz/ScatterPlotPanel
- signoz/GeoMapPanel
- signoz/TopListPanel
type: string
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
properties:
@@ -5740,21 +5737,6 @@ components:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec:
properties:
kind:
description: The panel kind.
enum:
- signoz/TopListPanel
type: string
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesTopListPanelSpec'
description: The options for this panel kind. {} accepts every default.
required:
- kind
- spec
type: object
DashboardtypesPanelSpec:
properties:
display:
@@ -6517,43 +6499,6 @@ components:
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
fixed window.'
type: object
DashboardtypesTopListAppearance:
properties:
barColor:
description: Hex color of every bar; a matching background threshold overrides
it.
type: string
showRank:
description: Numbers each row by its position in the list.
type: boolean
showShare:
description: Shows each row's share of the listed rows' total.
type: boolean
required:
- barColor
type: object
DashboardtypesTopListPanelSpec:
properties:
appearance:
allOf:
- $ref: '#/components/schemas/DashboardtypesTopListAppearance'
description: Rank, share and bar color options.
formatting:
allOf:
- $ref: '#/components/schemas/DashboardtypesPanelFormatting'
description: Unit and decimal precision of the values.
thresholds:
description: Rules that recolor a row when its value compares to a threshold
as specified.
items:
$ref: '#/components/schemas/DashboardtypesComparisonThreshold'
nullable: true
type: array
visualization:
allOf:
- $ref: '#/components/schemas/DashboardtypesBasicVisualization'
description: The time range the rows are computed over.
type: object
DashboardtypesUpdatableDashboardV2:
properties:
image:

View File

@@ -34,12 +34,6 @@
pylon: { enabled: false, appId: '', identitySecret: '' },
},
};
// OverlayScrollbars drives its handles with scroll-driven animations when the
// browser has `ScrollTimeline`. Those never finish, and Storybook waits up to
// 5s for running animations after every `play`, so each story with a scroller
// would pay the full 5s. Without it the handles are positioned from script.
delete window.ScrollTimeline;
</script>
<script>

View File

@@ -7190,63 +7190,6 @@ export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDa
spec: DashboardtypesGeoMapPanelSpecDTO;
}
/**
* The panel kind.
*/
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind {
'signoz/TopListPanel' = 'signoz/TopListPanel',
}
export interface DashboardtypesTopListAppearanceDTO {
/**
* @type string
* @description Hex color of every bar; a matching background threshold overrides it.
*/
barColor: string;
/**
* @type boolean
* @description Numbers each row by its position in the list.
*/
showRank?: boolean;
/**
* @type boolean
* @description Shows each row's share of the listed rows' total.
*/
showShare?: boolean;
}
export interface DashboardtypesTopListPanelSpecDTO {
/**
* @description Rank, share and bar color options.
*/
appearance?: DashboardtypesTopListAppearanceDTO;
/**
* @description Unit and decimal precision of the values.
*/
formatting?: DashboardtypesPanelFormattingDTO;
/**
* @type array,null
* @description Rules that recolor a row when its value compares to a threshold as specified.
*/
thresholds?: DashboardtypesComparisonThresholdDTO[] | null;
/**
* @description The time range the rows are computed over.
*/
visualization?: DashboardtypesBasicVisualizationDTO;
}
export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO {
/**
* @enum signoz/TopListPanel
* @type string
* @description The panel kind.
*/
kind: DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind;
/**
* @description The options for this panel kind. {} accepts every default.
*/
spec: DashboardtypesTopListPanelSpecDTO;
}
export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTO
@@ -7259,8 +7202,7 @@ export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTO;
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO;
export enum Querybuildertypesv5RequestTypeDTO {
scalar = 'scalar',
@@ -8548,7 +8490,6 @@ export enum DashboardtypesPanelPluginKindDTO {
'signoz/HeatmapPanel' = 'signoz/HeatmapPanel',
'signoz/ScatterPlotPanel' = 'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
'signoz/TopListPanel' = 'signoz/TopListPanel',
}
/**
* The RFC 6902 operations, applied in order against the dashboard's postable shape.

View File

@@ -55,7 +55,6 @@ export function mapPanelTypeToRequestType(panelType: PANEL_TYPES): RequestType {
case PANEL_TYPES.PIE:
case PANEL_TYPES.VALUE:
case PANEL_TYPES.GEO_MAP:
case PANEL_TYPES.TOP_LIST:
return 'scalar';
case PANEL_TYPES.TRACE:
return 'trace';
@@ -280,8 +279,7 @@ export function createAggregation(
panelType === PANEL_TYPES.SCATTER ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.GEO_MAP ||
panelType === PANEL_TYPES.TOP_LIST);
panelType === PANEL_TYPES.GEO_MAP);
if (queryData.dataSource === DataSource.METRICS) {
return [
@@ -301,6 +299,10 @@ export function createAggregation(
reduceTo: haveReduceTo
? queryData?.aggregations?.[0]?.reduceTo || queryData?.reduceTo
: undefined,
...(queryData?.aggregations?.[0]?.comparisonSpaceAggregationParam && {
comparisonSpaceAggregationParam:
queryData.aggregations[0].comparisonSpaceAggregationParam,
}),
},
];
}

View File

@@ -12,13 +12,7 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
import { get, isEmpty } from 'lodash-es';
import { ChevronUp } from '@signozhq/icons';
import {
Querybuildertypesv5BucketOptionsDTO,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType,
} from 'api/generated/services/sigNoz.schemas';
import { isLoneBuilderQuery } from 'lib/query/builderEnvelope';
import { Querybuildertypesv5BucketOptionsDTO } from 'api/generated/services/sigNoz.schemas';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { MetricAggregation } from 'types/api/v5/queryRange';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
@@ -153,34 +147,10 @@ function QueryAddOns({
[resolvedFields],
);
// A panel's default limit applies only to a lone query: per-query limits can keep
// different groups and break a formula's join.
const isLoneQuery = useMemo(
() =>
isLoneBuilderQuery([
...(currentQuery.builder?.queryData ?? [query]).map((data) => ({
type:
data.builderQueryType ??
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
})),
...(currentQuery.builder?.queryFormulas ?? []).map(() => ({
type: Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula,
})),
...(currentQuery.builder?.queryTraceOperator ?? []).map(() => ({
type:
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType.builder_trace_operator,
})),
]),
[currentQuery.builder, query],
);
const placeholderOf = useCallback(
(key: InputAddOnField): string =>
(key === QueryBuilderField.Limit && !isLoneQuery
? undefined
: resolvedFields.get(key)?.placeholder) ??
ADD_ON_DEFINITIONS[key].placeholder,
[resolvedFields, isLoneQuery],
resolvedFields.get(key)?.placeholder ?? ADD_ON_DEFINITIONS[key].placeholder,
[resolvedFields],
);
const isDisabled = useCallback(

View File

@@ -67,9 +67,7 @@ function QueryAggregationOptions({
onChange={onChange}
queryData={queryData}
maxAggregations={
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.TOP_LIST
panelType === PANEL_TYPES.VALUE || panelType === PANEL_TYPES.PIE
? 1
: undefined
}

View File

@@ -7,7 +7,6 @@ const SCALAR_PANEL_TYPES: ReadonlySet<string> = new Set<string>([
PANEL_TYPES.PIE,
PANEL_TYPES.VALUE,
PANEL_TYPES.GEO_MAP,
PANEL_TYPES.TOP_LIST,
]);
export function isScalarPanelType(panelType?: string | null): boolean {

View File

@@ -15,9 +15,6 @@ import QueryAddOns from '../QueryV2/QueryAddOns/QueryAddOns';
// Mocks: only what is required for this component to render and for us to assert handler calls
const mockHandleChangeQueryData = jest.fn();
const mockHandleSetQueryData = jest.fn();
let mockCurrentQuery: { unit: string | undefined; builder?: unknown } = {
unit: undefined,
};
jest.mock('hooks/queryBuilder/useQueryBuilderOperations', () => ({
useQueryOperations: (): {
@@ -30,10 +27,10 @@ jest.mock('hooks/queryBuilder/useQueryBuilderOperations', () => ({
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: (): {
handleSetQueryData: typeof mockHandleSetQueryData;
currentQuery: typeof mockCurrentQuery;
currentQuery: { unit: string | undefined };
} => ({
handleSetQueryData: mockHandleSetQueryData,
currentQuery: mockCurrentQuery,
currentQuery: { unit: undefined },
}),
}));
@@ -232,77 +229,6 @@ describe('QueryAddOns', () => {
);
});
describe('a pinned limit with a default', () => {
const renderPinnedLimit = (): void => {
render(
<QueryAddOns
query={baseQuery()}
version="v5"
isRawQuery={false}
showReduceTo={false}
panelType={PANEL_TYPES.TOP_LIST}
index={0}
fieldsConfig={{
[QueryBuilderField.Limit]: {
state: 'pinned',
placeholder: 'Default 10',
},
}}
isForTraceOperator={false}
/>,
);
};
afterEach(() => {
mockCurrentQuery = { unit: undefined };
});
it('is open with its default as the placeholder', () => {
renderPinnedLimit();
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
'placeholder',
'Default 10',
);
});
it('drops the default for an AI query, which the request leaves unlimited', () => {
mockCurrentQuery = {
unit: undefined,
builder: {
queryData: [{ ...baseQuery(), builderQueryType: 'builder_ai_query' }],
queryFormulas: [],
queryTraceOperator: [],
},
};
renderPinnedLimit();
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
'placeholder',
'Enter limit',
);
});
it('drops the default once a formula joins the query', () => {
mockCurrentQuery = {
unit: undefined,
builder: {
queryData: [baseQuery()],
queryFormulas: [{ expression: 'A * 2' }],
queryTraceOperator: [],
},
};
renderPinnedLimit();
expect(screen.getByTestId('input-Limit')).toHaveAttribute(
'placeholder',
'Enter limit',
);
});
});
it('auto-opens Order By and Limit when present in query', () => {
const query = baseQuery({
orderBy: [{ columnName: 'duration', order: 'desc' }],

View File

@@ -35,7 +35,6 @@ export const getComponentForPanelType = (
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.GEO_MAP]: null,
[PANEL_TYPES.TOP_LIST]: null,
// Dashboards v2 renders this kind; nothing reaches the V1 chart map for it.
[PANEL_TYPES.TEXT]: null,
[PANEL_TYPES.SCATTER]: null,

View File

@@ -341,7 +341,6 @@ export enum PANEL_TYPES {
HISTOGRAM = 'histogram',
HEATMAP = 'heatmap',
GEO_MAP = 'geo_map',
TOP_LIST = 'top_list',
TEXT = 'text',
EMPTY_WIDGET = 'EMPTY_WIDGET',
}

View File

@@ -4,7 +4,7 @@ import { QueryKey } from 'react-query';
import { useSelector } from 'react-redux';
import { Button, Select, Skeleton, Table } from 'antd';
import logEvent from 'api/common/logEvent';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import ROUTES from 'constants/routes';
import {
getQueryRangeRequestData,
@@ -36,10 +36,12 @@ import { openInNewTab } from 'utils/navigation';
import triangleRulerUrl from '@/assets/Icons/triangle-ruler.svg';
import { DOCS_LINKS } from '../constants';
import { columns, TIME_PICKER_OPTIONS } from './constants';
import { getColumns, TIME_PICKER_OPTIONS } from './constants';
const homeInterval = 30 * 60 * 1000;
const columns = getColumns(true);
// Extracted EmptyState component
const EmptyState = memo(
({
@@ -69,7 +71,7 @@ const EmptyState = memo(
type="default"
className="periscope-btn secondary"
onClick={(): void => {
logEvent('Homepage: Get Started clicked', {
void logEvent('Homepage: Get Started clicked', {
source: 'Service Metrics',
});
@@ -90,7 +92,7 @@ const EmptyState = memo(
type="link"
className="learn-more-link"
onClick={(): void => {
logEvent('Homepage: Learn more clicked', {
void logEvent('Homepage: Learn more clicked', {
source: 'Service Metrics',
});
window.open(
@@ -118,7 +120,10 @@ const ServicesListTable = memo(
services: ServicesList[];
onRowClick: (record: ServicesList, event: React.MouseEvent) => void;
}): JSX.Element => (
<div className="services-list-container home-data-item-container metrics-services-list">
<div
className="services-list-container home-data-item-container metrics-services-list"
data-testid="home-services-table"
>
<div className="services-list">
<Table<ServicesList>
columns={columns}
@@ -197,7 +202,7 @@ function ServiceMetrics({
(option) => option.value === value,
);
logEvent('Homepage: Services time interval updated', {
void logEvent('Homepage: Services time interval updated', {
updatedTimeInterval: timeInterval?.label,
});
@@ -222,7 +227,7 @@ function ServiceMetrics({
const dataQueries = useGetQueriesRange(
queryRangeRequestData,
ENTITY_VERSION_V4,
ENTITY_VERSION_V5,
{
queryKey: useMemo(
() => [
@@ -258,12 +263,7 @@ function ServiceMetrics({
);
const sortedServices = useMemo(
() =>
services?.sort((a, b) => {
const aUpdateAt = new Date(a.p99).getTime();
const bUpdateAt = new Date(b.p99).getTime();
return bUpdateAt - aUpdateAt;
}) || [],
() => [...services].sort((a, b) => b.p99 - a.p99),
[services],
);
@@ -281,7 +281,7 @@ function ServiceMetrics({
const handleRowClick = useCallback(
(record: ServicesList, event: React.MouseEvent) => {
logEvent('Homepage: Service clicked', {
void logEvent('Homepage: Service clicked', {
serviceName: record.serviceName,
});
safeNavigate(`${ROUTES.APPLICATION}/${record.serviceName}`, {
@@ -348,7 +348,7 @@ function ServiceMetrics({
type="link"
className="periscope-btn link learn-more-link"
onClick={(): void => {
logEvent('Homepage: All Services clicked', {});
void logEvent('Homepage: All Services clicked', {});
}}
>
All Services <ArrowRight size={12} />

View File

@@ -22,10 +22,12 @@ import { openInNewTab } from 'utils/navigation';
import triangleRulerUrl from '@/assets/Icons/triangle-ruler.svg';
import { DOCS_LINKS } from '../constants';
import { columns, TIME_PICKER_OPTIONS } from './constants';
import { getColumns, TIME_PICKER_OPTIONS } from './constants';
const homeInterval = 30 * 60 * 1000;
const columns = getColumns(false);
export default function ServiceTraces({
onUpdateChecklistDoneItem,
loadingUserPreferences,
@@ -91,7 +93,7 @@ export default function ServiceTraces({
(option) => option.value === value,
);
logEvent('Homepage: Services time interval updated', {
void logEvent('Homepage: Services time interval updated', {
updatedTimeInterval: timeInterval?.label,
});
@@ -126,7 +128,7 @@ export default function ServiceTraces({
type="default"
className="periscope-btn secondary"
onClick={(): void => {
logEvent('Homepage: Get Started clicked', {
void logEvent('Homepage: Get Started clicked', {
source: 'Service Traces',
});
@@ -147,7 +149,7 @@ export default function ServiceTraces({
type="link"
className="learn-more-link"
onClick={(): void => {
logEvent('Homepage: Learn more clicked', {
void logEvent('Homepage: Learn more clicked', {
source: 'Service Traces',
});
window.open(
@@ -168,7 +170,10 @@ export default function ServiceTraces({
const renderDashboardsList = useCallback(
() => (
<div className="services-list-container home-data-item-container traces-services-list">
<div
className="services-list-container home-data-item-container traces-services-list"
data-testid="home-services-table"
>
<div className="services-list">
<Table<ServicesList>
columns={columns}
@@ -178,7 +183,7 @@ export default function ServiceTraces({
className="services-table"
onRow={(record: ServicesList): Record<string, unknown> => ({
onClick: (event: React.MouseEvent): void => {
logEvent('Homepage: Service clicked', {
void logEvent('Homepage: Service clicked', {
serviceName: record.serviceName,
});
@@ -246,7 +251,7 @@ export default function ServiceTraces({
type="link"
className="periscope-btn link learn-more-link"
onClick={(): void => {
logEvent('Homepage: All Services clicked', {});
void logEvent('Homepage: All Services clicked', {});
}}
>
All Services <ArrowRight size={12} />

View File

@@ -0,0 +1,65 @@
import { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
import {
Querybuildertypesv5ColumnTypeDTO,
Querybuildertypesv5RequestTypeDTO,
type QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, waitFor } from 'tests/test-utils';
import ServiceMetrics from '../ServiceMetrics';
const topLevelOperations: ServiceDataProps = { SampleApp: ['GET'] };
// A = p99 (ms), D = ops/s, F1 = error rate
const scalarTable: QueryRangeV5200 = {
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: {
results: [
{
columns: ['A', 'D', 'F1'].map((queryName) => ({
name: '__result_0',
queryName,
aggregationIndex: 0,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
})),
data: [[148.25, 12.4, 1.8]],
},
],
},
},
};
describe('Home ServiceMetrics', () => {
beforeEach(() => {
server.use(
rest.post(
'http://localhost/api/v1/service/top_level_operations',
(_, res, ctx) => res(ctx.status(200), ctx.json(topLevelOperations)),
),
rest.post('http://localhost/api/v5/query_range', (_, res, ctx) =>
res(ctx.status(200), ctx.json(scalarTable)),
),
);
});
it('shows the span-metrics p99 in ms as sent', async () => {
render(
<ServiceMetrics
onUpdateChecklistDoneItem={jest.fn()}
loadingUserPreferences={false}
/>,
);
await waitFor(() =>
expect(
Array.from(
screen.getByTestId('home-services-table').querySelectorAll('tbody tr td'),
).map((cell) => cell.textContent),
).toStrictEqual(['SampleApp', '148.25', '1.80', '12.40']),
);
});
});

View File

@@ -0,0 +1,45 @@
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, waitFor } from 'tests/test-utils';
import { ServicesList } from 'types/api/metrics/getService';
import ServiceTraces from '../ServiceTraces';
const services: ServicesList[] = [
{
serviceName: 'SampleApp',
p99: 148_250_000,
avgDuration: 0,
numCalls: 100,
callRate: 12.4,
numErrors: 2,
errorRate: 1.8,
},
];
describe('Home ServiceTraces', () => {
beforeEach(() => {
server.use(
rest.post('http://localhost/api/v2/services', (_, res, ctx) =>
res(ctx.status(200), ctx.json({ status: 'success', data: services })),
),
);
});
it('shows the traces p99 in ms from ns', async () => {
render(
<ServiceTraces
onUpdateChecklistDoneItem={jest.fn()}
loadingUserPreferences={false}
/>,
);
await waitFor(() =>
expect(
Array.from(
screen.getByTestId('home-services-table').querySelectorAll('tbody tr td'),
).map((cell) => cell.textContent),
).toStrictEqual(['SampleApp', '148.25', '1.80', '12.40']),
);
});
});

View File

@@ -1,7 +1,9 @@
import { TableProps } from 'antd';
import { ServicesList } from 'types/api/metrics/getService';
export const columns: TableProps<ServicesList>['columns'] = [
export const getColumns = (
isMetricData: boolean,
): TableProps<ServicesList>['columns'] => [
{
title: 'APPLICATION',
dataIndex: 'serviceName',
@@ -11,7 +13,8 @@ export const columns: TableProps<ServicesList>['columns'] = [
title: 'P99 LATENCY (in ms)',
dataIndex: 'p99',
key: 'p99',
render: (value: number): string => (value / 1000000).toFixed(2),
render: (value: number): string =>
isMetricData ? value.toFixed(2) : (value / 1000000).toFixed(2),
},
{
title: 'ERROR RATE (% of total)',

View File

@@ -33,7 +33,7 @@ jest.mock('../../TracesTable/TracesTable', () => ({
<button
data-testid="remove-total-tokens"
type="button"
onClick={(): void => onColumnRemove?.('trace:total_tokens:number')}
onClick={(): void => onColumnRemove?.('trace:total_tokens:float64')}
>
remove
</button>
@@ -48,7 +48,7 @@ const QUERY_RANGE_URL = `${ENVIRONMENT.baseURL}/api/v5/query_range`;
const TOTAL_TOKENS = {
name: 'total_tokens',
fieldContext: 'trace',
fieldDataType: 'number',
fieldDataType: 'float64',
};
const storedColumnNames = (): string[] | undefined => {

View File

@@ -63,7 +63,7 @@ const mockFieldKeys = (names: string[]): void => {
{
name,
fieldContext: TelemetrytypesFieldContextDTO.trace,
fieldDataType: TelemetrytypesFieldDataTypeDTO.number,
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
},
],
]),

View File

@@ -73,7 +73,7 @@ export const TRACE_VIEW_DEFAULT_COLUMNS: TelemetryFieldKey[] = [
name: 'estimated_total_cost',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'number',
fieldDataType: 'float64',
},
{ name: 'trace_duration_nano' },
{ name: 'span_count' },
@@ -81,37 +81,37 @@ export const TRACE_VIEW_DEFAULT_COLUMNS: TelemetryFieldKey[] = [
name: 'total_tokens',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'number',
fieldDataType: 'float64',
},
{
name: 'input_tokens',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'number',
fieldDataType: 'float64',
},
{
name: 'output_tokens',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'number',
fieldDataType: 'float64',
},
{
name: 'distinct_tool_count',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'number',
fieldDataType: 'float64',
},
{
name: 'llm_call_count',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'number',
fieldDataType: 'float64',
},
{
name: 'tool_call_count',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'number',
fieldDataType: 'float64',
},
{ name: 'start_time' },
{ name: 'end_time' },
@@ -122,7 +122,7 @@ export const TRACE_VIEW_DEFAULT_COLUMNS: TelemetryFieldKey[] = [
name: 'max_llm_duration_nano',
signal: 'traces',
fieldContext: 'trace',
fieldDataType: 'number',
fieldDataType: 'float64',
},
];

View File

@@ -1,3 +1,4 @@
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
import {
alphabet,
initialFormulaBuilderFormValues,
@@ -6,7 +7,9 @@ import {
import getStep from 'lib/getStep';
import store from 'store';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { SpaceAggregation, TimeAggregation } from 'types/api/v5/queryRange';
import {
DataSource,
MetricAggregateOperator,
QueryBuilderData,
ReduceOperators,
@@ -18,6 +21,38 @@ import {
BuilderQuerieswithFormulaProps,
} from '../Tabs/types';
// The query spreads in default `aggregations` (avg / sum, or count() for traces),
// and v5 reads those before the top-level time / space fields, so set them here.
const getAggregations = ({
dataSource,
key,
aggregateOperator,
timeAggregation,
spaceAggregation,
comparisonSpaceAggregationParam,
}: {
dataSource: DataSource;
key: string;
aggregateOperator: string;
timeAggregation: MetricAggregateOperator;
spaceAggregation: MetricAggregateOperator;
comparisonSpaceAggregationParam?: MetrictypesComparisonSpaceAggregationParamDTO;
}): IBuilderQuery['aggregations'] =>
dataSource === DataSource.TRACES
? [{ expression: `${aggregateOperator}(${key})` }]
: [
{
metricName: key,
temporality: '',
timeAggregation: timeAggregation as TimeAggregation,
spaceAggregation: spaceAggregation as SpaceAggregation,
reduceTo: ReduceOperators.AVG,
...(comparisonSpaceAggregationParam && {
comparisonSpaceAggregationParam,
}),
},
];
export const getQueryBuilderQueries = ({
autocompleteData,
groupBy = [],
@@ -31,23 +66,33 @@ export const getQueryBuilderQueries = ({
}: BuilderQueriesProps): QueryBuilderData => ({
queryFormulas: [],
queryData: autocompleteData.map((item, index) => {
const operator = aggregateOperator
? aggregateOperator[index]
: MetricAggregateOperator.SUM_RATE;
const newQueryData: IBuilderQuery = {
...initialQueryBuilderFormValuesMap.metrics,
aggregateOperator: ((): string => {
if (aggregateOperator) {
return aggregateOperator[index];
}
return MetricAggregateOperator.SUM_RATE;
})(),
aggregateOperator: operator,
aggregations: getAggregations({
dataSource,
key: item.key,
aggregateOperator: operator,
timeAggregation: timeAggregateOperators[index],
spaceAggregation: spaceAggregateOperators[index],
}),
disabled: false,
groupBy,
aggregateAttribute: item,
legend: legends[index],
stepInterval: getStep({
end: store.getState().globalTime.maxTime,
inputFormat: 'ns',
start: store.getState().globalTime.minTime,
}),
// v5 sets the metrics step (multiples of 300s from 1 day up); its traces
// default is ~300 points, far denser than these cards
stepInterval:
dataSource === DataSource.METRICS
? null
: getStep({
end: store.getState().globalTime.maxTime,
inputFormat: 'ns',
start: store.getState().globalTime.minTime,
}),
filters: {
items: filterItems[index],
op: 'AND',
@@ -78,6 +123,8 @@ export const getQueryBuilderQuerieswithFormula = ({
legendFormulas,
timeAggregateOperators,
spaceAggregateOperators,
comparisonSpaceAggregationParams = [],
stepInterval,
dataSource,
}: BuilderQuerieswithFormulaProps): QueryBuilderData => ({
queryFormulas: expressions.map((expression, index) => ({
@@ -87,6 +134,14 @@ export const getQueryBuilderQuerieswithFormula = ({
})),
queryData: autocompleteData.map((_, index) => ({
...initialQueryBuilderFormValuesMap.metrics,
aggregations: getAggregations({
dataSource,
key: autocompleteData[index].key,
aggregateOperator: timeAggregateOperators[index],
timeAggregation: timeAggregateOperators[index],
spaceAggregation: spaceAggregateOperators[index],
comparisonSpaceAggregationParam: comparisonSpaceAggregationParams[index],
}),
timeAggregation: timeAggregateOperators[index],
spaceAggregation: spaceAggregateOperators[index],
temporality: Temporality.Delta,
@@ -101,11 +156,7 @@ export const getQueryBuilderQuerieswithFormula = ({
items: additionalItems[index],
op: 'AND',
},
stepInterval: getStep({
end: store.getState().globalTime.maxTime,
inputFormat: 'ns',
start: store.getState().globalTime.minTime,
}),
stepInterval: stepInterval ?? null,
dataSource,
})),
queryTraceOperator: [],

View File

@@ -1,3 +1,4 @@
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
import { OPERATORS } from 'constants/queryBuilder';
import {
BaseAutocompleteData,
@@ -22,11 +23,10 @@ import {
} from '../constant';
import {
ApDexMetricsQueryBuilderQueriesProps,
ApDexProps,
LatencyProps,
OperationPerSecProps,
} from '../Tabs/types';
import { convertMilSecToNanoSec, getNearestHighestBucketValue } from '../utils';
import { getNearestHighestBucketValue } from '../utils';
import {
getQueryBuilderQueries,
getQueryBuilderQuerieswithFormula,
@@ -40,11 +40,10 @@ export const latency = ({
}: LatencyProps): QueryBuilderData => {
const signozLatencyBucketMetrics = WidgetKeys.SignozLatencyBucket;
const signozMetricsServiceName = WidgetKeys.OTelServiceName;
const newAutoCompleteData: BaseAutocompleteData = {
key: isSpanMetricEnable
? signozLatencyBucketMetrics
: WidgetKeys.DurationNano,
: WidgetKeys.SpanDurationNano,
dataType: DataTypes.Float64,
type: isSpanMetricEnable ? '' : MetricsType.Tag,
};
@@ -55,7 +54,7 @@ export const latency = ({
{
id: '',
key: {
key: isSpanMetricEnable ? signozMetricsServiceName : WidgetKeys.ServiceName,
key: WidgetKeys.OTelServiceName,
dataType: DataTypes.String,
type: isSpanMetricEnable ? MetricsType.Resource : MetricsType.Tag,
},
@@ -106,175 +105,6 @@ export const latency = ({
});
};
export const apDexTracesQueryBuilderQueries = ({
servicename,
tagFilterItems,
topLevelOperationsRoute,
threashold,
}: ApDexProps): QueryBuilderData => {
const autoCompleteDataA: BaseAutocompleteData = {
dataType: DataTypes.Float64,
key: '',
type: '',
};
const autoCompleteDataB: BaseAutocompleteData = {
dataType: DataTypes.Float64,
key: '',
type: '',
};
const autoCompleteDataC: BaseAutocompleteData = {
dataType: DataTypes.Float64,
key: '',
type: '',
};
const filterItemA: TagFilterItem[] = [
{
id: '',
key: {
key: WidgetKeys.ServiceName,
dataType: DataTypes.String,
type: MetricsType.Tag,
},
op: OPERATORS['='],
value: servicename,
},
{
id: '',
key: {
key: WidgetKeys.Name,
dataType: DataTypes.String,
type: MetricsType.Tag,
},
op: OPERATORS.IN,
value: [...topLevelOperationsRoute],
},
...tagFilterItems,
];
const filterItemB: TagFilterItem[] = [
{
id: '',
key: {
key: WidgetKeys.HasError,
dataType: DataTypes.bool,
type: MetricsType.Tag,
},
op: OPERATORS['='],
value: false,
},
{
id: '',
key: {
key: WidgetKeys.DurationNano,
dataType: DataTypes.Float64,
type: MetricsType.Tag,
},
op: OPERATORS['<='],
value: convertMilSecToNanoSec(threashold),
},
{
id: '',
key: {
key: WidgetKeys.ServiceName,
dataType: DataTypes.String,
type: MetricsType.Tag,
},
op: OPERATORS['='],
value: servicename,
},
{
id: '',
key: {
key: WidgetKeys.Name,
dataType: DataTypes.String,
type: MetricsType.Tag,
},
op: OPERATORS.IN,
value: [...topLevelOperationsRoute],
},
];
const filterItemC: TagFilterItem[] = [
{
id: '',
key: {
key: WidgetKeys.DurationNano,
dataType: DataTypes.Float64,
type: MetricsType.Tag,
},
op: OPERATORS['<='],
value: convertMilSecToNanoSec(threashold * 4),
},
{
id: '',
key: {
key: WidgetKeys.HasError,
dataType: DataTypes.bool,
type: MetricsType.Tag,
},
op: OPERATORS['='],
value: false,
},
{
id: '',
key: {
key: WidgetKeys.ServiceName,
dataType: DataTypes.String,
type: MetricsType.Tag,
},
op: OPERATORS['='],
value: servicename,
},
{
id: '',
key: {
key: WidgetKeys.Name,
dataType: DataTypes.String,
type: MetricsType.Tag,
},
op: OPERATORS.IN,
value: [...topLevelOperationsRoute],
},
];
const autocompleteData = [
autoCompleteDataA,
autoCompleteDataB,
autoCompleteDataC,
];
const additionalItems = [filterItemA, filterItemB, filterItemC];
const legends = [GraphTitle.APDEX];
const disabled = Array(3).fill(true);
const expressions = [FORMULA.APDEX_TRACES];
const legendFormulas = [GraphTitle.APDEX];
const timeAggregateOperators = [
MetricAggregateOperator.COUNT,
MetricAggregateOperator.COUNT,
MetricAggregateOperator.COUNT,
];
const spaceAggregateOperators = [
MetricAggregateOperator.EMPTY,
MetricAggregateOperator.EMPTY,
MetricAggregateOperator.EMPTY,
];
const dataSource = DataSource.TRACES;
return getQueryBuilderQuerieswithFormula({
autocompleteData,
additionalItems,
legends,
disabled,
expressions,
legendFormulas,
timeAggregateOperators,
spaceAggregateOperators,
dataSource,
});
};
export const apDexMetricsQueryBuilderQueries = ({
servicename,
tagFilterItems,
@@ -283,6 +113,30 @@ export const apDexMetricsQueryBuilderQueries = ({
delta,
metricsBuckets,
}: ApDexMetricsQueryBuilderQueriesProps): QueryBuilderData => {
// the comparison count stops at the largest finite bucket, so a threshold past it
// reads the count metric, which is the +Inf bucket
const countAtOrBelow = (
ms: number,
): {
key: string;
spaceAggregation: MetricAggregateOperator;
param?: MetrictypesComparisonSpaceAggregationParamDTO;
} => {
const bucket = getNearestHighestBucketValue(ms, metricsBuckets);
return bucket === '+Inf'
? {
key: WidgetKeys.SignozLatencyCount,
spaceAggregation: MetricAggregateOperator.SUM,
}
: {
key: WidgetKeys.SignozLatencyBucket,
spaceAggregation: MetricAggregateOperator.COUNT,
param: { operator: '<=', threshold: Number(bucket) },
};
};
const satisfied = countAtOrBelow(threashold * 1000);
const tolerating = countAtOrBelow(threashold * 1000 * 4);
const autoCompleteDataA: BaseAutocompleteData = {
key: WidgetKeys.SignozLatencyCount,
dataType: DataTypes.Float64,
@@ -290,13 +144,13 @@ export const apDexMetricsQueryBuilderQueries = ({
};
const autoCompleteDataB: BaseAutocompleteData = {
key: WidgetKeys.SignozLatencyBucket,
key: satisfied.key,
dataType: DataTypes.Float64,
type: '',
};
const autoCompleteDataC: BaseAutocompleteData = {
key: WidgetKeys.SignozLatencyBucket,
key: tolerating.key,
dataType: DataTypes.Float64,
type: '',
};
@@ -336,16 +190,6 @@ export const apDexMetricsQueryBuilderQueries = ({
op: OPERATORS['!='],
value: 'STATUS_CODE_ERROR',
},
{
id: '',
key: {
key: WidgetKeys.Le,
dataType: DataTypes.String,
type: MetricsType.Tag,
},
op: OPERATORS['='],
value: getNearestHighestBucketValue(threashold * 1000, metricsBuckets),
},
{
id: '',
key: {
@@ -370,16 +214,6 @@ export const apDexMetricsQueryBuilderQueries = ({
];
const filterItemC: TagFilterItem[] = [
{
id: '',
key: {
key: WidgetKeys.Le,
dataType: DataTypes.String,
type: MetricsType.Tag,
},
op: OPERATORS['='],
value: getNearestHighestBucketValue(threashold * 1000 * 4, metricsBuckets),
},
{
id: '',
key: {
@@ -426,16 +260,23 @@ export const apDexMetricsQueryBuilderQueries = ({
? [FORMULA.APDEX_DELTA_SPAN_METRICS]
: [FORMULA.APDEX_CUMULATIVE_SPAN_METRICS];
const legendFormulas = [GraphTitle.APDEX];
// v5 forces increase on histograms, so the total matches it
const timeAggregateOperators = [
MetricAggregateOperator.RATE,
MetricAggregateOperator.RATE,
MetricAggregateOperator.RATE,
MetricAggregateOperator.INCREASE,
MetricAggregateOperator.INCREASE,
MetricAggregateOperator.INCREASE,
];
// a plain sum keeps the le label on B and C, and the formula then cannot join them
const spaceAggregateOperators = [
MetricAggregateOperator.SUM,
MetricAggregateOperator.SUM,
MetricAggregateOperator.SUM,
satisfied.spaceAggregation,
tolerating.spaceAggregation,
];
const comparisonSpaceAggregationParams = [
undefined,
satisfied.param,
tolerating.param,
];
const dataSource = DataSource.METRICS;
@@ -448,6 +289,7 @@ export const apDexMetricsQueryBuilderQueries = ({
legendFormulas,
timeAggregateOperators,
spaceAggregateOperators,
comparisonSpaceAggregationParams,
dataSource,
});
};

View File

@@ -0,0 +1,204 @@
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { QueryBuilderData } from 'types/common/queryBuilder';
import { QueryEnvelope } from 'types/api/v5/queryRange';
import { EQueryType } from 'types/common/dashboard';
import {
apDexMetricsQueryBuilderQueries,
errorPercentage,
latency,
} from '../OverviewQueries';
const toV5Queries = (builder: QueryBuilderData): QueryEnvelope[] =>
prepareQueryRangePayloadV5({
query: {
queryType: EQueryType.QUERY_BUILDER,
promql: [],
builder,
clickhouse_sql: [],
id: 'query',
},
graphType: PANEL_TYPES.TIME_SERIES,
selectedTime: 'GLOBAL_TIME',
}).queryPayload.compositeQuery.queries;
const getAggregations = (queries: QueryEnvelope[]): unknown[] =>
queries.map(
(query) => (query.spec as { aggregations?: unknown[] }).aggregations,
);
const getFilters = (queries: QueryEnvelope[]): unknown[] =>
queries.map((query) => (query.spec as { filter?: unknown }).filter);
describe('service details queries on v5', () => {
it('keeps the latency percentiles on the span metrics histogram', () => {
const queries = toV5Queries(
latency({
servicename: 'frontend',
tagFilterItems: [],
isSpanMetricEnable: true,
topLevelOperationsRoute: ['GET /'],
}),
);
expect(getAggregations(queries)).toStrictEqual(
['p50', 'p90', 'p99'].map((spaceAggregation) => [
{
metricName: 'signoz_latency.bucket',
temporality: undefined,
timeAggregation: '',
spaceAggregation,
reduceTo: undefined,
},
]),
);
});
it('builds the traces latency percentiles from span duration', () => {
const queries = toV5Queries(
latency({
servicename: 'frontend',
tagFilterItems: [],
topLevelOperationsRoute: ['GET /'],
}),
);
expect(getAggregations(queries)).toStrictEqual([
[{ expression: 'p50(duration_nano)' }],
[{ expression: 'p90(duration_nano)' }],
[{ expression: 'p99(duration_nano)' }],
]);
expect(getFilters(queries)[0]).toStrictEqual({
expression: "service.name = 'frontend' AND name in ['GET /']",
});
});
it('rates the error and total calls behind the error percentage', () => {
const queries = toV5Queries(
errorPercentage({
servicename: 'frontend',
tagFilterItems: [],
topLevelOperations: ['GET /'],
}),
);
expect(getAggregations(queries).slice(0, 2)).toStrictEqual(
Array(2).fill([
{
metricName: 'signoz_calls_total',
temporality: undefined,
timeAggregation: 'rate',
spaceAggregation: 'sum',
reduceTo: undefined,
},
]),
);
});
it('counts the apdex buckets at the threshold instead of filtering on le', () => {
const queries = toV5Queries(
apDexMetricsQueryBuilderQueries({
servicename: 'frontend',
tagFilterItems: [],
topLevelOperationsRoute: ['GET /'],
threashold: 0.5,
delta: true,
metricsBuckets: [100, 250, 500, 1000, 2000, 5000],
}),
);
expect(getAggregations(queries).slice(0, 3)).toStrictEqual([
[
{
metricName: 'signoz_latency.count',
temporality: undefined,
timeAggregation: 'increase',
spaceAggregation: 'sum',
reduceTo: undefined,
},
],
...[500, 2000].map((threshold) => [
{
metricName: 'signoz_latency.bucket',
temporality: undefined,
timeAggregation: 'increase',
spaceAggregation: 'count',
reduceTo: undefined,
comparisonSpaceAggregationParam: { operator: '<=', threshold },
},
]),
]);
expect(getFilters(queries).slice(1, 3)).toStrictEqual([
{
expression:
"status.code != 'STATUS_CODE_ERROR' AND service.name = 'frontend' AND operation in ['GET /']",
},
{
expression:
"status.code != 'STATUS_CODE_ERROR' AND service.name = 'frontend' AND operation in ['GET /']",
},
]);
});
it('reads the count metric when the apdex threshold is past the largest bucket', () => {
const queries = toV5Queries(
apDexMetricsQueryBuilderQueries({
servicename: 'frontend',
tagFilterItems: [],
topLevelOperationsRoute: ['GET /'],
threashold: 0.5,
delta: true,
metricsBuckets: [100, 250, 500, 1000],
}),
);
expect(getAggregations(queries)[2]).toStrictEqual([
{
metricName: 'signoz_latency.count',
temporality: undefined,
timeAggregation: 'increase',
spaceAggregation: 'sum',
reduceTo: undefined,
},
]);
});
it('leaves the metrics step to v5 on single and formula queries', () => {
const queries = [
...toV5Queries(
latency({
servicename: 'frontend',
tagFilterItems: [],
isSpanMetricEnable: true,
topLevelOperationsRoute: ['GET /'],
}),
),
...toV5Queries(
errorPercentage({
servicename: 'frontend',
tagFilterItems: [],
topLevelOperations: ['GET /'],
}),
),
].filter((query) => query.type === 'builder_query');
expect(
queries.map(
(query) => (query.spec as { stepInterval?: unknown }).stepInterval,
),
).toStrictEqual(Array(queries.length).fill(null));
});
it('keeps the card step on the traces latency', () => {
const [p50] = toV5Queries(
latency({
servicename: 'frontend',
tagFilterItems: [],
topLevelOperationsRoute: ['GET /'],
}),
);
expect((p50.spec as { stepInterval?: unknown }).stepInterval).toBe(60);
});
});

View File

@@ -5,7 +5,7 @@ import { useAppLocation } from 'lib/router/useAppLocation';
import { useAppParams } from 'lib/router/useAppParams';
import { Col } from 'antd';
import logEvent from 'api/common/logEvent';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import Graph from 'container/WidgetCard/Card';
@@ -201,7 +201,7 @@ function DBCall(): JSX.Element {
);
}}
onDragSelect={onDragSelect}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
/>
</GraphContainer>
@@ -240,7 +240,7 @@ function DBCall(): JSX.Element {
);
}}
onDragSelect={onDragSelect}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
/>
</GraphContainer>

View File

@@ -5,7 +5,7 @@ import { useAppLocation } from 'lib/router/useAppLocation';
import { useAppParams } from 'lib/router/useAppParams';
import { Col } from 'antd';
import logEvent from 'api/common/logEvent';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import Graph from 'container/WidgetCard/Card';
@@ -273,7 +273,7 @@ function External(): JSX.Element {
);
}}
onDragSelect={onDragSelect}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
/>
</GraphContainer>
@@ -317,7 +317,7 @@ function External(): JSX.Element {
);
}}
onDragSelect={onDragSelect}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
/>
</GraphContainer>
@@ -362,7 +362,7 @@ function External(): JSX.Element {
)
}
onDragSelect={onDragSelect}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
/>
</GraphContainer>
@@ -406,7 +406,7 @@ function External(): JSX.Element {
);
}}
onDragSelect={onDragSelect}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
/>
</GraphContainer>

View File

@@ -8,7 +8,7 @@ import {
apDexToolTipUrl,
apDexToolTipUrlText,
} from 'constants/apDex';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { PANEL_TYPES } from 'constants/queryBuilder';
import Graph from 'container/WidgetCard/Card';
import DisplayThreshold from 'container/WidgetCard/Header/DisplayThreshold';
@@ -95,7 +95,7 @@ function ApDexMetrics({
onClickHandler={handleGraphClick('ApDex')}
threshold={threshold}
isQueryEnabled={isQueryEnabled}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
/>
);

View File

@@ -1,6 +1,6 @@
import { useMemo } from 'react';
import { useAppParams } from 'lib/router/useAppParams';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { FeatureKeys } from 'constants/features';
import { PANEL_TYPES } from 'constants/queryBuilder';
import Graph from 'container/WidgetCard/Card';
@@ -13,7 +13,10 @@ import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsAppli
import { latency } from 'container/MetricsApplication/MetricsPageQueries/OverviewQueries';
import { Card, GraphContainer } from 'container/MetricsApplication/styles';
import useResourceAttribute from 'hooks/useResourceAttribute';
import { resourceAttributesToTagFilterItems } from 'hooks/useResourceAttribute/utils';
import {
resourceAttributesToTagFilterItems,
resourceAttributesToTracesFilterItems,
} from 'hooks/useResourceAttribute/utils';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';
import { useAppContext } from 'providers/App/App';
@@ -49,9 +52,9 @@ function ServiceOverview({
const tagFilterItems = useMemo(
() =>
handleNonInQueryRange(
resourceAttributesToTagFilterItems(queries, !isSpanMetricEnable),
) || [],
isSpanMetricEnable
? handleNonInQueryRange(resourceAttributesToTagFilterItems(queries))
: resourceAttributesToTracesFilterItems(queries),
[isSpanMetricEnable, queries],
);
@@ -72,7 +75,7 @@ function ServiceOverview({
},
title: GraphTitle.LATENCY,
panelTypes: PANEL_TYPES.TIME_SERIES,
yAxisUnit: 'ns',
yAxisUnit: isSpanMetricEnable ? 'ms' : 'ns',
id: SERVICE_CHART_ID.latency,
}),
[isSpanMetricEnable, servicename, tagFilterItems, topLevelOperationsRoute],
@@ -116,7 +119,7 @@ function ServiceOverview({
widget={latencyWidget}
onClickHandler={handleGraphClick('Service')}
isQueryEnabled={isQueryEnabled}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
/>
</GraphContainer>

View File

@@ -1,7 +1,7 @@
import { Typography } from '@signozhq/ui/typography';
import axios from 'axios';
import { SOMETHING_WENT_WRONG } from 'constants/api';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import Graph from 'container/WidgetCard/Card';
import { SERVICE_DETAIL_DRILLDOWN_ENABLED } from 'container/MetricsApplication/constant';
import { Card, GraphContainer } from 'container/MetricsApplication/styles';
@@ -33,7 +33,7 @@ function TopLevelOperation({
onClickHandler={handleGraphClick(opName)}
onDragSelect={onDragSelect}
isQueryEnabled={!topLevelOperationsIsLoading}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
/>
</GraphContainer>

View File

@@ -2,7 +2,7 @@ import { ReactNode, useMemo } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { useAppParams } from 'lib/router/useAppParams';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { topOperationMetricsDownloadOptions } from 'container/MetricsApplication/constant';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
@@ -15,6 +15,7 @@ import useResourceAttribute from 'hooks/useResourceAttribute';
import { convertRawQueriesToTraceSelectedTags } from 'hooks/useResourceAttribute/utils';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
import { AppState } from 'store/reducers';
import { QueryDataV3 } from 'types/api/widgets/getQuery';
import { EQueryType } from 'types/common/dashboard';
import { GlobalReducer } from 'types/reducer/globalTime';
import { v4 as uuid } from 'uuid';
@@ -70,7 +71,7 @@ function TopOperationMetrics(): JSX.Element {
globalSelectedInterval,
variables: {},
},
ENTITY_VERSION_V4,
ENTITY_VERSION_V5,
{
queryKey: [
`GetMetricsQueryRange-${keyOperationWidget?.timePreferance}-${globalSelectedInterval}-${keyOperationWidget?.id}`,
@@ -88,7 +89,9 @@ function TopOperationMetrics(): JSX.Element {
},
);
const queryTableData = data?.payload?.data?.newResult?.data?.result || [];
const queryTableData = (data?.payload?.data?.newResult?.data?.result ||
data?.payload?.data?.result ||
[]) as QueryDataV3[];
const renderColumnCell = useMemo(
() =>

View File

@@ -0,0 +1,95 @@
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
import { FeatureKeys } from 'constants/features';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import Graph from 'container/WidgetCard/Card';
import { IResourceAttribute } from 'hooks/useResourceAttribute/types';
import { encode } from 'js-base64';
import { defaultFeatureFlags, render } from 'tests/test-utils';
import ServiceOverview from '../ServiceOverview';
jest.mock('container/WidgetCard/Card', () => ({
__esModule: true,
default: jest.fn(() => null),
}));
const resourceAttributes: IResourceAttribute[] = [
{
id: 'env',
tagKey: 'resource_deployment.environment',
operator: 'Not IN',
tagValue: ['prod'],
},
];
describe('ServiceOverview', () => {
it('filters the traces latency on the resource attribute with its operator', () => {
render(
<ServiceOverview
stepInterval={60}
selectedTimeStamp={0}
selectedTraceTags="[]"
onDragSelect={jest.fn()}
handleGraphClick={jest.fn()}
topLevelOperationsRoute={['GET /']}
topLevelOperationsIsLoading={false}
/>,
undefined,
{
initialRoute: `/services/frontend?${QueryParams.resourceAttributes}=${encodeURIComponent(
encode(JSON.stringify(resourceAttributes)),
)}`,
routePath: ROUTES.SERVICE_METRICS,
},
);
const { widget } = jest.mocked(Graph).mock.calls[0][0];
const [latencyQuery] = prepareQueryRangePayloadV5({
query: widget.query,
graphType: widget.panelTypes,
selectedTime: 'GLOBAL_TIME',
}).queryPayload.compositeQuery.queries;
expect(latencyQuery.spec).toMatchObject({
filter: {
expression:
"service.name = 'frontend' AND name in ['GET /'] AND deployment.environment NOT IN ['prod']",
},
});
});
it.each([
{ spanMetrics: false, unit: 'ns' },
{ spanMetrics: true, unit: 'ms' },
])(
'reads the latency in $unit when span metrics is $spanMetrics',
({ spanMetrics, unit }) => {
render(
<ServiceOverview
stepInterval={60}
selectedTimeStamp={0}
selectedTraceTags="[]"
onDragSelect={jest.fn()}
handleGraphClick={jest.fn()}
topLevelOperationsRoute={['GET /']}
topLevelOperationsIsLoading={false}
/>,
undefined,
{
initialRoute: '/services/frontend',
routePath: ROUTES.SERVICE_METRICS,
appContextOverrides: {
featureFlags: defaultFeatureFlags.map((flag) =>
flag.name === FeatureKeys.USE_SPAN_METRICS
? { ...flag, active: spanMetrics }
: flag,
),
},
},
);
expect(jest.mocked(Graph).mock.calls[0][0].widget.yAxisUnit).toBe(unit);
},
);
});

View File

@@ -1,4 +1,5 @@
import { ReactNode } from 'react';
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
@@ -43,6 +44,12 @@ export interface BuilderQuerieswithFormulaProps {
additionalItems: TagFilterItem[][];
timeAggregateOperators: MetricAggregateOperator[];
spaceAggregateOperators: MetricAggregateOperator[];
comparisonSpaceAggregationParams?: (
| MetrictypesComparisonSpaceAggregationParamDTO
| undefined
)[];
// v5 picks its own step when none is sent; v4 needs one
stepInterval?: number;
dataSource: DataSource;
}

View File

@@ -85,6 +85,7 @@ export enum WidgetKeys {
HasError = 'hasError',
Address = 'address',
DurationNano = 'durationNano',
SpanDurationNano = 'duration_nano',
StatusCode = 'status.code',
Operation = 'operation',
OperationName = 'operationName',

View File

@@ -54,9 +54,6 @@ export const getNearestHighestBucketValue = (
return nearestBucket?.toString() || '+Inf';
};
export const convertMilSecToNanoSec = (value: number): number =>
value * 1000000000;
export const convertedTracesToDownloadData = (
originalData: TopOperationList[],
): Record<string, string>[] =>

View File

@@ -23,9 +23,7 @@ export const getColumns = (
{
key: ColumnKey.P99,
columnOption: {
title: `${ColumnTitle[ColumnKey.P99]}${
isMetricData ? ' (in ns)' : ' (in ms)'
}`,
title: `${ColumnTitle[ColumnKey.P99]} (in ms)`,
sorter: (a: ServicesList, b: ServicesList): number => a.p99 - b.p99,
render: (value: number): string => {
if (Number.isNaN(value)) {

View File

@@ -7,7 +7,7 @@ import { SolidAlertTriangle } from '@signozhq/icons';
import { Flex } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import { ResizeTable } from 'components/ResizeTable';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { MAX_RPS_LIMIT } from 'constants/global';
import ResourceAttributesFilter from 'container/ResourceAttributesFilter';
import { useGetQueriesRange } from 'hooks/queryBuilder/useGetQueriesRange';
@@ -40,9 +40,9 @@ function ServiceMetricTable({
const { isFetchingActiveLicense, trialInfo } = useAppContext();
const { isCloudUser: isCloudUserVal } = useGetTenantLicense();
const queries = useGetQueriesRange(queryRangeRequestData, ENTITY_VERSION_V4, {
const queries = useGetQueriesRange(queryRangeRequestData, ENTITY_VERSION_V5, {
queryKey: [
`GetMetricsQueryRange-${queryRangeRequestData[0].selectedTime}-${globalSelectedInterval}`,
`GetMetricsQueryRange-${queryRangeRequestData[0]?.selectedTime}-${globalSelectedInterval}`,
maxTime,
minTime,
globalSelectedInterval,

View File

@@ -1,193 +1,123 @@
import useGetTopLevelOperations from 'hooks/useGetTopLevelOperations';
import { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
import {
Querybuildertypesv5ColumnTypeDTO,
Querybuildertypesv5RequestTypeDTO,
type QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { act, render, screen } from 'tests/test-utils';
import { render, screen, waitFor } from 'tests/test-utils';
import ServicesUsingMetrics from './index';
// Mock the useGetTopLevelOperations hook
jest.mock('hooks/useGetTopLevelOperations', () => ({
__esModule: true,
default: jest.fn(),
}));
const topLevelOperations: ServiceDataProps = {
SampleApp: ['GET'],
TestApp: ['POST'],
};
const mockUseGetTopLevelOperations =
useGetTopLevelOperations as jest.MockedFunction<
typeof useGetTopLevelOperations
>;
// A = p99, D = ops/s, F1 = error rate
const metricsByService: Record<string, [number, number, number]> = {
SampleApp: [100, 50, 2.5],
TestApp: [200, 10, 0],
};
const scalarTable = (service: string): QueryRangeV5200 => ({
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: {
results: [
{
columns: [
{
name: 'service.name',
queryName: 'A',
aggregationIndex: 0,
columnType: Querybuildertypesv5ColumnTypeDTO.group,
},
...['A', 'D', 'F1'].map((queryName) => ({
name: '__result_0',
queryName,
aggregationIndex: 0,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
})),
],
data: [[service, ...metricsByService[service]]],
},
],
},
},
});
const mockTopLevelOperations = (operations: ServiceDataProps): void => {
server.use(
rest.post(
'http://localhost/api/v1/service/top_level_operations',
(_, res, ctx) => res(ctx.status(200), ctx.json(operations)),
),
);
};
const table = (): HTMLElement => screen.getByTestId('services-table');
const rowCells = (service: string): (string | null)[] =>
Array.from(table().querySelectorAll(`tr[data-row-key="${service}"] td`)).map(
(cell) => cell.textContent,
);
describe('ServicesUsingMetrics', () => {
beforeEach(() => {
// Reset all mocks before each test
jest.clearAllMocks();
});
it('should render the ServicesUsingMetrics component', async () => {
// Mock successful API response
mockUseGetTopLevelOperations.mockReturnValue({
data: {
SampleApp: ['GET'],
TestApp: ['POST'],
},
isLoading: false,
isError: false,
error: null,
isIdle: false,
isLoadingError: false,
isRefetchError: false,
isSuccess: true,
status: 'success',
dataUpdatedAt: 0,
errorUpdatedAt: 0,
failureCount: 0,
failureReason: null,
isFetching: false,
isFetchingNextPage: false,
isFetchingPreviousPage: false,
isPlaceholderData: false,
isPreviousData: false,
isStale: false,
refetch: jest.fn(),
remove: jest.fn(),
} as any);
// Mock the query range API responses
server.use(
rest.post('*/api/v1/query_range', (req, res, ctx) =>
res(
ctx.status(200),
ctx.json({
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'A' },
values: [[Date.now() / 1000, '100']],
},
{
metric: { __name__: 'D' },
values: [[Date.now() / 1000, '50']],
},
{
metric: { __name__: 'F1' },
values: [[Date.now() / 1000, '2.5']],
},
],
},
}),
),
),
rest.post('http://localhost/api/v5/query_range', async (req, res, ctx) => {
const body = JSON.stringify(await req.json());
const service = Object.keys(metricsByService).find((name) =>
body.includes(`'${name}'`),
);
return res(ctx.status(200), ctx.json(scalarTable(service ?? '')));
}),
);
await act(async () => {
render(<ServicesUsingMetrics />);
});
// Wait for the component to load and render
await screen.findByText(/application/i);
expect(screen.getByText(/p99 latency \(in ns\)/i)).toBeInTheDocument();
expect(screen.getByText(/error rate \(% of total\)/i)).toBeInTheDocument();
});
it('should render the ServicesUsingMetrics component with loading', async () => {
// Mock loading state
mockUseGetTopLevelOperations.mockReturnValue({
data: undefined,
isLoading: true,
isError: false,
error: null,
isIdle: false,
isLoadingError: false,
isRefetchError: false,
isSuccess: false,
status: 'loading',
dataUpdatedAt: 0,
errorUpdatedAt: 0,
failureCount: 0,
failureReason: null,
isFetching: true,
isFetchingNextPage: false,
isFetchingPreviousPage: false,
isPlaceholderData: false,
isPreviousData: false,
isStale: false,
refetch: jest.fn(),
remove: jest.fn(),
} as any);
it('fills each row from the v5 table', async () => {
mockTopLevelOperations(topLevelOperations);
render(<ServicesUsingMetrics />);
await act(async () => {
render(<ServicesUsingMetrics />);
});
// Should show loading spinner
expect(screen.getByLabelText(/loading/i)).toBeInTheDocument();
await waitFor(() =>
expect(rowCells('SampleApp')).toStrictEqual([
'SampleApp',
'100.00',
'2.50',
'50.00',
]),
);
expect(rowCells('TestApp')).toStrictEqual([
'TestApp',
'200.00',
'0.00',
'10.00',
]);
});
it('should not render if the data is not present', async () => {
// Mock successful API response with data
mockUseGetTopLevelOperations.mockReturnValue({
data: {
SampleApp: ['GET'],
TestApp: ['GET'],
},
isLoading: false,
isError: false,
error: null,
isIdle: false,
isLoadingError: false,
isRefetchError: false,
isSuccess: true,
status: 'success',
dataUpdatedAt: 0,
errorUpdatedAt: 0,
failureCount: 0,
failureReason: null,
isFetching: false,
isFetchingNextPage: false,
isFetchingPreviousPage: false,
isPlaceholderData: false,
isPreviousData: false,
isStale: false,
refetch: jest.fn(),
remove: jest.fn(),
} as any);
it('labels the span-metrics p99 in ms', async () => {
mockTopLevelOperations(topLevelOperations);
render(<ServicesUsingMetrics />);
// Mock the query range API responses
server.use(
rest.post('*/api/v1/query_range', (req, res, ctx) =>
res(
ctx.status(200),
ctx.json({
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'A' },
values: [[Date.now() / 1000, '100']],
},
{
metric: { __name__: 'D' },
values: [[Date.now() / 1000, '50']],
},
{
metric: { __name__: 'F1' },
values: [[Date.now() / 1000, '2.5']],
},
],
},
}),
await waitFor(() =>
expect(
Array.from(table().querySelectorAll('thead th')).map(
(cell) => cell.textContent,
),
),
).toContain('P99 latency (in ms)'),
);
});
await act(async () => {
render(<ServicesUsingMetrics />);
});
it('renders an empty list when no service has top level operations', async () => {
mockTopLevelOperations({});
render(<ServicesUsingMetrics />);
// Wait for the services to be rendered
await screen.findByText(/SampleApp/i);
expect(screen.getByText(/TestApp/i)).toBeInTheDocument();
await waitFor(() =>
expect(table().querySelectorAll('tr[data-row-key]')).toHaveLength(0),
);
});
});

View File

@@ -0,0 +1,16 @@
import { getQueryRangeRequestData } from '../utils';
describe('getQueryRangeRequestData', () => {
it('leaves the step of the services list queries to v5', () => {
const [request] = getQueryRangeRequestData({
topLevelOperations: [['frontend', ['GET /']]],
globalSelectedInterval: '15m',
});
const steps = request.query.builder.queryData.map(
(query) => query.stepInterval,
);
expect(steps).toStrictEqual(Array(steps.length).fill(null));
});
});

View File

@@ -3,7 +3,6 @@ import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsAppli
import { updateStepInterval } from 'hooks/queryBuilder/useStepInterval';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { ServicesList } from 'types/api/metrics/getService';
import { QueryDataV3 } from 'types/api/widgets/getQuery';
import { EQueryType } from 'types/common/dashboard';
import { v4 as uuid } from 'uuid';
@@ -13,13 +12,12 @@ import {
GetServiceListFromQueryProps,
} from './types';
export function getSeriesValue(
queryArray: QueryDataV3[] | undefined,
function getRowValue(
row: Record<string, unknown> | undefined,
queryName: string,
): string {
const queryObject = queryArray?.find((item) => item?.queryName === queryName);
const series = queryObject ? queryObject.series : 0;
return series ? series[0].values[0].value : '0';
): number {
const value = Number(row?.[queryName]);
return Number.isFinite(value) ? value : 0;
}
export const getQueryRangeRequestData = ({
@@ -71,14 +69,13 @@ export const getServiceListFromQuery = ({
numErrors: 0,
};
services.push(serviceData);
}
if (query.data) {
const queryArray = query.data?.payload?.data?.newResult?.data?.result;
} else if (query.data) {
const row = query.data?.payload?.data?.result?.[0]?.table?.rows?.[0]?.data;
const serviceData: ServicesList = {
serviceName: topLevelOperations[index][0].toString(),
p99: parseFloat(getSeriesValue(queryArray, 'A')),
callRate: parseFloat(getSeriesValue(queryArray, 'D')),
errorRate: parseFloat(getSeriesValue(queryArray, 'F1')),
p99: getRowValue(row, 'A'),
callRate: getRowValue(row, 'D'),
errorRate: getRowValue(row, 'F1'),
avgDuration: 0,
numCalls: 0,
numErrors: 0,

View File

@@ -33,7 +33,6 @@ export const PANEL_TYPES_VS_FULL_VIEW_TABLE: PanelTypeAndGraphManagerVisibilityP
HISTOGRAM: false,
HEATMAP: false,
GEO_MAP: false,
TOP_LIST: false,
TEXT: false,
EMPTY_WIDGET: false,
};

View File

@@ -25,5 +25,4 @@ export const PanelTypeVsPanelWrapper = {
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.GEO_MAP]: null,
[PANEL_TYPES.TOP_LIST]: null,
};

View File

@@ -96,22 +96,8 @@ export const convertRawQueriesToTraceSelectedTags = (
/* Convert resource attributes to tagFilter items for queryBuilder */
export const resourceAttributesToTagFilterItems = (
queries: IResourceAttribute[],
isTraceDataSource = false,
): TagFilterItem[] => {
if (isTraceDataSource) {
return convertRawQueriesToTraceSelectedTags(queries).map((e) => ({
id: e.Key,
op: e.Operator,
value: e.StringValues,
key: {
dataType: DataTypes.String,
type: MetricsType.Resource,
key: e.Key,
},
}));
}
return queries.map((res) => ({
): TagFilterItem[] =>
queries.map((res) => ({
id: `${res.id}`,
key: {
key: res.tagKey,
@@ -121,7 +107,6 @@ export const resourceAttributesToTagFilterItems = (
op: `${res.operator}`,
value: `${res.tagValue}`.split(','),
}));
};
/* Convert resource attributes to trace filters items for queryBuilder */
export const resourceAttributesToTracesFilterItems = (
queries: IResourceAttribute[],

View File

@@ -32,17 +32,6 @@ export function isAIBuilderEnvelope(
);
}
/** Exactly one `builder_query`: the only request a panel's default row limit applies to. */
export function isLoneBuilderQuery<T extends { type: string }>(
envelopes: T[],
): envelopes is [Extract<T, Querybuildertypesv5QueryEnvelopeBuilderDTO>] {
return (
envelopes.length === 1 &&
envelopes[0].type ===
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
);
}
const BUILDER_PLUGIN_KINDS: string[] = [
DashboardtypesQueryPluginKindDTO['signoz/BuilderQuery'],
DashboardtypesQueryPluginKindDTO['signoz/AIBuilderQuery'],

View File

@@ -18,7 +18,6 @@ export type PartialPanelTypes = {
[PANEL_TYPES.HISTOGRAM]: 'histogram';
[PANEL_TYPES.HEATMAP]: 'heatmap';
[PANEL_TYPES.GEO_MAP]: 'geo_map';
[PANEL_TYPES.TOP_LIST]: 'top_list';
};
export type BuilderField = keyof IBuilderQuery;
@@ -155,7 +154,6 @@ export const panelTypeDataSourceFormValuesMap: Record<
[PANEL_TYPES.PIE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.SCATTER]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.GEO_MAP]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.TOP_LIST]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.VALUE]: bySource(SINGLE_VALUE, SINGLE_VALUE_METRICS),
[PANEL_TYPES.LIST]: bySource(RAW_ROWS, RAW_ROWS_METRICS),
};

View File

@@ -49,7 +49,7 @@
font-family: var(--font-mono);
font-size: var(--font-size-xs);
font-weight: 600;
color: var(--l1-foreground);
color: var(--text-vanilla-100);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -70,11 +70,11 @@
font-family: var(--font-mono);
font-size: var(--font-size-xs);
font-variant-numeric: tabular-nums;
color: var(--l1-foreground);
color: var(--text-vanilla-100);
}
.rowMuted {
color: var(--l3-foreground);
color: var(--text-vanilla-400);
}
.rowLabel {

View File

@@ -1,9 +1,14 @@
import { useMemo } from 'react';
import cx from 'classnames';
import { Pin } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { ScatterTooltipProps } from '../types';
import TooltipCard from './components/TooltipCard/TooltipCard';
import { buildChannelRows, resolveHoveredPoint } from './scatterTooltipContent';
import Styles from './ScatterTooltip.module.scss';
/** Own component: the shared Tooltip lists one row per series at a shared x. */
export default function ScatterTooltip({
uPlotInstance,
@@ -45,18 +50,90 @@ export default function ScatterTooltip({
}
return (
<TooltipCard
title={hoveredPoint.label}
color={hoveredPoint.color}
rows={rows.map((row) => ({ key: row.label, ...row }))}
mutedRows={labels.map((label) => ({
key: label.key,
label: label.key,
value: label.value,
}))}
isPinned={isPinned}
footer={renderTooltipFooter?.({ isPinned, dismiss })}
testId="scatter-tooltip"
/>
<div
className={cx(Styles.container, { [Styles.pinned]: isPinned })}
data-pinned={isPinned}
data-testid="scatter-tooltip"
>
<div className={Styles.header}>
<span
className={Styles.marker}
style={{
backgroundColor: hoveredPoint.color,
borderColor: hoveredPoint.color,
}}
/>
<Typography.Text
as="span"
className={Styles.title}
title={hoveredPoint.label}
testId="scatter-tooltip-title"
>
{hoveredPoint.label}
</Typography.Text>
{isPinned && (
<Button
variant="ghost"
color="secondary"
size="sm"
prefix={<Pin size={12} />}
testId="scatter-tooltip-status"
>
Pinned
</Button>
)}
</div>
<span className={Styles.divider} />
<div className={Styles.rows}>
{rows.map((row) => (
<div
key={row.label}
className={Styles.row}
data-testid="scatter-tooltip-row"
>
<Typography.Text as="span" className={Styles.rowLabel}>
{row.label}
</Typography.Text>
<Typography.Text as="span" className={Styles.rowValue}>
{row.value}
</Typography.Text>
</div>
))}
</div>
{labels.length > 0 && (
<>
<span className={Styles.divider} />
<div className={Styles.rows}>
{labels.map((label) => (
<div
key={label.key}
className={cx(Styles.row, Styles.rowMuted)}
data-testid="scatter-tooltip-label"
>
<Typography.Text
as="span"
className={Styles.rowLabel}
title={label.key}
>
{label.key}
</Typography.Text>
<Typography.Text
as="span"
className={Styles.rowValue}
title={label.value}
>
{label.value}
</Typography.Text>
</div>
))}
</div>
</>
)}
{renderTooltipFooter?.({ isPinned, dismiss })}
</div>
);
}

View File

@@ -1,119 +0,0 @@
import type { ReactNode } from 'react';
import cx from 'classnames';
import { Pin } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import Styles from './TooltipCard.module.scss';
export interface TooltipCardRow {
key: string;
label: string;
value: string;
}
interface TooltipCardProps {
title: string;
/** The marker beside the title, matching the item's mark on the chart. */
color: string;
/** What the item says. */
rows: TooltipCardRow[];
/** What names the item, below the rows and muted. */
mutedRows?: TooltipCardRow[];
isPinned?: boolean;
footer?: ReactNode;
/** Prefixes the test ids of the title, status, rows and muted rows. */
testId: string;
}
/** One item's tooltip: a marked title, then label/value rows, on the shared tooltip surface. */
export default function TooltipCard({
title,
color,
rows,
mutedRows = [],
isPinned = false,
footer,
testId,
}: TooltipCardProps): JSX.Element {
return (
<div
className={cx(Styles.container, { [Styles.pinned]: isPinned })}
data-pinned={isPinned}
data-testid={testId}
>
<div className={Styles.header}>
<span
className={Styles.marker}
style={{ backgroundColor: color, borderColor: color }}
/>
<Typography.Text
as="span"
className={Styles.title}
title={title}
testId={`${testId}-title`}
>
{title}
</Typography.Text>
{isPinned && (
<Button
variant="ghost"
color="secondary"
size="sm"
prefix={<Pin size={12} />}
testId={`${testId}-status`}
>
Pinned
</Button>
)}
</div>
<span className={Styles.divider} />
<div className={Styles.rows}>
{rows.map((row) => (
<div key={row.key} className={Styles.row} data-testid={`${testId}-row`}>
<Typography.Text as="span" className={Styles.rowLabel}>
{row.label}
</Typography.Text>
<Typography.Text as="span" className={Styles.rowValue}>
{row.value}
</Typography.Text>
</div>
))}
</div>
{mutedRows.length > 0 && (
<>
<span className={Styles.divider} />
<div className={Styles.rows}>
{mutedRows.map((row) => (
<div
key={row.key}
className={cx(Styles.row, Styles.rowMuted)}
data-testid={`${testId}-label`}
>
<Typography.Text
as="span"
className={Styles.rowLabel}
title={row.label}
>
{row.label}
</Typography.Text>
<Typography.Text
as="span"
className={Styles.rowValue}
title={row.value}
>
{row.value}
</Typography.Text>
</div>
))}
</div>
</>
)}
{footer}
</div>
);
}

View File

@@ -26,22 +26,6 @@ export const SWITCH_SKETCHES = {
))}
</SketchSvg>
),
rank: (
<SketchSvg>
{[5, 11, 17].map((y, index) => (
<g key={y}>
<circle cx={4} cy={y} r={1.2} fill="var(--l3-foreground)" />
<path d={`M9 ${y} H${36 - index * 9}`} />
</g>
))}
</SketchSvg>
),
share: (
<SketchSvg>
<path d="M3 11 H37" strokeDasharray="3 3" />
<rect x={3} y={8} width={22} height={6} fill="var(--l3-foreground)" />
</SketchSvg>
),
combine: (
<SketchSvg>
<rect x={4} y={10} width={6} height={10} />

View File

@@ -26,7 +26,6 @@ import { fitBubbleRadius } from 'pages/DashboardPage/DashboardContainer/Panels/k
import type { SeededPluginSpec } from 'pages/DashboardPage/DashboardContainer/Panels/utils/buildPluginSpec';
import type { SectionEditorContext } from './sectionContext';
import AppearanceSection from './sections/AppearanceSection/AppearanceSection';
import AxesSection from './sections/AxesSection/AxesSection';
import BucketsSection from './sections/BucketsSection/BucketsSection';
import ChartAppearanceSection from './sections/ChartAppearanceSection/ChartAppearanceSection';
@@ -152,13 +151,6 @@ export const SECTION_REGISTRY: {
update: (spec, chartAppearance): PanelSpec =>
updatePluginSlice(spec, 'chartAppearance', chartAppearance),
},
[SectionKind.Appearance]: {
Component: AppearanceSection,
get: (spec): SectionSpecMap[SectionKind.Appearance] | undefined =>
getPluginSlice<SectionSpecMap[SectionKind.Appearance]>(spec, 'appearance'),
update: (spec, appearance): PanelSpec =>
updatePluginSlice(spec, 'appearance', appearance),
},
[SectionKind.Visualization]: {
Component: VisualizationSection,
get: (spec): PanelVisualizationSlice | undefined =>

View File

@@ -1,65 +0,0 @@
import type {
SectionEditorProps,
SectionKind,
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
import ConfigSwitch from '../../controls/ConfigSwitch/ConfigSwitch';
import { SWITCH_SKETCHES } from '../../controls/drawings/switchSketches';
import { createFieldResetter } from '../../utils/changes';
import BarColorField from './BarColorField';
import { DEFAULT_BAR_COLOR } from './barColorOptions';
/**
* Edits the `appearance` slice of a Top List panel spec: bar color, row numbers and
* each row's share of the listed total. Each control is gated by its `controls` flag.
*/
function AppearanceSection({
value,
savedValue,
controls,
onChange,
}: SectionEditorProps<SectionKind.Appearance>): JSX.Element {
const reset = createFieldResetter(value, savedValue, onChange);
const appearance = {
...value,
barColor: value?.barColor || DEFAULT_BAR_COLOR,
};
return (
<>
{controls.barColor && (
<BarColorField
{...reset('barColor')}
value={appearance.barColor}
onChange={(barColor): void => onChange({ ...appearance, barColor })}
/>
)}
{controls.showRank && (
<ConfigSwitch
testId="panel-editor-v2-show-rank"
title="Show rank"
description="Numbers each row by its position."
sketch={SWITCH_SKETCHES.rank}
changed={reset('showRank').changed}
value={appearance.showRank ?? false}
onChange={(showRank): void => onChange({ ...appearance, showRank })}
/>
)}
{controls.showShare && (
<ConfigSwitch
testId="panel-editor-v2-show-share"
title="Show share of total"
description="Each row's percentage of the listed rows' sum. Suits counts and sums, not averages or percentiles."
sketch={SWITCH_SKETCHES.share}
changed={reset('showShare').changed}
value={appearance.showShare ?? false}
onChange={(showShare): void => onChange({ ...appearance, showShare })}
/>
)}
</>
);
}
export default AppearanceSection;

View File

@@ -1,42 +0,0 @@
import ColorSwatches from '../../controls/ColorSwatches/ColorSwatches';
import ConfigField from '../../controls/ConfigField/ConfigField';
import type { FieldResetProps } from '../../utils/changes';
import { BAR_COLOR_OPTIONS, findBarColorPreset } from './barColorOptions';
interface BarColorFieldProps extends Partial<FieldResetProps> {
value: string;
onChange: (barColor: string) => void;
}
function BarColorField({
value,
onChange,
changed,
onReset,
}: BarColorFieldProps): JSX.Element {
const preset = findBarColorPreset(value);
return (
<ConfigField
label="Bar color"
help="Fills every row's bar."
changed={changed}
onReset={onReset}
>
<ColorSwatches
testId="panel-editor-v2-bar-color"
label="Bar color"
value={preset}
options={BAR_COLOR_OPTIONS}
onChange={onChange}
custom={{
value: preset ? undefined : value,
initial: value,
onChange,
}}
/>
</ConfigField>
);
}
export default BarColorField;

View File

@@ -1,93 +0,0 @@
import { Color } from '@signozhq/design-tokens';
import { TooltipProvider } from '@signozhq/ui/tooltip';
import type {
SectionEditorProps,
SectionKind,
} from 'pages/DashboardPage/DashboardContainer/Panels/types/sections';
import {
render as renderWithProviders,
screen,
userEvent,
} from 'tests/test-utils';
import AppearanceSection from '../AppearanceSection';
type OnChange = SectionEditorProps<SectionKind.Appearance>['onChange'];
// Color swatches use a radix tooltip, which needs a TooltipProvider ancestor.
const render = (ui: JSX.Element): ReturnType<typeof renderWithProviders> =>
renderWithProviders(<TooltipProvider>{ui}</TooltipProvider>);
describe('AppearanceSection', () => {
it('renders only the controls whose flag is set', () => {
render(
<AppearanceSection
value={undefined}
controls={{ showRank: true }}
onChange={jest.fn()}
/>,
);
expect(screen.getByTestId('panel-editor-v2-show-rank')).toBeInTheDocument();
expect(
screen.queryByTestId('panel-editor-v2-show-share'),
).not.toBeInTheDocument();
});
it.each([
{ testId: 'panel-editor-v2-show-rank', field: 'showRank' },
{ testId: 'panel-editor-v2-show-share', field: 'showShare' },
])('toggles $field through onChange', async ({ testId, field }) => {
const user = userEvent.setup();
const onChange = jest.fn() as jest.MockedFunction<OnChange>;
render(
<AppearanceSection
value={{ showRank: false, showShare: false, barColor: '#4E74F8' }}
controls={{ showRank: true, showShare: true }}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId(testId));
expect(onChange).toHaveBeenCalledWith({
showRank: false,
showShare: false,
barColor: '#4E74F8',
[field]: true,
});
});
it('picks a bar color, keeping the other fields', async () => {
const user = userEvent.setup();
const onChange = jest.fn() as jest.MockedFunction<OnChange>;
render(
<AppearanceSection
value={{ showRank: true, barColor: '#4E74F8' }}
controls={{ barColor: true }}
onChange={onChange}
/>,
);
await user.click(screen.getByTestId('panel-editor-v2-bar-color-forest'));
expect(onChange).toHaveBeenCalledWith({
showRank: true,
barColor: Color.BG_FOREST_500,
});
});
it('shows the default bar color when the spec has none', () => {
render(
<AppearanceSection
value={undefined}
controls={{ barColor: true }}
onChange={jest.fn()}
/>,
);
expect(
screen.getByTestId('panel-editor-v2-bar-color-robin').querySelector('input'),
).toBeChecked();
});
});

View File

@@ -1,26 +0,0 @@
import { Color } from '@signozhq/design-tokens';
import type { ColorSwatchOption } from '../../controls/ColorSwatches/ColorSwatches';
export const BAR_COLOR_OPTIONS: ColorSwatchOption<string>[] = [
{ id: 'robin', color: Color.BG_ROBIN_500 },
{ id: 'aqua', color: Color.BG_AQUA_500 },
{ id: 'forest', color: Color.BG_FOREST_500 },
{ id: 'amber', color: Color.BG_AMBER_500 },
{ id: 'sienna', color: Color.BG_SIENNA_500 },
].map(({ id, color }) => ({
value: color,
id,
label: id.charAt(0).toUpperCase() + id.slice(1),
fill: color,
}));
/** Matches the server's default for an unset `appearance.barColor`. */
export const DEFAULT_BAR_COLOR = Color.BG_ROBIN_500;
/** The preset a hex matches, ignoring case. */
export function findBarColorPreset(hex: string): string | undefined {
return BAR_COLOR_OPTIONS.find(
(option) => option.value.toLowerCase() === hex.toLowerCase(),
)?.value;
}

View File

@@ -37,7 +37,6 @@ const EXPECTED_QUERY_TYPES: Record<PanelKind, EQueryType[]> = {
'signoz/HeatmapPanel': [QUERY_BUILDER, CLICKHOUSE, PROM],
'signoz/PieChartPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/GeoMapPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/TopListPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/TablePanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/ListPanel': [QUERY_BUILDER],
'signoz/ScatterPlotPanel': [QUERY_BUILDER, CLICKHOUSE],
@@ -86,7 +85,6 @@ const EXPECTED_QUERY_MODES: Record<PanelKind, QueryMode[]> = {
'signoz/ListPanel': [QUERY_BUILDER, QueryMode.AI_QUERY_BUILDER],
'signoz/ScatterPlotPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/GeoMapPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/TopListPanel': [QUERY_BUILDER, CLICKHOUSE],
'signoz/TextPanel': [],
};
@@ -100,7 +98,6 @@ const EXPECTED_SIGNALS: Record<PanelKind, TelemetrytypesSignalDTO[]> = {
'signoz/HeatmapPanel': [metrics],
'signoz/PieChartPanel': [metrics, logs, traces],
'signoz/GeoMapPanel': [metrics, logs, traces],
'signoz/TopListPanel': [metrics, logs, traces],
'signoz/TablePanel': [metrics, logs, traces],
// List renders raw rows; metrics produce no row data.
'signoz/ListPanel': [logs, traces],
@@ -167,14 +164,6 @@ const EXPECTED_QUERY_CAPABILITIES: Partial<
orderTiebreaker: false,
serverPaginated: false,
},
'signoz/TopListPanel': {
requestType: scalar,
formatTableResultForUI: false,
bucketedStepInterval: false,
orderTiebreaker: false,
serverPaginated: false,
defaultRowLimit: 10,
},
// Only Table, Scatter Plot and Geo Map ask the server to join their scalar results into UI rows.
'signoz/TablePanel': {
requestType: scalar,

View File

@@ -1,102 +0,0 @@
import { useCallback, useMemo } from 'react';
import NoData from '../../components/NoData/NoData';
import PanelStyles from '../../panel.module.scss';
import type { PanelRendererProps } from '../../types/rendererProps';
import { resolveDecimalPrecision } from '../../utils/chartAppearance/resolvers';
import { enrichPieClick } from '../../utils/drilldown/enrichPieClick';
import { getBuilderQueries } from '../../utils/getBuilderQueries';
import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
import { mapNumberThresholds } from '../NumberPanel/utils';
import TopList from './components/TopList/TopList';
import { LABEL_NAME_SEPARATOR, prepareTopListData } from './utils/prepareData';
import type { TopListRow } from './types';
import { ACCENT_COLOR, type RowColors } from './utils/rowDisplay';
function TopListPanelRenderer({
panelId,
panel,
data,
isFetching,
refetch,
onClick,
enableDrillDown,
}: PanelRendererProps<'signoz/TopListPanel'>): JSX.Element {
const spec = panel.spec.plugin.spec;
const { rows, valueName, labelColumnNames } = useMemo(
() => prepareTopListData(data),
[data],
);
const thresholds = useMemo(
() => mapNumberThresholds(spec.thresholds),
[spec.thresholds],
);
const precision = useMemo(
() => resolveDecimalPrecision(spec.formatting?.decimalPrecision),
[spec.formatting?.decimalPrecision],
);
const builderQueries = useMemo(
() => getBuilderQueries(panel.spec.queries || []),
[panel.spec.queries],
);
const handleSelect = useCallback(
(
row: TopListRow,
colors: RowColors,
coordinates: { x: number; y: number },
): void => {
if (!onClick) {
return;
}
const payload = enrichPieClick({
slice: {
label: row.label,
value: row.value ?? 0,
color: colors.barColor ?? ACCENT_COLOR,
queryName: row.queryName,
labels: row.labels,
},
builderQueries,
coordinates,
timeRange: getPanelTimeRange(data.requestPayload),
});
if (payload) {
onClick(payload);
}
},
[onClick, builderQueries, data.requestPayload],
);
return (
<div
data-testid="top-list-panel-renderer"
className={PanelStyles.panelContainer}
>
{rows.length === 0 ? (
<NoData isFetching={isFetching} onRetry={refetch} panel={panel} />
) : (
<TopList
panelId={panelId}
rows={rows}
valueName={valueName}
labelName={labelColumnNames.join(LABEL_NAME_SEPARATOR)}
unit={spec.formatting?.unit}
precision={precision}
thresholds={thresholds}
barColor={spec.appearance?.barColor ?? undefined}
showRank={spec.appearance?.showRank}
showShare={spec.appearance?.showShare}
onSelect={enableDrillDown ? handleSelect : undefined}
/>
)}
</div>
);
}
export default TopListPanelRenderer;

View File

@@ -1,188 +0,0 @@
import {
DashboardtypesComparisonOperatorDTO,
DashboardtypesThresholdFormatDTO,
} from 'api/generated/services/sigNoz.schemas';
import { PanelMode } from 'lib/visualization/panels/types';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { render, screen, userEvent } from 'tests/test-utils';
import type { PanelRendererProps } from '../../../types/rendererProps';
import TopListPanelRenderer from '../Renderer';
import {
groupColumn,
scalarResponse,
topListPanel as panelWith,
valueColumn,
} from './fixtures';
import { mockListLayout } from './mockListLayout';
function dataWith(rows: [string, number][]): PanelQueryData {
return {
response: scalarResponse([
{
queryName: 'A',
columns: [groupColumn('service.name'), valueColumn()],
data: rows,
},
]),
requestPayload: undefined,
legendMap: {},
};
}
const SERVICES: [string, number][] = [
['checkout', 50],
['payment', 100],
['auth', 25],
];
function renderPanel(
props: Partial<PanelRendererProps<'signoz/TopListPanel'>>,
): ReturnType<typeof render> {
return render(
<TopListPanelRenderer
panelId="panel-1"
panel={panelWith({})}
data={dataWith(SERVICES)}
isFetching={false}
error={null}
panelMode={PanelMode.DASHBOARD_VIEW}
{...props}
/>,
);
}
type OnClick = NonNullable<
PanelRendererProps<'signoz/TopListPanel'>['onClick']
>;
const rowLabels = (): string[] =>
screen
.getAllByTestId('top-list-row')
.map(
(row) =>
row.getAttribute('aria-label') ??
row.closest('li')?.getAttribute('aria-label') ??
'',
);
mockListLayout();
describe('TopListPanelRenderer', () => {
it('ranks rows by value with bars relative to the largest value', () => {
renderPanel({});
expect(rowLabels()).toStrictEqual([
'payment: 100',
'checkout: 50',
'auth: 25',
]);
expect(
screen.getAllByTestId('top-list-row-fill').map((fill) => fill.style.width),
).toStrictEqual(['100%', '50%', '25%']);
});
it('formats values with the panel unit', () => {
renderPanel({ panel: panelWith({ formatting: { unit: 'ms' } }) });
expect(screen.getAllByTestId('top-list-row-value')[0]).toHaveTextContent(
'100 ms',
);
});
it('recolours the bar for a background threshold and the value for a text threshold', () => {
renderPanel({
panel: panelWith({
thresholds: [
{
color: '#F1575F',
operator: DashboardtypesComparisonOperatorDTO.above,
value: 90,
format: DashboardtypesThresholdFormatDTO.background,
},
{
color: '#F5B225',
operator: DashboardtypesComparisonOperatorDTO.above,
value: 40,
format: DashboardtypesThresholdFormatDTO.text,
},
],
}),
});
const [paymentFill, checkoutFill] =
screen.getAllByTestId('top-list-row-fill');
const [paymentValue, checkoutValue] =
screen.getAllByTestId('top-list-row-value');
expect(paymentFill.style.getPropertyValue('--fill-color')).toBe('#F1575F');
expect(paymentValue.style.color).toBe('');
expect(checkoutValue).toHaveStyle({ color: '#F5B225' });
expect(checkoutFill.style.getPropertyValue('--fill-color')).toBe('');
});
it('opens the drilldown with the clicked row', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClick = jest.fn() as jest.MockedFunction<OnClick>;
renderPanel({ onClick, enableDrillDown: true });
await user.pointer({
keys: '[MouseLeft]',
target: screen.getAllByTestId('top-list-row')[1],
coords: { clientX: 10, clientY: 20 },
});
expect(onClick).toHaveBeenCalledTimes(1);
expect(onClick.mock.calls[0][0]).toMatchObject({
coordinates: { x: 10, y: 20 },
context: { queryName: 'A', label: 'checkout' },
});
});
it('anchors the drilldown under the row when opened from the keyboard', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClick = jest.fn() as jest.MockedFunction<OnClick>;
renderPanel({ onClick, enableDrillDown: true });
const row = screen.getAllByTestId('top-list-row')[0];
jest
.spyOn(row, 'getBoundingClientRect')
.mockReturnValue({ left: 30, bottom: 60 } as DOMRect);
row.focus();
await user.keyboard('{Enter}');
expect(onClick.mock.calls[0][0]).toMatchObject({
coordinates: { x: 30, y: 60 },
context: { label: 'payment' },
});
});
it('does not drill down when drilldown is disabled', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClick = jest.fn() as jest.MockedFunction<OnClick>;
renderPanel({ onClick });
await user.click(screen.getAllByTestId('top-list-row')[0]);
expect(onClick).not.toHaveBeenCalled();
});
it('moves focus between rows with the arrow keys', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderPanel({ enableDrillDown: true, onClick: jest.fn() });
const rows = screen.getAllByTestId('top-list-row');
rows[0].focus();
await user.keyboard('{ArrowDown}');
expect(rows[1]).toHaveFocus();
await user.keyboard('{ArrowUp}');
expect(rows[0]).toHaveFocus();
});
it('renders No Data when the query returns no rows', () => {
renderPanel({ data: dataWith([]) });
expect(screen.getByTestId('panel-no-data')).toBeInTheDocument();
expect(screen.queryByTestId('top-list')).not.toBeInTheDocument();
});
});

View File

@@ -1,379 +0,0 @@
import { act, render, screen, userEvent } from 'tests/test-utils';
import TopList from '../components/TopList/TopList';
import { HEADER_HEIGHT, LIST_PADDING_Y, ROW_GAP } from '../constants';
import { mockListLayout } from './mockListLayout';
import type { TopListRow } from '../types';
function rowsOf(count: number): TopListRow[] {
return Array.from({ length: count }, (_, index) => ({
key: `A-${index}`,
label: `service-${index}`,
isEmptyLabel: false,
value: count - index,
rawValue: count - index,
ratio: (count - index) / count,
share: null,
queryName: 'A',
labels: { 'service.name': `service-${index}` },
}));
}
const renderList = (
count: number,
{ clickable = false } = {},
): ReturnType<typeof render> =>
render(
<TopList
panelId="panel-1"
rows={rowsOf(count)}
valueName="count()"
thresholds={[]}
onSelect={clickable ? jest.fn() : undefined}
/>,
);
const renderedRows = (): HTMLElement[] =>
screen.queryAllByTestId('top-list-row');
mockListLayout();
const focusedRowIndex = (): string | null =>
document.activeElement?.getAttribute('data-row-index') ?? null;
// Moving focus can scroll the window first, and the target row mounts a frame later.
let user: ReturnType<typeof userEvent.setup>;
beforeEach(() => {
user = userEvent.setup({ pointerEventsCheck: 0 });
});
async function pressKey(key: string): Promise<void> {
await user.keyboard(`{${key}}`);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 100));
});
}
const hover = (element: Element): Promise<void> => user.hover(element);
describe('TopList', () => {
it('renders every row of a list that fits', () => {
renderList(5);
expect(renderedRows()).toHaveLength(5);
});
it.each([100, 1000])('renders only a window of a %i-row list', (count) => {
renderList(count);
const rendered = renderedRows().length;
expect(rendered).toBeGreaterThan(0);
expect(rendered).toBeLessThan(40);
});
it('jumps to the first and last rows with Home and End', async () => {
renderList(20, { clickable: true });
renderedRows()[5].focus();
await pressKey('End');
expect(focusedRowIndex()).toBe('19');
await pressKey('Home');
expect(focusedRowIndex()).toBe('0');
});
it('stays put at the ends of the list', async () => {
renderList(3, { clickable: true });
const rows = renderedRows();
rows[0].focus();
await pressKey('ArrowUp');
expect(rows[0]).toHaveFocus();
});
it('numbers rows and shows their share when asked', () => {
const rows = rowsOf(2).map((row, index) => ({
...row,
share: index === 0 ? 2 / 3 : 1 / 3,
}));
render(
<TopList
panelId="panel-1"
rows={rows}
valueName="count()"
thresholds={[]}
showRank
showShare
/>,
);
expect(
screen.getAllByTestId('top-list-row-rank').map((rank) => rank.textContent),
).toStrictEqual(['1', '2']);
expect(
screen
.getAllByTestId('top-list-row-share')
.map((share) => share.textContent),
).toStrictEqual(['67%', '33%']);
});
it('paints bars the panel color unless a background threshold matches', () => {
render(
<TopList
panelId="panel-1"
rows={rowsOf(2)}
valueName="count()"
barColor="#00C853"
thresholds={[
{ value: 2, operator: '>=', color: 'Red', format: 'background' },
]}
/>,
);
const fills = screen.getAllByTestId('top-list-row-fill');
expect(fills[0].style.getPropertyValue('--fill-color')).not.toBe('#00C853');
expect(fills[1].style.getPropertyValue('--fill-color')).toBe('#00C853');
});
it('heads the columns that are shown', () => {
render(
<TopList
panelId="panel-1"
rows={rowsOf(2)}
valueName="count()"
labelName="service.name"
thresholds={[]}
showRank
showShare
/>,
);
expect(screen.getByTestId('top-list-header').textContent).toBe(
'#service.nameSharecount()',
);
});
it('explains a header on hover with its full name', async () => {
render(
<TopList
panelId="panel-1"
rows={rowsOf(2)}
valueName="sum(signoz_calls_total)"
labelName="service.name"
thresholds={[]}
/>,
);
await hover(screen.getByTestId('top-list-header-value'));
const tooltip = await screen.findAllByTestId(
'top-list-header-tooltip',
{},
{ timeout: 2000 },
);
expect(tooltip[0]).toHaveTextContent(
'sum(signoz_calls_total)The value each row is ranked by.',
);
});
it('follows the pointer with the hovered row in the tooltip', async () => {
const rows = rowsOf(2).map((row) => ({ ...row, share: 0.5 }));
render(
<TopList
panelId="panel-1"
rows={rows}
valueName="count()"
thresholds={[]}
showShare
/>,
);
await hover(renderedRows()[1]);
await expect(
screen.findByTestId('top-list-tooltip-title'),
).resolves.toHaveTextContent('service-1');
expect(
screen.getAllByTestId('top-list-tooltip-row').map((row) => row.textContent),
).toStrictEqual(['count()1', 'Share of listed total50%']);
});
it('hides the tooltip over the empty space below the rows', async () => {
renderList(2);
await hover(renderedRows()[1]);
await screen.findByTestId('top-list-tooltip');
await hover(screen.getByTestId('top-list'));
expect(screen.queryByTestId('top-list-tooltip')).not.toBeInTheDocument();
});
it('hides the tooltip when the pointer leaves the list', async () => {
renderList(2);
await hover(renderedRows()[0]);
await screen.findByTestId('top-list-tooltip');
await user.unhover(screen.getByTestId('top-list').parentElement as Element);
expect(screen.queryByTestId('top-list-tooltip')).not.toBeInTheDocument();
});
it('hints at drilldown, not pinning, when rows are clickable', async () => {
render(
<TopList
panelId="panel-1"
rows={rowsOf(2)}
valueName="count()"
thresholds={[]}
onSelect={jest.fn()}
/>,
);
await hover(renderedRows()[0]);
const footer = await screen.findByTestId('uplot-tooltip-footer');
expect(footer).toHaveTextContent('Click to drilldown');
expect(footer).not.toHaveTextContent('to pin the tooltip');
});
it('leaves the footer out when rows are not clickable', async () => {
renderList(2);
await hover(renderedRows()[0]);
await screen.findByTestId('top-list-tooltip');
expect(screen.queryByTestId('uplot-tooltip-footer')).not.toBeInTheDocument();
});
it('shows neither rank nor share by default', () => {
renderList(3);
expect(screen.queryByTestId('top-list-row-rank')).not.toBeInTheDocument();
expect(screen.queryByTestId('top-list-row-share')).not.toBeInTheDocument();
});
it('cuts the middle out of a label wider than its bar', () => {
// 100px bar, 17px of label inset, 10px per character: 8 characters fit.
jest.spyOn(Element.prototype, 'clientWidth', 'get').mockReturnValue(100);
jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
font: '',
measureText: (text: string) => ({ width: text.length * 10 }),
} as unknown as CanvasRenderingContext2D);
renderList(1, { clickable: true });
expect(screen.getByTestId('top-list-row-label')).toHaveTextContent(
'serv…e-0',
);
expect(renderedRows()[0]).toHaveAttribute('aria-label', 'service-0: 1');
});
it('focuses a row that was out of view once it renders', async () => {
renderList(1000, { clickable: true });
renderedRows()[0].focus();
await pressKey('End');
expect(focusedRowIndex()).toBe('999');
});
it('scrolls a row moved to below the view fully into it', async () => {
renderList(100, { clickable: true });
const container = screen.getByTestId('top-list').parentElement as HTMLElement;
const rowHeight = parseInt(
screen.getByTestId('top-list').style.getPropertyValue('--row-height'),
10,
);
const rowsTop = LIST_PADDING_Y / 2 + HEADER_HEIGHT + ROW_GAP;
const rowBottom = (index: number): number =>
rowsTop + index * (rowHeight + ROW_GAP) + rowHeight;
const firstHidden = Array.from({ length: 100 }, (_, index) => index).find(
(index) => rowBottom(index) > container.clientHeight,
) as number;
(
container.querySelector(
`[data-row-index="${firstHidden - 1}"]`,
) as HTMLElement
).focus();
await pressKey('ArrowDown');
expect(focusedRowIndex()).toBe(String(firstHidden));
expect(container.scrollTop + container.clientHeight).toBeGreaterThanOrEqual(
rowBottom(firstHidden),
);
});
it('makes one row the Tab stop and moves it with focus', async () => {
renderList(5, { clickable: true });
const tabStops = (): string[] =>
renderedRows()
.filter((row) => row.tabIndex === 0)
.map((row) => row.getAttribute('data-row-index') as string);
expect(tabStops()).toStrictEqual(['0']);
renderedRows()[0].focus();
await pressKey('ArrowDown');
expect(tabStops()).toStrictEqual(['1']);
});
it('moves through rows that are not clickable by keyboard', async () => {
renderList(20);
renderedRows()[0].focus();
await pressKey('End');
expect(focusedRowIndex()).toBe('19');
});
it('positions each row in the whole list', () => {
renderList(100);
const [first] = renderedRows();
expect(first.closest('li')).toHaveAttribute('aria-posinset', '1');
expect(first.closest('li')).toHaveAttribute('aria-setsize', '100');
});
it('renders rows that are not clickable as plain list items', () => {
renderList(3);
expect(renderedRows().map((row) => row.tagName)).toStrictEqual([
'DIV',
'DIV',
'DIV',
]);
expect(renderedRows()[0].closest('li')).toHaveAttribute(
'aria-label',
'service-0: 3',
);
});
it('keeps the tooltip on the hovered row when a refetch reorders the rows', async () => {
const rows = rowsOf(3);
const { rerender } = render(
<TopList
panelId="panel-1"
rows={rows}
valueName="count()"
thresholds={[]}
/>,
);
await hover(renderedRows()[1]);
await expect(
screen.findByTestId('top-list-tooltip-title'),
).resolves.toHaveTextContent('service-1');
rerender(
<TopList
panelId="panel-1"
rows={[rows[1], rows[0], rows[2]]}
valueName="count()"
thresholds={[]}
/>,
);
expect(screen.getByTestId('top-list-tooltip-title')).toHaveTextContent(
'service-1',
);
});
});

View File

@@ -1,109 +0,0 @@
import {
DashboardtypesPanelKindDTO,
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpecDTOKind as TopListPluginKind,
Querybuildertypesv5ColumnTypeDTO,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal as TraceSignal,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
Querybuildertypesv5RequestTypeDTO,
type DashboardtypesTopListAppearanceDTO,
type DashboardtypesTopListPanelSpecDTO,
type Querybuildertypesv5ColumnDescriptorDTO,
type Querybuildertypesv5MetricAggregationDTO,
type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTO as TraceQuerySpec,
type Querybuildertypesv5QueryEnvelopeBuilderDTO,
type Querybuildertypesv5QueryEnvelopeDTO,
type Querybuildertypesv5QueryEnvelopeFormulaDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
type Querybuildertypesv5ScalarDataDTO,
type Querybuildertypesv5TraceAggregationDTO,
type QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelOfKind } from '../../../types/rendererProps';
export function topListPanel(
spec: DashboardtypesTopListPanelSpecDTO = {},
): PanelOfKind<'signoz/TopListPanel'> {
return {
kind: DashboardtypesPanelKindDTO.Panel,
spec: {
display: { name: 'Top services' },
plugin: { kind: TopListPluginKind['signoz/TopListPanel'], spec },
queries: [],
},
};
}
export const appearance = (
overrides: Partial<DashboardtypesTopListAppearanceDTO> = {},
): DashboardtypesTopListAppearanceDTO => ({
barColor: '#4E74F8',
...overrides,
});
export const groupColumn = (
name: string,
queryName = 'A',
): Querybuildertypesv5ColumnDescriptorDTO => ({
name,
queryName,
columnType: Querybuildertypesv5ColumnTypeDTO.group,
});
export const valueColumn = (
name = '__result',
aggregationIndex = 0,
queryName = 'A',
): Querybuildertypesv5ColumnDescriptorDTO => ({
name,
queryName,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
aggregationIndex,
});
export function scalarResponse(
results: Querybuildertypesv5ScalarDataDTO[],
): QueryRangeV5200 {
return {
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: { results },
},
};
}
export const requestWith = (
queries: Querybuildertypesv5QueryEnvelopeDTO[],
): Querybuildertypesv5QueryRangeRequestDTO => ({
compositeQuery: { queries },
});
export const builderQuery = (
spec: Omit<TraceQuerySpec, 'signal'>,
): Querybuildertypesv5QueryEnvelopeBuilderDTO => ({
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
spec: { signal: TraceSignal.traces, ...spec },
});
export const traceQuery = (
aggregation: Querybuildertypesv5TraceAggregationDTO,
): Querybuildertypesv5QueryEnvelopeBuilderDTO =>
builderQuery({ name: 'A', aggregations: [aggregation] });
export const metricQuery = (
aggregation: Querybuildertypesv5MetricAggregationDTO,
): Querybuildertypesv5QueryEnvelopeBuilderDTO => ({
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
spec: { name: 'A', signal: MetricSignal.metrics, aggregations: [aggregation] },
});
export const formulaQuery = (
name: string,
expression: string,
): Querybuildertypesv5QueryEnvelopeFormulaDTO => ({
type: Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula,
spec: { name, expression },
});

View File

@@ -1,70 +0,0 @@
const CONTAINER_HEIGHT = 280;
const CONTAINER_WIDTH = 600;
const ROW_HEIGHT = 28;
const SCROLL_HEIGHT = ROW_HEIGHT * 1000;
const heightOf = (element: Element): number =>
element.hasAttribute('data-index') ? ROW_HEIGHT : CONTAINER_HEIGHT;
/**
* jsdom has no layout, so the virtualized list would render no rows. Gives the scroll
* container and the measured rows (`data-index`) real heights, and makes `scrollTo`
* move `scrollTop` and fire `scroll` the way a browser does.
*/
export function mockListLayout(): void {
const originalScrollTo = Object.getOwnPropertyDescriptor(
Element.prototype,
'scrollTo',
);
beforeEach(() => {
jest
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
.mockImplementation(function rect(this: HTMLElement): DOMRect {
const height = heightOf(this);
return {
width: CONTAINER_WIDTH,
height,
top: 0,
left: 0,
bottom: height,
right: CONTAINER_WIDTH,
x: 0,
y: 0,
toJSON: () => ({}),
};
});
jest
.spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
.mockImplementation(function height(this: HTMLElement): number {
return heightOf(this);
});
jest
.spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
.mockReturnValue(CONTAINER_WIDTH);
jest
.spyOn(Element.prototype, 'clientHeight', 'get')
.mockReturnValue(CONTAINER_HEIGHT);
jest
.spyOn(Element.prototype, 'scrollHeight', 'get')
.mockReturnValue(SCROLL_HEIGHT);
Element.prototype.scrollTo = function scrollTo(
this: Element,
options?: ScrollToOptions | number,
): void {
if (typeof options === 'object' && options.top !== undefined) {
this.scrollTop = options.top;
this.dispatchEvent(new Event('scroll'));
}
};
});
afterEach(() => {
jest.restoreAllMocks();
if (originalScrollTo) {
Object.defineProperty(Element.prototype, 'scrollTo', originalScrollTo);
} else {
delete (Element.prototype as Partial<Element>).scrollTo;
}
});
}

View File

@@ -1,64 +0,0 @@
@use '../../../../../../../../styles/scrollbar' as *;
.container {
flex: 1;
min-height: 0;
overflow-y: auto;
@include custom-scrollbar;
}
// Rows share these columns through subgrid; the shown ones are set inline. Vertical
// padding is set inline too, where it also stands in for unrendered rows.
.list {
display: grid;
align-content: start;
column-gap: 10px;
row-gap: 1px;
margin: 0;
padding-inline: 4px;
list-style: none;
}
// Zero-height row holding the widest value, so the shared columns keep
// their size while rows scroll in and out of the rendered window. The negative
// margin cancels the row gap after it.
.sizer {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
height: 0;
margin-bottom: -1px;
padding: 0 8px;
overflow: hidden;
visibility: hidden;
white-space: nowrap;
}
.sizerValue {
font-size: 12px;
font-weight: var(--font-weight-medium);
font-variant-numeric: tabular-nums;
}
.sizerMuted {
font-size: 12px;
font-variant-numeric: tabular-nums;
}
// Measured for label truncation, so it carries the label's font.
.sizerBar {
font-size: 12px;
}
// Lets the pointer pass through to the rows underneath; otherwise the tooltip catches
// it and stops following.
// Sized to its content like the chart tooltips, up to TooltipPlugin's maxWidth/maxHeight;
// the floor keeps a short one from collapsing narrower than a scatter tooltip.
.tooltip {
width: max-content;
min-width: 320px;
max-width: 450px;
max-height: 600px;
overflow: auto;
pointer-events: none;
}

View File

@@ -1,201 +0,0 @@
import {
type CSSProperties,
useCallback,
useMemo,
useRef,
useState,
} from 'react';
import type { PrecisionOption } from 'components/Graph/types';
import { useResizeObserver } from 'hooks/useDimensions';
import TooltipFooter from 'lib/visualization/panels/components/TooltipFooter';
import type { PanelThreshold } from '../../../../types/threshold';
import { HEADER_HEIGHT, LIST_PADDING_Y } from '../../constants';
import { useLabelFitter } from '../../hooks/useLabelFitter';
import { useTopListTooltip } from '../../hooks/useTopListTooltip';
import { useTopListVirtualizer } from '../../hooks/useTopListVirtualizer';
import type { TopListRow as TopListRowData } from '../../types';
import {
getGridColumns,
getNavigationTarget,
getRowHeight,
getWidestShare,
getWidestValue,
type RowColors,
} from '../../utils/rowDisplay';
import TopListHeader from '../TopListHeader/TopListHeader';
import TopListRow from '../TopListRow/TopListRow';
import TopListTooltip from '../TopListTooltip/TopListTooltip';
import styles from './TopList.module.scss';
const RESIZE_DEBOUNCE_MS = 100;
interface TopListProps {
/** Identifies the panel in tooltip analytics. */
panelId: string;
rows: TopListRowData[];
/** What the values measure, named in each row's tooltip. */
valueName: string;
/** Heads the label column: the group-by keys behind each label. */
labelName?: string;
unit?: string;
precision?: PrecisionOption;
thresholds: PanelThreshold[];
/** Bar color where no threshold recolours it; unset uses the accent. */
barColor?: string;
showRank?: boolean;
showShare?: boolean;
onSelect?: (
row: TopListRowData,
colors: RowColors,
coordinates: { x: number; y: number },
) => void;
}
function TopList({
panelId,
rows,
valueName,
labelName = '',
unit,
precision,
thresholds,
barColor,
showRank = false,
showShare = false,
onSelect,
}: TopListProps): JSX.Element {
const containerRef = useRef<HTMLDivElement>(null);
const sizerBarRef = useRef<HTMLSpanElement>(null);
const fitLabel = useLabelFitter(sizerBarRef);
const tooltip = useTopListTooltip();
const hoveredRow = useMemo(
() =>
tooltip.rowKey === null
? undefined
: rows.find((row) => row.key === tooltip.rowKey),
[rows, tooltip.rowKey],
);
const { height } = useResizeObserver(containerRef, RESIZE_DEBOUNCE_MS);
const rowHeight = getRowHeight(rows.length, height - HEADER_HEIGHT);
const { virtualItems, paddingTop, paddingBottom, focusRow } =
useTopListVirtualizer({ count: rows.length, rowHeight, containerRef });
const [focusedIndex, setFocusedIndex] = useState(0);
// The focused row may be scrolled out of the rendered window; the list stays reachable by Tab.
const tabStop = virtualItems.some(({ index }) => index === focusedIndex)
? focusedIndex
: virtualItems[0]?.index;
const widestValue = useMemo(
() => getWidestValue(rows, unit, precision),
[rows, unit, precision],
);
const widestShare = useMemo(
() => (showShare ? getWidestShare(rows) : ''),
[rows, showShare],
);
const handleNavigate = useCallback(
(index: number, key: string): boolean => {
const target = getNavigationTarget(index, key, rows.length);
if (target === null) {
return false;
}
focusRow(target);
return true;
},
[rows.length, focusRow],
);
const listStyle = {
'--row-height': `${rowHeight}px`,
'--header-height': `${HEADER_HEIGHT}px`,
gridTemplateColumns: getGridColumns(showRank, showShare),
paddingTop: LIST_PADDING_Y / 2 + paddingTop,
paddingBottom: LIST_PADDING_Y / 2 + paddingBottom,
} as CSSProperties;
return (
<div
ref={containerRef}
className={styles.container}
onScroll={tooltip.hide}
onMouseLeave={tooltip.hide}
onMouseMove={tooltip.hideOffRow}
>
<ol
ref={tooltip.listRef}
data-testid="top-list"
className={styles.list}
style={listStyle}
>
<TopListHeader
valueName={valueName}
labelName={labelName}
showRank={showRank}
showShare={showShare}
/>
<li aria-hidden className={styles.sizer}>
{showRank && (
<span className={styles.sizerMuted}>{String(rows.length)}</span>
)}
<span ref={sizerBarRef} className={styles.sizerBar} />
{showShare && <span className={styles.sizerMuted}>{widestShare}</span>}
<span className={styles.sizerValue}>{widestValue}</span>
</li>
{virtualItems.map(({ index }) => (
<TopListRow
key={rows[index].key}
row={rows[index]}
index={index}
count={rows.length}
isTabStop={index === tabStop}
unit={unit}
precision={precision}
thresholds={thresholds}
barColor={barColor}
showRank={showRank}
showShare={showShare}
fitLabel={fitLabel}
onHover={tooltip.show}
onSelect={onSelect}
onNavigate={handleNavigate}
onFocus={setFocusedIndex}
/>
))}
</ol>
{hoveredRow && (
<tooltip.TooltipInPortal
top={tooltip.top}
left={tooltip.left}
unstyled
applyPositionStyle
className={styles.tooltip}
>
<TopListTooltip
row={hoveredRow}
valueName={valueName}
unit={unit}
precision={precision}
thresholds={thresholds}
barColor={barColor}
showShare={showShare}
footer={
onSelect && (
<TooltipFooter
id={panelId}
isPinned={false}
canPin={false}
dismiss={tooltip.hide}
/>
)
}
/>
</tooltip.TooltipInPortal>
)}
</div>
);
}
export default TopList;

View File

@@ -1,17 +0,0 @@
import styles from './TopListHeader.module.scss';
interface HeaderTooltipProps {
name: string;
description: string;
}
function HeaderTooltip({ name, description }: HeaderTooltipProps): JSX.Element {
return (
<div data-testid="top-list-header-tooltip" className={styles.tooltip}>
<span className={styles.tooltipName}>{name}</span>
<span className={styles.tooltipDescription}>{description}</span>
</div>
);
}
export default HeaderTooltip;

View File

@@ -1,55 +0,0 @@
// Stays on top while rows scroll under it, so it needs the panel's surface.
.header {
position: sticky;
top: 0;
z-index: 1;
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
align-items: center;
height: var(--header-height);
padding: 0 8px;
border-bottom: 1px solid var(--l1-border);
background: var(--l2-background);
font-size: 12px;
line-height: 16px;
color: var(--l3-foreground);
white-space: nowrap;
}
// Capped so a long value name doesn't widen its column past the values.
.cell {
justify-self: end;
max-width: 120px;
overflow: hidden;
text-align: right;
text-overflow: ellipsis;
cursor: default;
}
// Lines up with the labels inside the bars.
.label {
justify-self: start;
max-width: 100%;
min-width: 0;
padding: 0 8px;
overflow: hidden;
text-overflow: ellipsis;
cursor: default;
}
.tooltip {
display: flex;
flex-direction: column;
gap: 2px;
max-width: 280px;
}
.tooltipName {
font-weight: var(--font-weight-medium);
word-break: break-word;
}
.tooltipDescription {
color: var(--l2-foreground);
}

View File

@@ -1,74 +0,0 @@
import { Tooltip } from '@signozhq/ui/tooltip';
import HeaderTooltip from './HeaderTooltip';
import styles from './TopListHeader.module.scss';
interface TopListHeaderProps {
valueName: string;
/** The group-by keys behind each label; empty when the query has no group-by. */
labelName: string;
showRank: boolean;
showShare: boolean;
}
function TopListHeader({
valueName,
labelName,
showRank,
showShare,
}: TopListHeaderProps): JSX.Element {
return (
<li aria-hidden data-testid="top-list-header" className={styles.header}>
{showRank && (
<Tooltip
title={<HeaderTooltip name="Rank" description="Position in the list." />}
>
<span className={styles.cell}>#</span>
</Tooltip>
)}
{labelName ? (
<Tooltip
title={
<HeaderTooltip
name={labelName}
description="The group each row stands for."
/>
}
align="start"
>
<span className={styles.label}>{labelName}</span>
</Tooltip>
) : (
<span />
)}
{showShare && (
<Tooltip
title={
<HeaderTooltip
name="Share"
description="Each row's value as a percentage of the listed rows' total."
/>
}
>
<span className={styles.cell}>Share</span>
</Tooltip>
)}
<Tooltip
title={
<HeaderTooltip
name={valueName}
description="The value each row is ranked by."
/>
}
align="end"
>
<span data-testid="top-list-header-value" className={styles.cell}>
{valueName}
</span>
</Tooltip>
</li>
);
}
export default TopListHeader;

View File

@@ -1,116 +0,0 @@
.item {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
}
.row {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
align-items: center;
height: var(--row-height);
padding: 0 8px;
border: 0;
border-radius: 2px;
outline: 1px solid transparent;
outline-offset: -1px;
background: transparent;
font: inherit;
text-align: left;
transition: background-color 120ms;
// The panel surface is --l2-background, so the hovered row sits a level above it.
&:hover {
background: var(--l3-background);
}
&:focus-visible {
outline-color: var(--bg-robin-500);
}
}
.isInteractive {
cursor: pointer;
}
.value {
font-size: 12px;
line-height: 16px;
font-weight: var(--font-weight-medium);
color: var(--l1-foreground);
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
// Rank and share: supporting numbers beside the value.
.muted {
font-size: 12px;
line-height: 16px;
color: var(--l3-foreground);
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.isNonNumeric {
color: var(--l3-foreground);
}
// The label sits on the bar, spanning the whole column so it isn't cut at the fill.
// The track sits a level above the panel surface (--l2-background).
.bar {
position: relative;
display: flex;
align-items: center;
min-width: 0;
height: calc(var(--row-height) - 4px);
border-radius: 2px;
background: var(--l3-background);
transition: background-color 120ms;
.row:hover & {
background: var(--l3-background-hover);
}
}
.fill {
position: absolute;
inset: 0 auto 0 0;
border-radius: 2px;
background: color-mix(in srgb, var(--bg-robin-500) 35%, transparent);
.row:hover & {
background: color-mix(in srgb, var(--bg-robin-500) 48%, transparent);
}
}
.hasFillColor {
background: color-mix(in srgb, var(--fill-color) 35%, transparent);
.row:hover & {
background: color-mix(in srgb, var(--fill-color) 48%, transparent);
}
}
.label {
position: relative;
min-width: 0;
padding: 0 8px;
overflow: hidden;
font-size: 12px;
line-height: 16px;
color: var(--l2-foreground);
white-space: nowrap;
text-overflow: ellipsis;
.row:hover & {
color: var(--l1-foreground);
}
}
.isEmptyLabel {
font-style: italic;
color: var(--l3-foreground);
}

View File

@@ -1,193 +0,0 @@
import {
type CSSProperties,
memo,
useMemo,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
} from 'react';
import cx from 'classnames';
import type { PrecisionOption } from 'components/Graph/types';
import type { PanelThreshold } from '../../../../types/threshold';
import type { TopListRow as TopListRowData } from '../../types';
import {
formatRowValue,
formatShare,
resolveRowColors,
type RowColors,
} from '../../utils/rowDisplay';
import styles from './TopListRow.module.scss';
interface TopListRowProps {
row: TopListRowData;
/** Position in the ranked list. */
index: number;
/** Rows in the list, rendered or not. */
count: number;
/** The list's one Tab stop; arrow keys move it. */
isTabStop: boolean;
unit?: string;
precision?: PrecisionOption;
thresholds: PanelThreshold[];
/** Bar color where no threshold recolours it; unset uses the accent. */
barColor?: string;
showRank: boolean;
showShare: boolean;
/** Shortens a label to fit its bar. */
fitLabel: (label: string) => string;
/** Moves the list's tooltip to this row, at the pointer. */
onHover: (rowKey: string, event: ReactMouseEvent<HTMLElement>) => void;
onSelect?: (
row: TopListRowData,
colors: RowColors,
coordinates: { x: number; y: number },
) => void;
/** Handles a navigation key; returns whether it moved focus. */
onNavigate: (index: number, key: string) => boolean;
onFocus: (index: number) => void;
}
function TopListRow({
row,
index,
count,
isTabStop,
unit,
precision,
thresholds,
barColor,
showRank,
showShare,
fitLabel,
onHover,
onSelect,
onNavigate,
onFocus,
}: TopListRowProps): JSX.Element {
const displayValue = useMemo(
() => formatRowValue(row, unit, precision),
[row, unit, precision],
);
const colors = useMemo(
() => resolveRowColors(row.value, thresholds, unit, barColor),
[row.value, thresholds, unit, barColor],
);
const displayShare = showShare ? formatShare(row.share) : null;
const knownShare =
displayShare !== null && row.share !== null ? displayShare : undefined;
const displayLabel = useMemo(() => fitLabel(row.label), [fitLabel, row.label]);
const handleClick = (event: ReactMouseEvent<HTMLButtonElement>): void => {
if (!onSelect) {
return;
}
// Enter/Space clicks carry no pointer position; anchor the menu under the row.
if (event.detail === 0) {
const { left, bottom } = event.currentTarget.getBoundingClientRect();
onSelect(row, colors, { x: left, y: bottom });
return;
}
onSelect(row, colors, { x: event.clientX, y: event.clientY });
};
const handleMouseMove = (event: ReactMouseEvent<HTMLElement>): void =>
onHover(row.key, event);
const handleKeyDown = (event: ReactKeyboardEvent<HTMLElement>): void => {
if (onNavigate(index, event.key)) {
event.preventDefault();
}
};
const ariaLabel = `${row.label}: ${displayValue}${
knownShare ? `, ${knownShare} of listed total` : ''
}`;
const content = (
<>
{showRank && (
<span data-testid="top-list-row-rank" className={styles.muted}>
{index + 1}
</span>
)}
<span className={styles.bar}>
<span
data-testid="top-list-row-fill"
className={cx(styles.fill, {
[styles.hasFillColor]: !!colors.barColor,
})}
style={
{
width: `${row.ratio * 100}%`,
'--fill-color': colors.barColor,
} as CSSProperties
}
/>
<span
data-testid="top-list-row-label"
className={cx(styles.label, { [styles.isEmptyLabel]: row.isEmptyLabel })}
>
{displayLabel}
</span>
</span>
{displayShare && (
<span data-testid="top-list-row-share" className={styles.muted}>
{displayShare}
</span>
)}
<span
data-testid="top-list-row-value"
className={cx(styles.value, {
[styles.isNonNumeric]: row.value === null,
})}
style={{ color: colors.valueColor }}
>
{displayValue}
</span>
</>
);
return (
<li
className={styles.item}
aria-setsize={count}
aria-posinset={index + 1}
aria-label={onSelect ? undefined : ariaLabel}
>
{onSelect ? (
<button
type="button"
aria-haspopup="menu"
aria-label={ariaLabel}
tabIndex={isTabStop ? 0 : -1}
data-row-index={index}
data-testid="top-list-row"
className={cx(styles.row, styles.isInteractive)}
onClick={handleClick}
onMouseMove={handleMouseMove}
onKeyDown={handleKeyDown}
onFocus={(): void => onFocus(index)}
>
{content}
</button>
) : (
// Focusable without an action so the keyboard can still walk the list.
// oxlint-disable-next-line jsx-a11y/no-static-element-interactions
<div
// oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex
tabIndex={isTabStop ? 0 : -1}
data-row-index={index}
data-testid="top-list-row"
className={styles.row}
onMouseMove={handleMouseMove}
onKeyDown={handleKeyDown}
onFocus={(): void => onFocus(index)}
>
{content}
</div>
)}
</li>
);
}
export default memo(TopListRow);

View File

@@ -1,55 +0,0 @@
import { type ReactNode, useMemo } from 'react';
import type { PrecisionOption } from 'components/Graph/types';
import TooltipCard from 'lib/uPlotV2/components/Tooltip/components/TooltipCard/TooltipCard';
import type { PanelThreshold } from '../../../../types/threshold';
import type { TopListRow } from '../../types';
import {
ACCENT_COLOR,
getTooltipContent,
resolveRowColors,
} from '../../utils/rowDisplay';
interface TopListTooltipProps {
row: TopListRow;
/** What the values measure. */
valueName: string;
unit?: string;
precision?: PrecisionOption;
thresholds: PanelThreshold[];
/** Bar color where no threshold recolours it; unset uses the accent. */
barColor?: string;
showShare: boolean;
/** Hints for what a click does; none when rows aren't clickable. */
footer?: ReactNode;
}
function TopListTooltip({
row,
valueName,
unit,
precision,
thresholds,
barColor,
showShare,
footer,
}: TopListTooltipProps): JSX.Element {
const { rows, mutedRows } = useMemo(
() => getTooltipContent(row, { valueName, unit, precision, showShare }),
[row, valueName, unit, precision, showShare],
);
const colors = resolveRowColors(row.value, thresholds, unit, barColor);
return (
<TooltipCard
title={row.label}
color={colors.barColor ?? ACCENT_COLOR}
rows={rows}
mutedRows={mutedRows}
footer={footer}
testId="top-list-tooltip"
/>
);
}
export default TopListTooltip;

View File

@@ -1,10 +0,0 @@
/** Groups shown when the query sets no limit. */
export const DEFAULT_LIMIT = 10;
/** Row heights by density, roomiest first: comfortable, default, compact. */
export const ROW_HEIGHTS = [32, 28, 24] as const;
export const DEFAULT_ROW_HEIGHT = 28;
export const ROW_GAP = 1;
/** The list's top and bottom padding combined. */
export const LIST_PADDING_Y = 12;
/** The sticky column header row. */
export const HEADER_HEIGHT = 24;

View File

@@ -1,72 +0,0 @@
import { ChartBarDecreasing } from '@signozhq/icons';
import { QueryBuilderField } from 'components/QueryBuilderV2/queryBuilderFields.types';
import type { PanelDefinition } from '../../types/panelDefinition';
import { QueryModeKind } from '../../types/panelCapabilities';
import QueryBuilderEditorPane from 'pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/QueryBuilderEditorPane';
import Renderer from './Renderer';
import { DEFAULT_LIMIT } from './constants';
import { sections } from './sections';
import { getTopListDataWarning } from './utils/warnings';
import {
Querybuildertypesv5RequestTypeDTO,
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
import { QueryMode } from 'types/api/queryBuilder/queryBuilderData';
export const definition: PanelDefinition<'signoz/TopListPanel'> = {
kind: 'signoz/TopListPanel',
displayName: 'Top List',
mode: 'query',
icon: ChartBarDecreasing,
Renderer,
EditorPane: QueryBuilderEditorPane,
sections,
supportedQueryModesKindMap: {
[QueryMode.QUERY_BUILDER]: {
kind: QueryModeKind.SIGNAL,
signals: [
TelemetrytypesSignalDTO.metrics,
TelemetrytypesSignalDTO.logs,
TelemetrytypesSignalDTO.traces,
],
},
[QueryMode.CLICKHOUSE]: { kind: QueryModeKind.SIGNAL_LESS },
},
queryBuilderFields: {
// A list without a group by is a single row.
[QueryBuilderField.GroupBy]: { state: 'pinned' },
// Picks top or bottom N on the server; a client-side flip would show the top N reversed.
[QueryBuilderField.OrderBy]: {
state: 'pinned',
placeholder: 'Default highest first',
},
[QueryBuilderField.Limit]: {
state: 'pinned',
placeholder: `Default ${DEFAULT_LIMIT} for Top List`,
},
// Ignored for logs and traces scalars; for metrics they apply before reduceTo.
[QueryBuilderField.Functions]: { state: 'hidden' },
},
queryCapabilities: {
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
formatTableResultForUI: false,
bucketedStepInterval: false,
orderTiebreaker: false,
serverPaginated: false,
defaultRowLimit: DEFAULT_LIMIT,
},
// Formulas join their inputs on group values, so every query groups by the same keys.
syncedQueryBuilderFields: [QueryBuilderField.GroupBy],
getDataWarning: getTopListDataWarning,
actions: {
view: true,
edit: true,
clone: true,
download: { csv: true, png: true, svg: true },
createAlert: false,
search: false,
drilldown: true,
},
};

View File

@@ -1,53 +0,0 @@
import { type RefObject, useCallback, useMemo } from 'react';
import { useResizeObserver } from 'hooks/useDimensions';
import { truncateMiddle } from '../utils/rowDisplay';
/** The label's horizontal padding inside the bar, plus a pixel for canvas/DOM rounding. */
const LABEL_INSET_X = 17;
const RESIZE_DEBOUNCE_MS = 100;
let canvasContext: CanvasRenderingContext2D | null | undefined;
function getCanvasContext(): CanvasRenderingContext2D | null {
if (canvasContext === undefined) {
canvasContext = document.createElement('canvas').getContext('2d');
}
return canvasContext;
}
/**
* Middle-truncates labels to the bar column, measured on `barRef`, which must carry the
* label's font. Labels pass through unchanged until the column has a width.
*/
export function useLabelFitter(
barRef: RefObject<HTMLElement>,
): (label: string) => string {
const { width } = useResizeObserver(barRef, RESIZE_DEBOUNCE_MS);
const maxWidth = width - LABEL_INSET_X;
const font = useMemo(() => {
const node = barRef.current;
if (!node || maxWidth <= 0) {
return null;
}
const { fontWeight, fontSize, fontFamily } = getComputedStyle(node);
return `${fontWeight} ${fontSize} ${fontFamily}`;
}, [barRef, maxWidth]);
return useCallback(
(label: string): string => {
const context = font ? getCanvasContext() : null;
if (!context || !font) {
return label;
}
context.font = font;
return truncateMiddle(
label,
maxWidth,
(value) => context.measureText(value).width,
);
},
[font, maxWidth],
);
}

View File

@@ -1,78 +0,0 @@
import {
type FC,
type MouseEvent as ReactMouseEvent,
useCallback,
useRef,
} from 'react';
import { useTooltip, useTooltipInPortal } from '@visx/tooltip';
import type { TooltipInPortalProps } from '@visx/tooltip/lib/hooks/useTooltipInPortal';
/** Above the dashboard grid, like the chart tooltips. */
const TOOLTIP_Z_INDEX = 1000;
interface TopListTooltip {
/** The hovered row's key, or null when the tooltip is hidden. */
rowKey: string | null;
top?: number;
left?: number;
show: (rowKey: string, event: ReactMouseEvent<HTMLElement>) => void;
hide: () => void;
/** Hides the tooltip when the pointer is over the list but not on a row. */
hideOffRow: (event: ReactMouseEvent<HTMLElement>) => void;
/** The element the tooltip is positioned against. */
listRef: (element: HTMLElement | null) => void;
TooltipInPortal: FC<TooltipInPortalProps>;
}
/** One tooltip for the whole list, following the pointer the way the chart tooltips do. */
export function useTopListTooltip(): TopListTooltip {
const {
tooltipOpen,
tooltipData,
tooltipTop,
tooltipLeft,
showTooltip,
hideTooltip,
} = useTooltip<string>();
const { containerRef, containerBounds, TooltipInPortal } = useTooltipInPortal({
scroll: true,
detectBounds: true,
zIndex: TOOLTIP_Z_INDEX,
});
// Read at event time so `show` stays stable for the memoised rows.
const boundsRef = useRef(containerBounds);
boundsRef.current = containerBounds;
const show = useCallback(
(rowKey: string, event: ReactMouseEvent<HTMLElement>): void => {
const { left, top } = boundsRef.current;
showTooltip({
tooltipData: rowKey,
tooltipLeft: event.clientX - left,
tooltipTop: event.clientY - top,
});
},
[showTooltip],
);
const hideOffRow = useCallback(
(event: ReactMouseEvent<HTMLElement>): void => {
if (!(event.target as Element).closest('[data-row-index]')) {
hideTooltip();
}
},
[hideTooltip],
);
return {
rowKey: tooltipOpen ? (tooltipData ?? null) : null,
top: tooltipTop,
left: tooltipLeft,
show,
hide: hideTooltip,
hideOffRow,
listRef: containerRef,
TooltipInPortal,
};
}

View File

@@ -1,92 +0,0 @@
import { type RefObject, useCallback, useEffect, useRef } from 'react';
import { useVirtualizer, type VirtualItem } from '@tanstack/react-virtual';
import { HEADER_HEIGHT, LIST_PADDING_Y, ROW_GAP } from '../constants';
const OVERSCAN = 10;
/** Size assumed until the container is measured, so the first paint isn't empty. */
const INITIAL_RECT = { width: 0, height: 600 };
/** Frames to wait for a scrolled-to row to mount before giving up on focusing it. */
const FOCUS_RETRY_FRAMES = 10;
/** The first row's offset in the container: the list's top padding, the header and the gap below it. */
const ROWS_OFFSET = LIST_PADDING_Y / 2 + HEADER_HEIGHT + ROW_GAP;
interface UseTopListVirtualizerArgs {
count: number;
rowHeight: number;
containerRef: RefObject<HTMLDivElement>;
}
interface TopListVirtualizer {
/** The rows to render: those in view plus an overscan either side. */
virtualItems: VirtualItem[];
/** Space standing in for the rows above and below the rendered window. */
paddingTop: number;
paddingBottom: number;
/** Scrolls the row into view if needed, then focuses it. */
focusRow: (index: number) => void;
}
export function useTopListVirtualizer({
count,
rowHeight,
containerRef,
}: UseTopListVirtualizerArgs): TopListVirtualizer {
const virtualizer = useVirtualizer({
count,
getScrollElement: () => containerRef.current,
estimateSize: () => rowHeight,
gap: ROW_GAP,
scrollMargin: ROWS_OFFSET,
// Keeps a row scrolled to from landing under the sticky header.
scrollPaddingStart: HEADER_HEIGHT,
scrollPaddingEnd: LIST_PADDING_Y / 2,
overscan: OVERSCAN,
initialRect: INITIAL_RECT,
});
const focusFrame = useRef<number>();
// Every row takes the density's height, so a density change re-lays out every row.
useEffect(() => {
virtualizer.measure();
}, [virtualizer, rowHeight]);
useEffect(() => (): void => cancelAnimationFrame(focusFrame.current ?? 0), []);
const focusRow = useCallback(
(index: number): void => {
cancelAnimationFrame(focusFrame.current ?? 0);
virtualizer.scrollToIndex(index, { align: 'auto' });
let attempts = 0;
const tryFocus = (): void => {
const row = containerRef.current?.querySelector<HTMLElement>(
`[data-row-index="${index}"]`,
);
if (row) {
// The virtualizer already scrolled; a native focus scroll would fight it.
row.focus({ preventScroll: true });
return;
}
if (attempts < FOCUS_RETRY_FRAMES) {
attempts += 1;
focusFrame.current = requestAnimationFrame(tryFocus);
}
};
tryFocus();
},
[virtualizer, containerRef],
);
const virtualItems = virtualizer.getVirtualItems();
const first = virtualItems[0];
const last = virtualItems[virtualItems.length - 1];
return {
virtualItems,
// Item offsets include the scroll margin; the total size doesn't.
paddingTop: first ? first.start - ROWS_OFFSET : 0,
paddingBottom: last
? virtualizer.getTotalSize() - (last.end - ROWS_OFFSET)
: 0,
focusRow,
};
}

View File

@@ -1,22 +0,0 @@
import {
SectionKind,
ThresholdVariant,
type SectionConfig,
} from '../../types/sections';
export const sections: SectionConfig[] = [
{
kind: SectionKind.Visualization,
controls: { switchPanelKind: true, timePreference: true },
},
{
kind: SectionKind.Appearance,
controls: { showRank: true, showShare: true, barColor: true },
},
{ kind: SectionKind.Formatting, controls: { unit: true, decimals: true } },
{
kind: SectionKind.Thresholds,
controls: { variant: ThresholdVariant.COMPARISON },
},
{ kind: SectionKind.ContextLinks },
];

View File

@@ -1,38 +0,0 @@
export interface TopListRow {
/**
* Unique per row and built from its group values, so it follows the row across
* refetches; labels can repeat (e.g. a legend with no `{{…}}`).
*/
key: string;
label: string;
/** True when every group value behind the label was missing, or the legend filled to blank. */
isEmptyLabel: boolean;
/** The ranked value, or null when the cell isn't a finite number ("NaN", "Inf", "n/a", null). */
value: number | null;
/** The cell as the server sent it, shown when `value` is null. */
rawValue: unknown;
/** Bar length: `value` over the largest positive value, 0–1. Zero for values ≤ 0 and null. */
ratio: number;
/** `value` over the sum of every row's value; null for null values and when any value is negative. */
share: number | null;
/** Source query, the drilldown target. */
queryName: string;
/** Group-by key → value, the drilldown filters. */
labels: Record<string, string>;
}
export interface TopListData {
rows: TopListRow[];
/** Group-by columns behind each label; empty when the query has no group-by. */
labelColumnNames: string[];
/** The ranked value column. */
valueColumnName: string;
/** What the ranked value measures. Unlike `valueColumnName`, never the legend template. */
valueName: string;
/** Value columns after the first, which the ranking ignores. */
ignoredValueColumns: string[];
/** Other enabled queries and formulas, which the ranking ignores. */
ignoredResults: string[];
/** The group-by key the ranked query orders by, when it orders by one instead of its value. */
orderedByGroupKey: string | null;
}

View File

@@ -1,110 +0,0 @@
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import {
groupColumn,
requestWith,
scalarResponse,
topListPanel as panelWith,
traceQuery,
valueColumn,
} from '../../__tests__/fixtures';
import { getTopListCsvRows } from '../csv';
function dataWith(groupColumns: string[], rows: unknown[][]): PanelQueryData {
return {
response: scalarResponse([
{
queryName: 'A',
columns: [...groupColumns.map((name) => groupColumn(name)), valueColumn()],
data: rows,
},
]),
requestPayload: undefined,
legendMap: {},
};
}
describe('getTopListCsvRows', () => {
it('exports the rows in ranked order with formatted values', () => {
const data = dataWith(
['service.name'],
[
['auth', 25],
['payment', 1500],
],
);
expect(
getTopListCsvRows(panelWith({ formatting: { unit: 'ms' } }), data),
).toStrictEqual([
{ 'service.name': 'payment', A: '1.5 s' },
{ 'service.name': 'auth', A: '25 ms' },
]);
});
it('names the label column after every group-by key', () => {
const data = dataWith(['http.route', 'region'], [['GET /orders', 'eu', 3]]);
expect(Object.keys(getTopListCsvRows(panelWith({}), data)[0])).toStrictEqual([
'http.route, region',
'A',
]);
});
it('heads the value column with what it measures, not the legend template', () => {
const data = {
...dataWith(['service.name'], [['auth', 25]]),
legendMap: { A: '{{service.name}}' },
};
expect(getTopListCsvRows(panelWith({}), data)).toStrictEqual([
{ 'service.name': 'auth', A: '25' },
]);
});
it('falls back to a generic label header without a group-by', () => {
const data = dataWith([], [[42]]);
expect(getTopListCsvRows(panelWith({}), data)).toStrictEqual([
{ Label: 'A', A: '42' },
]);
});
it('adds rank and share columns when the panel shows them', () => {
const data = dataWith(
['service.name'],
[
['auth', 25],
['payment', 75],
],
);
const panel = panelWith({
appearance: { showRank: true, showShare: true, barColor: '#4E74F8' },
});
expect(getTopListCsvRows(panel, data)).toStrictEqual([
{ Rank: '1', 'service.name': 'payment', A: '75', Share: '75%' },
{ Rank: '2', 'service.name': 'auth', A: '25', Share: '25%' },
]);
});
it('suffixes a header that repeats another instead of overwriting its column', () => {
const data = {
...dataWith(['Rank'], [['auth', 25]]),
requestPayload: requestWith([
traceQuery({ expression: 'count()', alias: 'Share' }),
]),
};
const panel = panelWith({
appearance: { showRank: true, showShare: true, barColor: '#4E74F8' },
});
expect(getTopListCsvRows(panel, data)).toStrictEqual([
{ Rank: '1', 'Rank (2)': 'auth', Share: '25', 'Share (2)': '100%' },
]);
});
it('exports nothing for an empty result', () => {
expect(getTopListCsvRows(panelWith({}), dataWith([], []))).toStrictEqual([]);
});
});

View File

@@ -1,285 +0,0 @@
import {
MetrictypesSpaceAggregationDTO,
Querybuildertypesv5OrderDirectionDTO,
type Querybuildertypesv5MetricAggregationDTO,
type Querybuildertypesv5QueryEnvelopeDTO,
type Querybuildertypesv5TraceAggregationDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import {
appearance,
builderQuery,
formulaQuery as formula,
groupColumn,
metricQuery,
requestWith,
scalarResponse,
topListPanel,
traceQuery,
valueColumn,
} from '../../__tests__/fixtures';
import { prepareTopListData } from '../prepareData';
import { getTopListDataWarning } from '../warnings';
const panel = topListPanel();
interface Result {
queryName: string;
rows: [string, number][];
}
function dataWith(
results: Result[],
queries: Querybuildertypesv5QueryEnvelopeDTO[],
): PanelQueryData {
return {
response: scalarResponse(
results.map(({ queryName, rows }) => ({
queryName,
columns: [
groupColumn('service.name', queryName),
valueColumn('__result', 0, queryName),
],
data: rows,
})),
),
requestPayload: requestWith(queries),
legendMap: {},
};
}
const query = (
name: string,
limit?: number,
): Querybuildertypesv5QueryEnvelopeDTO => builderQuery({ name, limit });
type Aggregation =
| Querybuildertypesv5TraceAggregationDTO
| Querybuildertypesv5MetricAggregationDTO;
/** Metrics aggregate a metric, traces and logs an expression. */
const isMetric = (
aggregation: Aggregation,
): aggregation is Querybuildertypesv5MetricAggregationDTO =>
'metricName' in aggregation;
const aggregated = (
aggregation: Aggregation,
): Querybuildertypesv5QueryEnvelopeDTO =>
isMetric(aggregation) ? metricQuery(aggregation) : traceQuery(aggregation);
const A: Result = { queryName: 'A', rows: [['checkout', 10]] };
const B: Result = { queryName: 'B', rows: [['checkout', 2]] };
const F1: Result = { queryName: 'F1', rows: [['checkout', 5]] };
describe('top list with several queries', () => {
it('ranks the first query in builder order, whatever order the response lists them in', () => {
const data = dataWith(
[F1, B, A],
[query('A'), query('B'), formula('F1', 'A / B')],
);
const { rows, ignoredResults } = prepareTopListData(data);
expect(rows.map((row) => [row.queryName, row.value])).toStrictEqual([
['A', 10],
]);
expect(ignoredResults).toStrictEqual(['B', 'F1']);
});
it('ranks the formula when its inputs are disabled', () => {
// The server leaves disabled queries out of the response.
const data = dataWith([F1], [query('A'), query('B'), formula('F1', 'A / B')]);
expect(prepareTopListData(data).rows[0].queryName).toBe('F1');
expect(getTopListDataWarning(panel, data)).toBeNull();
});
it('names the results the ranking leaves out', () => {
const data = dataWith([A, B], [query('A'), query('B')]);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'The list ranks "A" only; "B" is not shown. Disable the queries you don\'t want to rank.',
]);
});
it('warns when a formula reads inputs cut to their own limit', () => {
const data = dataWith(
[F1],
[query('A', 10), query('B', 10), query('C', 5), formula('F1', 'A / B')],
);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'"A", "B" are limited before the formula combines them, so the formula only sees groups in every input\'s top N. Set the limit on the formula instead.',
]);
});
it('stays quiet about limited formula inputs when the list ranks a query', () => {
const data = dataWith(
[A],
[query('A', 10), query('B', 10), formula('F1', 'A / B')],
);
expect(prepareTopListData(data).rows[0].queryName).toBe('A');
expect(getTopListDataWarning(panel, data)).toBeNull();
});
it("lists rows in the query's ascending order for a bottom N", () => {
const data = dataWith(
[
{
queryName: 'A',
rows: [
['checkout', 10],
['auth', 2],
['search', 5],
],
},
],
[
builderQuery({
name: 'A',
order: [
{
key: { name: 'count()' },
direction: Querybuildertypesv5OrderDirectionDTO.asc,
},
],
}),
],
);
expect(prepareTopListData(data).rows.map((row) => row.value)).toStrictEqual([
2, 5, 10,
]);
});
it('warns when the query orders by a group key instead of the value', () => {
const data = dataWith(
[
{
queryName: 'A',
rows: [
['auth', 2],
['checkout', 10],
],
},
],
[
builderQuery({
name: 'A',
groupBy: [{ name: 'service.name' }],
order: [
{
key: { name: 'service.name' },
direction: Querybuildertypesv5OrderDirectionDTO.asc,
},
],
}),
],
);
const { rows } = prepareTopListData(data);
expect(rows.map((row) => row.value)).toStrictEqual([10, 2]);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'The query orders by "service.name", so the list shows the first groups by that key rather than the top values. Order by the value instead.',
]);
});
});
describe('top list value name', () => {
it.each([
{
scenario: 'an alias',
aggregation: { alias: 'requests', expression: 'count()' },
expected: 'requests',
},
{
scenario: 'an expression',
aggregation: { expression: 'p99(duration_nano)' },
expected: 'p99(duration_nano)',
},
{
scenario: 'a metric',
aggregation: {
metricName: 'signoz_calls_total',
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
},
expected: 'sum(signoz_calls_total)',
},
])('names the value after $scenario', ({ aggregation, expected }) => {
expect(
prepareTopListData(dataWith([A], [aggregated(aggregation)])).valueName,
).toBe(expected);
});
it('names a ranked formula after its expression', () => {
const data = dataWith([F1], [query('A'), query('B'), formula('F1', 'A / B')]);
expect(prepareTopListData(data).valueName).toBe('A / B');
});
it('falls back to the query name with nothing to describe it', () => {
expect(prepareTopListData(dataWith([A], [query('A')])).valueName).toBe('A');
});
});
describe('share of total warning', () => {
const sharePanel = topListPanel({
appearance: appearance({ showShare: true }),
});
const shareMessage = (data: PanelQueryData): string | undefined =>
getTopListDataWarning(sharePanel, data)?.messages?.find((message) =>
message.startsWith('Share of total'),
);
it.each([
{
scenario: 'a percentile',
aggregation: { expression: 'p99(duration_nano)' },
},
{ scenario: 'an average', aggregation: { expression: 'avg(duration_nano)' } },
{ scenario: 'a maximum', aggregation: { expression: 'max(duration_nano)' } },
{
scenario: 'a metric averaged across series',
aggregation: {
metricName: 'cpu',
spaceAggregation: MetrictypesSpaceAggregationDTO.avg,
},
},
])('warns when ranking $scenario', ({ aggregation }) => {
expect(shareMessage(dataWith([A], [aggregated(aggregation)]))).toBeDefined();
});
it.each([
{ scenario: 'a count', aggregation: { expression: 'count()' } },
{ scenario: 'a sum', aggregation: { expression: 'sum(bytes)' } },
{
scenario: 'a metric summed across series',
aggregation: {
metricName: 'signoz_calls_total',
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
},
},
])('stays quiet when ranking $scenario', ({ aggregation }) => {
expect(
shareMessage(dataWith([A], [aggregated(aggregation)])),
).toBeUndefined();
});
it('stays quiet for a formula, whose aggregation it cannot tell', () => {
const data = dataWith([F1], [query('A'), query('B'), formula('F1', 'A / B')]);
expect(shareMessage(data)).toBeUndefined();
});
it('stays quiet when the panel does not show shares', () => {
const data = dataWith(
[A],
[aggregated({ expression: 'p99(duration_nano)' })],
);
expect(getTopListDataWarning(panel, data)).toBeNull();
});
});

View File

@@ -1,333 +0,0 @@
import type {
PanelTable,
PanelTableColumn,
} from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { EMPTY_LABEL, prepareTopListRows } from '../prepareData';
const groupColumn = (name: string): PanelTableColumn => ({
name,
id: name,
queryName: 'A',
isValueColumn: false,
});
const valueColumn = (name = 'count()'): PanelTableColumn => ({
name,
id: name,
queryName: 'A',
isValueColumn: true,
});
function serviceTable(
rows: [unknown, unknown][],
overrides: Partial<PanelTable> = {},
): PanelTable {
return {
queryName: 'A',
legend: '',
columns: [groupColumn('service.name'), valueColumn()],
rows: rows.map(([service, value]) => ({
data: { 'service.name': service, 'count()': value },
})),
...overrides,
};
}
const summarize = (table: PanelTable): [string, number | null, number][] =>
prepareTopListRows([table]).rows.map((row) => [
row.label,
row.value,
row.ratio,
]);
describe('prepareTopListRows', () => {
it('ranks rows by value, descending, with bars relative to the largest value', () => {
const table = serviceTable([
['auth', 30],
['payment', 40],
['checkout', 10],
]);
expect(summarize(table)).toStrictEqual([
['payment', 40, 1],
['auth', 30, 0.75],
['checkout', 10, 0.25],
]);
});
it('breaks ties by label so the order is stable across refreshes', () => {
const table = serviceTable([
['search', 5],
['auth', 5],
['checkout', 5],
]);
expect(summarize(table).map(([label]) => label)).toStrictEqual([
'auth',
'checkout',
'search',
]);
});
it('keeps non-numeric values without a bar, sorted last, with the raw cell for display', () => {
const table = serviceTable([
['nan', 'NaN'],
['inf', 'Inf'],
['missing', 'n/a'],
['null', null],
['ok', 7],
]);
const { rows } = prepareTopListRows([table]);
expect(rows.map((row) => [row.label, row.value, row.ratio])).toStrictEqual([
['ok', 7, 1],
['inf', null, 0],
['missing', null, 0],
['nan', null, 0],
['null', null, 0],
]);
expect(rows[1].rawValue).toBe('Inf');
});
it('keeps zero and negative values with an empty bar', () => {
const table = serviceTable([
['down', -4],
['flat', 0],
['up', 8],
]);
expect(summarize(table)).toStrictEqual([
['up', 8, 1],
['flat', 0, 0],
['down', -4, 0],
]);
});
it('shows rows with empty bars when no value is positive', () => {
const table = serviceTable([
['a', 0],
['b', -1],
]);
expect(summarize(table)).toStrictEqual([
['a', 0, 0],
['b', -1, 0],
]);
});
it('gives each numeric row its share of the total', () => {
const table = serviceTable([
['auth', 30],
['payment', 60],
['missing', 'n/a'],
['checkout', 10],
]);
expect(
prepareTopListRows([table]).rows.map((row) => [row.label, row.share]),
).toStrictEqual([
['payment', 0.6],
['auth', 0.3],
['checkout', 0.1],
['missing', null],
]);
});
it.each([
{ scenario: 'any value is negative', values: [8, -4] },
{ scenario: 'the total is zero', values: [0, 0] },
])('gives no shares when $scenario', ({ values }) => {
const table = serviceTable(
values.map((value, index) => [`s${index}`, value]),
);
expect(
prepareTopListRows([table]).rows.map((row) => row.share),
).toStrictEqual([null, null]);
});
it.each([
{ legend: '', expected: 'count()' },
{ legend: '{{service.name}}', expected: 'A' },
])(
'names the value $expected when the legend is "$legend"',
({ legend, expected }) => {
const table = serviceTable([['auth', 1]], {
legend,
columns: [groupColumn('service.name'), valueColumn(legend || 'count()')],
});
expect(prepareTopListRows([table]).valueName).toBe(expected);
},
);
it('parses numeric strings', () => {
const table = serviceTable([
['a', '12'],
['b', ' '],
]);
expect(summarize(table)).toStrictEqual([
['a', 12, 1],
['b', null, 0],
]);
});
it('labels a missing group value as empty for both null (traces/logs) and "" (metrics)', () => {
const table = serviceTable([
[null, 2],
['', 1],
]);
const { rows } = prepareTopListRows([table]);
expect(rows.map((row) => [row.label, row.isEmptyLabel])).toStrictEqual([
[EMPTY_LABEL, true],
[EMPTY_LABEL, true],
]);
expect(new Set(rows.map((row) => row.key)).size).toBe(2);
});
it('joins several group values, marking only the missing ones', () => {
const table: PanelTable = {
queryName: 'A',
legend: '',
columns: [groupColumn('http.route'), groupColumn('region'), valueColumn()],
rows: [
{
data: { 'http.route': 'GET /orders', region: 'us-east-1', 'count()': 3 },
},
{ data: { 'http.route': 'GET /cart', region: null, 'count()': 1 } },
],
};
expect(summarize(table).map(([label]) => label)).toStrictEqual([
'GET /orders · us-east-1',
`GET /cart · ${EMPTY_LABEL}`,
]);
});
it('fills a legend template, rendering a key the row lacks as empty', () => {
const table = serviceTable([['checkout', 1]], {
legend: '{{service.name}} ({{region}})',
});
expect(summarize(table)[0][0]).toBe('checkout ()');
});
it('labels a legend that fills to blank as empty', () => {
const table = serviceTable([['checkout', 1]], { legend: ' {{region}} ' });
const [row] = prepareTopListRows([table]).rows;
expect(row.label).toBe(EMPTY_LABEL);
expect(row.isEmptyLabel).toBe(true);
});
it('keys rows by their group values, so a reordered refetch keeps each key on its row', () => {
const keysByService = (rows: [unknown, unknown][]): Record<string, string> =>
Object.fromEntries(
prepareTopListRows([serviceTable(rows)]).rows.map((row) => [
row.label,
row.key,
]),
);
expect(
keysByService([
['auth', 1],
['payment', 2],
]),
).toStrictEqual(
keysByService([
['payment', 2],
['auth', 1],
]),
);
});
it('keeps rows distinct when a legend without variables gives them all one label', () => {
const table = serviceTable(
[
['a', 2],
['b', 1],
],
{ legend: 'requests' },
);
const { rows } = prepareTopListRows([table]);
expect(rows.map((row) => row.label)).toStrictEqual(['requests', 'requests']);
expect(new Set(rows.map((row) => row.key)).size).toBe(2);
});
it('labels a query without a group-by by its name', () => {
const table: PanelTable = {
queryName: 'A',
legend: '',
columns: [valueColumn()],
rows: [{ data: { 'count()': 42 } }],
};
const data = prepareTopListRows([table]);
expect(data.labelColumnNames).toStrictEqual([]);
expect(data.rows.map((row) => [row.label, row.value])).toStrictEqual([
['A', 42],
]);
});
it('ranks by the first value column and reports the rest as ignored', () => {
const table: PanelTable = {
queryName: 'A',
legend: '',
columns: [groupColumn('host'), valueColumn('p99'), valueColumn('p50')],
rows: [
{ data: { host: 'a', p99: 1, p50: 9 } },
{ data: { host: 'b', p99: 2, p50: 1 } },
],
};
const data = prepareTopListRows([table]);
expect(data.rows.map((row) => [row.label, row.value])).toStrictEqual([
['b', 2],
['a', 1],
]);
expect(data.ignoredValueColumns).toStrictEqual(['p50']);
});
it('carries the query and group values for drilldown filters', () => {
const table = serviceTable([
['checkout', 1],
['', 2],
[null, 3],
]);
const { rows } = prepareTopListRows([table]);
expect(rows.map((row) => [row.queryName, row.labels])).toStrictEqual([
['A', {}],
['A', { 'service.name': '' }],
['A', { 'service.name': 'checkout' }],
]);
});
it('returns no rows when no table has a value column', () => {
expect(prepareTopListRows([])).toStrictEqual({
rows: [],
labelColumnNames: [],
valueColumnName: '',
valueName: '',
ignoredValueColumns: [],
ignoredResults: [],
orderedByGroupKey: null,
});
expect(
prepareTopListRows([
{ queryName: 'A', legend: '', columns: [groupColumn('x')], rows: [] },
]).rows,
).toStrictEqual([]);
});
});

View File

@@ -1,25 +0,0 @@
import type { PanelTable } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { prepareTopListRows } from '../prepareData';
describe('prepareTopListRows with an unlimited SQL result', () => {
it('ranks more rows than a function call can take as arguments', () => {
const count = 200_000;
const table: PanelTable = {
queryName: 'A',
legend: '',
columns: [
{ name: 'host', id: 'host', queryName: 'A', isValueColumn: false },
{ name: 'hits', id: 'hits', queryName: 'A', isValueColumn: true },
],
rows: Array.from({ length: count }, (_, index) => ({
data: { host: `host-${index}`, hits: index + 1 },
})),
};
const { rows } = prepareTopListRows([table]);
expect(rows).toHaveLength(count);
expect(rows[0]).toMatchObject({ label: `host-${count - 1}`, ratio: 1 });
});
});

View File

@@ -1,110 +0,0 @@
import type { TopListRow } from '../../types';
import {
formatShare,
getRowHeight,
getTooltipContent,
truncateMiddle,
} from '../rowDisplay';
// Each case: rows that fit at a density, given a 1px gap and 12px of list padding.
describe('getRowHeight', () => {
it.each([
{ count: 10, height: 10 * 32 + 9 + 12, expected: 32 },
{ count: 10, height: 10 * 32 + 9 + 11, expected: 28 },
{ count: 10, height: 10 * 28 + 9 + 12, expected: 28 },
{ count: 10, height: 10 * 28 + 9 + 11, expected: 24 },
{ count: 200, height: 400, expected: 24 },
])(
'uses $expected px rows for $count rows in $height px',
({ count, height, expected }) => {
expect(getRowHeight(count, height)).toBe(expected);
},
);
it('falls back to the default height before the panel is measured', () => {
expect(getRowHeight(10, 0)).toBe(28);
});
});
describe('formatShare', () => {
it.each([
{ share: 0.5, expected: '50%' },
{ share: 0.12345, expected: '12%' },
{ share: 0.0995, expected: '10%' },
{ share: 0.0456, expected: '4.6%' },
{ share: 0.0004, expected: '<0.1%' },
{ share: 0, expected: '0%' },
{ share: 1, expected: '100%' },
{ share: null, expected: '—' },
])('formats $share as $expected', ({ share, expected }) => {
expect(formatShare(share)).toBe(expected);
});
});
describe('truncateMiddle', () => {
const byLength = (text: string): number => text.length;
it('keeps a label that fits', () => {
expect(truncateMiddle('checkout', 8, byLength)).toBe('checkout');
});
it('keeps both ends of a label that does not', () => {
expect(truncateMiddle('recommendationservice', 9, byLength)).toBe(
'reco…vice',
);
});
it('leaves only the ellipsis when nothing else fits', () => {
expect(truncateMiddle('checkout', 1, byLength)).toBe('…');
});
});
describe('getTooltipContent', () => {
const row = (overrides: Partial<TopListRow> = {}): TopListRow => ({
key: 'A-0',
label: 'checkout',
isEmptyLabel: false,
value: 1500,
rawValue: 1500,
ratio: 1,
share: 0.25,
queryName: 'A',
labels: { 'service.name': 'checkout' },
...overrides,
});
const options = {
valueName: 'p99(duration_nano)',
unit: 'ms',
showShare: true,
};
it('names the value and its share', () => {
expect(getTooltipContent(row(), options).rows).toStrictEqual([
{ key: 'value', label: 'p99(duration_nano)', value: '1.5 s' },
{ key: 'share', label: 'Share of listed total', value: '25%' },
]);
});
it('leaves the share out when the panel hides it or the row has none', () => {
expect(
getTooltipContent(row(), { ...options, showShare: false }).rows,
).toHaveLength(1);
expect(getTooltipContent(row({ share: null }), options).rows).toHaveLength(1);
});
it('lists the group values only when the label is not one already', () => {
expect(getTooltipContent(row(), options).mutedRows).toStrictEqual([]);
expect(
getTooltipContent(
row({
label: 'checkout · eu',
labels: { 'service.name': 'checkout', region: 'eu' },
}),
options,
).mutedRows,
).toStrictEqual([
{ key: 'service.name', label: 'service.name', value: 'checkout' },
{ key: 'region', label: 'region', value: 'eu' },
]);
});
});

View File

@@ -1,95 +0,0 @@
import {
Querybuildertypesv5QueryEnvelopeClickHouseSQLDTOType,
type Querybuildertypesv5ColumnDescriptorDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import {
groupColumn as group,
requestWith,
scalarResponse,
topListPanel,
valueColumn as aggregation,
} from '../../__tests__/fixtures';
import { getTopListDataWarning } from '../warnings';
const panel = topListPanel();
function dataWith(
columns: Querybuildertypesv5ColumnDescriptorDTO[],
rows: unknown[][],
legend = '',
requestPayload?: Querybuildertypesv5QueryRangeRequestDTO,
): PanelQueryData {
return {
response: scalarResponse([{ queryName: 'A', columns, data: rows }]),
requestPayload,
legendMap: legend ? { A: legend } : {},
};
}
describe('getTopListDataWarning', () => {
it('stays quiet for a grouped single-value result', () => {
const data = dataWith(
[group('service.name'), aggregation('__result')],
[
['checkout', 2],
['auth', 1],
],
);
expect(getTopListDataWarning(panel, data)).toBeNull();
});
it('stays quiet when there are no rows', () => {
expect(getTopListDataWarning(panel, dataWith([], []))).toBeNull();
});
it('warns when the query has no group by', () => {
const data = dataWith([aggregation('__result')], [[42]]);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'The query has no group by, so the list shows a single total. Add a group by to rank its groups.',
]);
});
it('names the value columns the ranking ignores', () => {
const data = dataWith(
[
group('host'),
aggregation('p99'),
aggregation('p50', 1),
aggregation('p90', 2),
],
[['a', 1, 2, 3]],
'',
// ClickHouse value columns keep their SQL alias as their name.
requestWith([
{
type: Querybuildertypesv5QueryEnvelopeClickHouseSQLDTOType.clickhouse_sql,
spec: { name: 'A', query: 'SELECT 1' },
},
]),
);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'The list ranks the first value column only; "p50", "p90" are not shown.',
]);
});
it('warns when every row shares one label', () => {
const data = dataWith(
[group('service.name'), aggregation('__result')],
[
['checkout', 2],
['auth', 1],
],
'requests',
);
expect(getTopListDataWarning(panel, data)?.messages).toStrictEqual([
'Every row has the same label. Use {{group-by key}} variables in the legend to tell rows apart.',
]);
});
});

View File

@@ -1,68 +0,0 @@
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import type { PanelOfKind } from '../../../types/rendererProps';
import { resolveDecimalPrecision } from '../../../utils/chartAppearance/resolvers';
import { LABEL_NAME_SEPARATOR, prepareTopListData } from './prepareData';
import type { TopListRow } from '../types';
import { formatRowValue, formatShare } from './rowDisplay';
const RANK_HEADER = 'Rank';
const LABEL_HEADER = 'Label';
const VALUE_HEADER = 'Value';
const SHARE_HEADER = 'Share';
interface CsvColumn {
header: string;
cell: (row: TopListRow, index: number) => string;
}
/** Suffixes repeated headers (`Share`, `Share (2)`) so no column overwrites another. */
function uniqueHeaders(headers: string[]): string[] {
const seen = new Set<string>();
return headers.map((header) => {
let unique = header;
for (let n = 2; seen.has(unique); n += 1) {
unique = `${header} (${n})`;
}
seen.add(unique);
return unique;
});
}
/** The list as shown: rows in ranked order with their rank, label, formatted value and share. */
export function getTopListCsvRows(
panel: PanelOfKind<'signoz/TopListPanel'>,
data: PanelQueryData,
): Record<string, string>[] {
const { formatting, appearance } = panel.spec.plugin.spec;
const { rows, labelColumnNames, valueName } = prepareTopListData(data);
const precision = resolveDecimalPrecision(formatting?.decimalPrecision);
const columns: CsvColumn[] = [
{
header: labelColumnNames.join(LABEL_NAME_SEPARATOR) || LABEL_HEADER,
cell: (row) => row.label,
},
{
header: valueName || VALUE_HEADER,
cell: (row) => formatRowValue(row, formatting?.unit, precision),
},
];
if (appearance?.showRank) {
columns.unshift({
header: RANK_HEADER,
cell: (_, index) => String(index + 1),
});
}
if (appearance?.showShare) {
columns.push({ header: SHARE_HEADER, cell: (row) => formatShare(row.share) });
}
const headers = uniqueHeaders(columns.map(({ header }) => header));
return rows.map((row, index) =>
Object.fromEntries(
columns.map(({ cell }, column) => [headers[column], cell(row, index)]),
),
);
}

View File

@@ -1,216 +0,0 @@
import { prepareScalarTables } from 'pages/DashboardPage/DashboardContainer/queryV5/prepareScalarTables';
import type {
PanelQueryData,
PanelTable,
PanelTableColumn,
PanelTableRow,
} from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import { getScalarResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
import {
describeValue,
getQueryOrder,
getRankedOrder,
type SortDirection,
} from './querySpec';
import type { TopListData, TopListRow } from '../types';
export const EMPTY_LABEL = '(empty)';
const LABEL_SEPARATOR = ' · ';
/** Joins the group-by keys heading the label column. */
export const LABEL_NAME_SEPARATOR = ', ';
const LEGEND_VARIABLE = /\{\{\s*([^}]+?)\s*\}\}/g;
const EMPTY_DATA: TopListData = {
rows: [],
labelColumnNames: [],
valueColumnName: '',
valueName: '',
ignoredValueColumns: [],
ignoredResults: [],
orderedByGroupKey: null,
};
/** A missing group value is `null` for traces/logs and `""` for metrics. */
function isMissing(value: unknown): boolean {
return value == null || value === '';
}
/** Finite numbers only: the server sends NaN/±Inf as "NaN"/"Inf"/"-Inf" and a missing value as "n/a". */
function toFiniteNumber(value: unknown): number | null {
if (typeof value === 'number') {
return Number.isFinite(value) ? value : null;
}
if (typeof value === 'string' && value.trim() !== '') {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
return null;
}
function toGroupValue(value: unknown): string {
return typeof value === 'object'
? JSON.stringify(value)
: String(value as string | number | boolean);
}
function getCell(row: PanelTableRow, column: PanelTableColumn): unknown {
return row.data[column.id || column.name];
}
function resolveLabel(
labelColumns: PanelTableColumn[],
row: PanelTableRow,
labels: Record<string, string>,
table: PanelTable,
): Pick<TopListRow, 'label' | 'isEmptyLabel'> {
if (table.legend) {
// Unlike `getLabelName`, a key the row doesn't carry renders empty, not "undefined".
const label = table.legend.replace(
LEGEND_VARIABLE,
(_, key: string) => labels[key] ?? '',
);
return label.trim()
? { label, isEmptyLabel: false }
: { label: EMPTY_LABEL, isEmptyLabel: true };
}
if (labelColumns.length === 0) {
return { label: table.queryName, isEmptyLabel: false };
}
const parts = labelColumns.map((column) => getCell(row, column));
if (parts.every(isMissing)) {
return { label: EMPTY_LABEL, isEmptyLabel: true };
}
return {
label: parts
.map((part) => (isMissing(part) ? EMPTY_LABEL : toGroupValue(part)))
.join(LABEL_SEPARATOR),
isEmptyLabel: false,
};
}
/** By value in the query's direction; non-numeric values last; ties by label so the order is stable across refreshes. */
function compareRows(direction: SortDirection) {
return (a: TopListRow, b: TopListRow): number => {
if (a.value === null || b.value === null) {
if (a.value === b.value) {
return a.label.localeCompare(b.label);
}
return a.value === null ? 1 : -1;
}
const byValue = direction === 'asc' ? a.value - b.value : b.value - a.value;
return byValue || a.label.localeCompare(b.label);
};
}
/** Tables in builder order; the response lists them in no particular order. */
function orderTables(tables: PanelTable[], queryOrder: string[]): PanelTable[] {
const position = (table: PanelTable): number => {
const index = queryOrder.indexOf(table.queryName);
return index === -1 ? queryOrder.length : index;
};
return [...tables].sort((a, b) => position(a) - position(b));
}
const hasValueColumn = (table: PanelTable): boolean =>
table.columns.some((column) => column.isValueColumn);
/**
* Ranks the first value column of the first table that has one. The server already
* orders and limits, but its order isn't stable on ties, so the rows are sorted again here.
* A query ordered by a group key still lists by value: its rows are the first N groups.
*/
export function prepareTopListRows(
tables: PanelTable[],
direction: SortDirection = 'desc',
): TopListData {
const [table, ...otherTables] = tables.filter(hasValueColumn);
if (!table) {
return EMPTY_DATA;
}
const [valueColumn, ...ignoredColumns] = table.columns.filter(
(column) => column.isValueColumn,
);
const labelColumns = table.columns.filter((column) => !column.isValueColumn);
const keyCounts = new Map<string, number>();
const rows = table.rows.map((row): TopListRow => {
const labels: Record<string, string> = {};
labelColumns.forEach((column) => {
const value = getCell(row, column);
if (value != null) {
labels[column.name] = toGroupValue(value);
}
});
const groupKey = `${table.queryName}-${JSON.stringify(
labelColumns.map((column) => getCell(row, column) ?? null),
)}`;
const repeats = keyCounts.get(groupKey) ?? 0;
keyCounts.set(groupKey, repeats + 1);
const rawValue = getCell(row, valueColumn);
return {
key: repeats ? `${groupKey}-${repeats}` : groupKey,
...resolveLabel(labelColumns, row, labels, table),
value: toFiniteNumber(rawValue),
rawValue,
ratio: 0,
share: null,
queryName: valueColumn.queryName,
labels,
};
});
const values = rows
.map((row) => row.value)
.filter((value): value is number => value !== null);
const max = values.reduce((largest, value) => Math.max(largest, value), 0);
const total = values.some((value) => value < 0)
? 0
: values.reduce((sum, value) => sum + value, 0);
rows.forEach((row) => {
row.ratio =
max > 0 && row.value !== null && row.value > 0 ? row.value / max : 0;
row.share = total > 0 && row.value !== null ? row.value / total : null;
});
return {
rows: rows.sort(compareRows(direction)),
labelColumnNames: labelColumns.map((column) => column.name),
valueColumnName: valueColumn.name,
// A lone aggregation's column takes the legend, which labels rows here, not values.
valueName:
table.legend && valueColumn.name === table.legend
? valueColumn.queryName
: valueColumn.name,
ignoredValueColumns: ignoredColumns.map((column) => column.name),
ignoredResults: otherTables.map((other) => other.queryName),
orderedByGroupKey: null,
};
}
/** Ranks the first enabled query or formula, in builder order, in its order direction. */
export function prepareTopListData(data: PanelQueryData): TopListData {
const tables = prepareScalarTables({
results: getScalarResults(data.response),
legendMap: data.legendMap ?? {},
requestPayload: data.requestPayload,
});
const ordered = orderTables(tables, getQueryOrder(data.requestPayload));
const { direction, groupKey } = getRankedOrder(
data.requestPayload,
ordered.find(hasValueColumn)?.queryName,
);
const prepared = prepareTopListRows(ordered, direction);
const rankedQuery = prepared.rows[0]?.queryName;
// A bare query name ("A") says nothing about the value; the query spec can.
const valueName =
rankedQuery && prepared.valueName === rankedQuery
? (describeValue(data.requestPayload, rankedQuery) ?? rankedQuery)
: prepared.valueName;
return { ...prepared, valueName, orderedByGroupKey: groupKey };
}

View File

@@ -1,138 +0,0 @@
import {
Querybuildertypesv5QueryEnvelopeBuilderAIDTOType,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
type Querybuildertypesv5BuilderQuerySpecDTO,
type Querybuildertypesv5QueryBuilderFormulaDTO,
type Querybuildertypesv5QueryBuilderTraceOperatorDTO,
type Querybuildertypesv5QueryEnvelopeDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
} from 'api/generated/services/sigNoz.schemas';
export type SortDirection = 'asc' | 'desc';
export function findQueryEnvelope(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string | undefined,
): Querybuildertypesv5QueryEnvelopeDTO | undefined {
return requestPayload?.compositeQuery?.queries?.find(
(envelope) => envelope.spec?.name === queryName,
);
}
type RankedSpec =
| Querybuildertypesv5BuilderQuerySpecDTO
| Querybuildertypesv5QueryBuilderFormulaDTO
| Querybuildertypesv5QueryBuilderTraceOperatorDTO;
/** Builder queries, formulas and trace operators; PromQL and ClickHouse SQL have no spec to read. */
function findQuerySpec(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string | undefined,
): RankedSpec | undefined {
const envelope = findQueryEnvelope(requestPayload, queryName);
switch (envelope?.type) {
case Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query:
case Querybuildertypesv5QueryEnvelopeBuilderAIDTOType.builder_ai_query:
case Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula:
case Querybuildertypesv5QueryEnvelopeTraceOperatorDTOType.builder_trace_operator:
return envelope.spec;
default:
return undefined;
}
}
const isMetricSpec = (
spec: RankedSpec,
): spec is Extract<RankedSpec, { signal: MetricSignal }> =>
'signal' in spec && spec.signal === MetricSignal.metrics;
const AGGREGATION_FUNCTION = /^\s*([a-z_]\w*)\s*\(/i;
/**
* The ranked aggregation's function, lowercased: `p99` for `p99(duration_nano)`, the space
* aggregation for a metric. Null for formulas and ClickHouse SQL, which have none to read.
*/
export function getRankedAggregationFunction(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string,
): string | null {
const spec = findQuerySpec(requestPayload, queryName);
if (!spec || !('aggregations' in spec)) {
return null;
}
const name = isMetricSpec(spec)
? spec.aggregations?.[0]?.spaceAggregation
: spec.aggregations?.[0]?.expression?.match(AGGREGATION_FUNCTION)?.[1];
return name ? name.toLowerCase() : null;
}
/** The ranked aggregation as the query writes it: its alias, expression or formula. */
export function describeValue(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string,
): string | null {
const spec = findQuerySpec(requestPayload, queryName);
if (!spec) {
return null;
}
if (isMetricSpec(spec)) {
const [aggregation] = spec.aggregations ?? [];
if (!aggregation?.metricName) {
return null;
}
return aggregation.spaceAggregation
? `${aggregation.spaceAggregation}(${aggregation.metricName})`
: aggregation.metricName;
}
if ('aggregations' in spec) {
const [aggregation] = spec.aggregations ?? [];
if (aggregation?.alias || aggregation?.expression) {
return aggregation.alias || aggregation.expression || null;
}
}
return ('expression' in spec && spec.expression) || null;
}
interface RankedOrder {
direction: SortDirection;
groupKey: string | null;
}
/**
* How the ranked query orders its rows. The server orders by value, descending, when
* no order is set; ordering by a group-by key returns the first N groups by that key.
*/
export function getRankedOrder(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
queryName: string | undefined,
): RankedOrder {
const spec = findQuerySpec(requestPayload, queryName);
const [order] = spec?.order ?? [];
const keyName = order?.key?.name;
if (!keyName) {
return { direction: 'desc', groupKey: null };
}
if (
spec &&
'groupBy' in spec &&
spec.groupBy?.some((key) => key.name === keyName)
) {
return { direction: 'desc', groupKey: keyName };
}
return {
direction: order.direction === 'asc' ? 'asc' : 'desc',
groupKey: null,
};
}
/** The request's queries and formulas, in builder order. */
export function getQueryOrder(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
): string[] {
return (requestPayload?.compositeQuery?.queries ?? [])
.map((envelope) => envelope.spec?.name)
.filter((name): name is string => Boolean(name));
}

View File

@@ -1,207 +0,0 @@
import type { PrecisionOption } from 'components/Graph/types';
import type { TooltipCardRow } from 'lib/uPlotV2/components/Tooltip/components/TooltipCard/TooltipCard';
import type { PanelThreshold } from '../../../types/threshold';
import { resolveActiveThreshold } from '../../../utils/evaluateThresholds';
import { formatPanelValue } from '../../../utils/formatPanelValue';
import {
DEFAULT_ROW_HEIGHT,
LIST_PADDING_Y,
ROW_GAP,
ROW_HEIGHTS,
} from '../constants';
import type { TopListRow } from '../types';
export const ACCENT_COLOR = 'var(--bg-robin-500)';
const NO_VALUE = '—';
export interface RowColors {
barColor?: string;
valueColor?: string;
}
/**
* A matching threshold recolours the bar (`background` format) or the value (`text`).
* Bars no threshold recolours take `barColor`.
*/
export function resolveRowColors(
value: number | null,
thresholds: PanelThreshold[],
unit?: string,
barColor?: string,
): RowColors {
const base = { barColor };
if (value === null || thresholds.length === 0) {
return base;
}
const { threshold } = resolveActiveThreshold(thresholds, value, unit);
if (!threshold) {
return base;
}
return threshold.format === 'background'
? { barColor: threshold.color }
: { ...base, valueColor: threshold.color };
}
/** Non-numeric cells ("NaN", "n/a") are shown as the server sent them. */
export function formatRowValue(
row: TopListRow,
unit?: string,
precision?: PrecisionOption,
): string {
if (row.value !== null) {
return formatPanelValue(row.value, unit, precision);
}
if (typeof row.rawValue === 'string' && row.rawValue !== '') {
return row.rawValue;
}
return NO_VALUE;
}
/** Under 10% to one decimal, whole percents above; a nonzero share never reads as 0%. */
export function formatShare(share: number | null): string {
if (share === null) {
return NO_VALUE;
}
const percent = share * 100;
if (percent > 0 && percent < 0.1) {
return '<0.1%';
}
return `${percent < 10 ? Number(percent.toFixed(1)) : Math.round(percent)}%`;
}
interface TooltipContentOptions {
valueName: string;
unit?: string;
precision?: PrecisionOption;
showShare: boolean;
}
/**
* The value and, when shown, the share; then the group values behind the label, unless
* the label is the lone group value already.
*/
export function getTooltipContent(
row: TopListRow,
{ valueName, unit, precision, showShare }: TooltipContentOptions,
): { rows: TooltipCardRow[]; mutedRows: TooltipCardRow[] } {
const rows: TooltipCardRow[] = [
{
key: 'value',
label: valueName,
value: formatRowValue(row, unit, precision),
},
];
if (showShare && row.share !== null) {
rows.push({
key: 'share',
label: 'Share of listed total',
value: formatShare(row.share),
});
}
const groups = Object.entries(row.labels);
const isLabelTheGroup = groups.length === 1 && groups[0][1] === row.label;
return {
rows,
mutedRows: isLabelTheGroup
? []
: groups.map(([key, value]) => ({ key, label: key, value })),
};
}
const ELLIPSIS = '…';
/**
* Cuts the middle out of `text` so it fits `maxWidth`, keeping both ends: with
* multi-key labels and paths, the tail often tells rows apart.
*/
export function truncateMiddle(
text: string,
maxWidth: number,
measure: (value: string) => number,
): string {
if (measure(text) <= maxWidth) {
return text;
}
const fit = (kept: number): string =>
text.slice(0, Math.ceil(kept / 2)) +
ELLIPSIS +
text.slice(text.length - Math.floor(kept / 2));
let low = 0;
let high = text.length - 1;
while (low < high) {
const mid = Math.ceil((low + high) / 2);
if (measure(fit(mid)) <= maxWidth) {
low = mid;
} else {
high = mid - 1;
}
}
return fit(low);
}
/** The row a navigation key moves focus to, or null when the key isn't one or the move leaves the list. */
export function getNavigationTarget(
index: number,
key: string,
count: number,
): number | null {
const targets: Record<string, number> = {
ArrowDown: index + 1,
ArrowUp: index - 1,
Home: 0,
End: count - 1,
};
const target = targets[key];
return target === undefined || target < 0 || target >= count ? null : target;
}
const longest = (values: string[]): string =>
values.reduce(
(widest, value) => (value.length > widest.length ? value : widest),
'',
);
/**
* The widest formatted value across all rows. The list renders only the rows in view,
* so a hidden row carrying it keeps the value column from resizing as rows scroll in
* and out.
*/
export function getWidestValue(
rows: TopListRow[],
unit?: string,
precision?: PrecisionOption,
): string {
return longest(rows.map((row) => formatRowValue(row, unit, precision)));
}
/** The widest share across all rows, for the same reason as `getWidestValue`. */
export function getWidestShare(rows: TopListRow[]): string {
return longest(rows.map((row) => formatShare(row.share)));
}
/** The roomiest row height at which every row fits; compact when none does. */
export function getRowHeight(count: number, availableHeight: number): number {
if (availableHeight <= 0) {
return DEFAULT_ROW_HEIGHT;
}
const fits = (rowHeight: number): boolean =>
count * rowHeight + Math.max(count - 1, 0) * ROW_GAP + LIST_PADDING_Y <=
availableHeight;
return ROW_HEIGHTS.find(fits) ?? ROW_HEIGHTS[ROW_HEIGHTS.length - 1];
}
/** Grid columns in display order: rank, the bar with its label, share, then value. */
export function getGridColumns(showRank: boolean, showShare: boolean): string {
return [
showRank && 'max-content',
'minmax(0, 1fr)',
showShare && 'max-content',
'max-content',
]
.filter(Boolean)
.join(' ');
}

View File

@@ -1,140 +0,0 @@
import {
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
type Querybuildertypesv5QueryEnvelopeBuilderDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { PanelStatusDetail } from 'pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/types';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import type { PanelOfKind } from '../../../types/rendererProps';
import { prepareTopListData } from './prepareData';
import { findQueryEnvelope, getRankedAggregationFunction } from './querySpec';
import type { TopListData } from '../types';
/** Aggregations whose group values don't add up to a meaningful total. */
const NON_ADDITIVE_FUNCTION = /^(avg|min|max|median|p\d+|quantile)/;
const quoteAll = (names: string[]): string =>
names.map((name) => `"${name}"`).join(', ');
const verbFor = (names: string[]): string =>
names.length === 1 ? 'is' : 'are';
/**
* Builder queries with a limit that the ranked formula reads. Each input is cut to its
* own top N before the formula joins them, so the formula only sees groups that made
* every input's cut.
*/
function getLimitedFormulaInputs(
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
rankedQuery: string,
): string[] {
const ranked = findQueryEnvelope(requestPayload, rankedQuery);
if (
ranked?.type !==
Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula
) {
return [];
}
const expression = ranked.spec?.expression ?? '';
return (requestPayload?.compositeQuery?.queries ?? [])
.filter(
(envelope): envelope is Querybuildertypesv5QueryEnvelopeBuilderDTO =>
envelope.type ===
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
)
.filter((envelope) => (envelope.spec?.limit ?? 0) > 0)
.map((envelope) => envelope.spec?.name)
.filter(
(name): name is string =>
Boolean(name) && new RegExp(`\\b${name}\\b`).test(expression),
);
}
function collectIssues(
{
rows,
labelColumnNames,
ignoredValueColumns,
ignoredResults,
orderedByGroupKey,
}: TopListData,
limitedFormulaInputs: string[],
): string[] {
const issues: string[] = [];
if (ignoredResults.length > 0) {
issues.push(
`The list ranks "${rows[0].queryName}" only; ${quoteAll(ignoredResults)} ${verbFor(ignoredResults)} not shown. Disable the queries you don't want to rank.`,
);
}
if (limitedFormulaInputs.length > 0) {
issues.push(
`${quoteAll(limitedFormulaInputs)} ${verbFor(limitedFormulaInputs)} limited before the formula combines them, so the formula only sees groups in every input's top N. Set the limit on the formula instead.`,
);
}
if (orderedByGroupKey) {
issues.push(
`The query orders by "${orderedByGroupKey}", so the list shows the first groups by that key rather than the top values. Order by the value instead.`,
);
}
if (labelColumnNames.length === 0) {
issues.push(
'The query has no group by, so the list shows a single total. Add a group by to rank its groups.',
);
}
if (ignoredValueColumns.length > 0) {
issues.push(
`The list ranks the first value column only; ${quoteAll(ignoredValueColumns)} ${verbFor(ignoredValueColumns)} not shown.`,
);
}
if (rows.length > 1 && rows.every((row) => row.label === rows[0].label)) {
issues.push(
'Every row has the same label. Use {{group-by key}} variables in the legend to tell rows apart.',
);
}
return issues;
}
/** Share of total sums the rows, which says nothing for averages, percentiles, min or max. */
function getShareIssue(
{ rows, valueName }: TopListData,
requestPayload: Querybuildertypesv5QueryRangeRequestDTO | undefined,
): string | null {
const aggregation = getRankedAggregationFunction(
requestPayload,
rows[0].queryName,
);
if (!aggregation || !NON_ADDITIVE_FUNCTION.test(aggregation)) {
return null;
}
return `Share of total adds up "${valueName}" across rows, which isn't meaningful for averages, percentiles, minimums or maximums. Turn it off in Appearance, or rank a count or sum.`;
}
export function getTopListDataWarning(
panel: PanelOfKind<'signoz/TopListPanel'>,
data: PanelQueryData,
): PanelStatusDetail | null {
const topList = prepareTopListData(data);
if (topList.rows.length === 0) {
return null;
}
const shareIssue = panel.spec.plugin.spec.appearance?.showShare
? getShareIssue(topList, data.requestPayload)
: null;
const issues = [
...collectIssues(
topList,
getLimitedFormulaInputs(data.requestPayload, topList.rows[0].queryName),
),
...(shareIssue ? [shareIssue] : []),
];
if (issues.length === 0) {
return null;
}
return {
message: 'This list may not rank what you expect.',
messages: issues,
};
}

View File

@@ -7,7 +7,6 @@ import { definition as PieChart } from './kinds/PieChartPanel/definition';
import { definition as ScatterPlot } from './kinds/ScatterPlotPanel/definition';
import { definition as TimeSeries } from './kinds/TimeSeriesPanel/definition';
import { definition as GeoMap } from './kinds/GeoMapPanel/definition';
import { definition as TopList } from './kinds/TopListPanel/definition';
import { definition as Table } from './kinds/TablePanel/definition';
import { definition as List } from './kinds/ListPanel/definition';
import { definition as Text } from './kinds/TextPanel/definition';
@@ -30,7 +29,6 @@ export const PANELS: PanelRegistry = {
[PieChart.kind]: PieChart,
[ScatterPlot.kind]: ScatterPlot,
[GeoMap.kind]: GeoMap,
[TopList.kind]: TopList,
[Histogram.kind]: Histogram,
[Heatmap.kind]: Heatmap,
[List.kind]: List,

View File

@@ -37,7 +37,6 @@ export type PanelInteractionMap = Record<PanelKind, object> & {
'signoz/HeatmapPanel': { onDragSelect?: DragSelect };
'signoz/TablePanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/PieChartPanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/TopListPanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/NumberPanel': { onClick?: (event: DrilldownClickPayload) => void };
'signoz/ScatterPlotPanel': {
onClick?: (event: DrilldownClickPayload) => void;

View File

@@ -26,7 +26,6 @@ export const PANEL_KIND_TO_PANEL_TYPE: Record<PanelKind, PANEL_TYPES> = {
'signoz/ListPanel': PANEL_TYPES.LIST,
'signoz/HeatmapPanel': PANEL_TYPES.HEATMAP,
'signoz/GeoMapPanel': PANEL_TYPES.GEO_MAP,
'signoz/TopListPanel': PANEL_TYPES.TOP_LIST,
'signoz/TextPanel': PANEL_TYPES.TEXT,
'signoz/ScatterPlotPanel': PANEL_TYPES.SCATTER,
};

View File

@@ -28,7 +28,6 @@ import type {
DashboardtypesTextPresentationDTO,
DashboardtypesThresholdWithLabelDTO,
DashboardtypesTimePreferenceDTO,
DashboardtypesTopListAppearanceDTO,
TelemetrytypesTelemetryFieldKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { LegendSeriesResolver } from '../utils/legendSeries';
@@ -80,8 +79,6 @@ export enum SectionKind {
ScatterAxes = 'scatterAxes',
/** 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. */
Appearance = 'appearance',
}
/**
@@ -172,7 +169,6 @@ export interface SectionSpecMap {
[SectionKind.Dimensions]: DashboardtypesScatterPlotDimensionsDTO; // spec.plugin.spec.dimensions (Scatter Plot)
[SectionKind.ScatterAxes]: DashboardtypesScatterPlotAxesDTO; // spec.plugin.spec.axes (Scatter Plot)
[SectionKind.Location]: GeoMapPlacementSlice; // spec.plugin.spec.location + .map (Geo Map)
[SectionKind.Appearance]: DashboardtypesTopListAppearanceDTO; // spec.plugin.spec.appearance (Top List)
}
/**
@@ -238,11 +234,6 @@ export interface SectionControls {
// Editor discriminator (not a spec field): which threshold variant a kind edits.
// axis → a `label` threshold picks the axis it marks (Scatter Plot).
[SectionKind.Thresholds]: { variant?: ThresholdVariant; axis?: boolean };
[SectionKind.Appearance]: {
showRank?: boolean;
showShare?: boolean;
barColor?: boolean;
};
}
export type ControlledSectionKind = keyof SectionControls;
@@ -293,7 +284,6 @@ export const SECTION_METADATA = {
[SectionKind.Dimensions]: { title: 'Dimensions', icon: Crosshair },
[SectionKind.ScatterAxes]: { title: 'Axes', icon: Scale3D },
[SectionKind.Location]: { title: 'Location', icon: MapPin },
[SectionKind.Appearance]: { title: 'Appearance', icon: Palette },
} as const satisfies Record<SectionKind, SectionMetadata>;
/**

View File

@@ -13,7 +13,6 @@ import {
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
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 geoMapSections } from '../../kinds/GeoMapPanel/sections';
@@ -343,33 +342,6 @@ describe('buildPluginSpec', () => {
});
});
describe('appearance seed', () => {
const sections: SectionConfig[] = [
{
kind: SectionKind.Appearance,
controls: { showRank: true, showShare: true, barColor: true },
},
];
it('carries the toggles and bar color across a switch between kinds that declare them', () => {
const oldSpec = oldSpecWith({
appearance: { showRank: true, showShare: false, barColor: '#00C853' },
});
expect(buildPluginSpec(sections, { oldSpec }).appearance).toStrictEqual({
barColor: '#00C853',
showRank: true,
showShare: false,
});
});
it('seeds only the default bar color for a new panel, where unset toggles read as off', () => {
expect(buildPluginSpec(sections)).toStrictEqual({
appearance: { barColor: DEFAULT_BAR_COLOR },
});
});
});
describe('chartAppearance seed', () => {
it('seeds only the declared defaulting controls', () => {
const sections: SectionConfig[] = [

View File

@@ -29,7 +29,6 @@ import {
type SectionSpecMap,
ThresholdVariant,
} from '../types/sections';
import { DEFAULT_BAR_COLOR } from '../../PanelEditor/ConfigPane/sections/AppearanceSection/barColorOptions';
import { getTableColumnKeys } from './getTableColumnKeys';
/** Cross-section of the per-kind spec union; assigned to `plugin.spec` (unknown) at the boundary. */
@@ -38,7 +37,6 @@ export interface SeededPluginSpec {
axes?: SectionSpecMap[SectionKind.Axes];
legend?: SectionSpecMap[SectionKind.Legend];
chartAppearance?: SectionSpecMap[SectionKind.ChartAppearance];
appearance?: SectionSpecMap[SectionKind.Appearance];
formatting?: Pick<
PanelFormattingSlice,
'unit' | 'decimalPrecision' | 'columnUnits'
@@ -220,23 +218,6 @@ function seedMapMarks(
}
const SECTION_SEEDS: SectionSeeds = {
[SectionKind.Appearance]: {
specKey: 'appearance',
// Carries the toggles the target kind declares; unset reads as off.
seed: (
controls,
{ oldPluginSpec },
): SectionSpecMap[SectionKind.Appearance] => {
const old = oldPluginSpec?.appearance;
return {
barColor: (controls.barColor && old?.barColor) || DEFAULT_BAR_COLOR,
...(controls.showRank &&
old?.showRank !== undefined && { showRank: old.showRank }),
...(controls.showShare &&
old?.showShare !== undefined && { showShare: old.showShare }),
};
},
},
[SectionKind.TextLayout]: {
specKey: 'presentation',
// Explicit alignment defaults (not the API's implicit ones) so the controls

View File

@@ -53,11 +53,6 @@ const PANEL_TYPE_META: Record<PanelKind, PanelTypeMeta> = {
description: 'Values by country, state or coordinates',
isNew: true,
},
'signoz/TopListPanel': {
group: 'compare',
description: 'Groups ranked by a single value',
isNew: true,
},
'signoz/HistogramPanel': {
group: 'distributions',
description: 'Distribution of values into buckets',

View File

@@ -11,8 +11,6 @@ const AREA_FILL = { fill: 'var(--bg-robin-500)', fillOpacity: 0.22 };
const RING_TRACK = { stroke: 'var(--l3-background)' };
const RING_PRIMARY = { stroke: 'var(--bg-robin-500)' };
const RING_SECONDARY = { stroke: 'var(--bg-robin-400)', strokeOpacity: 0.55 };
const RING_TRACK_FILL = { fill: 'var(--l3-background)' };
const BAR_FILL = { fill: 'var(--bg-robin-500)' };
const DOT_FILL = { fill: 'var(--bg-robin-500)', fillOpacity: 0.55 };
/** `[cx, cy, r]`: a loose up-and-right cloud with one large outlier. */
@@ -58,8 +56,6 @@ const HEATMAP_CELLS = [
[0.4, 0.85, 0.7, 0.2],
[0.3, 0.65, 0.9, 0.45],
];
// 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) => [
{ ...(i === 0 ? HEAD : CELL), width },
]);
@@ -106,30 +102,6 @@ export const PANEL_TYPE_PREVIEWS: Record<PanelKind, JSX.Element> = {
))}
</svg>
),
'signoz/TopListPanel': (
<svg viewBox="0 0 120 44" preserveAspectRatio="none" className={styles.svg}>
{TOP_LIST_BARS.map((width, row) => (
<g key={width}>
<rect
x={0}
y={row * 11 + 2}
width={120}
height={7}
rx={1.5}
style={RING_TRACK_FILL}
/>
<rect
x={0}
y={row * 11 + 2}
width={(width / 100) * 120}
height={7}
rx={1.5}
style={BAR_FILL}
/>
</g>
))}
</svg>
),
'signoz/HistogramPanel': (
<PreviewBars
heights={[14, 26, 52, 88, 100, 70, 40, 20, 10]}

View File

@@ -3,7 +3,6 @@ import logEvent from 'api/common/logEvent';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
import { getTableCsvRows } from 'pages/DashboardPage/DashboardContainer/Panels/kinds/TablePanel/tableCsv';
import { getTopListCsvRows } from 'pages/DashboardPage/DashboardContainer/Panels/kinds/TopListPanel/utils/csv';
import { toPanelType } from 'pages/DashboardPage/DashboardContainer/Panels/types/panelKind';
import type { PanelOfKind } from 'pages/DashboardPage/DashboardContainer/Panels/types/rendererProps';
import { downloadCsv } from 'pages/DashboardPage/DashboardContainer/Panels/utils/downloadCsv';
@@ -16,9 +15,10 @@ interface UseDownloadPanelCsvArgs {
data: PanelQueryData;
/**
* Whether the kind's definition declares CSV as a downloadable format
* (`actions.download.csv`). Only Table, Scatter Plot, Geo Map and Top List carry
* tabular data, so this is the same gate the menu uses — kept here so the callback
* stays a no-op when invoked for a kind that can't produce CSV.
* (`actions.download.csv`). Only kinds drawn from a joined scalar table
* (Table, Scatter Plot, Geo Map) carry tabular data, so this is the same gate the
* menu uses — kept here so the callback stays a no-op when invoked for a kind that
* can't produce CSV.
*/
canDownloadCsv: boolean;
}
@@ -38,15 +38,12 @@ export function useDownloadPanelCsv({
if (!canDownloadCsv) {
return;
}
const rows =
panel.spec.plugin.kind === 'signoz/TopListPanel'
? getTopListCsvRows(panel as PanelOfKind<'signoz/TopListPanel'>, data)
: getTableCsvRows(
panel as PanelOfKind<
'signoz/TablePanel' | 'signoz/ScatterPlotPanel' | 'signoz/GeoMapPanel'
>,
data,
);
const rows = getTableCsvRows(
panel as PanelOfKind<
'signoz/TablePanel' | 'signoz/ScatterPlotPanel' | 'signoz/GeoMapPanel'
>,
data,
);
if (rows.length === 0) {
return;
}

View File

@@ -19,10 +19,7 @@ import {
} from 'api/generated/services/sigNoz.schemas';
import type { PanelQueryCapabilities } from '../Panels/types/panelCapabilities';
import {
isBuilderEnvelope,
isLoneBuilderQuery,
} from 'lib/query/builderEnvelope';
import { isBuilderEnvelope } from 'lib/query/builderEnvelope';
// Narrow view over the envelope spec variants. Orval erases envelope `spec` to `unknown`, so
// shared fields are read through this view with a localized cast at the envelope boundary.
@@ -224,11 +221,13 @@ function withDefaultRowLimit(
envelopes: Querybuildertypesv5QueryEnvelopeDTO[],
limit: number,
): Querybuildertypesv5QueryEnvelopeDTO[] {
if (!isLoneBuilderQuery(envelopes)) {
return envelopes;
}
const [envelope] = envelopes;
if (envelope.spec?.limit) {
if (
envelopes.length !== 1 ||
envelope.type !==
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query ||
envelope.spec?.limit
) {
return envelopes;
}
return [

View File

@@ -108,7 +108,6 @@ export function panelTypeToRequestType(
case PANEL_TYPES.VALUE:
case PANEL_TYPES.SCATTER:
case PANEL_TYPES.GEO_MAP:
case PANEL_TYPES.TOP_LIST:
return Querybuildertypesv5RequestTypeDTO.scalar;
case PANEL_TYPES.LIST:
return Querybuildertypesv5RequestTypeDTO.raw;

View File

@@ -51,7 +51,8 @@ interface QueryRangeV5Body {
/**
* Home detects logs and traces with one `query_range` call each, told apart by
* the signal on the query spec.
* the signal on the query spec. The span-metrics services card queries metrics
* and falls through to its own handler, which follows the data state.
*/
const signalOf = (body: QueryRangeV5Body): string | undefined =>
body.compositeQuery?.queries?.[0]?.spec?.signal;
@@ -129,6 +130,10 @@ export const homeMocks = defineStoryMocks({
rest.post('http://localhost/api/v5/query_range', async (req, res, ctx) => {
const signal = signalOf((await req.json()) as QueryRangeV5Body);
if (signal === 'metrics') {
return undefined;
}
const isActive =
signal === 'traces' ? values.tracesIngestion : values.logsIngestion;
@@ -138,6 +143,11 @@ export const homeMocks = defineStoryMocks({
);
}),
rest.post(
'http://localhost/api/v5/query_range',
response.json(() => spanMetricsResponse()),
),
rest.get('http://localhost/api/v1/user/preferences', (_req, res, ctx) =>
res(
ctx.status(200),
@@ -191,11 +201,6 @@ export const homeMocks = defineStoryMocks({
'http://localhost/api/v1/service/top_level_operations',
response.json(() => topLevelOperationsResponse(values.services)),
),
rest.post(
'http://localhost/api/v4/query_range',
response.json(() => spanMetricsResponse()),
),
],
config: ({ servicesSource }) => ({
appContext: { featureFlags: homeFeatureFlags(servicesSource) },

View File

@@ -23,12 +23,15 @@ import type { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
import { alertRulesFixture } from 'mocks-server/__mockdata__/alert_rules';
import { defaultFeatureFlags } from 'tests/fixtures/appContextMock';
import type { FeatureFlagProps } from 'types/api/features/getFeaturesFlags';
import type { MetricRangePayloadV3 } from 'types/api/metrics/getQueryRange';
import type { ServicesList } from 'types/api/metrics/getService';
import type { UserPreference } from 'types/api/preferences/preference';
import type { MetricRangePayloadV5 } from 'types/api/v5/queryRange';
import { baseUserPreferences } from '@/storybook/msw/__story_mockdata__/appShell';
import { queryRangeV5ScalarResponse } from '@/storybook/msw/__story_mockdata__/queryRange';
import {
queryRangeV5ScalarResponse,
queryRangeV5ScalarTableResponse,
} from '@/storybook/msw/__story_mockdata__/queryRange';
export { queryRangeV5ScalarResponse };
@@ -328,33 +331,11 @@ export const topLevelOperationsResponse = (count: number): ServiceDataProps =>
);
/**
* Span-metrics latency, error rate and ops per second come off a table panel.
* The page reads them from `newResult`, which the table branch of
* `GetMetricQueryRange` never adds, so the columns render as zero however
* complete this body is. That is the app's gap, not the mock's.
* The span-metrics card sends one table query per service; `A` is p99 (ms), `D`
* ops per second and `F1` the error rate.
*/
export const spanMetricsResponse = (): {
status: string;
data: MetricRangePayloadV3['data'];
} => ({
status: 'success',
data: {
resultType: 'table',
result: [
{
queryName: '',
legend: '',
series: null,
list: null,
table: {
columns: [
{ name: 'A', queryName: 'A', isValueColumn: true },
{ name: 'D', queryName: 'D', isValueColumn: true },
{ name: 'F1', queryName: 'F1', isValueColumn: true },
],
rows: [{ data: { A: 148_000_000, D: 12.4, F1: 1.8 } }],
},
},
],
},
});
export const spanMetricsResponse = (): MetricRangePayloadV5 =>
queryRangeV5ScalarTableResponse({
aggregations: ['A', 'D', 'F1'],
rows: [[148, 12.4, 1.8]],
});

View File

@@ -3,8 +3,13 @@
* Do not hand-edit: regenerate instead.
*/
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { FeatureKeys } from 'constants/features';
import { QueryParams } from 'constants/query';
import { rest } from 'msw';
import { createAppContextMock } from 'tests/fixtures/appContextMock';
import type { FeatureFlagProps } from 'types/api/features/getFeaturesFlags';
import { USER_ROLES } from 'types/roles';
import { choiceControl, countControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
@@ -12,18 +17,20 @@ import {
attributeKeysResponse,
attributeValuesResponse,
} from '@/storybook/msw/__story_mockdata__/attributes';
import { queryRangeV3ForRequest } from '@/storybook/msw/__story_mockdata__/queryRange';
import { queryRangeV5ForRequest } from '@/storybook/msw/__story_mockdata__/queryRange';
import {
apDexSettingsResponse,
METRICS_APPLICATION_TABS,
METRICS_LABEL_VALUES,
metricMetaResponse,
SERVICE_MODES,
SERVICE_NAME,
TOP_OPERATION_MAX,
topLevelOperationsResponse,
topOperationsResponse,
type MetricsApplicationTabKey,
type ServiceMode,
} from './__story_mockdata__/metricsApplication';
const VIEW = 'Service · view';
@@ -40,6 +47,17 @@ const RESOURCE_ATTRIBUTE_KEYS = [
const APDEX_THRESHOLD = 0.5;
const { featureFlags: baseFeatureFlags } = createAppContextMock(
USER_ROLES.ADMIN,
);
const featureFlagsFor = (mode: ServiceMode): FeatureFlagProps[] =>
(baseFeatureFlags ?? []).map((flag) =>
flag.name === FeatureKeys.USE_SPAN_METRICS
? { ...flag, active: mode === 'span-metrics' }
: flag,
);
export const metricsApplicationMocks = defineStoryMocks({
controls: {
tab: choiceControl<MetricsApplicationTabKey>('Tab', {
@@ -48,6 +66,13 @@ export const metricsApplicationMocks = defineStoryMocks({
options: METRICS_APPLICATION_TABS,
value: 'OVER_METRICS',
}),
mode: choiceControl<ServiceMode>('Source', {
group: VIEW,
description:
'Where latency and the key operations table read from: traces, or the span metrics the `use_span_metrics` flag switches them to.',
options: SERVICE_MODES,
value: 'traces',
}),
operations: countControl('Key operations', {
group: DATA,
description: 'Rows in the key operations table below the graphs.',
@@ -63,16 +88,22 @@ export const metricsApplicationMocks = defineStoryMocks({
}),
},
handlers: (values, response) => {
const queryRange = response.json(async (req) =>
queryRangeV3ForRequest(await req.json(), {
count: values.series,
labelValues: METRICS_LABEL_VALUES,
}),
);
return [
rest.post('http://localhost/api/v3/query_range', queryRange),
rest.post('http://localhost/api/v4/query_range', queryRange),
rest.post(
'http://localhost/api/v5/query_range',
response.json(async (req) => {
const body = await req.json();
// the only scalar request is the span-metrics key operations table
return queryRangeV5ForRequest(body, {
count:
body.requestType === Querybuildertypesv5RequestTypeDTO.scalar
? values.operations
: values.series,
labelValues: METRICS_LABEL_VALUES,
});
}),
),
rest.post(
'http://localhost/api/v1/service/top_level_operations',
response.json(() => topLevelOperationsResponse(SERVICE_NAME)),
@@ -132,5 +163,6 @@ export const metricsApplicationMocks = defineStoryMocks({
},
config: (values) => ({
route: `/services/${SERVICE_NAME}?${QueryParams.tab}=${values.tab}`,
appContext: { featureFlags: featureFlagsFor(values.mode) },
}),
});

View File

@@ -1,12 +1,12 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import ROUTES from 'constants/routes';
import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import MetricsApplication from '../MetricsApplication';
import { openDownloadMenu } from './__story_mockdata__/metricsApplication.play';
import { metricsApplicationMocks } from './MetricsApplication.stories.mocks';
type MetricsApplicationArgs = PageStoryArgs<typeof metricsApplicationMocks>;
@@ -40,6 +40,14 @@ type Story = StoryObj<MetricsApplicationArgs>;
*/
export const Default: Story = {};
/**
* The overview read from span metrics, which the `use_span_metrics` flag
* switches it to: histogram latency and the metrics key operations table.
*/
export const SpanMetrics: Story = {
args: { mode: 'span-metrics' },
};
/** The database calls the service makes, by system and by upstream. */
export const DatabaseCalls: Story = {
args: { tab: 'DB_CALL_METRICS' },
@@ -65,14 +73,5 @@ export const NoOperations: Story = {
* be taken away in.
*/
export const DownloadMenu: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'download-menu-trigger',
{},
{ timeout: 15000 },
),
);
await screen.findByRole('menu');
},
play: openDownloadMenu,
};

View File

@@ -0,0 +1,23 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, within } from 'storybook/test';
interface PlayContext {
canvasElement: HTMLElement;
}
export const openDownloadMenu = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'download-menu-trigger',
{},
{ timeout: 15000 },
),
);
await screen.findByRole('menu');
};

Some files were not shown because too many files have changed in this diff Show More