Compare commits

..

35 Commits

Author SHA1 Message Date
Tushar Vats
c4f654031b refactor(telemetrystore): keep settings hook receivers named after their role 2026-11-17 19:21:03 +05:30
Tushar Vats
c7ddcd3ffa fix(querier): preview clickhouse sql as its query user 2026-11-17 19:21:03 +05:30
Tushar Vats
cb7f8ab84d feat(telemetrystore): run profile stores as their own clickhouse users
The server applies the user's settings profile and grants at login, so nothing depends on the client sending profile with each query.
2026-11-17 19:10:52 +05:30
Tushar Vats
3721e28826 test(telemetrystore): drop the direct clickhouse profile suite 2026-11-17 18:49:56 +05:30
Tushar Vats
9f888978dc refactor(telemetrystore): name settings hook receivers after their role 2026-11-17 18:40:52 +05:30
Tushar Vats
907e59f317 refactor(telemetrystore): set the profile in the settings hook 2026-11-17 18:30:28 +05:30
Tushar Vats
4f423ac50f refactor(telemetrystore): name provider receivers after their role 2026-11-17 16:09:40 +05:30
Tushar Vats
e0bfc56556 test(telemetrystore): use generated and library mocks in provider tests 2026-11-17 16:09:40 +05:30
Tushar Vats
8fe86ffe3f revert(telemetrystore): restore the inline read limit error mappings 2026-11-17 15:25:43 +05:30
Tushar Vats
0b45c8d786 test(telemetrystore): cover settings profiles, hook settings and limit errors 2026-11-17 15:23:13 +05:30
Tushar Vats
6265c0c1c8 refactor(telemetrystore): share the read limit error mapping 2026-11-17 15:23:13 +05:30
Tushar Vats
cba0354826 refactor(telemetrystore): send hook settings and the profile from the store
Hooks add to the query event's settings and the store sends them once, adding the profile last, so the profile no longer depends on the settings hook or the context.
2026-11-17 15:07:51 +05:30
Tushar Vats
400a66c83d refactor(telemetrystore): drop the missing-profile fallback
Whoever lists a profile ensures it exists in ClickHouse, so startup no longer queries it.
2026-11-17 14:42:27 +05:30
Tushar Vats
be6bf4e0a5 refactor(telemetrystore): run settings profiles over the main pool with WithProfile
The profile goes with each query through the settings hook, so no profile needs its own pool or a new constructor argument.
2026-11-17 14:13:59 +05:30
Tushar Vats
85c6c1547e test(querier): document clickhouse sql settings under a read-only profile 2026-11-17 13:59:52 +05:30
Tushar Vats
02591cce68 feat(telemetrystore): map read-only mode errors to readonly_mode 2026-11-17 13:59:52 +05:30
Tushar Vats
5874b393c3 test(querier): check every clickhouse_query profile limit 2026-11-17 13:53:50 +05:30
Tushar Vats
de57bb88f5 feat(telemetrystore): map result and read limit errors
Queries that go past a profile's result or read limits now return 400 result_too_large or read_too_large instead of a 500.
2026-11-17 13:53:50 +05:30
Tushar Vats
2b6bce9530 test(querier): move the clickhouse sql profile test to queriercommon 2026-11-17 13:20:58 +05:30
Tushar Vats
d8cdb9a3bf test(querier): reject clickhouse sql settings that escape the clickhouse_query profile 2026-11-17 13:16:53 +05:30
Tushar Vats
243b3f2636 feat(telemetrystore): fall back to the main store when the settings profile is missing
A profile listed before it exists in ClickHouse would fail every query, so startup checks it once.
2026-11-17 12:07:18 +05:30
Tushar Vats
fec811acf1 feat(querier): run clickhouse sql queries with the clickhouse_query settings profile
Only user-written ClickHouse SQL needs the profile's limits, so builder queries keep the main store.
2026-11-17 12:07:01 +05:30
Tushar Vats
1367e0ab40 test(telemetrystore): verify query settings cannot escape a settings profile 2026-11-17 11:35:54 +05:30
Tushar Vats
9436d63ef2 refactor(telemetrystore): set the settings profile on the connection
The profile goes with every query as a custom setting, so one user serves every profile and a SETTINGS clause cannot escape it.
2026-11-17 11:35:54 +05:30
Tushar Vats
e68f368c0f revert(telemetrystore): keep pool metrics as on main 2026-11-17 11:25:39 +05:30
Tushar Vats
1c18a61845 refactor(telemetrystore): label pool metrics by the dsn user 2026-11-17 11:25:39 +05:30
Tushar Vats
985ed61a35 refactor(telemetrystore): build a store per settings profile instead of WithProfile
Each profile gets its own store from the factory, so it owns its pool and the TelemetryStore interface is unchanged.
2026-11-17 11:25:39 +05:30
Tushar Vats
b7b1cbca87 feat(telemetrystore): report connection pool metrics per profile 2026-11-17 11:25:39 +05:30
Tushar Vats
68c6da8db8 feat(telemetrystore): run reads with the default profile and writes on the main dsn
Writes and schema changes keep the unconstrained main dsn, so the default profile only has to suit reads.
2026-11-17 11:25:39 +05:30
Tushar Vats
9a8c15fa6d feat(telemetrystore): name the default profile as the unlimited fallback 2026-11-17 11:25:39 +05:30
Tushar Vats
857185b41d refactor(telemetrystore): bind the settings profile with WithProfile instead of the context
The profile depends on the caller, not the request, so it is bound when the store is wired. An unconfigured profile falls back to the default connection so callers work before profiles exist in ClickHouse.
2026-11-17 11:25:39 +05:30
Tushar Vats
7f6a2611d0 feat(telemetrystore): warn when a query falls back from an unknown profile
Assisted-by: Claude Opus 5.5
2026-11-17 11:25:39 +05:30
Tushar Vats
0cf34784b5 feat(telemetrystore): fall back to the default connection for an unknown profile
Assisted-by: Claude Opus 5.5
2026-11-17 11:25:39 +05:30
Tushar Vats
48cffc91a2 refactor(telemetrystore): run profile queries over native connections
Native keeps typed errors and progress stats. It sets the profile at login, so each profile gets its own user and connection.

Assisted-by: Claude Opus 5.5
2026-11-17 11:25:39 +05:30
Tushar Vats
8bd3d6276d feat(telemetrystore): run queries with a clickhouse settings profile
The native protocol cannot pick a profile per query, so profile queries use a separate HTTP connection.

Assisted-by: Claude Opus 5.5
2026-11-17 11:25:39 +05:30
108 changed files with 893 additions and 5371 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

@@ -205,6 +205,11 @@ telemetrystore:
max_bytes_to_read: 0
max_result_rows: 0
ignore_data_skipping_indices: ""
# Stores queries can run with, for example clickhouse_query. Each runs as the ClickHouse user in its dsn, under
# that user's settings profile and grants.
profiles: {}
# clickhouse_query:
# dsn: tcp://signoz_query:password@localhost:9000
##################### Prometheus #####################
prometheus:
@@ -364,7 +369,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:
@@ -12047,9 +11992,8 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
type: object
notificationSettings:
allOf:
@@ -12166,9 +12110,8 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
type: object
notificationSettings:
allOf:
@@ -16624,9 +16567,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- org-preference:list
- ADMIN
- tokenizer:
- org-preference:list
- ADMIN
summary: List org preferences
tags:
- preferences
@@ -16689,9 +16632,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- org-preference:read
- ADMIN
- tokenizer:
- org-preference:read
- ADMIN
summary: Get org preference
tags:
- preferences
@@ -16746,9 +16689,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- org-preference:update
- ADMIN
- tokenizer:
- org-preference:update
- ADMIN
summary: Update org preference
tags:
- preferences

