Compare commits

..

1 Commits

Author SHA1 Message Date
Ashu Ghildiyal
5887dab7dc fix(alerts): show invalid rule list queries the way the dashboards list does 2026-11-17 17:46:23 +05:30
92 changed files with 357 additions and 4758 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 [

View File

@@ -105,8 +105,3 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.error {
font-size: var(--font-size-xs);
color: var(--danger-foreground);
}

View File

@@ -20,7 +20,7 @@ interface Props {
query: string;
grammar: DslGrammar;
// Ids: `${testIdPrefix}-search-zone`, `-list-search*`, `-filter-zone`,
// `-filter-clear`, `-filter-created-by`, `-filter-updated`, `-query-error`.
// `-filter-clear`, `-filter-created-by`, `-filter-updated`.
testIdPrefix: string;
creatorOptions: CreatorOption[];
source: SuggestionSource;
@@ -35,8 +35,6 @@ interface Props {
hasExtraFilters?: boolean;
// Called by Clear after it empties the query.
onClearAll?: () => void;
// Shown under the search row.
error?: string;
// Wraps the search box and the filter controls (e.g. in an authz tooltip).
wrapControl?: (node: ReactElement) => ReactElement;
onSubmitted?: (hasQuery: boolean) => void;
@@ -65,7 +63,6 @@ function FilterZone({
extraFilters,
hasExtraFilters = false,
onClearAll,
error,
wrapControl = identity,
onSubmitted,
onFilterApplied,
@@ -115,14 +112,6 @@ function FilterZone({
)}
{rightSlot}
</div>
{error && (
<Typography.Text
className={styles.error}
testId={`${testIdPrefix}-query-error`}
>
{error}
</Typography.Text>
)}
<div className={styles.filtersRow}>
<Typography.Text className={styles.filtersLabel}>Filters</Typography.Text>
{wrapControl(

View File

@@ -0,0 +1,49 @@
.wrapper {
display: flex;
flex-direction: column;
height: 320px;
margin-top: 16px;
padding: 105px 141px;
gap: 4px;
justify-content: center;
align-items: flex-start;
border-radius: 6px;
border: 1px dashed var(--l1-border);
}
.img {
max-width: 100%;
}
.text {
font-family: Inter;
font-size: var(--font-size-sm);
font-style: normal;
line-height: 18px;
letter-spacing: -0.07px;
}
.title {
composes: text;
color: var(--l1-foreground);
font-weight: var(--font-weight-medium);
}
.detail {
composes: text;
color: var(--l2-foreground);
font-weight: var(--font-weight-normal);
}
.actionButtons {
display: flex;
gap: 24px;
align-items: center;
margin-top: 20px;
}
.learnMoreArrow {
margin-left: -20px;
color: var(--bg-robin-400);
cursor: pointer;
}

View File

@@ -0,0 +1,64 @@
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { ArrowUpRight } from '@signozhq/icons';
import { handleContactSupport } from 'container/Integrations/utils';
import awwSnapUrl from '@/assets/Icons/awwSnap.svg';
import { formatQueryErrorMessage } from './utils';
import styles from './InvalidQueryState.module.scss';
interface Props {
/** The backend's parse error for the list's DSL filter. */
errorMessage?: string;
isCloudUser: boolean;
testIdPrefix: string;
/** Runs before support opens, for analytics. */
onContactSupport?: () => void;
}
const INVALID_QUERY_FALLBACK = 'Please review the syntax and try again.';
function InvalidQueryState({
errorMessage,
isCloudUser,
testIdPrefix,
onContactSupport,
}: Props): JSX.Element {
const handleContactSupportClick = (): void => {
onContactSupport?.();
handleContactSupport(isCloudUser);
};
return (
<div className={styles.wrapper} data-testid={`${testIdPrefix}-invalid-query`}>
<img src={awwSnapUrl} alt="something went wrong" className={styles.img} />
<Typography.Text
className={styles.title}
data-testid={`${testIdPrefix}-invalid-query-title`}
>
Invalid query
</Typography.Text>
<Typography.Text
className={styles.detail}
data-testid={`${testIdPrefix}-invalid-query-detail`}
>
{formatQueryErrorMessage(errorMessage) || INVALID_QUERY_FALLBACK}
</Typography.Text>
<section className={styles.actionButtons}>
<Button
size="md"
variant="link"
color="primary"
onClick={handleContactSupportClick}
testId={`${testIdPrefix}-contact-support`}
>
Contact Support
</Button>
<ArrowUpRight size={16} className={styles.learnMoreArrow} />
</section>
</div>
);
}
export default InvalidQueryState;

View File

@@ -0,0 +1,53 @@
import { handleContactSupport } from 'container/Integrations/utils';
import { render, screen, userEvent } from 'tests/test-utils';
import InvalidQueryState from '../InvalidQueryState';
jest.mock('container/Integrations/utils', () => ({
handleContactSupport: jest.fn(),
}));
describe('InvalidQueryState', () => {
it('shows the backend message without its prefix and with quoted hints', () => {
render(
<InvalidQueryState
errorMessage="invalid filter query: unknown field `nme`"
isCloudUser={false}
testIdPrefix="list"
/>,
);
expect(screen.getByTestId('list-invalid-query-title')).toHaveTextContent(
'Invalid query',
);
expect(screen.getByTestId('list-invalid-query-detail')).toHaveTextContent(
/^unknown field "nme"$/,
);
});
it('falls back to a syntax hint without a message', () => {
render(<InvalidQueryState isCloudUser={false} testIdPrefix="list" />);
expect(screen.getByTestId('list-invalid-query-detail')).toHaveTextContent(
'Please review the syntax and try again.',
);
});
it('runs the callback, then opens support', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onContactSupport = jest.fn();
render(
<InvalidQueryState
errorMessage="bad"
isCloudUser
testIdPrefix="list"
onContactSupport={onContactSupport}
/>,
);
await user.click(screen.getByTestId('list-contact-support'));
expect(onContactSupport).toHaveBeenCalledTimes(1);
expect(jest.mocked(handleContactSupport)).toHaveBeenCalledWith(true);
});
});

View File

@@ -0,0 +1,13 @@
// Normalize BE query-parse error messages for display:
// - Drop the "invalid filter query:" prefix (the UI already says "Invalid query").
// - Backticks → double quotes for the format hint that follows the em-dash.
// - Trim surrounding whitespace.
export const formatQueryErrorMessage = (raw: string | undefined): string => {
if (!raw) {
return '';
}
return raw
.replace(/^invalid filter query:\s*/i, '')
.replace(/`([^`]+)`/g, '"$1"')
.trim();
};

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

@@ -194,7 +194,7 @@ describe('ListAlertRules — search', () => {
});
it.each(['rule_list_filter_invalid', 'rule_list_invalid'])(
'shows the backend message and no-results state for %s',
'shows the invalid query state with the backend message for %s',
async (code) => {
const user = userEvent.setup({ delay: null });
server.use(
@@ -219,12 +219,11 @@ describe('ListAlertRules — search', () => {
await runSearchQuery(user, "nme = 'x'");
await expect(
screen.findByTestId('alert-rules-query-error'),
screen.findByTestId('alert-rules-invalid-query-detail'),
).resolves.toHaveTextContent('unknown field "nme"');
const empty = screen.getByTestId('no-results-empty-state');
expect(within(empty).getByTestId('no-results-subtitle')).toHaveTextContent(
'The filter query is invalid. Fix it or clear the search.',
);
expect(
screen.queryByTestId('no-results-empty-state'),
).not.toBeInTheDocument();
expect(screen.queryByTestId('error-empty-state')).not.toBeInTheDocument();
expect(screen.queryByText('High CPU Alert')).not.toBeInTheDocument();
},

View File

@@ -10,7 +10,6 @@ interface Props {
states: string[];
creatorOptions: CreatorOption[];
source: SuggestionSource;
error: string | null;
onQueryChange: (query: string) => void;
onStatesChange: (states: string[]) => void;
}
@@ -20,7 +19,6 @@ function AlertRulesFilterZone({
states,
creatorOptions,
source,
error,
onQueryChange,
onStatesChange,
}: Props): JSX.Element {
@@ -36,7 +34,6 @@ function AlertRulesFilterZone({
extraFilters={<RuleStatesFilter states={states} onChange={onStatesChange} />}
hasExtraFilters={states.length > 0}
onClearAll={(): void => onStatesChange([])}
error={error ?? undefined}
/>
);
}

View File

@@ -1,6 +1,7 @@
import { useCallback, useMemo } from 'react';
import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
import NoResultsEmptyState from 'components/Alerts/NoResultsEmptyState';
import InvalidQueryState from 'components/ListFilter/InvalidQueryState/InvalidQueryState';
import ListCommandHeader from 'components/ListViews/ListCommandHeader/ListCommandHeader';
import ListStatusBar from 'components/ListViews/ListStatusBar/ListStatusBar';
import ViewsRail from 'components/ListViews/ViewsRail/ViewsRail';
@@ -8,6 +9,7 @@ import TanStackTable from 'components/TanStackTableView';
import { useCalculatedPageSize } from 'components/TanStackTableView/useCalculatedPageSize';
import { useTableParams } from 'components/TanStackTableView/useTableParams';
import useComponentPermission from 'hooks/useComponentPermission';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useAppContext } from 'providers/App/App';
import { useTimezone } from 'providers/Timezone';
@@ -38,6 +40,7 @@ const DEFAULT_LIMIT = 10;
function ListAlertRules(): JSX.Element {
const { user } = useAppContext();
const { isCloudUser } = useGetTenantLicense();
const [addNewAlert, action] = useComponentPermission(
['add_new_alert', 'action'],
user.role,
@@ -199,7 +202,6 @@ function ListAlertRules(): JSX.Element {
states={filter.states}
creatorOptions={creatorOptions}
source={source}
error={queryError}
onQueryChange={submitQuery}
onStatesChange={changeStates}
/>
@@ -209,14 +211,16 @@ function ListAlertRules(): JSX.Element {
<div ref={containerRef} className={styles.tableContainer}>
{isError ? (
<ErrorEmptyState title="Failed to load alert rules" onRefresh={refetch} />
) : isEmptyDueToFilters && queryError ? (
<InvalidQueryState
errorMessage={queryError}
isCloudUser={!!isCloudUser}
testIdPrefix="alert-rules"
/>
) : isEmptyDueToFilters ? (
<NoResultsEmptyState
title="No matching alert rules"
subtitle={
queryError
? 'The filter query is invalid. Fix it or clear the search.'
: 'No alert rules match your search. Try adjusting your search criteria.'
}
subtitle="No alert rules match your search. Try adjusting your search criteria."
onClear={handleClearFilters}
clearButtonText="Clear Search"
/>

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

@@ -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

@@ -139,7 +139,7 @@ export const alertRulesMocks = defineStoryMocks({
invalidQuery: choiceControl<InvalidQueryChoice>('Invalid query', {
group: LIST,
description:
'The 400 code any request carrying a `query` answers with. Both show the server message under the search box.',
'The 400 code any request carrying a `query` answers with. Both replace the list with the Invalid query state and the server message.',
options: INVALID_QUERY_CHOICES,
value: 'off',
}),

View File

@@ -64,7 +64,7 @@ export const NoMatchingRules: Story = {
},
};
/** The query the list was asked for does not parse: the server's message sits under the search box. */
/** The query the list was asked for does not parse: the Invalid query state, with the server's message, replaces the list. */
export const InvalidQuery: Story = {
args: { invalidQuery: 'rule_list_filter_invalid' },
parameters: {

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

@@ -14,12 +14,6 @@
font-weight: var(--font-weight-medium);
}
.errorDetail {
composes: bodyText from '../states.module.scss';
color: var(--l2-foreground);
font-weight: var(--font-weight-normal);
}
.actionButtons {
display: flex;
gap: 24px;

View File

@@ -2,12 +2,12 @@ import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { ArrowUpRight, RotateCw } from '@signozhq/icons';
import logEvent from 'api/common/logEvent';
import InvalidQueryState from 'components/ListFilter/InvalidQueryState/InvalidQueryState';
import { handleContactSupport } from 'container/Integrations/utils';
import { DashboardListEvents } from 'pages/DashboardsListPage/constants/events';
import awwSnapUrl from '@/assets/Icons/awwSnap.svg';
import { formatQueryErrorMessage } from '../../../utils/helpers';
import styles from './ErrorState.module.scss';
interface Props {
@@ -19,7 +19,6 @@ interface Props {
const GENERIC_MESSAGE =
'Something went wrong :/ Please retry or contact support.';
const INVALID_QUERY_FALLBACK = 'Please review the syntax and try again.';
function ErrorState({
isCloudUser,
@@ -32,8 +31,6 @@ function ErrorState({
const isClientError =
httpStatus !== undefined && httpStatus >= 400 && httpStatus < 500;
const cleanedDetail = formatQueryErrorMessage(errorMessage);
const handleRetry = (): void => {
void logEvent(DashboardListEvents.ErrorStateAction, {
action: 'retry',
@@ -41,45 +38,47 @@ function ErrorState({
onRetry();
};
const handleContactSupportClick = (): void => {
const logContactSupport = (): void => {
void logEvent(DashboardListEvents.ErrorStateAction, {
action: 'contactSupport',
});
};
const handleContactSupportClick = (): void => {
logContactSupport();
handleContactSupport(isCloudUser);
};
if (isClientError) {
return (
<InvalidQueryState
errorMessage={errorMessage}
isCloudUser={isCloudUser}
testIdPrefix="dashboards-list"
onContactSupport={logContactSupport}
/>
);
}
return (
<div className={styles.wrapper}>
<img src={awwSnapUrl} alt="something went wrong" className={styles.img} />
{isClientError ? (
<>
<Typography.Text className={styles.errorText}>
Invalid query
</Typography.Text>
<Typography.Text className={styles.errorDetail}>
{cleanedDetail || INVALID_QUERY_FALLBACK}
</Typography.Text>
</>
) : (
<Typography.Text className={styles.errorText}>
{GENERIC_MESSAGE}
</Typography.Text>
)}
<Typography.Text className={styles.errorText}>
{GENERIC_MESSAGE}
</Typography.Text>
<section className={styles.actionButtons}>
{!isClientError && (
<Button
size="md"
variant="outlined"
color="secondary"
prefix={<RotateCw size={16} />}
onClick={handleRetry}
testId="dashboards-list-retry"
>
Retry
</Button>
)}
<Button
size="md"
variant="outlined"
color="secondary"
prefix={<RotateCw size={16} />}
onClick={handleRetry}
testId="dashboards-list-retry"
>
Retry
</Button>
<Button
size="md"
variant="link"

View File

@@ -58,17 +58,3 @@ export const lastUpdatedLabel = (time: string | undefined): string => {
const seconds = diff.diff(ref, 'seconds');
return `Last Updated ${seconds} sec ago`;
};
// Normalize BE query-parse error messages for display:
// - Drop the "invalid filter query:" prefix (the UI already says "Invalid query").
// - Backticks → double quotes for the format hint that follows the em-dash.
// - Trim surrounding whitespace.
export const formatQueryErrorMessage = (raw: string | undefined): string => {
if (!raw) {
return '';
}
return raw
.replace(/^invalid filter query:\s*/i, '')
.replace(/`([^`]+)`/g, '"$1"')
.trim();
};

View File

@@ -78,7 +78,6 @@ export const panelTypeToExplorerView: Record<PANEL_TYPES, ExplorerViews> = {
[PANEL_TYPES.HISTOGRAM]: ExplorerViews.TIMESERIES,
[PANEL_TYPES.HEATMAP]: ExplorerViews.TIMESERIES,
[PANEL_TYPES.GEO_MAP]: ExplorerViews.TABLE,
[PANEL_TYPES.TOP_LIST]: ExplorerViews.TABLE,
// Dashboard-only visualisation; explorers never offer it.
[PANEL_TYPES.TEXT]: ExplorerViews.LIST,
[PANEL_TYPES.SCATTER]: ExplorerViews.TABLE,

View File

@@ -151,13 +151,7 @@ func (provider *provider) addServiceAccountRoutes(router *mux.Router) error {
ErrorStatusCodes: []int{http.StatusNotFound},
Deprecated: false,
SecuritySchemes: nil,
}, handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceServiceAccount,
Verb: coretypes.VerbUpdate,
Category: coretypes.ActionCategoryAccessControl,
ID: provider.claimServiceAccountIDExtractor(),
Selector: coretypes.IDSelector,
}))).Methods(http.MethodPut).GetError(); err != nil {
})).Methods(http.MethodPut).GetError(); err != nil {
return err
}
@@ -500,18 +494,3 @@ func (provider *provider) serviceAccountIDExtractor() coretypes.ResourceIDExtrac
return serviceAccountRole.ServiceAccountID.String(), nil
})
}
func (provider *provider) claimServiceAccountIDExtractor() coretypes.ResourceIDExtractor {
return coretypes.NewResourceIDExtractor(coretypes.PhaseRequest, func(ec coretypes.ExtractorContext) (string, error) {
if ec.Request == nil {
return "", nil
}
claims, err := authtypes.ClaimsFromContext(ec.Request.Context())
if err != nil {
return "", err
}
return claims.ServiceAccountID, nil
})
}

View File

@@ -75,7 +75,7 @@ func newConfig() factory.Config {
Interval: 1 * time.Hour, // 1 hour
},
Token: TokenConfig{
MaxPerUser: 20,
MaxPerUser: 5,
},
},
JWT: JWTConfig{

View File

@@ -26,7 +26,7 @@ var (
)
const (
expectedLastObservedAtCacheEntries int64 = 20000 // 1000 users * Max 20 tokens per user
expectedLastObservedAtCacheEntries int64 = 5000 // 1000 users * Max 5 tokens per user
)
type provider struct {

View File

@@ -2245,96 +2245,6 @@ func TestNumberPanelDefaults(t *testing.T) {
assert.Contains(t, outputStr, `"operator":"above"`, "expected stored/response JSON to contain operator:above")
}
func TestTopListPanelSpec(t *testing.T) {
testCases := []struct {
name string
spec string
wantErr bool
wantAppearance TopListAppearance
}{
{
name: "AllFields_RoundTrip",
spec: `{
"formatting": {"unit": "ms", "decimalPrecision": 2},
"appearance": {"showRank": true, "showShare": true, "barColor": "#E5484D"},
"thresholds": [{"value": 500, "operator": "above", "format": "background", "color": "Red"}]
}`,
wantAppearance: TopListAppearance{ShowRank: true, ShowShare: true, BarColor: "#E5484D"},
},
{
name: "MissingBarColor_Defaulted",
spec: `{
"formatting": {"unit": "s", "decimalPrecision": 1},
"appearance": {"showRank": true},
"thresholds": [{"value": 5, "operator": "below", "format": "text", "color": "Green"}]
}`,
wantAppearance: TopListAppearance{ShowRank: true, BarColor: DefaultTopListBarColor},
},
{
name: "MissingAppearance_Defaulted",
spec: `{"formatting": {"unit": "ms", "decimalPrecision": 0}}`,
wantAppearance: TopListAppearance{BarColor: DefaultTopListBarColor},
},
{
name: "InvalidBarColor_Rejected",
spec: `{"appearance": {"barColor": "blue"}}`,
wantErr: true,
},
{
name: "EmptyBarColor_Rejected",
spec: `{"appearance": {"barColor": ""}}`,
wantErr: true,
},
{
name: "UnknownField_Rejected",
spec: `{"legend": {}}`,
wantErr: true,
},
{
name: "UnknownAppearanceField_Rejected",
spec: `{"appearance": {"showPoints": true}}`,
wantErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
d, err := unmarshalDashboard([]byte(`{
"variables": [],
"panels": {
"p1": {
"kind": "Panel",
"spec": {
"links": [],
"plugin": {"kind": "signoz/TopListPanel", "spec": ` + testCase.spec + `},
"queries": [{"kind": "scalar", "spec": {"plugin": {"kind": "signoz/ClickHouseSQL", "spec": {"name": "A", "query": "SELECT 1"}}}}]
}
}
},
"links": [],
"layouts": []
}`))
if testCase.wantErr {
assert.Error(t, err)
return
}
require.NoError(t, err, "unmarshal and validate failed")
require.IsType(t, &TopListPanelSpec{}, d.Panels["p1"].Spec.Plugin.Spec)
spec := d.Panels["p1"].Spec.Plugin.Spec.(*TopListPanelSpec)
output, err := json.Marshal(d)
require.NoError(t, err, "marshal dashboard failed")
roundTripped, err := unmarshalDashboard(output)
require.NoError(t, err, "round trip failed")
require.IsType(t, &TopListPanelSpec{}, roundTripped.Panels["p1"].Spec.Plugin.Spec)
roundTrippedSpec := roundTripped.Panels["p1"].Spec.Plugin.Spec.(*TopListPanelSpec)
assert.Equal(t, spec.Formatting, roundTrippedSpec.Formatting)
assert.Equal(t, spec.Thresholds, roundTrippedSpec.Thresholds)
assert.Equal(t, testCase.wantAppearance, roundTrippedSpec.Appearance)
})
}
}
func geoMapDashboard(spec, queryPlugin string) []byte {
return []byte(`{
"variables": [],
@@ -2824,7 +2734,7 @@ func TestPanelTypeQueryTypeCompatibility(t *testing.T) {
switch panelKind {
case "signoz/ListPanel":
return "raw"
case "signoz/TablePanel", "signoz/NumberPanel", "signoz/PieChartPanel", "signoz/HistogramPanel", "signoz/ScatterPlotPanel", "signoz/GeoMapPanel", "signoz/TopListPanel":
case "signoz/TablePanel", "signoz/NumberPanel", "signoz/PieChartPanel", "signoz/HistogramPanel", "signoz/ScatterPlotPanel", "signoz/GeoMapPanel":
return "scalar"
default:
return "time_series"
@@ -2889,13 +2799,6 @@ func TestPanelTypeQueryTypeCompatibility(t *testing.T) {
{"GeoMap+Composite(trace_operator)", mkComposite("signoz/GeoMapPanel", "builder_trace_operator", `{"name":"T1","expression":"A => B"}`), true},
{"GeoMap+Composite(formula)", mkComposite("signoz/GeoMapPanel", "builder_formula", `{"name":"F1","expression":"A+B"}`), false},
{"GeoMap+Composite(promql)", mkComposite("signoz/GeoMapPanel", "promql", `{"name":"A","query":"up"}`), true},
{"TopList+ClickHouse", mkQuery("signoz/TopListPanel", "signoz/ClickHouseSQL", `{"name":"A","query":"SELECT 1"}`), false},
{"TopList+PromQL", mkQuery("signoz/TopListPanel", "signoz/PromQLQuery", `{"name":"A","query":"up"}`), true},
{"TopList+Formula", mkQuery("signoz/TopListPanel", "signoz/Formula", `{"name":"F1","expression":"A+B"}`), false},
{"TopList+TraceOperator", mkQuery("signoz/TopListPanel", "signoz/TraceOperator", `{"name":"T1","expression":"A => B"}`), false},
{"TopList+Composite(clickhouse)", mkComposite("signoz/TopListPanel", "clickhouse_sql", `{"name":"A","query":"SELECT 1"}`), false},
{"TopList+Composite(formula)", mkComposite("signoz/TopListPanel", "builder_formula", `{"name":"F1","expression":"A+B"}`), false},
{"TopList+Composite(promql)", mkComposite("signoz/TopListPanel", "promql", `{"name":"A","query":"up"}`), true},
}
for _, tc := range cases {

View File

@@ -40,7 +40,6 @@ func (PanelPlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
string(PanelKindHeatmap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec"),
string(PanelKindScatterPlot): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec"),
string(PanelKindGeoMap): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec"),
string(PanelKindTopList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTopListPanelSpec"),
})
}
@@ -76,7 +75,6 @@ func (PanelPlugin) JSONSchemaOneOf() []any {
PanelPluginVariant[HeatmapPanelSpec]{Kind: string(PanelKindHeatmap)},
PanelPluginVariant[ScatterPlotPanelSpec]{Kind: string(PanelKindScatterPlot)},
PanelPluginVariant[GeoMapPanelSpec]{Kind: string(PanelKindGeoMap)},
PanelPluginVariant[TopListPanelSpec]{Kind: string(PanelKindTopList)},
}
}
@@ -252,7 +250,6 @@ var (
PanelKindHeatmap: func() any { return new(HeatmapPanelSpec) },
PanelKindScatterPlot: func() any { return new(ScatterPlotPanelSpec) },
PanelKindGeoMap: func() any { return new(GeoMapPanelSpec) },
PanelKindTopList: func() any { return new(TopListPanelSpec) },
}
queryPluginSpecs = map[QueryPluginKind]func() any{
QueryKindBuilder: func() any { return new(BuilderQuerySpec) },
@@ -281,7 +278,6 @@ var (
PanelKindHeatmap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindPromQL, QueryKindClickHouseSQL},
PanelKindScatterPlot: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindGeoMap: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindClickHouseSQL},
PanelKindTopList: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
}
)

View File

@@ -146,14 +146,13 @@ func redactLeafQuery(spec any) any {
case qb.ClickHouseQuery:
return qb.ClickHouseQuery{Name: s.Name, Legend: s.Legend}
case qb.QueryBuilderFormula:
return qb.QueryBuilderFormula{Name: s.Name, Expression: s.Expression, Order: s.Order, Legend: s.Legend}
return qb.QueryBuilderFormula{Name: s.Name, Expression: s.Expression, Legend: s.Legend}
case qb.QueryBuilderTraceOperator:
return qb.QueryBuilderTraceOperator{
Name: s.Name,
Expression: s.Expression,
Aggregations: s.Aggregations,
GroupBy: s.GroupBy,
Order: s.Order,
Legend: s.Legend,
}
}
@@ -167,7 +166,6 @@ func redactBuilderQuery[T any](q qb.QueryBuilderQuery[T]) qb.QueryBuilderQuery[T
Source: q.Source,
Aggregations: q.Aggregations,
GroupBy: q.GroupBy,
Order: q.Order,
Legend: q.Legend,
}
}

View File

@@ -12,7 +12,7 @@ import (
)
func TestRedactLeafQuery(t *testing.T) {
t.Run("builder query drops filter, having, limit and keeps display fields and order", func(t *testing.T) {
t.Run("builder query drops filter, having, limit and keeps display fields", func(t *testing.T) {
input := qb.QueryBuilderQuery[qb.MetricAggregation]{
Name: "A",
Signal: telemetrytypes.SignalMetrics,
@@ -24,7 +24,6 @@ func TestRedactLeafQuery(t *testing.T) {
Filter: &qb.Filter{Expression: "service.name = 'checkout'"},
Having: &qb.Having{},
Limit: 100,
Order: []qb.OrderBy{{Direction: qb.OrderDirectionAsc}},
}
redacted, ok := redactLeafQuery(input).(qb.QueryBuilderQuery[qb.MetricAggregation])
@@ -44,7 +43,6 @@ func TestRedactLeafQuery(t *testing.T) {
require.Len(t, redacted.Aggregations, 1)
assert.Equal(t, "system_cpu_usage", redacted.Aggregations[0].MetricName)
assert.Len(t, redacted.GroupBy, 1)
assert.Equal(t, input.Order, redacted.Order)
})
t.Run("promql query drops the raw query, step and disabled", func(t *testing.T) {
@@ -77,15 +75,13 @@ func TestRedactLeafQuery(t *testing.T) {
assert.Equal(t, "logs", redacted.Legend)
})
t.Run("formula keeps its expression and order but drops limit and having", func(t *testing.T) {
order := []qb.OrderBy{{Direction: qb.OrderDirectionAsc}}
t.Run("formula keeps its expression but drops limit and having", func(t *testing.T) {
redacted, ok := redactLeafQuery(qb.QueryBuilderFormula{
Name: "F1",
Expression: "A / B",
Legend: "ratio",
Limit: 50,
Having: &qb.Having{},
Order: order,
}).(qb.QueryBuilderFormula)
require.True(t, ok)
@@ -94,7 +90,6 @@ func TestRedactLeafQuery(t *testing.T) {
assert.Equal(t, "ratio", redacted.Legend)
assert.Zero(t, redacted.Limit)
assert.Nil(t, redacted.Having)
assert.Equal(t, order, redacted.Order)
})
t.Run("trace operator drops filter but keeps expression and aggregations", func(t *testing.T) {

View File

@@ -4,7 +4,6 @@ import (
"bytes"
"encoding/json"
"maps"
"regexp"
"slices"
"strconv"
@@ -202,11 +201,10 @@ const (
PanelKindHeatmap PanelPluginKind = "signoz/HeatmapPanel"
PanelKindScatterPlot PanelPluginKind = "signoz/ScatterPlotPanel"
PanelKindGeoMap PanelPluginKind = "signoz/GeoMapPanel"
PanelKindTopList PanelPluginKind = "signoz/TopListPanel"
)
func (PanelPluginKind) Enum() []any {
return []any{PanelKindTimeSeries, PanelKindBarChart, PanelKindAreaChart, PanelKindNumber, PanelKindPieChart, PanelKindTable, PanelKindHistogram, PanelKindList, PanelKindText, PanelKindHeatmap, PanelKindScatterPlot, PanelKindGeoMap, PanelKindTopList}
return []any{PanelKindTimeSeries, PanelKindBarChart, PanelKindAreaChart, PanelKindNumber, PanelKindPieChart, PanelKindTable, PanelKindHistogram, PanelKindList, PanelKindText, PanelKindHeatmap, PanelKindScatterPlot, PanelKindGeoMap}
}
func (k PanelPluginKind) rendersWithoutQuery() bool {
@@ -278,49 +276,6 @@ type PieChartPanelSpec struct {
Legend Legend `json:"legend" description:"Legend placement and slice colors."`
}
type TopListPanelSpec struct {
Visualization BasicVisualization `json:"visualization" description:"The time range the rows are computed over."`
Formatting PanelFormatting `json:"formatting" description:"Unit and decimal precision of the values."`
Appearance TopListAppearance `json:"appearance" description:"Rank, share and bar color options."`
Thresholds []ComparisonThreshold `json:"thresholds" validate:"dive" description:"Rules that recolor a row when its value compares to a threshold as specified."`
}
type TopListAppearance struct {
ShowRank bool `json:"showRank" description:"Numbers each row by its position in the list."`
ShowShare bool `json:"showShare" description:"Shows each row's share of the listed rows' total."`
BarColor TopListBarColor `json:"barColor" required:"true" description:"Hex color of every bar; a matching background threshold overrides it."`
}
type TopListBarColor string
const DefaultTopListBarColor TopListBarColor = "#4E74F8"
// Same forms as go-playground/validator's hexcolor: #RGB, #RGBA, #RRGGBB, #RRGGBBAA.
var hexColorRegex = regexp.MustCompile(`^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$`)
func (c TopListBarColor) ValueOrDefault() string {
if c == "" {
return string(DefaultTopListBarColor)
}
return string(c)
}
func (c TopListBarColor) MarshalJSON() ([]byte, error) {
return json.Marshal(c.ValueOrDefault())
}
func (c *TopListBarColor) UnmarshalJSON(data []byte) error {
var v string
if err := json.Unmarshal(data, &v); err != nil {
return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid barColor: must be a hex color string")
}
if !hexColorRegex.MatchString(v) {
return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "invalid barColor %q: must be a hex color such as #4E74F8", v)
}
*c = TopListBarColor(v)
return nil
}
type TablePanelSpec struct {
Visualization BasicVisualization `json:"visualization" description:"The time range the rows are computed over."`
Formatting TableFormatting `json:"formatting" description:"Per-column units and decimal precision."`

View File

@@ -768,12 +768,9 @@ def cleanup_notification_channels(
def create_webhook_notification_channel(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
notification_channel: types.TestContainerDocker,
get_token: Callable[[str, str], str],
) -> Callable[[str, str, dict, bool], str]:
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
# The ruler drops alerts put before the org's alertmanager registers and resends only after a minute.
wait_for_alertmanager_sync(signoz, admin_token, notification_channel)
# function to create notification channel
def _create_webhook_notification_channel(