View File

@@ -267,7 +267,9 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel)
resultLabels := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel).Labels()
lb.SetRuleLabels(r.Labels().Map(), expand)
for name, value := range r.Labels().Map() {
lb.Set(name, expand(value))
}
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

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

@@ -2,9 +2,9 @@ import type { ErrorEvent, StackFrame } from '@sentry/react';
import { AxiosError, AxiosHeaders } from 'axios';
import {
isInjectedScriptError,
hasNoAppFrames,
isExpectedRequestFailure,
isThirdPartyScriptError,
isExternalIntegrationError,
SENTRY_IGNORE_ERRORS,
} from '../sentryFilters';
@@ -27,7 +27,7 @@ function eventWithFrames(...filenames: string[]): ErrorEvent {
};
}
describe('isThirdPartyScriptError', () => {
describe('isExternalIntegrationError', () => {
it.each([
[
'PostHog recorder',
@@ -39,12 +39,14 @@ describe('isThirdPartyScriptError', () => {
],
['Appcues', 'https://fast.appcues.com/123456.js'],
])('drops an error with a %s frame', (_, url) => {
expect(isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, url))).toBe(true);
expect(isExternalIntegrationError(eventWithFrames(APP_BUNDLE, url))).toBe(
true,
);
});
it('drops it when the top frame is our bundle', () => {
expect(
isThirdPartyScriptError(
isExternalIntegrationError(
eventWithFrames(
'https://us-assets.i.posthog.com/static/posthog-recorder.js?v=1.298.0',
'<anonymous>',
@@ -56,13 +58,13 @@ describe('isThirdPartyScriptError', () => {
it('keeps an error from our bundle only', () => {
expect(
isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
isExternalIntegrationError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
).toBe(false);
});
it('keeps an error from a host that only contains an integration name', () => {
expect(
isThirdPartyScriptError(
isExternalIntegrationError(
eventWithFrames(
'https://posthog.example.com/app.js',
'https://notusepylon.com/widget.js',
@@ -72,11 +74,11 @@ describe('isThirdPartyScriptError', () => {
});
it('keeps an error without a stack trace', () => {
expect(isThirdPartyScriptError({ type: undefined })).toBe(false);
expect(isExternalIntegrationError({ type: undefined })).toBe(false);
});
});
describe('isInjectedScriptError', () => {
describe('hasNoAppFrames', () => {
const PAGE_URL = 'https://example.us.signoz.cloud/dashboard/01a081e1';
function eventWithStackFrames(frames: StackFrame[]): ErrorEvent {
@@ -90,7 +92,7 @@ describe('isInjectedScriptError', () => {
it('drops a script appended to the page', () => {
expect(
isInjectedScriptError(
hasNoAppFrames(
eventWithStackFrames([
{ filename: PAGE_URL, lineno: 1, colno: 30, function: 'global code' },
{ filename: '[native code]', function: 'eval' },
@@ -102,7 +104,7 @@ describe('isInjectedScriptError', () => {
it('drops a browser extension error', () => {
expect(
isInjectedScriptError(
hasNoAppFrames(
eventWithStackFrames([
{ filename: 'chrome-extension://abc/content.js', lineno: 4, colno: 12 },
]),
@@ -110,46 +112,21 @@ describe('isInjectedScriptError', () => {
).toBe(true);
});
it('drops an error thrown from injected code behind the Sentry wrapper', () => {
expect(
isInjectedScriptError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
).toBe(true);
});
it('keeps an error thrown from our bundle after an anonymous frame', () => {
expect(
isInjectedScriptError(eventWithFrames('<anonymous>', APP_BUNDLE)),
).toBe(false);
});
it('keeps an error with a frame from our bundle', () => {
expect(isInjectedScriptError(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(
false,
);
expect(hasNoAppFrames(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(false);
});
it('keeps an error without a stack trace', () => {
expect(isInjectedScriptError({ type: undefined })).toBe(false);
expect(hasNoAppFrames({ type: undefined })).toBe(false);
});
it('keeps an error whose frames have no position', () => {
expect(
isInjectedScriptError(
hasNoAppFrames(
eventWithStackFrames([{ filename: '[native code]', function: 'eval' }]),
),
).toBe(false);
});
it('keeps an error a builtin threw for our bundle', () => {
expect(
isInjectedScriptError(
eventWithStackFrames([
{ filename: APP_BUNDLE, lineno: 1, colno: 1 },
{ filename: '<anonymous>', function: 'JSON.parse' },
]),
),
).toBe(false);
});
});
describe('SENTRY_IGNORE_ERRORS', () => {

View File

@@ -44,9 +44,9 @@ import defaultRoutes, {
} from './routes';
import type { EnabledRouteKeys } from './RouteGate';
import {
isInjectedScriptError,
hasNoAppFrames,
isExpectedRequestFailure,
isThirdPartyScriptError,
isExternalIntegrationError,
SENTRY_IGNORE_ERRORS,
} from './sentryFilters';
@@ -360,12 +360,12 @@ function App(): JSX.Element {
return null;
}
if (isThirdPartyScriptError(event)) {
if (isExternalIntegrationError(event)) {
return null;
}
// Dev serves source from /src/, so every frame would look foreign there.
if (IS_PROD && isInjectedScriptError(event)) {
if (IS_PROD && hasNoAppFrames(event)) {
return null;
}

View File

@@ -28,15 +28,10 @@ export function isExpectedRequestFailure(error: unknown): boolean {
}
const APP_ASSETS_PATH = '/assets/';
const ANONYMOUS_FILENAME = '<anonymous>';
// Frames without a position are `[native code]` or a browser builtin such as
// `JSON.parse (<anonymous>)`, which say nothing about the script that threw.
// A positioned `<anonymous>` throwing (last) frame is code loaded without a
// URL: the DevTools console, CDP, or an extension's `executeScript`. Sentry's
// own timer wrapper is bundled with the app, so checking for any app frame
// alone misses it.
export function isInjectedScriptError(event: ErrorEvent): boolean {
// Frames without a position are `[native code]`, which says nothing about the
// script that threw.
export function hasNoAppFrames(event: ErrorEvent): boolean {
const frames = (event.exception?.values ?? [])
.flatMap((exception) => exception.stacktrace?.frames ?? [])
.filter(
@@ -45,13 +40,12 @@ export function isInjectedScriptError(event: ErrorEvent): boolean {
return (
frames.length > 0 &&
(frames[frames.length - 1].filename === ANONYMOUS_FILENAME ||
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH)))
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH))
);
}
// PostHog's lazy recorder, the Pylon widget and Appcues.
const THIRD_PARTY_SCRIPT_URLS = [
const EXTERNAL_SCRIPT_URLS = [
/^https?:\/\/[^/]+\.posthog\.com\//,
/^https?:\/\/(?:[^/]+\.)?usepylon\.com\//,
/^https?:\/\/(?:[^/]+\.)?appcues\.(?:com|net)\//,
@@ -59,10 +53,10 @@ const THIRD_PARTY_SCRIPT_URLS = [
// Checks every frame, not only the top one: a failed fetch from the recorder
// tops out in Sentry's own fetch wrapper, which is bundled with the app.
export function isThirdPartyScriptError(event: ErrorEvent): boolean {
export function isExternalIntegrationError(event: ErrorEvent): boolean {
return (event.exception?.values ?? []).some((exception) =>
(exception.stacktrace?.frames ?? []).some((frame) =>
THIRD_PARTY_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
EXTERNAL_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
),
);
}

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.
@@ -13215,7 +13156,7 @@ export interface RuletypesNotificationSettingsDTO {
export type RuletypesPostableRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
@@ -13332,7 +13273,7 @@ export interface RuletypesPostableRuleDTO {
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
@@ -13365,7 +13306,7 @@ export interface RuletypesPostableRuleViewDTO {
export type RuletypesRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
@@ -13424,7 +13365,7 @@ export interface RuletypesRuleDTO {
id: string;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
labels?: RuletypesRuleDTOLabels;
/**

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

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

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

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

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

@@ -5,8 +5,6 @@ import (
"github.com/SigNoz/signoz/pkg/http/handler"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/types/preferencetypes"
"github.com/gorilla/mux"
)
@@ -63,7 +61,7 @@ func (provider *provider) addPreferenceRoutes(router *mux.Router) error {
return err
}
if err := router.Handle("/api/v1/org/preferences", handler.New(provider.authzMiddleware.CheckResources(provider.preferenceHandler.ListByOrg, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
if err := router.Handle("/api/v1/org/preferences", handler.New(provider.authzMiddleware.AdminAccess(provider.preferenceHandler.ListByOrg), handler.OpenAPIDef{
ID: "ListOrgPreferences",
Tags: []string{"preferences"},
Summary: "List org preferences",
@@ -75,17 +73,12 @@ func (provider *provider) addPreferenceRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{},
Deprecated: false,
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceOrgPreference.Scope(coretypes.VerbList)}),
}, handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceOrgPreference,
Verb: coretypes.VerbList,
Category: coretypes.ActionCategoryDataAccess,
Selector: coretypes.WildcardSelector,
}))).Methods(http.MethodGet).GetError(); err != nil {
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
})).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/org/preferences/{name}", handler.New(provider.authzMiddleware.CheckResources(provider.preferenceHandler.GetByOrg, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
if err := router.Handle("/api/v1/org/preferences/{name}", handler.New(provider.authzMiddleware.AdminAccess(provider.preferenceHandler.GetByOrg), handler.OpenAPIDef{
ID: "GetOrgPreference",
Tags: []string{"preferences"},
Summary: "Get org preference",
@@ -97,18 +90,12 @@ func (provider *provider) addPreferenceRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceOrgPreference.Scope(coretypes.VerbRead)}),
}, handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceOrgPreference,
Verb: coretypes.VerbRead,
Category: coretypes.ActionCategoryDataAccess,
ID: coretypes.PathParam("name"),
Selector: coretypes.WildcardSelector,
}))).Methods(http.MethodGet).GetError(); err != nil {
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
})).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/org/preferences/{name}", handler.New(provider.authzMiddleware.CheckResources(provider.preferenceHandler.UpdateByOrg, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
if err := router.Handle("/api/v1/org/preferences/{name}", handler.New(provider.authzMiddleware.AdminAccess(provider.preferenceHandler.UpdateByOrg), handler.OpenAPIDef{
ID: "UpdateOrgPreference",
Tags: []string{"preferences"},
Summary: "Update org preference",
@@ -120,14 +107,8 @@ func (provider *provider) addPreferenceRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusNoContent,
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceOrgPreference.Scope(coretypes.VerbUpdate)}),
}, handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceOrgPreference,
Verb: coretypes.VerbUpdate,
Category: coretypes.ActionCategoryConfigurationChange,
ID: coretypes.PathParam("name"),
Selector: coretypes.WildcardSelector,
}))).Methods(http.MethodPut).GetError(); err != nil {
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
})).Methods(http.MethodPut).GetError(); err != nil {
return err
}

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

@@ -10,6 +10,10 @@ import (
const DefaultMaxConcurrentQueries = 8
// ClickHouseSQLProfile is the telemetrystore.clickhouse.profiles entry that user-written ClickHouse SQL
// queries run with, once it is in the config.
const ClickHouseSQLProfile = "clickhouse_query"
// Config represents the configuration for the querier.
type Config struct {
// CacheTTL is the TTL for cached query results

View File

@@ -8,6 +8,7 @@ import (
"sync"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/telemetrystore"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrystoretypes"
"github.com/SigNoz/signoz/pkg/valuer"
@@ -83,6 +84,7 @@ func (q *querier) QueryRangePreview(
// Render each executing query's statement and collect the ClickHouse-bound
// analysis work to run concurrently.
var previewTasks []qbtypes.PreviewTask
stores := make(map[string]telemetrystore.TelemetryStore, len(req.CompositeQuery.Queries))
for _, query := range req.CompositeQuery.Queries {
name := query.GetQueryName()
ps := prepared[name]
@@ -130,9 +132,12 @@ func (q *querier) QueryRangePreview(
ps.Warnings = append(ps.Warnings, stmt.Warnings...)
// EXPLAIN runs as the user the query would run as, so it cannot see past that user's grants.
stores[name] = q.telemetryStore
if query.Type == qbtypes.QueryTypeClickHouseSQL {
if bindErr := q.telemetryStore.Plan(ctx, stmt.Query, stmt.Args...); bindErr != nil {
if errors.Ast(bindErr, errors.TypeInvalidInput) || errors.Ast(bindErr, errors.TypeNotFound) {
stores[name] = q.telemetryStore.WithProfile(ClickHouseSQLProfile)
if bindErr := stores[name].Plan(ctx, stmt.Query, stmt.Args...); bindErr != nil {
if errors.Ast(bindErr, errors.TypeInvalidInput) || errors.Ast(bindErr, errors.TypeNotFound) || errors.Ast(bindErr, errors.TypeForbidden) {
ps.Error = bindErr
results[name] = ps
continue
@@ -168,7 +173,7 @@ func (q *querier) QueryRangePreview(
}
}
q.runPreviewTasks(ctx, previewTasks, results)
q.runPreviewTasks(ctx, previewTasks, stores, results)
// a filter and a column on the same unknown key report the same warning;
// QueryRange dedupes before it builds its response too
@@ -289,7 +294,7 @@ func (q *querier) traceOperatorPreviewComposite(req *qbtypes.QueryRangeRequest,
return append(queries, operator), nil
}
func (q *querier) runPreviewTasks(ctx context.Context, tasks []qbtypes.PreviewTask, previews map[string]qbtypes.QueryPreview) {
func (q *querier) runPreviewTasks(ctx context.Context, tasks []qbtypes.PreviewTask, stores map[string]telemetrystore.TelemetryStore, previews map[string]qbtypes.QueryPreview) {
if len(tasks) == 0 {
return
}
@@ -307,13 +312,14 @@ func (q *querier) runPreviewTasks(ctx context.Context, tasks []qbtypes.PreviewTa
go func(i int) {
defer wg.Done()
t := tasks[i]
store := stores[t.Name]
var out outcome
if granules, ok, scErr := q.telemetryStore.Indexes(ctx, t.Query, t.Args...); scErr != nil {
if granules, ok, scErr := store.Indexes(ctx, t.Query, t.Args...); scErr != nil {
out.warnings = append(out.warnings, "could not compute granule stats: "+scErr.Error())
} else if ok {
out.granules = &granules
}
if estimate, eErr := q.telemetryStore.Estimate(ctx, t.Query, t.Args...); eErr != nil {
if estimate, eErr := store.Estimate(ctx, t.Query, t.Args...); eErr != nil {
out.warnings = append(out.warnings, "could not run EXPLAIN ESTIMATE: "+eErr.Error())
} else {
out.estimate = estimate

View File

@@ -233,7 +233,7 @@ func (q *querier) buildQueries(
if !ok {
return nil, nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid clickhouse query spec %T", query.Spec)
}
chSQLQuery := newchSQLQuery(q.logger, q.telemetryStore, chQuery, nil, qbtypes.TimeRange{From: req.Start, To: req.End}, req.RequestType, tmplVars)
chSQLQuery := newchSQLQuery(q.logger, q.telemetryStore.WithProfile(ClickHouseSQLProfile), chQuery, nil, qbtypes.TimeRange{From: req.Start, To: req.End}, req.RequestType, tmplVars)
queries[chQuery.Name] = chSQLQuery
case qbtypes.QueryTypeTraceOperator:
traceOpQuery, ok := query.Spec.(qbtypes.QueryBuilderTraceOperator)
@@ -925,7 +925,7 @@ func (q *querier) createRangedQuery(_ valuer.UUID, originalQuery qbtypes.Query,
queryCopy := qt.query.Copy()
argsCopy := make([]any, len(qt.args))
copy(argsCopy, qt.args)
return newchSQLQuery(q.logger, q.telemetryStore, queryCopy, argsCopy, timeRange, qt.kind, qt.vars)
return newchSQLQuery(q.logger, q.telemetryStore.WithProfile(ClickHouseSQLProfile), queryCopy, argsCopy, timeRange, qt.kind, qt.vars)
// A builder query's window was moved into the shifted clock when it was
// built, so a range taken from that window must not be shifted again.

View File

@@ -201,7 +201,9 @@ func (r *PromRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(result.Metric...).Del(ruletypes.MetricNameLabel)
resultLabels := ruletypes.NewBuilder(result.Metric...).Del(ruletypes.MetricNameLabel).Labels()
lb.SetRuleLabels(r.labels.Map(), expand)
for name, value := range r.labels.Map() {
lb.Set(name, expand(value))
}
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -278,7 +278,9 @@ func (r *ThresholdRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel)
resultLabels := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel).Labels()
lb.SetRuleLabels(r.labels.Map(), expand)
for name, value := range r.labels.Map() {
lb.Set(name, expand(value))
}
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -277,7 +277,6 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewRemoveUnsupportedQuickFiltersFactory(),
sqlmigration.NewMigrateRelatedLinksTemplateFactory(),
sqlmigration.NewAddOrganizationTuplesFactory(sqlstore),
sqlmigration.NewAddOrgPreferenceTuplesFactory(sqlstore),
)
}

View File

@@ -1,133 +0,0 @@
package sqlmigration
import (
"context"
"database/sql"
"time"
"github.com/oklog/ulid/v2"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect"
"github.com/uptrace/bun/migrate"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/sqlstore"
)
type addOrgPreferenceTuples struct {
sqlstore sqlstore.SQLStore
}
func NewAddOrgPreferenceTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
return factory.NewProviderFactory(factory.MustNewName("add_org_preference_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
return &addOrgPreferenceTuples{sqlstore: sqlstore}, nil
})
}
func (migration *addOrgPreferenceTuples) Register(migrations *migrate.Migrations) error {
return migrations.Register(migration.Up, migration.Down)
}
func (migration *addOrgPreferenceTuples) Up(ctx context.Context, db *bun.DB) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
var storeID string
err = tx.QueryRowContext(ctx, `SELECT id FROM store WHERE name = ? LIMIT 1`, "signoz").Scan(&storeID)
if err != nil {
return err
}
var orgIDs []string
err = tx.NewSelect().
Table("organizations").
Column("id").
Scan(ctx, &orgIDs)
if err != nil && err != sql.ErrNoRows {
return err
}
isPG := migration.sqlstore.BunDB().Dialect().Name() == dialect.PG
tuples := []migrationTuple{
{"signoz-admin", "metaresource", "org-preference", "read"},
{"signoz-admin", "metaresource", "org-preference", "update"},
{"signoz-admin", "metaresource", "org-preference", "delete"},
{"signoz-admin", "metaresource", "org-preference", "create"},
{"signoz-admin", "metaresource", "org-preference", "list"},
}
for _, orgID := range orgIDs {
for _, tuple := range tuples {
entropy := ulid.DefaultEntropy()
now := time.Now().UTC()
tupleID := ulid.MustNew(ulid.Timestamp(now), entropy).String()
objectID := "organization/" + orgID + "/" + tuple.objectName + "/*"
roleSubject := "organization/" + orgID + "/role/" + tuple.roleName
if isPG {
user := "role:" + roleSubject + "#assignee"
result, err := tx.ExecContext(ctx, `
INSERT INTO tuple (store, object_type, object_id, relation, _user, user_type, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, object_type, object_id, relation, _user) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, user, "userset", tupleID, now,
)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
continue
}
_, err = tx.ExecContext(ctx, `
INSERT INTO changelog (store, object_type, object_id, relation, _user, operation, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, ulid, object_type) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, user, 0, tupleID, now,
)
if err != nil {
return err
}
} else {
result, err := tx.ExecContext(ctx, `
INSERT INTO tuple (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, user_type, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", "userset", tupleID, now,
)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
continue
}
_, err = tx.ExecContext(ctx, `
INSERT INTO changelog (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, operation, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, ulid, object_type) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", 0, tupleID, now,
)
if err != nil {
return err
}
}
}
}
return tx.Commit()
}
func (migration *addOrgPreferenceTuples) Down(context.Context, *bun.DB) error {
return nil
}

View File

@@ -26,6 +26,12 @@ var (
ErrCodeNotAnAggregate = errors.MustNewCode("not_an_aggregate")
ErrCodeIllegalAggregation = errors.MustNewCode("illegal_aggregation")
ErrCodeInvalidRegexp = errors.MustNewCode("invalid_regexp")
ErrCodeSettingNotAllowed = errors.MustNewCode("setting_not_allowed")
ErrCodeSettingsProfileNotFound = errors.MustNewCode("settings_profile_not_found")
ErrCodeResultTooLarge = errors.MustNewCode("result_too_large")
ErrCodeReadTooLarge = errors.MustNewCode("read_too_large")
ErrCodeReadonlyMode = errors.MustNewCode("readonly_mode")
ErrCodeAccessDenied = errors.MustNewCode("access_denied")
ErrCodeQueryCanceled = errors.MustNewCode("query_canceled")
ErrCodeQueryTimeout = errors.MustNewCode("query_timeout")
@@ -111,11 +117,47 @@ var clickHouseExceptionWrappers = map[chproto.Error]func(cause error, ex *clickh
return errors.WrapInvalidInputf(cause, ErrCodeInvalidRegexp, "regular expression does not compile: %s", ex.Message).
WithSuggestions("write the pattern in RE2 syntax, which has no lookaround or backreferences, and escape a backslash that is meant literally")
},
chproto.ErrTooManyRowsOrBytes: func(cause error, ex *clickhouse.Exception) error {
return errors.WrapInvalidInputf(cause, ErrCodeResultTooLarge, "query result too large: %s", ex.Message).
WithSuggestions("add a LIMIT, narrow the time range or select fewer columns")
},
chproto.ErrTooManyRows: func(cause error, ex *clickhouse.Exception) error {
return errors.WrapInvalidInputf(cause, ErrCodeReadTooLarge, "query read too much data: %s", ex.Message).
WithSuggestions("narrow the time range or add filters so the query reads less data")
},
chproto.ErrTooManyPartitions: func(cause error, ex *clickhouse.Exception) error {
return errors.WrapInvalidInputf(cause, ErrCodeReadTooLarge, "query read too much data: %s", ex.Message).
WithSuggestions("narrow the time range or add filters so the query reads less data")
},
chproto.ErrTooManyBytes: func(cause error, ex *clickhouse.Exception) error {
return errors.WrapInvalidInputf(cause, ErrCodeReadTooLarge, "query read too much data: %s", ex.Message).
WithSuggestions("narrow the time range or add filters so the query reads less data")
},
// A write, or a change to the readonly setting, under a read-only settings profile.
chproto.ErrReadonly: func(cause error, ex *clickhouse.Exception) error {
return errors.WrapInvalidInputf(cause, ErrCodeReadonlyMode, "query not allowed in read-only mode: %s", ex.Message).
WithSuggestions("run only SELECT queries and remove readonly from the SETTINGS clause")
},
// A query on a table outside the grants of the ClickHouse user it runs as.
chproto.ErrAccessDenied: func(cause error, ex *clickhouse.Exception) error {
return errors.WrapForbiddenf(cause, ErrCodeAccessDenied, "query not allowed: %s", ex.Message).
WithSuggestions("query only the telemetry tables")
},
chproto.ErrThereIsNoProfile: func(cause error, ex *clickhouse.Exception) error {
return errors.WrapNotFoundf(cause, ErrCodeSettingsProfileNotFound, "settings profile not found: %s", ex.Message)
},
// A SETTINGS clause went past a constraint of the query's settings profile.
chproto.ErrSettingConstraintViolation: func(cause error, ex *clickhouse.Exception) error {
return errors.WrapInvalidInputf(cause, ErrCodeSettingNotAllowed, "setting not allowed: %s", ex.Message).
WithSuggestions("remove the setting from the SETTINGS clause of the query")
},
}
type provider struct {
settings factory.ScopedProviderSettings
clickHouseConn clickhouse.Conn
profile string
profiles map[string]*provider
cluster string
hooks []telemetrystore.TelemetryStoreHook
}
@@ -129,21 +171,17 @@ func NewFactory(hookFactories ...factory.ProviderFactory[telemetrystore.Telemetr
func New(ctx context.Context, providerSettings factory.ProviderSettings, config telemetrystore.Config, hookFactories ...factory.ProviderFactory[telemetrystore.TelemetryStoreHook, telemetrystore.Config]) (telemetrystore.TelemetryStore, error) {
settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/telemetrystore/clickhousetelemetrystore")
options, err := clickhouse.ParseDSN(config.Clickhouse.DSN)
chConn, err := open(config.Clickhouse.DSN, config.Connection)
if err != nil {
return nil, err
}
options.MaxIdleConns = config.Connection.MaxIdleConns
options.MaxOpenConns = config.Connection.MaxOpenConns
options.DialTimeout = config.Connection.DialTimeout
// Read JSON columns natively: the driver mis-decodes JSON(max_dynamic_paths=0) columns without
// the flattened serialization, and reading them as a string collapses a key stored at both a
// scalar and an object path.
options.Settings["output_format_native_use_flattened_dynamic_and_json_serialization"] = 1
chConn, err := clickhouse.Open(options)
if err != nil {
return nil, err
profileConns := make(map[string]clickhouse.Conn, len(config.Clickhouse.Profiles))
for profile, profileConfig := range config.Clickhouse.Profiles {
profileConns[profile], err = open(profileConfig.DSN, config.Connection)
if err != nil {
return nil, err
}
}
hooks := make([]telemetrystore.TelemetryStoreHook, len(hookFactories))
@@ -178,49 +216,96 @@ func New(ctx context.Context, providerSettings factory.ProviderSettings, config
cluster: config.Clickhouse.Cluster,
hooks: hooks,
}
withProfiles(p, profileConns)
return p, nil
}
func (p *provider) ClickhouseDB() clickhouse.Conn {
return p
func open(dsn string, connection telemetrystore.ConnectionConfig) (clickhouse.Conn, error) {
options, err := clickhouse.ParseDSN(dsn)
if err != nil {
return nil, err
}
options.MaxIdleConns = connection.MaxIdleConns
options.MaxOpenConns = connection.MaxOpenConns
options.DialTimeout = connection.DialTimeout
// Read JSON columns natively: the driver mis-decodes JSON(max_dynamic_paths=0) columns without
// the flattened serialization, and reading them as a string collapses a key stored at both a
// scalar and an object path.
options.Settings["output_format_native_use_flattened_dynamic_and_json_serialization"] = 1
return clickhouse.Open(options)
}
func (p *provider) Estimate(ctx context.Context, stmt string, args ...any) ([]telemetrystoretypes.EstimateEntry, error) {
return RunExplainEstimate(ctx, p, stmt, args...)
// withProfiles gives every profile a copy of main that runs its queries over the profile's pool.
func withProfiles(main *provider, conns map[string]clickhouse.Conn) {
main.profiles = make(map[string]*provider, len(conns))
for profile, conn := range conns {
profiled := *main
profiled.profile = profile
profiled.clickHouseConn = conn
main.profiles[profile] = &profiled
}
}
func (p *provider) Plan(ctx context.Context, stmt string, args ...any) error {
return RunExplainPlan(ctx, p, stmt, args...)
func (provider *provider) WithProfile(profile string) telemetrystore.TelemetryStore {
if store, ok := provider.profiles[profile]; ok {
return store
}
return provider
}
func (p *provider) Indexes(ctx context.Context, stmt string, args ...any) (telemetrystoretypes.Granules, bool, error) {
return RunExplainIndexes(ctx, p, stmt, args...)
func (provider *provider) ClickhouseDB() clickhouse.Conn {
return provider
}
func (p *provider) Cluster() string {
return p.cluster
func (provider *provider) Estimate(ctx context.Context, stmt string, args ...any) ([]telemetrystoretypes.EstimateEntry, error) {
return RunExplainEstimate(ctx, provider, stmt, args...)
}
func (p *provider) Close() error {
return p.clickHouseConn.Close()
func (provider *provider) Plan(ctx context.Context, stmt string, args ...any) error {
return RunExplainPlan(ctx, provider, stmt, args...)
}
func (p *provider) Ping(ctx context.Context) error {
return p.clickHouseConn.Ping(ctx)
func (provider *provider) Indexes(ctx context.Context, stmt string, args ...any) (telemetrystoretypes.Granules, bool, error) {
return RunExplainIndexes(ctx, provider, stmt, args...)
}
func (p *provider) Stats() driver.Stats {
return p.clickHouseConn.Stats()
func (provider *provider) Cluster() string {
return provider.cluster
}
func (p *provider) Query(ctx context.Context, query string, args ...interface{}) (driver.Rows, error) {
// Close closes the profile pools with the main one. A profile store leaves its pool to the main store.
func (provider *provider) Close() error {
if provider.profile != "" {
return nil
}
errs := make([]error, 0, len(provider.profiles)+1)
for _, profiled := range provider.profiles {
errs = append(errs, profiled.clickHouseConn.Close())
}
errs = append(errs, provider.clickHouseConn.Close())
return errors.Join(errs...)
}
func (provider *provider) Ping(ctx context.Context) error {
return provider.clickHouseConn.Ping(ctx)
}
func (provider *provider) Stats() driver.Stats {
return provider.clickHouseConn.Stats()
}
func (provider *provider) Query(ctx context.Context, query string, args ...interface{}) (driver.Rows, error) {
event := telemetrystore.NewQueryEvent(query, args)
ctx = telemetrystore.WrapBeforeQuery(p.hooks, ctx, event)
rows, err := p.clickHouseConn.Query(ctx, query, args...)
ctx = telemetrystore.WrapBeforeQuery(provider.hooks, ctx, event)
rows, err := provider.clickHouseConn.Query(ctx, query, args...)
if err != nil {
event.Err = err
telemetrystore.WrapAfterQuery(p.hooks, ctx, event)
telemetrystore.WrapAfterQuery(provider.hooks, ctx, event)
return nil, castError(err)
}
@@ -228,71 +313,71 @@ func (p *provider) Query(ctx context.Context, query string, args ...interface{})
Rows: telemetrystore.WrapRows(rows),
ctx: ctx,
event: event,
onClose: func() { telemetrystore.WrapAfterQuery(p.hooks, ctx, event) },
onClose: func() { telemetrystore.WrapAfterQuery(provider.hooks, ctx, event) },
}, nil
}
func (p *provider) QueryRow(ctx context.Context, query string, args ...interface{}) driver.Row {
func (provider *provider) QueryRow(ctx context.Context, query string, args ...interface{}) driver.Row {
event := telemetrystore.NewQueryEvent(query, args)
ctx = telemetrystore.WrapBeforeQuery(p.hooks, ctx, event)
row := p.clickHouseConn.QueryRow(ctx, query, args...)
ctx = telemetrystore.WrapBeforeQuery(provider.hooks, ctx, event)
row := provider.clickHouseConn.QueryRow(ctx, query, args...)
if row == nil {
telemetrystore.WrapAfterQuery(p.hooks, ctx, event)
telemetrystore.WrapAfterQuery(provider.hooks, ctx, event)
return nil
}
event.Err = row.Err()
telemetrystore.WrapAfterQuery(p.hooks, ctx, event)
telemetrystore.WrapAfterQuery(provider.hooks, ctx, event)
return &rowWithCastError{Row: row}
}
func (p *provider) Select(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
func (provider *provider) Select(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
event := telemetrystore.NewQueryEvent(query, args)
ctx = telemetrystore.WrapBeforeQuery(p.hooks, ctx, event)
err := p.clickHouseConn.Select(ctx, dest, query, args...)
ctx = telemetrystore.WrapBeforeQuery(provider.hooks, ctx, event)
err := provider.clickHouseConn.Select(ctx, dest, query, args...)
event.Err = err
telemetrystore.WrapAfterQuery(p.hooks, ctx, event)
telemetrystore.WrapAfterQuery(provider.hooks, ctx, event)
return castError(err)
}
func (p *provider) Exec(ctx context.Context, query string, args ...interface{}) error {
func (provider *provider) Exec(ctx context.Context, query string, args ...interface{}) error {
event := telemetrystore.NewQueryEvent(query, args)
ctx = telemetrystore.WrapBeforeQuery(p.hooks, ctx, event)
err := p.clickHouseConn.Exec(ctx, query, args...)
ctx = telemetrystore.WrapBeforeQuery(provider.hooks, ctx, event)
err := provider.clickHouseConn.Exec(ctx, query, args...)
event.Err = err
telemetrystore.WrapAfterQuery(p.hooks, ctx, event)
telemetrystore.WrapAfterQuery(provider.hooks, ctx, event)
return castError(err)
}
func (p *provider) AsyncInsert(ctx context.Context, query string, wait bool, args ...interface{}) error {
func (provider *provider) AsyncInsert(ctx context.Context, query string, wait bool, args ...interface{}) error {
event := telemetrystore.NewQueryEvent(query, args)
ctx = telemetrystore.WrapBeforeQuery(p.hooks, ctx, event)
err := p.clickHouseConn.Exec(clickhouse.Context(ctx, clickhouse.WithAsync(wait)), query, args...)
ctx = telemetrystore.WrapBeforeQuery(provider.hooks, ctx, event)
err := provider.clickHouseConn.Exec(clickhouse.Context(ctx, clickhouse.WithAsync(wait)), query, args...)
event.Err = err
telemetrystore.WrapAfterQuery(p.hooks, ctx, event)
telemetrystore.WrapAfterQuery(provider.hooks, ctx, event)
return castError(err)
}
func (p *provider) PrepareBatch(ctx context.Context, query string, opts ...driver.PrepareBatchOption) (driver.Batch, error) {
func (provider *provider) PrepareBatch(ctx context.Context, query string, opts ...driver.PrepareBatchOption) (driver.Batch, error) {
event := telemetrystore.NewQueryEvent(query, nil)
ctx = telemetrystore.WrapBeforeQuery(p.hooks, ctx, event)
batch, err := p.clickHouseConn.PrepareBatch(ctx, query, opts...)
ctx = telemetrystore.WrapBeforeQuery(provider.hooks, ctx, event)
batch, err := provider.clickHouseConn.PrepareBatch(ctx, query, opts...)
event.Err = err
telemetrystore.WrapAfterQuery(p.hooks, ctx, event)
telemetrystore.WrapAfterQuery(provider.hooks, ctx, event)
if batch == nil {
return nil, castError(err)
@@ -300,12 +385,12 @@ func (p *provider) PrepareBatch(ctx context.Context, query string, opts ...drive
return &batchWithCastError{Batch: batch}, castError(err)
}
func (p *provider) ServerVersion() (*driver.ServerVersion, error) {
return p.clickHouseConn.ServerVersion()
func (provider *provider) ServerVersion() (*driver.ServerVersion, error) {
return provider.clickHouseConn.ServerVersion()
}
func (p *provider) Contributors() []string {
return p.clickHouseConn.Contributors()
func (provider *provider) Contributors() []string {
return provider.clickHouseConn.Contributors()
}
func castError(err error) error {

View File

@@ -0,0 +1,74 @@
package clickhousetelemetrystore
import (
"testing"
chproto "github.com/ClickHouse/ch-go/proto"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/DATA-DOG/go-sqlmock"
cmock "github.com/SigNoz/clickhouse-go-mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/errors"
)
func TestCastError_ProfileErrors(t *testing.T) {
testCases := []struct {
name string
code chproto.Error
want errors.Code
notFound bool
forbidden bool
}{
{name: "SettingConstraintViolation_SettingNotAllowed", code: chproto.ErrSettingConstraintViolation, want: ErrCodeSettingNotAllowed},
{name: "TooManyRowsOrBytes_ResultTooLarge", code: chproto.ErrTooManyRowsOrBytes, want: ErrCodeResultTooLarge},
{name: "TooManyRows_ReadTooLarge", code: chproto.ErrTooManyRows, want: ErrCodeReadTooLarge},
{name: "TooManyBytes_ReadTooLarge", code: chproto.ErrTooManyBytes, want: ErrCodeReadTooLarge},
{name: "TooManyPartitions_ReadTooLarge", code: chproto.ErrTooManyPartitions, want: ErrCodeReadTooLarge},
{name: "Readonly_ReadonlyMode", code: chproto.ErrReadonly, want: ErrCodeReadonlyMode},
{name: "AccessDenied_AccessDenied", code: chproto.ErrAccessDenied, want: ErrCodeAccessDenied, forbidden: true},
{name: "ThereIsNoProfile_SettingsProfileNotFound", code: chproto.ErrThereIsNoProfile, want: ErrCodeSettingsProfileNotFound, notFound: true},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := castError(&clickhouse.Exception{Code: int32(testCase.code), Message: testCase.name})
require.Error(t, err)
assert.True(t, errors.Asc(err, testCase.want), "got %v", err)
assert.Equal(t, testCase.notFound, errors.Ast(err, errors.TypeNotFound), "got %v", err)
assert.Equal(t, testCase.forbidden, errors.Ast(err, errors.TypeForbidden), "got %v", err)
assert.Equal(t, !testCase.notFound && !testCase.forbidden, errors.Ast(err, errors.TypeInvalidInput), "got %v", err)
})
}
}
func TestProviderWithProfile(t *testing.T) {
conn, err := cmock.NewClickHouseWithQueryMatcher(&clickhouse.Options{}, sqlmock.QueryMatcherEqual)
require.NoError(t, err)
conn.ExpectClose()
profileConn, err := cmock.NewClickHouseWithQueryMatcher(&clickhouse.Options{}, sqlmock.QueryMatcherEqual)
require.NoError(t, err)
profileConn.ExpectClose()
p := &provider{clickHouseConn: conn, cluster: "cluster"}
withProfiles(p, map[string]clickhouse.Conn{"clickhouse_query": profileConn})
profiled, ok := p.WithProfile("clickhouse_query").(*provider)
require.True(t, ok)
assert.NotSame(t, p, profiled)
assert.Equal(t, "clickhouse_query", profiled.profile)
assert.Same(t, profileConn, profiled.clickHouseConn)
assert.Same(t, conn, p.clickHouseConn)
assert.Equal(t, "cluster", profiled.Cluster())
assert.Empty(t, p.profile)
assert.Same(t, p, p.WithProfile("query_range"))
assert.Same(t, profiled, profiled.WithProfile("clickhouse_query"))
require.NoError(t, profiled.Close())
require.NoError(t, p.Close())
assert.NoError(t, conn.ExpectationsWereMet())
assert.NoError(t, profileConn.ExpectationsWereMet())
}

View File

@@ -37,6 +37,15 @@ type ClickhouseConfig struct {
// QuerySettings is the query settings for clickhouse.
QuerySettings QuerySettings `mapstructure:"settings"`
// Profiles are the stores TelemetryStore.WithProfile returns, by name. Each runs its queries as the
// ClickHouse user in its DSN, under that user's settings profile and grants.
Profiles map[string]ProfileConfig `mapstructure:"profiles"`
}
type ProfileConfig struct {
// DSN is the database source name of the ClickHouse user the profile's queries run as.
DSN string `mapstructure:"dsn"`
}
type QuerySettings struct {

View File

@@ -11,6 +11,10 @@ type TelemetryStore interface {
// ClickhouseDB returns the clickhouse connection, which can also EXPLAIN.
ClickhouseDB() clickhouse.Conn
// WithProfile returns a store that runs every query as the profile's ClickHouse user, or this store when
// the profile is not in the config.
WithProfile(profile string) TelemetryStore
// Cluster returns the cluster name.
Cluster() string

View File

@@ -4,6 +4,7 @@ import (
"context"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/types/ctxtypes"
@@ -25,33 +26,33 @@ func NewSettings(ctx context.Context, providerSettings factory.ProviderSettings,
}, nil
}
func (h *provider) BeforeQuery(ctx context.Context, _ *telemetrystore.QueryEvent) context.Context {
func (hook *provider) BeforeQuery(ctx context.Context, _ *telemetrystore.QueryEvent) context.Context {
settings := clickhouse.Settings{}
settings["log_comment"] = ctxtypes.CommentFromContext(ctx).String()
if ctx.Value("enforce_max_result_rows") != nil {
settings["max_result_rows"] = h.settings.MaxResultRows
settings["max_result_rows"] = hook.settings.MaxResultRows
}
if h.settings.MaxBytesToRead != 0 {
settings["max_bytes_to_read"] = h.settings.MaxBytesToRead
if hook.settings.MaxBytesToRead != 0 {
settings["max_bytes_to_read"] = hook.settings.MaxBytesToRead
}
if h.settings.MaxExecutionTime != 0 {
settings["max_execution_time"] = h.settings.MaxExecutionTime
if hook.settings.MaxExecutionTime != 0 {
settings["max_execution_time"] = hook.settings.MaxExecutionTime
}
if h.settings.MaxExecutionTimeLeaf != 0 {
settings["max_execution_time_leaf"] = h.settings.MaxExecutionTimeLeaf
if hook.settings.MaxExecutionTimeLeaf != 0 {
settings["max_execution_time_leaf"] = hook.settings.MaxExecutionTimeLeaf
}
if h.settings.TimeoutBeforeCheckingExecutionSpeed != 0 {
settings["timeout_before_checking_execution_speed"] = h.settings.TimeoutBeforeCheckingExecutionSpeed
if hook.settings.TimeoutBeforeCheckingExecutionSpeed != 0 {
settings["timeout_before_checking_execution_speed"] = hook.settings.TimeoutBeforeCheckingExecutionSpeed
}
if h.settings.IgnoreDataSkippingIndices != "" {
settings["ignore_data_skipping_indices"] = h.settings.IgnoreDataSkippingIndices
if hook.settings.IgnoreDataSkippingIndices != "" {
settings["ignore_data_skipping_indices"] = hook.settings.IgnoreDataSkippingIndices
}
if ctx.Value("clickhouse_max_threads") != nil {
@@ -76,4 +77,4 @@ func (h *provider) BeforeQuery(ctx context.Context, _ *telemetrystore.QueryEvent
return ctx
}
func (h *provider) AfterQuery(ctx context.Context, event *telemetrystore.QueryEvent) {}
func (hook *provider) AfterQuery(ctx context.Context, event *telemetrystore.QueryEvent) {}

View File

@@ -31,31 +31,36 @@ func New(_ telemetrystore.Config, matcher sqlmock.QueryMatcher) *Provider {
}
// ClickhouseDB returns the mock Clickhouse connection.
func (p *Provider) ClickhouseDB() clickhouse.Conn {
return p.clickhouseDB.(clickhouse.Conn)
func (provider *Provider) ClickhouseDB() clickhouse.Conn {
return provider.clickhouseDB.(clickhouse.Conn)
}
// WithProfile returns the same mock, so expectations set on it apply to profile queries.
func (provider *Provider) WithProfile(_ string) telemetrystore.TelemetryStore {
return provider
}
// Cluster returns the cluster name.
func (p *Provider) Cluster() string {
func (provider *Provider) Cluster() string {
return "cluster"
}
// Estimate runs EXPLAIN ESTIMATE against the mock connection.
func (p *Provider) Estimate(ctx context.Context, stmt string, args ...any) ([]telemetrystoretypes.EstimateEntry, error) {
return clickhousetelemetrystore.RunExplainEstimate(ctx, p.clickhouseDB.(clickhouse.Conn), stmt, args...)
func (provider *Provider) Estimate(ctx context.Context, stmt string, args ...any) ([]telemetrystoretypes.EstimateEntry, error) {
return clickhousetelemetrystore.RunExplainEstimate(ctx, provider.clickhouseDB.(clickhouse.Conn), stmt, args...)
}
// Plan runs EXPLAIN PLAN against the mock connection.
func (p *Provider) Plan(ctx context.Context, stmt string, args ...any) error {
return clickhousetelemetrystore.RunExplainPlan(ctx, p.clickhouseDB.(clickhouse.Conn), stmt, args...)
func (provider *Provider) Plan(ctx context.Context, stmt string, args ...any) error {
return clickhousetelemetrystore.RunExplainPlan(ctx, provider.clickhouseDB.(clickhouse.Conn), stmt, args...)
}
// Indexes runs EXPLAIN indexes against the mock connection.
func (p *Provider) Indexes(ctx context.Context, stmt string, args ...any) (telemetrystoretypes.Granules, bool, error) {
return clickhousetelemetrystore.RunExplainIndexes(ctx, p.clickhouseDB.(clickhouse.Conn), stmt, args...)
func (provider *Provider) Indexes(ctx context.Context, stmt string, args ...any) (telemetrystoretypes.Granules, bool, error) {
return clickhousetelemetrystore.RunExplainIndexes(ctx, provider.clickhouseDB.(clickhouse.Conn), stmt, args...)
}
// Mock returns the underlying Clickhouse mock instance for setting expectations.
func (p *Provider) Mock() cmock.ClickConnMockCommon {
return p.clickhouseDB
func (provider *Provider) Mock() cmock.ClickConnMockCommon {
return provider.clickhouseDB
}

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

@@ -71,7 +71,7 @@ type PostableRule struct {
RuleType RuleType `json:"ruleType" required:"true" description:"The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries."`
RuleCondition *RuleCondition `json:"condition" required:"true" description:"The query to evaluate and the thresholds applied to its result."`
Labels map[string]string `json:"labels,omitempty" description:"Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored."`
Labels map[string]string `json:"labels,omitempty" description:"Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label."`
Annotations map[string]string `json:"annotations,omitempty" description:"Free text attached to every alert, conventionally summary and description. Values may use Go templates with $value, $threshold and $labels."`
Disabled bool `json:"disabled" description:"Whether the rule is paused. A disabled rule is neither evaluated nor notifies. Defaults to false."`

View File

@@ -31,23 +31,6 @@ const (
AlertDescriptionLabel = "description"
)
// reservedLabelNames are written by the rule engine; a rule label with one of
// these names never reaches the alert.
var reservedLabelNames = map[string]struct{}{
MetricNameLabel: {},
TemporalityLabel: {},
AlertNameLabel: {},
AlertRuleIDLabel: {},
RuleSourceLabel: {},
NoDataLabel: {},
LabelThresholdName: {},
LabelSeverityName: {},
LabelLastSeen: {},
// TODO: the template layer reads is_recovering but nothing writes it;
// set it from Alert.IsRecovering.
LabelIsRecovering: {},
}
// Label is a key/value pair of strings.
// TODO(srikanthccv): https://github.com/SigNoz/signoz/issues/9232?
type Label struct {
@@ -302,20 +285,6 @@ func (b *Builder) Set(n, v string) *Builder {
return b
}
// SetRuleLabels adds the rule's labels, each expanded, skipping the names the
// engine writes.
// TODO: a rule label still overwrites a query result label of the same name;
// decide whether those are locked too.
func (b *Builder) SetRuleLabels(ruleLabels map[string]string, expand func(string) string) *Builder {
for name, value := range ruleLabels {
if _, reserved := reservedLabelNames[name]; reserved {
continue
}
b.Set(name, expand(value))
}
return b
}
// Labels returns the labels from the builder. If no modifications
// were made, the original labels are returned.
func (b *Builder) Labels() Labels {

View File

@@ -131,23 +131,14 @@ export interface Settings {
/** The member's table row. Search for the email first: the list pages at 20. */
row(email: string): Locator;
inviteButton(): Locator;
searchInput(): Locator;
resetLinkButton(): Locator;
/** The "is not authorized" message a denied list or drawer renders. */
deniedMessage(): Locator;
openInvite(): Promise<void>;
inviteDialog(): Locator;
invite(rows: { email: string; role: string }[]): Promise<void>;
openMember(email: string): Promise<void>;
drawer(): Locator;
nameInput(): Locator;
roleSelect(): Locator;
deleteButton(): Locator;
setRoles(roles: string[]): Promise<void>;
/** Add a role to the open member without clearing the others. */
addRole(role: string): Promise<void>;
/** Remove one role from the open member, leaving the others. */
removeRole(role: string): Promise<void>;
saveMember(): Promise<void>;
/** Mint a reset or invite link from the drawer and return it. */
generateLink(): Promise<string>;
@@ -423,9 +414,6 @@ export function settingsDriver(page: Page): Settings {
// antd keys each row by the member id; the email is what callers hold.
row: (email) => page.locator('tr[data-row-key]').filter({ hasText: email }),
inviteButton: () => page.getByTestId('invite-member-btn'),
searchInput: () => page.getByTestId('members-search-input'),
resetLinkButton: () => page.getByTestId('member-reset-link-btn'),
deniedMessage: () => page.getByText(/is not authorized/).first(),
openInvite: async () => {
await settings.members.inviteButton().click();
await expect(settings.members.inviteDialog()).toBeVisible();
@@ -461,7 +449,6 @@ export function settingsDriver(page: Page): Settings {
await expect(settings.members.drawer().getByText(email)).toBeVisible();
},
drawer: () => page.getByRole('dialog', { name: 'Member Details' }),
nameInput: () => page.getByPlaceholder('Enter name'),
roleSelect: () => selectById('member-role'),
deleteButton: () => page.getByTestId('member-delete-btn'),
setRoles: async (roles) => {
@@ -471,21 +458,6 @@ export function settingsDriver(page: Page): Settings {
await pickInDialog(settings.members.drawer(), select, role);
}
},
addRole: async (role) => {
await pickInDialog(
settings.members.drawer(),
settings.members.roleSelect(),
role,
);
},
removeRole: async (role) => {
await settings.members
.roleSelect()
.locator('.ant-select-selection-item')
.filter({ hasText: role })
.locator('.ant-select-selection-item-remove')
.click();
},
saveMember: async () => {
await page.getByTestId('member-save-btn').click();
await expect(

View File

@@ -1,7 +1,7 @@
import { withAuthFlows } from '../auth-flows';
import { guestDriver, kit, type Layer } from '../kit';
import { kit } from '../kit';
import { settingsDriver, withSettings, type Settings } from './driver';
import { withSettings } from './driver';
import {
withActiveEditor,
withCustomRoleSeed,
@@ -9,12 +9,6 @@ import {
withServiceAccountSeed,
} from './seeds';
/** The settings pages bound to the logged-out `guestPage`, for a signed-in member. */
const withGuestSettings: Layer<{ guestSettings: Settings }> = guestDriver(
'guestSettings',
({ page }) => settingsDriver(page),
);
/**
* The settings `test`. Seeds are test-scoped and lazy: a spec pays only for the
* ones it destructures. `authFlows` drives a guest context, for the flows that
@@ -22,10 +16,8 @@ const withGuestSettings: Layer<{ guestSettings: Settings }> = guestDriver(
*/
export const test = withAuthFlows(
withSettings(
withGuestSettings(
withActiveEditor(
withPendingMember(withServiceAccountSeed(withCustomRoleSeed(kit))),
),
withActiveEditor(
withPendingMember(withServiceAccountSeed(withCustomRoleSeed(kit))),
),
),
);

View File

@@ -1,11 +1,9 @@
import type { Browser, TestType } from '@playwright/test';
import type { User } from '../auth';
import type { AuthtypesTransactionGroupDTO } from '../schemas';
import { onAdminPage, type Layer } from '../kit';
import { usersApi, type CreatedUser } from '../users';
import { grantAll, roleName, settingsDriver, type Settings } from './driver';
import { grantAll, roleName, settingsDriver } from './driver';
/**
* Test-scoped seeds. Each test that asks for one gets its own copy, created on
@@ -125,40 +123,3 @@ export const withActiveEditor = perTest(
({ browser, value }) =>
onAdminPage(browser, (page) => usersApi(page).remove(value.id)),
);
export interface GrantedUser {
user: User;
role: string;
remove(): Promise<void>;
}
/**
* An active member whose only role is a fresh custom role holding
* `transactionGroups`. Call `remove` in a `finally`.
*/
export async function createGrantedUser(
settings: Settings,
workerIndex: number,
kind: string,
transactionGroups: AuthtypesTransactionGroupDTO[],
): Promise<GrantedUser> {
const name = roleName(kind, workerIndex);
const roleId = await settings.roles.createApi({ name, transactionGroups });
const label = `${kind}-w${workerIndex}-${Date.now()}`;
let member: CreatedUser;
try {
member = await settings.users.createActive(name, label);
} catch (error) {
await settings.users.removeByEmail(`e2e-${label}@signoz.test`);
await settings.roles.removeApi(roleId);
throw error;
}
return {
user: member.user,
role: name,
remove: async () => {
await settings.users.remove(member.id);
await settings.roles.removeApi(roleId);
},
};
}

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