Compare commits

..

6 Commits

Author SHA1 Message Date
SagarRajput-7
4de7d491a6 Merge branch 'main' into roles-details-page 2026-02-24 21:45:16 +05:30
SagarRajput-7
d2c3d21458 feat: made managed roles read only 2026-02-23 17:52:35 +05:30
SagarRajput-7
32afc485d1 feat: added permission detail side panel 2026-02-23 10:41:30 +05:30
SagarRajput-7
84d53001e6 feat: added empty state in members tab 2026-02-23 09:35:18 +05:30
SagarRajput-7
19420597de feat: added details page content 2026-02-23 09:33:39 +05:30
SagarRajput-7
2795b4f070 feat: added roles crud and details page 2026-02-23 07:09:04 +05:30
75 changed files with 3191 additions and 688 deletions

View File

@@ -54,7 +54,7 @@ jobs:
- sqlite
clickhouse-version:
- 25.5.6
- 25.12.5
- 25.10.5
schema-migrator-version:
- v0.142.0
postgres-version:

View File

@@ -26,7 +26,7 @@ import (
"github.com/SigNoz/signoz/pkg/query-service/utils/times"
"github.com/SigNoz/signoz/pkg/query-service/utils/timestamp"
"github.com/SigNoz/signoz/pkg/formatter"
"github.com/SigNoz/signoz/pkg/query-service/formatter"
baserules "github.com/SigNoz/signoz/pkg/query-service/rules"

View File

@@ -308,15 +308,3 @@ export const PublicDashboardPage = Loadable(
/* webpackChunkName: "Public Dashboard Page" */ 'pages/PublicDashboard'
),
);
export const AlertTypeSelectionPage = Loadable(
() =>
import(
/* webpackChunkName: "Alert Type Selection Page" */ 'pages/AlertTypeSelection'
),
);
export const MeterExplorerPage = Loadable(
() =>
import(/* webpackChunkName: "Meter Explorer Page" */ 'pages/MeterExplorer'),
);

View File

@@ -1,10 +1,12 @@
import { RouteProps } from 'react-router-dom';
import ROUTES from 'constants/routes';
import AlertTypeSelectionPage from 'pages/AlertTypeSelection';
import MessagingQueues from 'pages/MessagingQueues';
import MeterExplorer from 'pages/MeterExplorer';
import {
AlertHistory,
AlertOverview,
AlertTypeSelectionPage,
AllAlertChannels,
AllErrors,
ApiMonitoring,
@@ -27,8 +29,6 @@ import {
LogsExplorer,
LogsIndexToFields,
LogsSaveViews,
MessagingQueuesMainPage,
MeterExplorerPage,
MetricsExplorer,
OldLogsExplorer,
Onboarding,
@@ -399,28 +399,28 @@ const routes: AppRoutes[] = [
{
path: ROUTES.MESSAGING_QUEUES_KAFKA,
exact: true,
component: MessagingQueuesMainPage,
component: MessagingQueues,
key: 'MESSAGING_QUEUES_KAFKA',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_CELERY_TASK,
exact: true,
component: MessagingQueuesMainPage,
component: MessagingQueues,
key: 'MESSAGING_QUEUES_CELERY_TASK',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_OVERVIEW,
exact: true,
component: MessagingQueuesMainPage,
component: MessagingQueues,
key: 'MESSAGING_QUEUES_OVERVIEW',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_KAFKA_DETAIL,
exact: true,
component: MessagingQueuesMainPage,
component: MessagingQueues,
key: 'MESSAGING_QUEUES_KAFKA_DETAIL',
isPrivate: true,
},
@@ -463,21 +463,21 @@ const routes: AppRoutes[] = [
{
path: ROUTES.METER,
exact: true,
component: MeterExplorerPage,
component: MeterExplorer,
key: 'METER',
isPrivate: true,
},
{
path: ROUTES.METER_EXPLORER,
exact: true,
component: MeterExplorerPage,
component: MeterExplorer,
key: 'METER_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.METER_EXPLORER_VIEWS,
exact: true,
component: MeterExplorerPage,
component: MeterExplorer,
key: 'METER_EXPLORER_VIEWS',
isPrivate: true,
},

View File

@@ -1,5 +1,4 @@
import { YAxisCategoryNames } from '../constants';
import { UniversalYAxisUnit, YAxisCategory } from '../types';
import { UniversalYAxisUnit } from '../types';
import {
getUniversalNameFromMetricUnit,
mapMetricUnitToUniversalUnit,
@@ -42,29 +41,29 @@ describe('YAxisUnitSelector utils', () => {
describe('mergeCategories', () => {
it('merges categories correctly', () => {
const categories1: YAxisCategory[] = [
const categories1 = [
{
name: YAxisCategoryNames.Data,
name: 'Data',
units: [
{ name: 'bytes', id: UniversalYAxisUnit.BYTES },
{ name: 'kilobytes', id: UniversalYAxisUnit.KILOBYTES },
],
},
];
const categories2: YAxisCategory[] = [
const categories2 = [
{
name: YAxisCategoryNames.Data,
name: 'Data',
units: [{ name: 'bits', id: UniversalYAxisUnit.BITS }],
},
{
name: YAxisCategoryNames.Time,
name: 'Time',
units: [{ name: 'seconds', id: UniversalYAxisUnit.SECONDS }],
},
];
const mergedCategories = mergeCategories(categories1, categories2);
expect(mergedCategories).toEqual([
{
name: YAxisCategoryNames.Data,
name: 'Data',
units: [
{ name: 'bytes', id: UniversalYAxisUnit.BYTES },
{ name: 'kilobytes', id: UniversalYAxisUnit.KILOBYTES },
@@ -72,7 +71,7 @@ describe('YAxisUnitSelector utils', () => {
],
},
{
name: YAxisCategoryNames.Time,
name: 'Time',
units: [{ name: 'seconds', id: UniversalYAxisUnit.SECONDS }],
},
]);

View File

@@ -1,36 +1,5 @@
import { UnitFamilyConfig, UniversalYAxisUnit, YAxisUnit } from './types';
export enum YAxisCategoryNames {
Time = 'Time',
Data = 'Data',
DataRate = 'Data Rate',
Count = 'Count',
Operations = 'Operations',
Percentage = 'Percentage',
Boolean = 'Boolean',
None = 'None',
HashRate = 'Hash Rate',
Miscellaneous = 'Miscellaneous',
Acceleration = 'Acceleration',
Angular = 'Angular',
Area = 'Area',
Flops = 'FLOPs',
Concentration = 'Concentration',
Currency = 'Currency',
Datetime = 'Datetime',
PowerElectrical = 'Power/Electrical',
Flow = 'Flow',
Force = 'Force',
Mass = 'Mass',
Length = 'Length',
Pressure = 'Pressure',
Radiation = 'Radiation',
RotationSpeed = 'Rotation Speed',
Temperature = 'Temperature',
Velocity = 'Velocity',
Volume = 'Volume',
}
// Mapping of universal y-axis units to their AWS, UCUM, and OpenMetrics equivalents (if available)
export const UniversalYAxisUnitMappings: Partial<
Record<UniversalYAxisUnit, Set<YAxisUnit> | null>

View File

@@ -1,11 +1,10 @@
import { Y_AXIS_UNIT_NAMES } from './constants';
import { YAxisCategoryNames } from './constants';
import { UniversalYAxisUnit, YAxisCategory } from './types';
// Base categories for the universal y-axis units
export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
{
name: YAxisCategoryNames.Time,
name: 'Time',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.SECONDS],
@@ -38,7 +37,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Data,
name: 'Data',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.BYTES],
@@ -155,7 +154,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.DataRate,
name: 'Data Rate',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.BYTES_SECOND],
@@ -296,7 +295,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Count,
name: 'Count',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.COUNT],
@@ -313,7 +312,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Operations,
name: 'Operations',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.OPS_SECOND],
@@ -354,7 +353,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Percentage,
name: 'Percentage',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.PERCENT],
@@ -367,7 +366,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Boolean,
name: 'Boolean',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.TRUE_FALSE],
@@ -383,7 +382,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
{
name: YAxisCategoryNames.Time,
name: 'Time',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.DURATION_MS],
@@ -420,7 +419,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.DataRate,
name: 'Data Rate',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.DATA_RATE_PACKETS_PER_SECOND],
@@ -429,7 +428,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Boolean,
name: 'Boolean',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.ON_OFF],
@@ -438,7 +437,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.None,
name: 'None',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.NONE],
@@ -447,7 +446,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.HashRate,
name: 'Hash Rate',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.HASH_RATE_HASHES_PER_SECOND],
@@ -480,7 +479,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Miscellaneous,
name: 'Miscellaneous',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.MISC_STRING],
@@ -521,7 +520,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Acceleration,
name: 'Acceleration',
units: [
{
name:
@@ -542,7 +541,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Angular,
name: 'Angular',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.ANGULAR_DEGREE],
@@ -567,7 +566,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Area,
name: 'Area',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.AREA_SQUARE_METERS],
@@ -584,7 +583,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Flops,
name: 'FLOPs',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.FLOPS_FLOPS],
@@ -621,7 +620,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Concentration,
name: 'Concentration',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.CONCENTRATION_PPM],
@@ -678,7 +677,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Currency,
name: 'Currency',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.CURRENCY_USD],
@@ -775,7 +774,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Datetime,
name: 'Datetime',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.DATETIME_ISO],
@@ -812,7 +811,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.PowerElectrical,
name: 'Power/Electrical',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.POWER_WATT],
@@ -969,7 +968,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Flow,
name: 'Flow',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.FLOW_GALLONS_PER_MINUTE],
@@ -1006,7 +1005,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Force,
name: 'Force',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.FORCE_NEWTON_METERS],
@@ -1027,7 +1026,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Mass,
name: 'Mass',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.MASS_MILLIGRAM],
@@ -1052,7 +1051,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Length,
name: 'Length',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.LENGTH_MILLIMETER],
@@ -1081,7 +1080,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Pressure,
name: 'Pressure',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.PRESSURE_MILLIBAR],
@@ -1118,7 +1117,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Radiation,
name: 'Radiation',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.RADIATION_BECQUEREL],
@@ -1175,7 +1174,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.RotationSpeed,
name: 'Rotation Speed',
units: [
{
name:
@@ -1201,7 +1200,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Temperature,
name: 'Temperature',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.TEMPERATURE_CELSIUS],
@@ -1218,7 +1217,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Velocity,
name: 'Velocity',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.VELOCITY_METERS_PER_SECOND],
@@ -1239,7 +1238,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Volume,
name: 'Volume',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.VOLUME_MILLILITER],

View File

@@ -1,5 +1,3 @@
import { YAxisCategoryNames } from './constants';
export interface YAxisUnitSelectorProps {
value: string | undefined;
onChange: (value: UniversalYAxisUnit) => void;
@@ -671,7 +669,7 @@ export interface UnitFamilyConfig {
}
export interface YAxisCategory {
name: YAxisCategoryNames;
name: string;
units: {
name: string;
id: UniversalYAxisUnit;

View File

@@ -56,6 +56,7 @@ const ROUTES = {
TRACE_EXPLORER: '/trace-explorer',
BILLING: '/settings/billing',
ROLES_SETTINGS: '/settings/roles',
ROLE_DETAILS: '/settings/roles/:roleId',
SUPPORT: '/support',
LOGS_SAVE_VIEWS: '/logs/saved-views',
TRACES_SAVE_VIEWS: '/traces/saved-views',

View File

@@ -172,51 +172,23 @@ function ExplorerOptions({
const { user } = useAppContext();
const handleConditionalQueryModification = useCallback(
// eslint-disable-next-line sonarjs/cognitive-complexity
(defaultQuery: Query | null): string => {
const queryToUse = defaultQuery || query;
if (!queryToUse) {
throw new Error('No query provided');
}
if (
queryToUse?.builder?.queryData?.[0]?.aggregateOperator !==
StringOperators.NOOP &&
sourcepage !== DataSource.LOGS
StringOperators.NOOP
) {
return JSON.stringify(queryToUse);
}
// Convert NOOP to COUNT for alerts and strip orderBy for logs
// Modify aggregateOperator to count, as noop is not supported in alerts
const modifiedQuery = cloneDeep(queryToUse);
if (modifiedQuery && modifiedQuery.builder?.queryData) {
modifiedQuery.builder.queryData = modifiedQuery.builder.queryData.map(
(item) => {
const updatedItem = { ...item };
if (updatedItem.aggregateOperator === StringOperators.NOOP) {
updatedItem.aggregateOperator = StringOperators.COUNT;
}
modifiedQuery.builder.queryData[0].aggregateOperator = StringOperators.COUNT;
// Alerts do not support order by on logs explorer queries
if (sourcepage === DataSource.LOGS && panelType === PANEL_TYPES.LIST) {
updatedItem.orderBy = [];
}
return updatedItem;
},
);
}
try {
return JSON.stringify(modifiedQuery);
} catch (err) {
throw new Error(
'Failed to stringify modified query: ' +
(err instanceof Error ? err.message : String(err)),
);
}
return JSON.stringify(modifiedQuery);
},
[panelType, query, sourcepage],
[query],
);
const onCreateAlertsHandler = useCallback(
@@ -785,9 +757,9 @@ function ExplorerOptions({
);
}, [
disabled,
query,
isOneChartPerQuery,
onCreateAlertsHandler,
query,
splitedQueries,
]);

View File

@@ -1,4 +1,3 @@
import { useHistory } from 'react-router-dom';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { MOCK_QUERY } from 'container/QueryTable/Drilldown/__tests__/mockTableData';
import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
@@ -16,11 +15,6 @@ import { getExplorerToolBarVisibility } from '../utils';
// Mock dependencies
jest.mock('hooks/dashboard/useUpdateDashboard');
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: jest.fn(),
}));
jest.mock('../utils', () => ({
getExplorerToolBarVisibility: jest.fn(),
generateRGBAFromHex: jest.fn(() => 'rgba(0, 0, 0, 0.08)'),
@@ -35,7 +29,6 @@ const mockGetExplorerToolBarVisibility = jest.mocked(
);
const mockUseUpdateDashboard = jest.mocked(useUpdateDashboard);
const mockUseHistory = jest.mocked(useHistory);
// Mock data
const TEST_QUERY_ID = 'test-query-id';
@@ -110,6 +103,7 @@ describe('ExplorerOptionWrapper', () => {
beforeEach(() => {
jest.clearAllMocks();
mockGetExplorerToolBarVisibility.mockReturnValue(true);
// Mock useUpdateDashboard to return a mutation object
mockUseUpdateDashboard.mockReturnValue(({
mutate: jest.fn(),
@@ -123,28 +117,6 @@ describe('ExplorerOptionWrapper', () => {
} as unknown) as ReturnType<typeof useUpdateDashboard>);
});
it('should navigate to alert creation page when "Create an Alert" is clicked in logs-explorer', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockPush = jest.fn();
mockUseHistory.mockReturnValue(({
push: mockPush,
} as unknown) as ReturnType<typeof useHistory>);
renderExplorerOptionWrapper({ sourcepage: DataSource.LOGS });
const createAlertButton = screen.getByRole('button', {
name: 'Create an Alert',
});
await user.click(createAlertButton);
expect(mockPush).toHaveBeenCalledTimes(1);
const calledWith = mockPush.mock.calls[0][0] as string;
const [path, search = ''] = calledWith.split('?');
expect(path).toBe('/alerts/new');
const params = new URLSearchParams(search);
expect(params.has('compositeQuery')).toBe(true);
});
describe('onExport functionality', () => {
it('should call onExport when New Dashboard button is clicked in export modal', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });

View File

@@ -18,8 +18,8 @@ jest.mock('lib/query/createTableColumnsFromQuery', () => ({
jest.mock('container/NewWidget/utils', () => ({
unitOptions: jest.fn(() => [
{ value: 'none', label: 'None' },
{ value: '%', label: 'Percent (0 - 100)' },
{ value: 'ms', label: 'Milliseconds (ms)' },
{ value: 'percent', label: 'Percent' },
{ value: 'ms', label: 'Milliseconds' },
]),
}));
@@ -39,7 +39,7 @@ const defaultProps = {
],
thresholdTableOptions: 'cpu_usage',
columnUnits: { cpu_usage: 'percent', memory_usage: 'bytes' },
yAxisUnit: '%',
yAxisUnit: 'percent',
moveThreshold: jest.fn(),
};

View File

@@ -0,0 +1,99 @@
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { AutoComplete, Input, Typography } from 'antd';
import { find } from 'lodash-es';
import { flattenedCategories } from './dataFormatCategories';
const findCategoryById = (
searchValue: string,
): Record<string, string> | undefined =>
find(flattenedCategories, (option) => option.id === searchValue);
const findCategoryByName = (
searchValue: string,
): Record<string, string> | undefined =>
find(flattenedCategories, (option) => option.name === searchValue);
type OnSelectType = Dispatch<SetStateAction<string>> | ((val: string) => void);
/**
* @deprecated Use DashboardYAxisUnitSelectorWrapper instead.
*/
function YAxisUnitSelector({
value,
onSelect,
fieldLabel,
handleClear,
}: {
value: string;
onSelect: OnSelectType;
fieldLabel: string;
handleClear?: () => void;
}): JSX.Element {
const [inputValue, setInputValue] = useState('');
// Sync input value with the actual value prop
useEffect(() => {
const category = findCategoryById(value);
setInputValue(category?.name || '');
}, [value]);
const onSelectHandler = (selectedValue: string): void => {
const category = findCategoryByName(selectedValue);
if (category) {
onSelect(category.id);
setInputValue(selectedValue);
}
};
const onChangeHandler = (inputValue: string): void => {
setInputValue(inputValue);
// Clear the yAxisUnit if input is empty or doesn't match any option
if (!inputValue) {
onSelect('');
}
};
const onClearHandler = (): void => {
setInputValue('');
onSelect('');
if (handleClear) {
handleClear();
}
};
const options = flattenedCategories.map((options) => ({
value: options.name,
}));
return (
<div className="y-axis-unit-selector">
<Typography.Text className="heading">{fieldLabel}</Typography.Text>
<AutoComplete
style={{ width: '100%' }}
rootClassName="y-axis-root-popover"
options={options}
allowClear
value={inputValue}
onChange={onChangeHandler}
onClear={onClearHandler}
onSelect={onSelectHandler}
filterOption={(inputValue, option): boolean => {
if (option) {
return (
option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
);
}
return false;
}}
>
<Input placeholder="Unit" rootClassName="input" />
</AutoComplete>
</div>
);
}
export default YAxisUnitSelector;
YAxisUnitSelector.defaultProps = {
handleClear: (): void => {},
};

View File

@@ -0,0 +1,240 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { act } from 'react-dom/test-utils';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import YAxisUnitSelector from '../YAxisUnitSelector';
// Mock the dataFormatCategories to have predictable test data
jest.mock('../dataFormatCategories', () => ({
flattenedCategories: [
{ id: 'seconds', name: 'seconds (s)' },
{ id: 'milliseconds', name: 'milliseconds (ms)' },
{ id: 'hours', name: 'hours (h)' },
{ id: 'minutes', name: 'minutes (m)' },
],
}));
const MOCK_SECONDS = 'seconds';
const MOCK_MILLISECONDS = 'milliseconds';
describe('YAxisUnitSelector', () => {
const defaultProps = {
value: MOCK_SECONDS,
onSelect: jest.fn(),
fieldLabel: 'Y Axis Unit',
handleClear: jest.fn(),
};
let user: ReturnType<typeof userEvent.setup>;
beforeEach(() => {
jest.clearAllMocks();
user = userEvent.setup();
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('Rendering (Read) & (write)', () => {
it('renders with correct field label', () => {
render(
<YAxisUnitSelector
value={defaultProps.value}
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
expect(screen.getByText('Y Axis Unit')).toBeInTheDocument();
const input = screen.getByRole('combobox');
expect(input).toHaveValue('seconds (s)');
});
it('renders with custom field label', () => {
render(
<YAxisUnitSelector
value={defaultProps.value}
onSelect={defaultProps.onSelect}
fieldLabel="Custom Unit Label"
handleClear={defaultProps.handleClear}
/>,
);
expect(screen.getByText('Custom Unit Label')).toBeInTheDocument();
});
it('displays empty input when value prop is empty', () => {
render(
<YAxisUnitSelector
value=""
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
expect(screen.getByDisplayValue('')).toBeInTheDocument();
});
it('shows placeholder text', () => {
render(
<YAxisUnitSelector
value={defaultProps.value}
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
expect(screen.getByPlaceholderText('Unit')).toBeInTheDocument();
});
it('handles numeric input', async () => {
render(
<YAxisUnitSelector
value={defaultProps.value}
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
const input = screen.getByRole('combobox');
await user.clear(input);
await user.type(input, '12345');
expect(input).toHaveValue('12345');
});
it('handles mixed content input', async () => {
render(
<YAxisUnitSelector
value={defaultProps.value}
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
const input = screen.getByRole('combobox');
await user.clear(input);
await user.type(input, 'Test123!@#');
expect(input).toHaveValue('Test123!@#');
});
});
describe('State Management', () => {
it('syncs input value with value prop changes', async () => {
const { rerender } = render(
<YAxisUnitSelector
value={defaultProps.value}
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
const input = screen.getByRole('combobox');
// Initial value
expect(input).toHaveValue('seconds (s)');
// Change value prop
rerender(
<YAxisUnitSelector
value={MOCK_MILLISECONDS}
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
await waitFor(() => {
expect(input).toHaveValue('milliseconds (ms)');
});
});
it('handles empty value prop correctly', async () => {
const { rerender } = render(
<YAxisUnitSelector
value={defaultProps.value}
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
const input = screen.getByRole('combobox');
// Change to empty value
rerender(
<YAxisUnitSelector
value=""
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
await waitFor(() => {
expect(input).toHaveValue('');
});
});
it('handles invalid value prop gracefully', async () => {
const { rerender } = render(
<YAxisUnitSelector
value={defaultProps.value}
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
const input = screen.getByRole('combobox');
// Change to invalid value
rerender(
<YAxisUnitSelector
value="invalid_id"
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
await waitFor(() => {
expect(input).toHaveValue('');
});
});
it('maintains local state during typing', async () => {
render(
<YAxisUnitSelector
value={defaultProps.value}
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
const input = screen.getByRole('combobox');
// first clear then type
await user.clear(input);
await user.type(input, 'test');
expect(input).toHaveValue('test');
// Value prop change should not override local typing
await act(async () => {
// Simulate prop change
render(
<YAxisUnitSelector
value="bytes"
onSelect={defaultProps.onSelect}
fieldLabel={defaultProps.fieldLabel}
handleClear={defaultProps.handleClear}
/>,
);
});
// Local typing should be preserved
expect(input).toHaveValue('test');
});
});
});

View File

@@ -1,53 +1,613 @@
import { flattenDeep } from 'lodash-es';
import {
UniversalUnitToGrafanaUnit,
YAxisCategoryNames,
} from 'components/YAxisUnitSelector/constants';
import { YAxisSource } from 'components/YAxisUnitSelector/types';
import { getYAxisCategories } from 'components/YAxisUnitSelector/utils';
import { convertValue } from 'lib/getConvertedValue';
AccelerationFormats,
AngularFormats,
AreaFormats,
BooleanFormats,
CategoryNames,
ConcentrationFormats,
CurrencyFormats,
DataFormats,
DataRateFormats,
DataTypeCategories,
DatetimeFormats,
FlopsFormats,
FlowFormats,
ForceFormats,
HashRateFormats,
LengthFormats,
MassFormats,
MiscellaneousFormats,
PowerElectricalFormats,
PressureFormats,
RadiationFormats,
RotationSpeedFormats,
TemperatureFormats,
ThroughputFormats,
TimeFormats,
VelocityFormats,
VolumeFormats,
} from './types';
// Function to get the category name for a given unit ID (Grafana or universal)
export const getCategoryName = (unitId: string): YAxisCategoryNames | null => {
const categories = getYAxisCategories(YAxisSource.DASHBOARDS);
export const dataTypeCategories: DataTypeCategories = [
{
name: CategoryNames.Time,
formats: [
{ name: 'Hertz (1/s)', id: TimeFormats.Hertz },
{ name: 'nanoseconds (ns)', id: TimeFormats.Nanoseconds },
{ name: 'microseconds (µs)', id: TimeFormats.Microseconds },
{ name: 'milliseconds (ms)', id: TimeFormats.Milliseconds },
{ name: 'seconds (s)', id: TimeFormats.Seconds },
{ name: 'minutes (m)', id: TimeFormats.Minutes },
{ name: 'hours (h)', id: TimeFormats.Hours },
{ name: 'days (d)', id: TimeFormats.Days },
{ name: 'duration in ms (dtdurationms)', id: TimeFormats.DurationMs },
{ name: 'duration in s (dtdurations)', id: TimeFormats.DurationS },
{ name: 'duration in h:m:s (dthms)', id: TimeFormats.DurationHms },
{ name: 'duration in d:h:m:s (dtdhms)', id: TimeFormats.DurationDhms },
{ name: 'timeticks (timeticks)', id: TimeFormats.Timeticks },
{ name: 'clock in ms (clockms)', id: TimeFormats.ClockMs },
{ name: 'clock in s (clocks)', id: TimeFormats.ClockS },
],
},
{
name: CategoryNames.Throughput,
formats: [
{ name: 'counts/sec (cps)', id: ThroughputFormats.CountsPerSec },
{ name: 'ops/sec (ops)', id: ThroughputFormats.OpsPerSec },
{ name: 'requests/sec (reqps)', id: ThroughputFormats.RequestsPerSec },
{ name: 'reads/sec (rps)', id: ThroughputFormats.ReadsPerSec },
{ name: 'writes/sec (wps)', id: ThroughputFormats.WritesPerSec },
{ name: 'I/O operations/sec (iops)', id: ThroughputFormats.IOOpsPerSec },
{ name: 'counts/min (cpm)', id: ThroughputFormats.CountsPerMin },
{ name: 'ops/min (opm)', id: ThroughputFormats.OpsPerMin },
{ name: 'reads/min (rpm)', id: ThroughputFormats.ReadsPerMin },
{ name: 'writes/min (wpm)', id: ThroughputFormats.WritesPerMin },
],
},
{
name: CategoryNames.Data,
formats: [
{ name: 'bytes(IEC)', id: DataFormats.BytesIEC },
{ name: 'bytes(SI)', id: DataFormats.BytesSI },
{ name: 'bits(IEC)', id: DataFormats.BitsIEC },
{ name: 'bits(SI)', id: DataFormats.BitsSI },
{ name: 'kibibytes', id: DataFormats.KibiBytes },
{ name: 'kilobytes', id: DataFormats.KiloBytes },
{ name: 'mebibytes', id: DataFormats.MebiBytes },
{ name: 'megabytes', id: DataFormats.MegaBytes },
{ name: 'gibibytes', id: DataFormats.GibiBytes },
{ name: 'gigabytes', id: DataFormats.GigaBytes },
{ name: 'tebibytes', id: DataFormats.TebiBytes },
{ name: 'terabytes', id: DataFormats.TeraBytes },
{ name: 'pebibytes', id: DataFormats.PebiBytes },
{ name: 'petabytes', id: DataFormats.PetaBytes },
],
},
{
name: CategoryNames.DataRate,
formats: [
{ name: 'packets/sec', id: DataRateFormats.PacketsPerSec },
{ name: 'bytes/sec(IEC)', id: DataRateFormats.BytesPerSecIEC },
{ name: 'bytes/sec(SI)', id: DataRateFormats.BytesPerSecSI },
{ name: 'bits/sec(IEC)', id: DataRateFormats.BitsPerSecIEC },
{ name: 'bits/sec(SI)', id: DataRateFormats.BitsPerSecSI },
{ name: 'kibibytes/sec', id: DataRateFormats.KibiBytesPerSec },
{ name: 'kibibits/sec', id: DataRateFormats.KibiBitsPerSec },
{ name: 'kilobytes/sec', id: DataRateFormats.KiloBytesPerSec },
{ name: 'kilobits/sec', id: DataRateFormats.KiloBitsPerSec },
{ name: 'mebibytes/sec', id: DataRateFormats.MebiBytesPerSec },
{ name: 'mebibits/sec', id: DataRateFormats.MebiBitsPerSec },
{ name: 'megabytes/sec', id: DataRateFormats.MegaBytesPerSec },
{ name: 'megabits/sec', id: DataRateFormats.MegaBitsPerSec },
{ name: 'gibibytes/sec', id: DataRateFormats.GibiBytesPerSec },
{ name: 'gibibits/sec', id: DataRateFormats.GibiBitsPerSec },
{ name: 'gigabytes/sec', id: DataRateFormats.GigaBytesPerSec },
{ name: 'gigabits/sec', id: DataRateFormats.GigaBitsPerSec },
{ name: 'tebibytes/sec', id: DataRateFormats.TebiBytesPerSec },
{ name: 'tebibits/sec', id: DataRateFormats.TebiBitsPerSec },
{ name: 'terabytes/sec', id: DataRateFormats.TeraBytesPerSec },
{ name: 'terabits/sec', id: DataRateFormats.TeraBitsPerSec },
{ name: 'pebibytes/sec', id: DataRateFormats.PebiBytesPerSec },
{ name: 'pebibits/sec', id: DataRateFormats.PebiBitsPerSec },
{ name: 'petabytes/sec', id: DataRateFormats.PetaBytesPerSec },
{ name: 'petabits/sec', id: DataRateFormats.PetaBitsPerSec },
],
},
{
name: CategoryNames.HashRate,
formats: [
{ name: 'hashes/sec', id: HashRateFormats.HashesPerSec },
{ name: 'kilohashes/sec', id: HashRateFormats.KiloHashesPerSec },
{ name: 'megahashes/sec', id: HashRateFormats.MegaHashesPerSec },
{ name: 'gigahashes/sec', id: HashRateFormats.GigaHashesPerSec },
{ name: 'terahashes/sec', id: HashRateFormats.TeraHashesPerSec },
{ name: 'petahashes/sec', id: HashRateFormats.PetaHashesPerSec },
{ name: 'exahashes/sec', id: HashRateFormats.ExaHashesPerSec },
],
},
{
name: CategoryNames.Miscellaneous,
formats: [
{ name: 'none', id: MiscellaneousFormats.None },
{ name: 'String', id: MiscellaneousFormats.String },
{ name: 'short', id: MiscellaneousFormats.Short },
{ name: 'Percent (0-100)', id: MiscellaneousFormats.Percent },
{ name: 'Percent (0.0-1.0)', id: MiscellaneousFormats.PercentUnit },
{ name: 'Humidity (%H)', id: MiscellaneousFormats.Humidity },
{ name: 'Decibel', id: MiscellaneousFormats.Decibel },
{ name: 'Hexadecimal (0x)', id: MiscellaneousFormats.Hexadecimal0x },
{ name: 'Hexadecimal', id: MiscellaneousFormats.Hexadecimal },
{ name: 'Scientific notation', id: MiscellaneousFormats.ScientificNotation },
{ name: 'Locale format', id: MiscellaneousFormats.LocaleFormat },
{ name: 'Pixels', id: MiscellaneousFormats.Pixels },
],
},
{
name: CategoryNames.Acceleration,
formats: [
{ name: 'Meters/sec²', id: AccelerationFormats.MetersPerSecondSquared },
{ name: 'Feet/sec²', id: AccelerationFormats.FeetPerSecondSquared },
{ name: 'G unit', id: AccelerationFormats.GUnit },
],
},
{
name: CategoryNames.Angle,
formats: [
{ name: 'Degrees (°)', id: AngularFormats.Degree },
{ name: 'Radians', id: AngularFormats.Radian },
{ name: 'Gradian', id: AngularFormats.Gradian },
{ name: 'Arc Minutes', id: AngularFormats.ArcMinute },
{ name: 'Arc Seconds', id: AngularFormats.ArcSecond },
],
},
{
name: CategoryNames.Area,
formats: [
{ name: 'Square Meters (m²)', id: AreaFormats.SquareMeters },
{ name: 'Square Feet (ft²)', id: AreaFormats.SquareFeet },
{ name: 'Square Miles (mi²)', id: AreaFormats.SquareMiles },
],
},
{
name: CategoryNames.Computation,
formats: [
{ name: 'FLOP/s', id: FlopsFormats.FLOPs },
{ name: 'MFLOP/s', id: FlopsFormats.MFLOPs },
{ name: 'GFLOP/s', id: FlopsFormats.GFLOPs },
{ name: 'TFLOP/s', id: FlopsFormats.TFLOPs },
{ name: 'PFLOP/s', id: FlopsFormats.PFLOPs },
{ name: 'EFLOP/s', id: FlopsFormats.EFLOPs },
{ name: 'ZFLOP/s', id: FlopsFormats.ZFLOPs },
{ name: 'YFLOP/s', id: FlopsFormats.YFLOPs },
],
},
{
name: CategoryNames.Concentration,
formats: [
{ name: 'parts-per-million (ppm)', id: ConcentrationFormats.PPM },
{ name: 'parts-per-billion (ppb)', id: ConcentrationFormats.PPB },
{ name: 'nanogram per cubic meter (ng/m³)', id: ConcentrationFormats.NgM3 },
{
name: 'nanogram per normal cubic meter (ng/Nm³)',
id: ConcentrationFormats.NgNM3,
},
{ name: 'microgram per cubic meter (μg/m³)', id: ConcentrationFormats.UgM3 },
{
name: 'microgram per normal cubic meter (μg/Nm³)',
id: ConcentrationFormats.UgNM3,
},
{ name: 'milligram per cubic meter (mg/m³)', id: ConcentrationFormats.MgM3 },
{
name: 'milligram per normal cubic meter (mg/Nm³)',
id: ConcentrationFormats.MgNM3,
},
{ name: 'gram per cubic meter (g/m³)', id: ConcentrationFormats.GM3 },
{
name: 'gram per normal cubic meter (g/Nm³)',
id: ConcentrationFormats.GNM3,
},
{ name: 'milligrams per decilitre (mg/dL)', id: ConcentrationFormats.MgDL },
{ name: 'millimoles per litre (mmol/L)', id: ConcentrationFormats.MmolL },
],
},
{
name: CategoryNames.Currency,
formats: [
{ name: 'Dollars ($)', id: CurrencyFormats.USD },
{ name: 'Pounds (£)', id: CurrencyFormats.GBP },
{ name: 'Euro (€)', id: CurrencyFormats.EUR },
{ name: 'Yen (¥)', id: CurrencyFormats.JPY },
{ name: 'Rubles (₽)', id: CurrencyFormats.RUB },
{ name: 'Hryvnias (₴)', id: CurrencyFormats.UAH },
{ name: 'Real (R$)', id: CurrencyFormats.BRL },
{ name: 'Danish Krone (kr)', id: CurrencyFormats.DKK },
{ name: 'Icelandic Króna (kr)', id: CurrencyFormats.ISK },
{ name: 'Norwegian Krone (kr)', id: CurrencyFormats.NOK },
{ name: 'Swedish Krona (kr)', id: CurrencyFormats.SEK },
{ name: 'Czech koruna (czk)', id: CurrencyFormats.CZK },
{ name: 'Swiss franc (CHF)', id: CurrencyFormats.CHF },
{ name: 'Polish Złoty (PLN)', id: CurrencyFormats.PLN },
{ name: 'Bitcoin (฿)', id: CurrencyFormats.BTC },
{ name: 'Milli Bitcoin (฿)', id: CurrencyFormats.MBTC },
{ name: 'Micro Bitcoin (฿)', id: CurrencyFormats.UBTC },
{ name: 'South African Rand (R)', id: CurrencyFormats.ZAR },
{ name: 'Indian Rupee (₹)', id: CurrencyFormats.INR },
{ name: 'South Korean Won (₩)', id: CurrencyFormats.KRW },
{ name: 'Indonesian Rupiah (Rp)', id: CurrencyFormats.IDR },
{ name: 'Philippine Peso (PHP)', id: CurrencyFormats.PHP },
{ name: 'Vietnamese Dong (VND)', id: CurrencyFormats.VND },
],
},
{
name: CategoryNames.Datetime,
formats: [
{ name: 'Datetime ISO', id: DatetimeFormats.ISO },
{
name: 'Datetime ISO (No date if today)',
id: DatetimeFormats.ISONoDateIfToday,
},
{ name: 'Datetime US', id: DatetimeFormats.US },
{
name: 'Datetime US (No date if today)',
id: DatetimeFormats.USNoDateIfToday,
},
{ name: 'Datetime local', id: DatetimeFormats.Local },
{
name: 'Datetime local (No date if today)',
id: DatetimeFormats.LocalNoDateIfToday,
},
{ name: 'Datetime default', id: DatetimeFormats.System },
{ name: 'From Now', id: DatetimeFormats.FromNow },
],
},
{
name: CategoryNames.Energy,
formats: [
{ name: 'Watt (W)', id: PowerElectricalFormats.WATT },
{ name: 'Kilowatt (kW)', id: PowerElectricalFormats.KWATT },
{ name: 'Megawatt (MW)', id: PowerElectricalFormats.MEGWATT },
{ name: 'Gigawatt (GW)', id: PowerElectricalFormats.GWATT },
{ name: 'Milliwatt (mW)', id: PowerElectricalFormats.MWATT },
{ name: 'Watt per square meter (W/m²)', id: PowerElectricalFormats.WM2 },
{ name: 'Volt-Ampere (VA)', id: PowerElectricalFormats.VOLTAMP },
{ name: 'Kilovolt-Ampere (kVA)', id: PowerElectricalFormats.KVOLTAMP },
{
name: 'Volt-Ampere reactive (VAr)',
id: PowerElectricalFormats.VOLTAMPREACT,
},
{
name: 'Kilovolt-Ampere reactive (kVAr)',
id: PowerElectricalFormats.KVOLTAMPREACT,
},
{ name: 'Watt-hour (Wh)', id: PowerElectricalFormats.WATTH },
{
name: 'Watt-hour per Kilogram (Wh/kg)',
id: PowerElectricalFormats.WATTHPERKG,
},
{ name: 'Kilowatt-hour (kWh)', id: PowerElectricalFormats.KWATTH },
{ name: 'Kilowatt-min (kWm)', id: PowerElectricalFormats.KWATTM },
{ name: 'Ampere-hour (Ah)', id: PowerElectricalFormats.AMPH },
{ name: 'Kiloampere-hour (kAh)', id: PowerElectricalFormats.KAMPH },
{ name: 'Milliampere-hour (mAh)', id: PowerElectricalFormats.MAMPH },
{ name: 'Joule (J)', id: PowerElectricalFormats.JOULE },
{ name: 'Electron volt (eV)', id: PowerElectricalFormats.EV },
{ name: 'Ampere (A)', id: PowerElectricalFormats.AMP },
{ name: 'Kiloampere (kA)', id: PowerElectricalFormats.KAMP },
{ name: 'Milliampere (mA)', id: PowerElectricalFormats.MAMP },
{ name: 'Volt (V)', id: PowerElectricalFormats.VOLT },
{ name: 'Kilovolt (kV)', id: PowerElectricalFormats.KVOLT },
{ name: 'Millivolt (mV)', id: PowerElectricalFormats.MVOLT },
{ name: 'Decibel-milliwatt (dBm)', id: PowerElectricalFormats.DBM },
{ name: 'Ohm (Ω)', id: PowerElectricalFormats.OHM },
{ name: 'Kiloohm (kΩ)', id: PowerElectricalFormats.KOHM },
{ name: 'Megaohm (MΩ)', id: PowerElectricalFormats.MOHM },
{ name: 'Farad (F)', id: PowerElectricalFormats.FARAD },
{ name: 'Microfarad (µF)', id: PowerElectricalFormats.µFARAD },
{ name: 'Nanofarad (nF)', id: PowerElectricalFormats.NFARAD },
{ name: 'Picofarad (pF)', id: PowerElectricalFormats.PFARAD },
{ name: 'Femtofarad (fF)', id: PowerElectricalFormats.FFARAD },
{ name: 'Henry (H)', id: PowerElectricalFormats.HENRY },
{ name: 'Millihenry (mH)', id: PowerElectricalFormats.MHENRY },
{ name: 'Microhenry (µH)', id: PowerElectricalFormats.µHENRY },
{ name: 'Lumens (Lm)', id: PowerElectricalFormats.LUMENS },
],
},
{
name: CategoryNames.Flow,
formats: [
{ name: 'Gallons/min (gpm)', id: FlowFormats.FLOWGPM },
{ name: 'Cubic meters/sec (cms)', id: FlowFormats.FLOWCMS },
{ name: 'Cubic feet/sec (cfs)', id: FlowFormats.FLOWCFS },
{ name: 'Cubic feet/min (cfm)', id: FlowFormats.FLOWCFM },
{ name: 'Litre/hour', id: FlowFormats.LITREH },
{ name: 'Litre/min (L/min)', id: FlowFormats.FLOWLPM },
{ name: 'milliLitre/min (mL/min)', id: FlowFormats.FLOWMLPM },
{ name: 'Lux (lx)', id: FlowFormats.LUX },
],
},
{
name: CategoryNames.Force,
formats: [
{ name: 'Newton-meters (Nm)', id: ForceFormats.FORCENM },
{ name: 'Kilonewton-meters (kNm)', id: ForceFormats.FORCEKNM },
{ name: 'Newtons (N)', id: ForceFormats.FORCEN },
{ name: 'Kilonewtons (kN)', id: ForceFormats.FORCEKN },
],
},
{
name: CategoryNames.Mass,
formats: [
{ name: 'milligram (mg)', id: MassFormats.MASSMG },
{ name: 'gram (g)', id: MassFormats.MASSG },
{ name: 'pound (lb)', id: MassFormats.MASSLB },
{ name: 'kilogram (kg)', id: MassFormats.MASSKG },
{ name: 'metric ton (t)', id: MassFormats.MASST },
],
},
{
name: CategoryNames.Length,
formats: [
{ name: 'millimeter (mm)', id: LengthFormats.LENGTHMM },
{ name: 'inch (in)', id: LengthFormats.LENGTHIN },
{ name: 'feet (ft)', id: LengthFormats.LENGTHFT },
{ name: 'meter (m)', id: LengthFormats.LENGTHM },
{ name: 'kilometer (km)', id: LengthFormats.LENGTHKM },
{ name: 'mile (mi)', id: LengthFormats.LENGTHMI },
],
},
{
name: CategoryNames.Pressure,
formats: [
{ name: 'Millibars', id: PressureFormats.PRESSUREMBAR },
{ name: 'Bars', id: PressureFormats.PRESSUREBAR },
{ name: 'Kilobars', id: PressureFormats.PRESSUREKBAR },
{ name: 'Pascals', id: PressureFormats.PRESSUREPA },
{ name: 'Hectopascals', id: PressureFormats.PRESSUREHPA },
{ name: 'Kilopascals', id: PressureFormats.PRESSUREKPA },
{ name: 'Inches of mercury', id: PressureFormats.PRESSUREHG },
{ name: 'PSI', id: PressureFormats.PRESSUREPSI },
],
},
{
name: CategoryNames.Radiation,
formats: [
{ name: 'Becquerel (Bq)', id: RadiationFormats.RADBQ },
{ name: 'curie (Ci)', id: RadiationFormats.RADCI },
{ name: 'Gray (Gy)', id: RadiationFormats.RADGY },
{ name: 'rad', id: RadiationFormats.RADRAD },
{ name: 'Sievert (Sv)', id: RadiationFormats.RADSV },
{ name: 'milliSievert (mSv)', id: RadiationFormats.RADMSV },
{ name: 'microSievert (µSv)', id: RadiationFormats.RADUSV },
{ name: 'rem', id: RadiationFormats.RADREM },
{ name: 'Exposure (C/kg)', id: RadiationFormats.RADEXPCKG },
{ name: 'roentgen (R)', id: RadiationFormats.RADR },
{ name: 'Sievert/hour (Sv/h)', id: RadiationFormats.RADSVH },
{ name: 'milliSievert/hour (mSv/h)', id: RadiationFormats.RADMSVH },
{ name: 'microSievert/hour (µSv/h)', id: RadiationFormats.RADUSVH },
],
},
{
name: CategoryNames.RotationSpeed,
formats: [
{ name: 'Revolutions per minute (rpm)', id: RotationSpeedFormats.ROTRPM },
{ name: 'Hertz (Hz)', id: RotationSpeedFormats.ROTHZ },
{ name: 'Radians per second (rad/s)', id: RotationSpeedFormats.ROTRADS },
{ name: 'Degrees per second (°/s)', id: RotationSpeedFormats.ROTDEGS },
],
},
{
name: CategoryNames.Temperature,
formats: [
{ name: 'Celsius (°C)', id: TemperatureFormats.CELSIUS },
{ name: 'Fahrenheit (°F)', id: TemperatureFormats.FAHRENHEIT },
{ name: 'Kelvin (K)', id: TemperatureFormats.KELVIN },
],
},
{
name: CategoryNames.Velocity,
formats: [
{ name: 'meters/second (m/s)', id: VelocityFormats.METERS_PER_SECOND },
{ name: 'kilometers/hour (km/h)', id: VelocityFormats.KILOMETERS_PER_HOUR },
{ name: 'miles/hour (mph)', id: VelocityFormats.MILES_PER_HOUR },
{ name: 'knot (kn)', id: VelocityFormats.KNOT },
],
},
{
name: CategoryNames.Volume,
formats: [
{ name: 'millilitre (mL)', id: VolumeFormats.MILLILITRE },
{ name: 'litre (L)', id: VolumeFormats.LITRE },
{ name: 'cubic meter', id: VolumeFormats.CUBIC_METER },
{ name: 'Normal cubic meter', id: VolumeFormats.NORMAL_CUBIC_METER },
{ name: 'cubic decimeter', id: VolumeFormats.CUBIC_DECIMETER },
{ name: 'gallons', id: VolumeFormats.GALLONS },
],
},
{
name: CategoryNames.Boolean,
formats: [
{ name: 'True / False', id: BooleanFormats.TRUE_FALSE },
{ name: 'Yes / No', id: BooleanFormats.YES_NO },
{ name: 'On / Off', id: BooleanFormats.ON_OFF },
],
},
];
const foundCategory = categories.find((category) =>
category.units.some((unit) => {
// Units in Y-axis categories use universal unit IDs.
// Thresholds / column units often use Grafana-style IDs.
// Treat a unit as matching if either:
// - it is already the universal ID, or
// - it matches the mapped Grafana ID for that universal unit.
if (unit.id === unitId) {
return true;
}
export const flattenedCategories = flattenDeep(
dataTypeCategories.map((category) => category.formats),
);
const grafanaId = UniversalUnitToGrafanaUnit[unit.id];
return grafanaId === unitId;
}),
);
return foundCategory ? foundCategory.name : null;
type ConversionFactors = {
[key: string]: {
[key: string]: number | null;
};
};
// Object containing conversion factors for various categories and formats
const conversionFactors: ConversionFactors = {
[CategoryNames.Time]: {
[TimeFormats.Hertz]: 1,
[TimeFormats.Nanoseconds]: 1e-9,
[TimeFormats.Microseconds]: 1e-6,
[TimeFormats.Milliseconds]: 1e-3,
[TimeFormats.Seconds]: 1,
[TimeFormats.Minutes]: 60,
[TimeFormats.Hours]: 3600,
[TimeFormats.Days]: 86400,
[TimeFormats.DurationMs]: 1e-3,
[TimeFormats.DurationS]: 1,
[TimeFormats.DurationHms]: null, // Requires special handling
[TimeFormats.DurationDhms]: null, // Requires special handling
[TimeFormats.Timeticks]: null, // Requires special handling
[TimeFormats.ClockMs]: 1e-3,
[TimeFormats.ClockS]: 1,
},
[CategoryNames.Throughput]: {
[ThroughputFormats.CountsPerSec]: 1,
[ThroughputFormats.OpsPerSec]: 1,
[ThroughputFormats.RequestsPerSec]: 1,
[ThroughputFormats.ReadsPerSec]: 1,
[ThroughputFormats.WritesPerSec]: 1,
[ThroughputFormats.IOOpsPerSec]: 1,
[ThroughputFormats.CountsPerMin]: 1 / 60,
[ThroughputFormats.OpsPerMin]: 1 / 60,
[ThroughputFormats.ReadsPerMin]: 1 / 60,
[ThroughputFormats.WritesPerMin]: 1 / 60,
},
[CategoryNames.Data]: {
[DataFormats.BytesIEC]: 1,
[DataFormats.BytesSI]: 1,
[DataFormats.BitsIEC]: 0.125,
[DataFormats.BitsSI]: 0.125,
[DataFormats.KibiBytes]: 1024,
[DataFormats.KiloBytes]: 1000,
[DataFormats.MebiBytes]: 1048576,
[DataFormats.MegaBytes]: 1000000,
[DataFormats.GibiBytes]: 1073741824,
[DataFormats.GigaBytes]: 1000000000,
[DataFormats.TebiBytes]: 1099511627776,
[DataFormats.TeraBytes]: 1000000000000,
[DataFormats.PebiBytes]: 1125899906842624,
[DataFormats.PetaBytes]: 1000000000000000,
},
[CategoryNames.DataRate]: {
[DataRateFormats.PacketsPerSec]: null, // Cannot convert directly to other data rates
[DataRateFormats.BytesPerSecIEC]: 1,
[DataRateFormats.BytesPerSecSI]: 1,
[DataRateFormats.BitsPerSecIEC]: 0.125,
[DataRateFormats.BitsPerSecSI]: 0.125,
[DataRateFormats.KibiBytesPerSec]: 1024,
[DataRateFormats.KibiBitsPerSec]: 128,
[DataRateFormats.KiloBytesPerSec]: 1000,
[DataRateFormats.KiloBitsPerSec]: 125,
[DataRateFormats.MebiBytesPerSec]: 1048576,
[DataRateFormats.MebiBitsPerSec]: 131072,
[DataRateFormats.MegaBytesPerSec]: 1000000,
[DataRateFormats.MegaBitsPerSec]: 125000,
[DataRateFormats.GibiBytesPerSec]: 1073741824,
[DataRateFormats.GibiBitsPerSec]: 134217728,
[DataRateFormats.GigaBytesPerSec]: 1000000000,
[DataRateFormats.GigaBitsPerSec]: 125000000,
[DataRateFormats.TebiBytesPerSec]: 1099511627776,
[DataRateFormats.TebiBitsPerSec]: 137438953472,
[DataRateFormats.TeraBytesPerSec]: 1000000000000,
[DataRateFormats.TeraBitsPerSec]: 125000000000,
[DataRateFormats.PebiBytesPerSec]: 1125899906842624,
[DataRateFormats.PebiBitsPerSec]: 140737488355328,
[DataRateFormats.PetaBytesPerSec]: 1000000000000000,
[DataRateFormats.PetaBitsPerSec]: 125000000000000,
},
[CategoryNames.Miscellaneous]: {
[MiscellaneousFormats.None]: null,
[MiscellaneousFormats.String]: null,
[MiscellaneousFormats.Short]: null,
[MiscellaneousFormats.Percent]: 1,
[MiscellaneousFormats.PercentUnit]: 100,
[MiscellaneousFormats.Humidity]: 1,
[MiscellaneousFormats.Decibel]: null,
[MiscellaneousFormats.Hexadecimal0x]: null,
[MiscellaneousFormats.Hexadecimal]: null,
[MiscellaneousFormats.ScientificNotation]: null,
[MiscellaneousFormats.LocaleFormat]: null,
[MiscellaneousFormats.Pixels]: null,
},
[CategoryNames.Boolean]: {
[BooleanFormats.TRUE_FALSE]: null, // Not convertible
[BooleanFormats.YES_NO]: null, // Not convertible
[BooleanFormats.ON_OFF]: null, // Not convertible
},
};
// Function to get the conversion factor between two units in a specific category
function getConversionFactor(
fromUnit: string,
toUnit: string,
category: CategoryNames,
): number | null {
// Retrieves the conversion factors for the specified category
const categoryFactors = conversionFactors[category];
if (!categoryFactors) {
return null; // Returns null if the category does not exist
}
const fromFactor = categoryFactors[fromUnit];
const toFactor = categoryFactors[toUnit];
if (
fromFactor === undefined ||
toFactor === undefined ||
fromFactor === null ||
toFactor === null
) {
return null; // Returns null if either unit does not exist or is not convertible
}
return fromFactor / toFactor; // Returns the conversion factor ratio
}
// Function to convert a value from one unit to another
export function convertUnit(
value: number,
fromUnitId?: string,
toUnitId?: string,
): number | null {
if (!fromUnitId || !toUnitId) {
let fromUnit: string | undefined;
let toUnit: string | undefined;
// Finds the category that contains the specified units and extracts fromUnit and toUnit using array methods
const category = dataTypeCategories.find((category) =>
category.formats.some((format) => {
if (format.id === fromUnitId) {
fromUnit = format.id;
}
if (format.id === toUnitId) {
toUnit = format.id;
}
return fromUnit && toUnit; // Break out early if both units are found
}),
);
if (!category || !fromUnit || !toUnit) {
return null;
}
} // Return null if category or units are not found
const fromCategory = getCategoryName(fromUnitId);
const toCategory = getCategoryName(toUnitId);
// If either unit is unknown or the categories don't match, the conversion is invalid
if (!fromCategory || !toCategory || fromCategory !== toCategory) {
// Gets the conversion factor for the specified units
const conversionFactor = getConversionFactor(
fromUnit,
toUnit,
category.name as any,
);
if (conversionFactor === null) {
return null;
}
} // Return null if conversion is not possible
// Delegate the actual numeric conversion (or identity) to the shared helper,
// which understands both Grafana-style and universal unit IDs.
return convertValue(value, fromUnitId, toUnitId);
return value * conversionFactor;
}
// Function to get the category name for a given unit ID
export const getCategoryName = (unitId: string): CategoryNames | null => {
// Finds the category that contains the specified unit ID
const foundCategory = dataTypeCategories.find((category) =>
category.formats.some((format) => format.id === unitId),
);
return foundCategory ? (foundCategory.name as CategoryNames) : null;
};

View File

@@ -2,9 +2,6 @@ import { Layout } from 'react-grid-layout';
import { DefaultOptionType } from 'antd/es/select';
import { omitIdFromQuery } from 'components/ExplorerCard/utils';
import { PrecisionOptionsEnum } from 'components/Graph/types';
import { YAxisCategoryNames } from 'components/YAxisUnitSelector/constants';
import { YAxisSource } from 'components/YAxisUnitSelector/types';
import { getYAxisCategories } from 'components/YAxisUnitSelector/utils';
import {
initialQueryBuilderFormValuesMap,
PANEL_TYPES,
@@ -24,7 +21,11 @@ import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
import { getCategoryName } from './RightContainer/dataFormatCategories';
import {
dataTypeCategories,
getCategoryName,
} from './RightContainer/dataFormatCategories';
import { CategoryNames } from './RightContainer/types';
export const getIsQueryModified = (
currentQuery: Query,
@@ -605,21 +606,14 @@ export const PANEL_TYPE_TO_QUERY_TYPES: Record<PANEL_TYPES, EQueryType[]> = {
* the label and value for each format.
*/
export const getCategorySelectOptionByName = (
name?: YAxisCategoryNames,
): DefaultOptionType[] => {
const categories = getYAxisCategories(YAxisSource.DASHBOARDS);
if (!categories.length) {
return [];
}
return (
categories
.find((category) => category.name === name)
?.units.map((unit) => ({
label: unit.name,
value: unit.id,
})) || []
);
};
name?: CategoryNames | string,
): DefaultOptionType[] =>
dataTypeCategories
.find((category) => category.name === name)
?.formats.map((format) => ({
label: format.name,
value: format.id,
})) || [];
/**
* Generates unit options based on the provided column unit.

View File

@@ -1,13 +1,10 @@
import { YAxisCategoryNames } from 'components/YAxisUnitSelector/constants';
import { CategoryNames } from 'container/NewWidget/RightContainer/types';
export const categoryToSupport: YAxisCategoryNames[] = [
YAxisCategoryNames.None,
YAxisCategoryNames.Data,
YAxisCategoryNames.DataRate,
YAxisCategoryNames.Time,
YAxisCategoryNames.Count,
YAxisCategoryNames.Operations,
YAxisCategoryNames.Percentage,
YAxisCategoryNames.Miscellaneous,
YAxisCategoryNames.Boolean,
export const categoryToSupport = [
CategoryNames.Data,
CategoryNames.DataRate,
CategoryNames.Time,
CategoryNames.Throughput,
CategoryNames.Miscellaneous,
CategoryNames.Boolean,
];

View File

@@ -0,0 +1,375 @@
.permission-side-panel-backdrop {
position: fixed;
inset: 0;
z-index: 100;
background: transparent;
}
.permission-side-panel {
position: fixed;
top: 0;
right: 0;
bottom: 0;
z-index: 101;
width: 720px;
display: flex;
flex-direction: column;
background: var(--bg-ink-400);
border-left: 1px solid var(--bg-slate-500);
box-shadow: -4px 10px 16px 2px rgba(0, 0, 0, 0.2);
&__header {
display: flex;
align-items: center;
gap: 16px;
flex-shrink: 0;
height: 48px;
padding: 0 16px;
background: var(--bg-ink-400);
border-bottom: 1px solid var(--bg-slate-500);
}
&__close {
display: flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
padding: 0;
background: transparent;
border: none;
cursor: pointer;
color: var(--foreground);
flex-shrink: 0;
&:hover {
color: var(--text-base-white);
}
}
&__header-divider {
display: block;
width: 1px;
height: 16px;
background: var(--bg-slate-500);
flex-shrink: 0;
}
&__title {
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.07px;
color: var(--foreground);
}
&__content {
flex: 1;
overflow-y: auto;
padding: 12px 15px;
}
&__resource-list {
display: flex;
flex-direction: column;
border: 1px solid var(--bg-slate-500);
border-radius: 4px;
overflow: hidden;
}
&__footer {
display: flex;
align-items: center;
justify-content: flex-end;
flex-shrink: 0;
height: 56px;
padding: 0 16px;
gap: 12px;
background: var(--bg-ink-400);
border-top: 1px solid var(--bg-slate-500);
}
&__unsaved {
display: flex;
align-items: center;
gap: 8px;
margin-right: auto;
}
&__unsaved-dot {
display: block;
width: 6px;
height: 6px;
border-radius: 50px;
background: var(--bg-robin-500);
box-shadow: 0px 0px 6px 0px rgba(78, 116, 248, 0.4);
flex-shrink: 0;
}
&__unsaved-text {
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 24px;
letter-spacing: -0.07px;
color: var(--bg-robin-400);
}
&__footer-actions {
display: flex;
align-items: center;
gap: 12px;
}
&__cancel-btn {
display: flex !important;
align-items: center !important;
gap: 4px !important;
padding: 4px 8px !important;
height: 32px !important;
background: var(--bg-slate-500) !important;
border: none !important;
border-radius: 2px !important;
font-family: Inter !important;
font-size: 12px !important;
font-weight: 500 !important;
line-height: 24px !important;
color: var(--foreground) !important;
cursor: pointer !important;
box-shadow: none !important;
&:hover {
background: var(--bg-slate-400) !important;
color: var(--text-base-white) !important;
}
}
}
.psp-resource {
display: flex;
flex-direction: column;
border-bottom: 1px solid var(--bg-slate-500);
&:last-child {
border-bottom: none;
}
&__row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
cursor: pointer;
transition: background 0.15s ease;
&--expanded {
background: rgba(171, 189, 255, 0.04);
}
&:hover {
background: rgba(171, 189, 255, 0.03);
}
}
&__left {
display: flex;
align-items: center;
gap: 16px;
}
&__chevron {
display: flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
color: var(--foreground);
flex-shrink: 0;
}
&__label {
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.07px;
color: var(--text-base-white);
text-transform: capitalize;
}
&__switch-wrapper {
display: flex;
align-items: center;
flex-shrink: 0;
}
// Expanded body
&__body {
display: flex;
flex-direction: column;
gap: 2px;
padding: 8px 0 8px 44px;
background: rgba(171, 189, 255, 0.04);
}
&__radio-group {
display: flex;
flex-direction: column;
gap: 2px;
}
&__radio-item {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 0;
// RadioGroupLabel style
label {
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.07px;
color: var(--text-base-white);
cursor: pointer;
}
}
&__select-wrapper {
padding: 6px 16px 4px 24px;
}
&__select {
width: 100%;
.ant-select-selector {
background: var(--bg-ink-300) !important;
border: 1px solid var(--bg-slate-400) !important;
border-radius: 2px !important;
padding: 4px 6px !important;
min-height: 32px !important;
box-shadow: none !important;
&:hover,
&:focus-within {
border-color: var(--input) !important;
box-shadow: none !important;
}
}
.ant-select-selection-placeholder {
font-family: Inter;
font-size: 14px;
font-weight: 400;
color: var(--foreground);
opacity: 0.4;
}
.ant-select-selection-item {
background: var(--bg-slate-300) !important;
border: none !important;
border-radius: 2px !important;
padding: 0 6px !important;
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 20px;
color: var(--text-base-white) !important;
height: auto !important;
}
.ant-select-selection-item-remove {
color: var(--foreground) !important;
display: flex;
align-items: center;
}
.ant-select-arrow {
color: var(--foreground);
}
}
&__select-popup {
.ant-select-item {
font-family: Inter;
font-size: 14px;
font-weight: 400;
color: var(--foreground);
background: var(--bg-ink-300);
&-option-selected {
background: var(--bg-slate-400) !important;
color: var(--text-base-white) !important;
}
&-option-active {
background: rgba(171, 189, 255, 0.06) !important;
}
}
.ant-select-dropdown {
background: var(--bg-ink-300);
border: 1px solid var(--bg-slate-400);
border-radius: 2px;
padding: 4px 0;
}
}
}
.lightMode {
.permission-side-panel {
background: var(--bg-vanilla-100);
border-left-color: var(--bg-vanilla-300);
&__header {
background: var(--bg-vanilla-100);
border-bottom-color: var(--bg-vanilla-300);
}
&__header-divider {
background: var(--bg-vanilla-300);
}
&__footer {
background: var(--bg-vanilla-100);
border-top-color: var(--bg-vanilla-300);
}
&__cancel-btn {
background: var(--bg-vanilla-300) !important;
color: var(--bg-ink-400) !important;
&:hover {
background: var(--bg-vanilla-400) !important;
}
}
}
.psp-resource {
border-bottom-color: var(--bg-vanilla-300);
&__label {
color: var(--text-base-black);
}
&__radio-item label {
color: var(--text-base-black);
}
&__select .ant-select-selector {
background: var(--bg-vanilla-200) !important;
border-color: var(--bg-vanilla-300) !important;
}
&__select .ant-select-selection-item {
background: var(--bg-vanilla-300) !important;
color: var(--text-base-black) !important;
}
}
.permission-side-panel__resource-list {
border-color: var(--bg-vanilla-300);
}
}

View File

@@ -0,0 +1,335 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Button } from '@signozhq/button';
import { X } from '@signozhq/icons';
import { ChevronDown, ChevronRight } from '@signozhq/icons';
import {
RadioGroup,
RadioGroupItem,
RadioGroupLabel,
} from '@signozhq/radio-group';
import { Switch } from '@signozhq/switch';
import { Select } from 'antd';
import type {
PermissionConfig,
PermissionSidePanelProps,
ResourceConfig,
ResourceDefinition,
ScopeType,
} from './PermissionSidePanel.types';
import './PermissionSidePanel.styles.scss';
const DEFAULT_RESOURCE_CONFIG: ResourceConfig = {
enabled: false,
scope: 'all',
selectedIds: [],
};
function buildConfig(
resources: ResourceDefinition[],
initial?: PermissionConfig,
): PermissionConfig {
const config: PermissionConfig = {};
resources.forEach((r) => {
config[r.id] = initial?.[r.id] ?? { ...DEFAULT_RESOURCE_CONFIG };
});
return config;
}
function configsEqual(a: PermissionConfig, b: PermissionConfig): boolean {
return Object.keys(a).every((id) => {
const ac = a[id];
const bc = b[id];
if (!bc) {
return false;
}
return (
ac.enabled === bc.enabled &&
ac.scope === bc.scope &&
JSON.stringify([...ac.selectedIds].sort()) ===
JSON.stringify([...bc.selectedIds].sort())
);
});
}
interface ResourceRowProps {
resource: ResourceDefinition;
config: ResourceConfig;
isExpanded: boolean;
onToggle: (id: string, checked: boolean) => void;
onToggleExpand: (id: string) => void;
onScopeChange: (id: string, scope: ScopeType) => void;
onSelectedIdsChange: (id: string, ids: string[]) => void;
}
function ResourceRow({
resource,
config,
isExpanded,
onToggle,
onToggleExpand,
onScopeChange,
onSelectedIdsChange,
}: ResourceRowProps): JSX.Element {
return (
<div className="psp-resource">
<div
className={`psp-resource__row${
isExpanded ? ' psp-resource__row--expanded' : ''
}`}
role="button"
tabIndex={0}
onClick={(): void => onToggleExpand(resource.id)}
onKeyDown={(e): void => {
if (e.key === 'Enter' || e.key === ' ') {
onToggleExpand(resource.id);
}
}}
>
<div className="psp-resource__left">
<span className="psp-resource__chevron">
{isExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
</span>
<span className="psp-resource__label">{resource.label}</span>
</div>
<span
className="psp-resource__switch-wrapper"
role="presentation"
onClick={(e): void => e.stopPropagation()}
onKeyDown={(e): void => e.stopPropagation()}
>
<Switch
checked={config.enabled}
onCheckedChange={(checked): void => onToggle(resource.id, checked)}
color="robin"
/>
</span>
</div>
{isExpanded && (
<div className="psp-resource__body">
<RadioGroup
value={config.scope}
onValueChange={(val): void =>
onScopeChange(resource.id, val as ScopeType)
}
className="psp-resource__radio-group"
>
<div className="psp-resource__radio-item">
<RadioGroupItem value="all" id={`${resource.id}-all`} color="robin" />
<RadioGroupLabel htmlFor={`${resource.id}-all`}>All</RadioGroupLabel>
</div>
<div className="psp-resource__radio-item">
<RadioGroupItem
value="only_selected"
id={`${resource.id}-only-selected`}
color="robin"
/>
<RadioGroupLabel htmlFor={`${resource.id}-only-selected`}>
Only selected
</RadioGroupLabel>
</div>
</RadioGroup>
{config.scope === 'only_selected' && (
<div className="psp-resource__select-wrapper">
<Select
mode="multiple"
value={config.selectedIds}
onChange={(vals: string[]): void =>
onSelectedIdsChange(resource.id, vals)
}
options={resource.options ?? []}
placeholder="Select resources..."
className="psp-resource__select"
popupClassName="psp-resource__select-popup"
showSearch
filterOption={(input, option): boolean =>
String(option?.label ?? '')
.toLowerCase()
.includes(input.toLowerCase())
}
/>
</div>
)}
</div>
)}
</div>
);
}
function PermissionSidePanel({
open,
onClose,
permissionLabel,
resources,
initialConfig,
onSave,
}: PermissionSidePanelProps): JSX.Element | null {
const [config, setConfig] = useState<PermissionConfig>(() =>
buildConfig(resources, initialConfig),
);
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
useEffect(() => {
if (open) {
setConfig(buildConfig(resources, initialConfig));
setExpandedIds(new Set());
}
}, [open, resources, initialConfig]);
const savedConfig = useMemo(() => buildConfig(resources, initialConfig), [
resources,
initialConfig,
]);
const unsavedCount = useMemo(() => {
if (configsEqual(config, savedConfig)) {
return 0;
}
return Object.keys(config).filter((id) => {
const a = config[id];
const b = savedConfig[id];
if (!b) {
return true;
}
return (
a.enabled !== b.enabled ||
a.scope !== b.scope ||
JSON.stringify([...a.selectedIds].sort()) !==
JSON.stringify([...b.selectedIds].sort())
);
}).length;
}, [config, savedConfig]);
const updateResource = useCallback(
(id: string, patch: Partial<ResourceConfig>): void => {
setConfig((prev) => ({
...prev,
[id]: { ...prev[id], ...patch },
}));
},
[],
);
const handleToggle = useCallback(
(id: string, checked: boolean): void => {
updateResource(id, { enabled: checked });
},
[updateResource],
);
const handleToggleExpand = useCallback((id: string): void => {
setExpandedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) {
next.delete(id);
} else {
next.add(id);
}
return next;
});
}, []);
const handleScopeChange = useCallback(
(id: string, scope: ScopeType): void => {
updateResource(id, { scope, selectedIds: [] });
},
[updateResource],
);
const handleSelectedIdsChange = useCallback(
(id: string, ids: string[]): void => {
updateResource(id, { selectedIds: ids });
},
[updateResource],
);
const handleSave = useCallback((): void => {
onSave(config);
onClose();
}, [config, onSave, onClose]);
const handleDiscard = useCallback((): void => {
setConfig(buildConfig(resources, initialConfig));
setExpandedIds(new Set());
}, [resources, initialConfig]);
if (!open) {
return null;
}
return (
<>
<div
className="permission-side-panel-backdrop"
role="presentation"
onClick={onClose}
/>
<div className="permission-side-panel">
<div className="permission-side-panel__header">
<button
type="button"
className="permission-side-panel__close"
onClick={onClose}
aria-label="Close panel"
>
<X size={16} />
</button>
<span className="permission-side-panel__header-divider" />
<span className="permission-side-panel__title">
Edit {permissionLabel} Permissions
</span>
</div>
<div className="permission-side-panel__content">
<div className="permission-side-panel__resource-list">
{resources.map((resource) => (
<ResourceRow
key={resource.id}
resource={resource}
config={config[resource.id] ?? DEFAULT_RESOURCE_CONFIG}
isExpanded={expandedIds.has(resource.id)}
onToggle={handleToggle}
onToggleExpand={handleToggleExpand}
onScopeChange={handleScopeChange}
onSelectedIdsChange={handleSelectedIdsChange}
/>
))}
</div>
</div>
<div className="permission-side-panel__footer">
{unsavedCount > 0 && (
<div className="permission-side-panel__unsaved">
<span className="permission-side-panel__unsaved-dot" />
<span className="permission-side-panel__unsaved-text">
{unsavedCount} unsaved change{unsavedCount !== 1 ? 's' : ''}
</span>
</div>
)}
<div className="permission-side-panel__footer-actions">
<Button
className="permission-side-panel__cancel-btn"
prefixIcon={<X size={14} />}
onClick={unsavedCount > 0 ? handleDiscard : onClose}
size="sm"
>
{unsavedCount > 0 ? 'Discard' : 'Cancel'}
</Button>
<Button variant="solid" color="primary" size="sm" onClick={handleSave}>
Save Changes
</Button>
</div>
</div>
</div>
</>
);
}
export default PermissionSidePanel;

View File

@@ -0,0 +1,35 @@
export interface ResourceOption {
value: string;
label: string;
}
export interface ResourceDefinition {
id: string;
label: string;
/** Options for the "Only selected" dropdown — to be populated via API */
options?: ResourceOption[];
}
export type ScopeType = 'all' | 'only_selected';
export interface ResourceConfig {
enabled: boolean;
scope: ScopeType;
selectedIds: string[];
}
/** keyed by ResourceDefinition.id */
export type PermissionConfig = Record<string, ResourceConfig>;
export interface PermissionSidePanelProps {
open: boolean;
onClose: () => void;
/** e.g. "Read", "Create", "Delete" */
permissionLabel: string;
/** Ordered list of resources shown in the panel */
resources: ResourceDefinition[];
/** Pre-existing configuration to initialise from */
initialConfig?: PermissionConfig;
/** Called with the full resolved config when user saves */
onSave: (config: PermissionConfig) => void;
}

View File

@@ -0,0 +1,9 @@
export { default } from './PermissionSidePanel';
export type {
PermissionConfig,
PermissionSidePanelProps,
ResourceConfig,
ResourceDefinition,
ResourceOption,
ScopeType,
} from './PermissionSidePanel.types';

View File

@@ -0,0 +1,510 @@
.role-details-page {
display: flex;
flex-direction: column;
gap: 16px;
padding: 16px;
width: 100%;
max-width: 60vw;
margin: 0 auto;
.role-details-header {
display: flex;
flex-direction: column;
gap: 0;
}
.role-details-title {
color: var(--text-base-white);
font-family: Inter;
font-size: 18px;
font-weight: 500;
line-height: 28px;
letter-spacing: -0.09px;
}
.role-details-permission-item--readonly {
cursor: default !important;
pointer-events: none;
opacity: 0.55;
&:hover {
background: rgba(171, 189, 255, 0.08) !important;
}
}
.role-details-nav {
display: flex;
align-items: center;
justify-content: space-between;
}
.role-details-tabs {
display: flex;
align-items: center;
background: var(--bg-ink-400);
border: 1px solid var(--bg-slate-400);
border-radius: 2px;
box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
height: 32px;
overflow: hidden;
}
.role-details-tab {
display: flex;
align-items: center;
gap: 4px;
padding: 0 16px;
height: 32px;
cursor: pointer;
font-family: Inter;
font-size: 12px;
font-weight: 400;
line-height: 18px;
letter-spacing: -0.06px;
color: var(--foreground);
background: transparent;
border: none;
white-space: nowrap;
&--active {
background: var(--bg-slate-400);
color: var(--text-base-white);
border-radius: 2px 0 0 2px;
}
}
.role-details-tab-count {
display: flex;
align-items: center;
justify-content: center;
min-width: 20px;
padding: 0 6px;
border-radius: 50px;
background: var(--bg-slate-400);
font-size: 12px;
font-weight: 400;
line-height: 20px;
color: var(--foreground);
letter-spacing: -0.06px;
text-transform: uppercase;
}
.role-details-actions {
display: flex;
align-items: center;
gap: 12px;
}
.role-details-overview {
display: flex;
flex-direction: column;
gap: 16px;
}
.role-details-meta {
display: flex;
flex-direction: column;
gap: 16px;
}
.role-details-section-label {
font-family: Inter;
font-size: 12px;
font-weight: 500;
line-height: 20px;
letter-spacing: 0.48px;
text-transform: uppercase;
color: var(--foreground);
}
.role-details-description-text {
font-family: Inter;
font-size: 13px;
font-weight: 500;
line-height: 20px;
letter-spacing: -0.07px;
color: var(--foreground);
}
.role-details-info-row {
display: flex;
gap: 16px;
align-items: flex-start;
}
.role-details-info-col {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
.role-details-info-value {
display: flex;
align-items: center;
gap: 8px;
}
.role-details-info-name {
font-family: Inter;
font-size: 14px;
font-weight: 500;
line-height: 20px;
letter-spacing: -0.07px;
color: var(--foreground);
}
.role-details-permissions {
display: flex;
flex-direction: column;
gap: 16px;
padding-top: 8px;
}
.role-details-permissions-header {
display: flex;
align-items: center;
gap: 16px;
height: 20px;
}
.role-details-permissions-divider {
flex: 1;
border: none;
border-top: 2px dotted var(--bg-slate-300);
border-bottom: 2px dotted var(--bg-slate-300);
height: 7px;
margin: 0;
}
.role-details-permission-list {
display: flex;
flex-direction: column;
gap: 16px;
}
.role-details-permission-item {
display: flex;
align-items: center;
justify-content: space-between;
height: 44px;
padding: 0 12px;
background: rgba(171, 189, 255, 0.08);
border: 1px solid var(--bg-slate-500);
border-radius: 4px;
cursor: pointer;
transition: background 0.15s ease;
&:hover {
background: rgba(171, 189, 255, 0.12);
}
}
.role-details-permission-item-left {
display: flex;
align-items: center;
gap: 8px;
}
.role-details-permission-item-label {
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.07px;
color: var(--text-base-white);
}
.role-details-badge {
display: inline-flex;
align-items: center;
padding: 4px 8px;
border-radius: 999px;
background: var(--bg-slate-400);
font-family: Inter;
font-size: 11px;
font-weight: 500;
line-height: 1;
letter-spacing: 0.44px;
text-transform: uppercase;
color: var(--foreground);
}
.role-details-members {
display: flex;
flex-direction: column;
gap: 16px;
}
.role-details-members-search {
display: flex;
align-items: center;
gap: 6px;
height: 32px;
padding: 6px 6px 6px 8px;
background: var(--bg-ink-300);
border: 1px solid var(--bg-slate-400);
border-radius: 2px;
.role-details-members-search-icon {
flex-shrink: 0;
color: var(--foreground);
opacity: 0.5;
}
.role-details-members-search-input {
flex: 1;
height: 100%;
background: transparent;
border: none;
outline: none;
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 18px;
letter-spacing: -0.07px;
color: var(--foreground);
&::placeholder {
color: var(--foreground);
opacity: 0.4;
}
}
}
.role-details-members-content {
display: flex;
flex-direction: column;
min-height: 420px;
border: 1px dashed var(--bg-slate-500);
border-radius: 3px;
margin-top: -1px;
}
.role-details-members-empty-state {
display: flex;
flex: 1;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
padding: 48px 0;
flex-grow: 1;
.role-details-members-empty-emoji {
font-size: 32px;
line-height: 1;
}
.role-details-members-empty-text {
font-family: Inter;
font-size: 14px;
line-height: 18px;
letter-spacing: -0.07px;
&--bold {
font-weight: 500;
color: var(--text-base-white);
}
&--muted {
font-weight: 400;
color: var(--foreground);
}
}
}
.role-details-skeleton {
padding: 16px 0;
}
}
.role-details-delete-action-btn {
display: flex !important;
align-items: center !important;
justify-content: center !important;
width: 32px !important;
height: 32px !important;
min-width: 32px !important;
border: none !important;
border-radius: 2px !important;
background: transparent !important;
color: var(--bg-cherry-500) !important;
opacity: 0.6 !important;
padding: 0 !important;
transition: background-color 0.2s, opacity 0.2s;
box-shadow: none !important;
svg {
color: var(--bg-cherry-500) !important;
}
&:hover {
background: rgba(229, 72, 77, 0.1) !important;
opacity: 0.9 !important;
}
}
.role-details-delete-modal {
width: calc(100% - 30px) !important;
max-width: 384px;
.ant-modal-content {
padding: 0;
border-radius: 4px;
border: 1px solid var(--bg-slate-500);
background: var(--bg-ink-400);
box-shadow: 0px -4px 16px 2px rgba(0, 0, 0, 0.2);
.ant-modal-header {
padding: 16px;
background: var(--bg-ink-400);
margin-bottom: 0;
}
.ant-modal-body {
padding: 0 16px 28px 16px;
}
.ant-modal-footer {
display: flex;
justify-content: flex-end;
padding: 16px;
margin: 0;
.cancel-btn {
display: flex;
align-items: center;
border: none;
border-radius: 2px;
background: var(--bg-slate-500);
}
.delete-btn {
display: flex;
align-items: center;
border: none;
border-radius: 2px;
background: var(--bg-cherry-500);
margin-left: 12px;
&:hover {
color: var(--bg-vanilla-100);
background: var(--bg-cherry-600);
}
}
}
}
.title {
color: var(--bg-vanilla-100);
font-family: Inter;
font-size: 13px;
font-weight: 400;
line-height: 1;
letter-spacing: -0.065px;
}
.delete-text {
color: var(--bg-vanilla-400);
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.07px;
strong {
font-weight: 600;
color: var(--bg-vanilla-100);
}
}
}
.lightMode {
.role-details-delete-modal {
.ant-modal-content {
border-color: var(--bg-vanilla-200);
background: var(--bg-vanilla-100);
.ant-modal-header {
background: var(--bg-vanilla-100);
.title {
color: var(--bg-ink-500);
}
}
.ant-modal-body {
.delete-text {
color: var(--bg-ink-500);
strong {
color: var(--bg-ink-400);
}
}
}
.ant-modal-footer {
.cancel-btn {
background: var(--bg-vanilla-300);
color: var(--bg-ink-400);
}
}
}
}
}
.lightMode {
.role-details-page {
.role-details-title {
color: var(--text-base-black);
}
.role-details-members-search {
background: var(--bg-vanilla-100);
border-color: var(--bg-vanilla-300);
}
.role-details-members-content {
border-color: var(--bg-vanilla-300);
}
.role-details-members-empty-state {
.role-details-members-empty-text--bold {
color: var(--text-base-black);
}
}
.role-details-tabs {
background: var(--bg-vanilla-100);
border-color: var(--bg-vanilla-300);
}
.role-details-tab--active {
background: var(--bg-vanilla-300);
color: var(--text-base-black);
}
.role-details-tab-count {
background: var(--bg-vanilla-300);
}
.role-details-permission-item {
background: rgba(0, 0, 0, 0.04);
border-color: var(--bg-vanilla-300);
&:hover {
background: rgba(0, 0, 0, 0.07);
}
}
.role-details-permission-item-label {
color: var(--text-base-black);
}
.role-details-badge {
background: var(--bg-vanilla-300);
}
}
}

View File

@@ -0,0 +1,420 @@
/* eslint-disable sonarjs/cognitive-complexity */
import { useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { Button } from '@signozhq/button';
import { Callout } from '@signozhq/callout';
import { X } from '@signozhq/icons';
import { toast } from '@signozhq/sonner';
import { Modal, Skeleton } from 'antd';
import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
import { useDeleteRole, useGetRole } from 'api/generated/services/role';
import { RoletypesRoleDTO } from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import ROUTES from 'constants/routes';
import {
BadgePlus,
ChevronRight,
Eye,
LayoutList,
PencilRuler,
Search,
Table2,
Trash2,
Users,
} from 'lucide-react';
import { useErrorModal } from 'providers/ErrorModalProvider';
import { useTimezone } from 'providers/Timezone';
import { ErrorV2Resp } from 'types/api';
import APIError from 'types/api/error';
import { toAPIError } from 'utils/errorUtils';
import type {
PermissionConfig,
ResourceDefinition,
} from '../PermissionSidePanel';
import PermissionSidePanel from '../PermissionSidePanel';
import CreateRoleModal from '../RolesComponents/CreateRoleModal';
import './RoleDetailsPage.styles.scss';
// Placeholder resources — replace with API-driven data when integrating
const PERMISSION_RESOURCES: ResourceDefinition[] = [
{ id: 'dashboards', label: 'Dashboards' },
{ id: 'alerts', label: 'Alerts' },
{ id: 'logs_pipelines', label: 'Logs: Pipelines' },
{ id: 'logs_views', label: 'Logs: Views' },
{ id: 'traces_funnels', label: 'Traces: Funnels' },
{ id: 'traces_views', label: 'Traces: Views' },
{ id: 'integrations', label: 'Integrations' },
{ id: 'exceptions', label: 'Exceptions' },
];
type TabKey = 'overview' | 'members';
interface PermissionType {
key: string;
label: string;
icon: JSX.Element;
}
const PERMISSION_TYPES: PermissionType[] = [
{ key: 'create', label: 'Create', icon: <BadgePlus size={14} /> },
{ key: 'list', label: 'List', icon: <LayoutList size={14} /> },
{ key: 'read', label: 'Read', icon: <Eye size={14} /> },
{ key: 'update', label: 'Update', icon: <PencilRuler size={14} /> },
{ key: 'delete', label: 'Delete', icon: <Trash2 size={14} /> },
];
interface OverviewTabProps {
role: RoletypesRoleDTO;
isManaged: boolean;
onPermissionClick: (permissionLabel: string) => void;
}
function TimestampBadge({ date }: { date?: Date | string }): JSX.Element {
const { formatTimezoneAdjustedTimestamp } = useTimezone();
if (!date) {
return <span className="role-details-badge"></span>;
}
const d = new Date(date);
if (Number.isNaN(d.getTime())) {
return <span className="role-details-badge"></span>;
}
const formatted = formatTimezoneAdjustedTimestamp(
date,
DATE_TIME_FORMATS.DASH_DATETIME,
);
return <span className="role-details-badge">{formatted}</span>;
}
function OverviewTab({
role,
isManaged,
onPermissionClick,
}: OverviewTabProps): JSX.Element {
return (
<div className="role-details-overview">
{isManaged && (
<Callout
type="warning"
showIcon
message="This is a managed role. Permissions and settings are view-only and cannot be modified."
/>
)}
<div className="role-details-meta">
<div>
<p className="role-details-section-label">Description</p>
<p className="role-details-description-text">{role.description || '—'}</p>
</div>
<div className="role-details-info-row">
<div className="role-details-info-col">
<p className="role-details-section-label">Created At</p>
<div className="role-details-info-value">
<TimestampBadge date={role.createdAt} />
</div>
</div>
<div className="role-details-info-col">
<p className="role-details-section-label">Last Modified At</p>
<div className="role-details-info-value">
<TimestampBadge date={role.updatedAt} />
</div>
</div>
</div>
</div>
<div className="role-details-permissions">
<div className="role-details-permissions-header">
<span className="role-details-section-label">Permissions</span>
<hr className="role-details-permissions-divider" />
</div>
<div className="role-details-permission-list">
{PERMISSION_TYPES.map(({ key, label, icon }) =>
isManaged ? (
<div
key={key}
className="role-details-permission-item role-details-permission-item--readonly"
>
<div className="role-details-permission-item-left">
{icon}
<span className="role-details-permission-item-label">{label}</span>
</div>
</div>
) : (
<div
key={key}
className="role-details-permission-item"
role="button"
tabIndex={0}
onClick={(): void => onPermissionClick(label)}
onKeyDown={(e): void => {
if (e.key === 'Enter' || e.key === ' ') {
onPermissionClick(label);
}
}}
>
<div className="role-details-permission-item-left">
{icon}
<span className="role-details-permission-item-label">{label}</span>
</div>
<ChevronRight size={14} color="var(--foreground)" />
</div>
),
)}
</div>
</div>
</div>
);
}
function MembersTab(): JSX.Element {
const [searchQuery, setSearchQuery] = useState('');
return (
<div className="role-details-members">
<div className="role-details-members-search">
<Search size={12} className="role-details-members-search-icon" />
<input
type="text"
className="role-details-members-search-input"
placeholder="Search and add members..."
value={searchQuery}
onChange={(e): void => setSearchQuery(e.target.value)}
/>
</div>
<div className="role-details-members-content">
<div className="role-details-members-empty-state">
<span
className="role-details-members-empty-emoji"
role="img"
aria-label="monocle face"
>
🧐
</span>
<p className="role-details-members-empty-text">
<span className="role-details-members-empty-text--bold">
No members added.
</span>{' '}
<span className="role-details-members-empty-text--muted">
Start adding members to this role.
</span>
</p>
</div>
</div>
</div>
);
}
function RoleDetailsPage(): JSX.Element {
const { pathname } = useLocation();
const history = useHistory();
const { showErrorModal } = useErrorModal();
// Extract roleId from pathname — useParams doesn't work inside nested RouteTab (antd Tabs) routing
const roleIdMatch = pathname.match(/\/settings\/roles\/([^/]+)/);
const roleId = roleIdMatch ? roleIdMatch[1] : '';
const [activeTab, setActiveTab] = useState<TabKey>('overview');
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [activePermission, setActivePermission] = useState<string | null>(null);
const [permissionConfigs, setPermissionConfigs] = useState<
Record<string, PermissionConfig>
>({});
const { data, isLoading, isFetching, isError, error } = useGetRole({
id: roleId,
});
const role = data?.data?.data;
const isTransitioning = isFetching && role?.id !== roleId;
const isManaged = role?.type === 'managed';
const { mutate: deleteRole, isLoading: isDeleting } = useDeleteRole({
mutation: {
onSuccess: (): void => {
toast.success('Role deleted successfully');
history.push(ROUTES.ROLES_SETTINGS);
},
onError: (err): void => {
try {
ErrorResponseHandlerV2(err as AxiosError<ErrorV2Resp>);
} catch (apiError) {
showErrorModal(apiError as APIError);
}
},
},
});
const openEditModal = (): void => {
setIsEditModalOpen(true);
};
if (isLoading || isTransitioning) {
return (
<div className="role-details-page">
<Skeleton
active
paragraph={{ rows: 8 }}
className="role-details-skeleton"
/>
</div>
);
}
if (isError || !role) {
return (
<div className="role-details-page">
<ErrorInPlace
error={toAPIError(
error,
'An unexpected error occurred while fetching role details.',
)}
/>
</div>
);
}
return (
<div className="role-details-page">
<div className="role-details-header">
<h2 className="role-details-title">Role {role.name}</h2>
</div>
<div className="role-details-nav">
<div className="role-details-tabs">
<button
type="button"
className={`role-details-tab${
activeTab === 'overview' ? ' role-details-tab--active' : ''
}`}
onClick={(): void => setActiveTab('overview')}
>
<Table2 size={14} />
Overview
</button>
<button
type="button"
className={`role-details-tab${
activeTab === 'members' ? ' role-details-tab--active' : ''
}`}
onClick={(): void => setActiveTab('members')}
>
<Users size={14} />
Members
<span className="role-details-tab-count">0</span>
</button>
</div>
{!isManaged && (
<div className="role-details-actions">
<Button
variant="ghost"
color="secondary"
className="role-details-delete-action-btn"
onClick={(): void => setIsDeleteModalOpen(true)}
aria-label="Delete role"
>
<Trash2 size={14} />
</Button>
<Button
variant="solid"
color="secondary"
size="sm"
onClick={openEditModal}
>
Edit Role Details
</Button>
</div>
)}
</div>
{/* Content */}
{activeTab === 'overview' && (
<OverviewTab
role={role}
isManaged={isManaged}
onPermissionClick={(label): void => setActivePermission(label)}
/>
)}
{activeTab === 'members' && <MembersTab />}
{!isManaged && (
<>
<PermissionSidePanel
open={activePermission !== null}
onClose={(): void => setActivePermission(null)}
permissionLabel={activePermission ?? ''}
resources={PERMISSION_RESOURCES}
initialConfig={
activePermission ? permissionConfigs[activePermission] : undefined
}
onSave={(config): void => {
if (activePermission) {
setPermissionConfigs((prev) => ({
...prev,
[activePermission]: config,
}));
}
}}
/>
<CreateRoleModal
isOpen={isEditModalOpen}
onClose={(): void => setIsEditModalOpen(false)}
initialData={{
id: roleId,
name: role.name || '',
description: role.description || '',
}}
/>
</>
)}
{/* Delete Role Confirmation Modal */}
<Modal
open={isDeleteModalOpen}
onCancel={(): void => setIsDeleteModalOpen(false)}
title={<span className="title">Delete Role</span>}
closable
footer={[
<Button
key="cancel"
className="cancel-btn"
prefixIcon={<X size={16} />}
onClick={(): void => setIsDeleteModalOpen(false)}
size="sm"
>
Cancel
</Button>,
<Button
key="delete"
className="delete-btn"
prefixIcon={<Trash2 size={16} />}
onClick={(): void => deleteRole({ pathParams: { id: roleId } })}
loading={isDeleting}
size="sm"
>
Delete Role
</Button>,
]}
destroyOnClose
className="role-details-delete-modal"
>
<p className="delete-text">
Are you sure you want to delete the role <strong>{role.name}</strong>? This
action cannot be undone.
</p>
</Modal>
</div>
);
}
export default RoleDetailsPage;

View File

@@ -0,0 +1 @@
export { default } from './RoleDetailsPage';

View File

@@ -0,0 +1,176 @@
import { useCallback, useEffect } from 'react';
import { useQueryClient } from 'react-query';
import { Button } from '@signozhq/button';
import { X } from '@signozhq/icons';
import { Input, inputVariants } from '@signozhq/input';
import { toast } from '@signozhq/sonner';
import { Form, Modal } from 'antd';
import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
import {
invalidateGetRole,
invalidateListRoles,
useCreateRole,
usePatchRole,
} from 'api/generated/services/role';
import type { RoletypesPostableRoleDTO } from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
import { useErrorModal } from 'providers/ErrorModalProvider';
import { ErrorV2Resp } from 'types/api';
import APIError from 'types/api/error';
import '../RolesSettings.styles.scss';
export interface CreateRoleModalInitialData {
id: string;
name: string;
description?: string;
}
interface CreateRoleModalProps {
isOpen: boolean;
onClose: () => void;
initialData?: CreateRoleModalInitialData;
}
interface CreateRoleFormValues {
name: string;
description?: string;
}
function CreateRoleModal({
isOpen,
onClose,
initialData,
}: CreateRoleModalProps): JSX.Element {
const [form] = Form.useForm<CreateRoleFormValues>();
const queryClient = useQueryClient();
const { showErrorModal } = useErrorModal();
const isEditMode = !!initialData?.id;
useEffect(() => {
if (isOpen) {
if (isEditMode && initialData) {
form.setFieldsValue({
name: initialData.name,
description: initialData.description || '',
});
} else {
form.resetFields();
}
}
}, [isOpen, isEditMode, initialData, form]);
const handleSuccess = async (message: string): Promise<void> => {
await invalidateListRoles(queryClient);
if (isEditMode && initialData?.id) {
await invalidateGetRole(queryClient, { id: initialData.id });
}
toast.success(message);
form.resetFields();
onClose();
};
const handleError = (error: unknown): void => {
try {
ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
} catch (apiError) {
showErrorModal(apiError as APIError);
}
};
const { mutate: createRole, isLoading: isCreating } = useCreateRole({
mutation: {
onSuccess: () => handleSuccess('Role created successfully'),
onError: handleError,
},
});
const { mutate: patchRole, isLoading: isPatching } = usePatchRole({
mutation: {
onSuccess: () => handleSuccess('Role updated successfully'),
onError: handleError,
},
});
const onSubmit = useCallback(async (): Promise<void> => {
try {
const values = await form.validateFields();
if (isEditMode && initialData?.id) {
patchRole({
pathParams: { id: initialData.id },
data: { description: values.description || '' },
});
} else {
const data: RoletypesPostableRoleDTO = {
name: values.name,
...(values.description ? { description: values.description } : {}),
};
createRole({ data });
}
} catch {
// form validation failed; antd handles inline error display
}
}, [form, createRole, patchRole, isEditMode, initialData]);
const onCancel = useCallback((): void => {
form.resetFields();
onClose();
}, [form, onClose]);
const isLoading = isCreating || isPatching;
return (
<Modal
open={isOpen}
onCancel={onCancel}
title={isEditMode ? 'Edit Role Details' : 'Create a New Role'}
footer={[
<Button
key="cancel"
variant="solid"
color="secondary"
onClick={onCancel}
size="sm"
>
<X size={14} />
Cancel
</Button>,
<Button
key="submit"
variant="solid"
color="primary"
onClick={onSubmit}
loading={isLoading}
size="sm"
>
{isEditMode ? 'Save Changes' : 'Create Role'}
</Button>,
]}
destroyOnClose
className="create-role-modal"
width={530}
>
<Form form={form} layout="vertical" className="create-role-form">
<Form.Item
name="name"
label="Name"
rules={[{ required: true, message: 'Role name is required' }]}
>
<Input
disabled={isEditMode}
placeholder="Enter role name e.g. : Service Owner"
/>
</Form.Item>
<Form.Item name="description" label="Description">
<textarea
className={inputVariants()}
placeholder="A helpful description of the role"
/>
</Form.Item>
</Form>
</Modal>
);
}
export default CreateRoleModal;

View File

@@ -5,6 +5,7 @@ import { useListRoles } from 'api/generated/services/role';
import { RoletypesRoleDTO } from 'api/generated/services/sigNoz.schemas';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import ROUTES from 'constants/routes';
import useUrlQuery from 'hooks/useUrlQuery';
import LineClampedText from 'periscope/components/LineClampedText/LineClampedText';
import { useTimezone } from 'providers/Timezone';
@@ -174,9 +175,28 @@ function RolesListingTable({
);
}
const navigateToRole = (roleId: string): void => {
history.push(ROUTES.ROLE_DETAILS.replace(':roleId', roleId));
};
// todo: use table from periscope when its available for consumption
const renderRow = (role: RoletypesRoleDTO): JSX.Element => (
<div key={role.id} className="roles-table-row">
<div
key={role.id}
className="roles-table-row roles-table-row--clickable"
role="button"
tabIndex={0}
onClick={(): void => {
if (role.id) {
navigateToRole(role.id);
}
}}
onKeyDown={(e): void => {
if ((e.key === 'Enter' || e.key === ' ') && role.id) {
navigateToRole(role.id);
}
}}
>
<div className="roles-table-cell roles-table-cell--name">
{role.name ?? '—'}
</div>

View File

@@ -2,6 +2,7 @@
.roles-settings-header {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
width: 100%;
padding: 16px;
@@ -31,8 +32,28 @@
padding: 0 16px;
}
.roles-settings-toolbar {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
.role-settings-toolbar-button {
display: flex;
width: 156px;
height: 32px;
padding: 6px 12px;
justify-content: center;
align-items: center;
gap: 6px;
border-radius: 2px;
}
}
// todo: https://github.com/SigNoz/components/issues/116
.roles-search-wrapper {
flex: 1;
input {
width: 100%;
background: var(--l3-background);
@@ -153,6 +174,14 @@
background: rgba(171, 189, 255, 0.02);
border-bottom: 1px solid var(--secondary);
gap: 24px;
&--clickable {
cursor: pointer;
&:hover {
background: rgba(171, 189, 255, 0.05);
}
}
}
.roles-table-cell {
@@ -236,3 +265,151 @@
background: rgba(0, 0, 0, 0.01);
}
}
.create-role-modal {
.ant-modal-content {
padding: 0;
background: var(--bg-ink-400);
border: 1px solid var(--bg-slate-500);
border-radius: 4px;
}
.ant-modal-header {
background: var(--bg-ink-400);
border-bottom: 1px solid var(--bg-slate-500);
padding: 16px;
margin-bottom: 0;
}
.ant-modal-close {
top: 14px;
inset-inline-end: 16px;
width: 14px;
height: 14px;
color: var(--foreground);
.ant-modal-close-x {
font-size: 12px;
display: flex;
align-items: center;
justify-content: center;
}
}
.ant-modal-title {
color: var(--text-base-white);
font-family: Inter;
font-size: 13px;
font-weight: 400;
line-height: 1;
letter-spacing: -0.065px;
}
.ant-modal-body {
padding: 16px;
}
.create-role-form {
display: flex;
flex-direction: column;
gap: 16px;
.ant-form-item {
margin-bottom: 0;
}
.ant-form-item-label {
padding-bottom: 8px;
label {
color: var(--foreground);
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 20px;
}
}
// todo: https://github.com/SigNoz/components/issues/116
input,
textarea {
width: 100%;
background: var(--l3-background);
border: 1px solid var(--l3-border);
border-radius: 2px;
padding: 6px 8px;
font-family: Inter;
font-size: 14px;
font-weight: 400;
line-height: 18px;
letter-spacing: -0.07px;
color: var(--l1-foreground);
outline: none;
box-shadow: none;
&::placeholder {
color: var(--l3-foreground);
opacity: 0.4;
}
&:focus,
&:hover {
border-color: var(--input);
box-shadow: none;
}
}
input {
height: 32px;
}
input:disabled {
opacity: 0.5;
cursor: not-allowed;
&:hover {
border-color: var(--l3-border);
box-shadow: none;
}
}
textarea {
min-height: 100px;
resize: vertical;
}
}
.ant-modal-footer {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-end;
gap: 12px;
margin: 0;
padding: 0 16px;
height: 56px;
border-top: 1px solid var(--bg-slate-500);
}
}
.lightMode {
.create-role-modal {
.ant-modal-content {
background: var(--bg-vanilla-100);
border-color: var(--bg-vanilla-300);
}
.ant-modal-header {
background: var(--bg-vanilla-100);
border-bottom-color: var(--bg-vanilla-300);
}
.ant-modal-title {
color: var(--text-base-black);
}
.ant-modal-footer {
border-top-color: var(--bg-vanilla-300);
}
}
}

View File

@@ -1,12 +1,16 @@
import { useState } from 'react';
import { Button } from '@signozhq/button';
import { Plus } from '@signozhq/icons';
import { Input } from '@signozhq/input';
import CreateRoleModal from './RolesComponents/CreateRoleModal';
import RolesListingTable from './RolesComponents/RolesListingTable';
import './RolesSettings.styles.scss';
function RolesSettings(): JSX.Element {
const [searchQuery, setSearchQuery] = useState('');
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
return (
<div className="roles-settings" data-testid="roles-settings">
@@ -17,16 +21,31 @@ function RolesSettings(): JSX.Element {
</p>
</div>
<div className="roles-settings-content">
<div className="roles-search-wrapper">
<Input
type="search"
placeholder="Search for roles..."
value={searchQuery}
onChange={(e): void => setSearchQuery(e.target.value)}
/>
<div className="roles-settings-toolbar">
<div className="roles-search-wrapper">
<Input
type="search"
placeholder="Search for roles..."
value={searchQuery}
onChange={(e): void => setSearchQuery(e.target.value)}
/>
</div>
<Button
variant="solid"
color="primary"
className="role-settings-toolbar-button"
onClick={(): void => setIsCreateModalOpen(true)}
>
<Plus size={14} />
Custom role
</Button>
</div>
<RolesListingTable searchQuery={searchQuery} />
</div>
<CreateRoleModal
isOpen={isCreateModalOpen}
onClose={(): void => setIsCreateModalOpen(false)}
/>
</div>
);
}

View File

@@ -160,6 +160,7 @@ export const routesToSkip = [
ROUTES.LOGS_PIPELINES,
ROUTES.BILLING,
ROUTES.ROLES_SETTINGS,
ROUTES.ROLE_DETAILS,
ROUTES.SUPPORT,
ROUTES.WORKSPACE_LOCKED,
ROUTES.WORKSPACE_SUSPENDED,

View File

@@ -78,6 +78,7 @@ function SettingsPage(): JSX.Element {
isEnabled:
item.key === ROUTES.BILLING ||
item.key === ROUTES.ROLES_SETTINGS ||
item.key === ROUTES.ROLE_DETAILS ||
item.key === ROUTES.INTEGRATIONS ||
item.key === ROUTES.CUSTOM_DOMAIN_SETTINGS ||
item.key === ROUTES.API_KEYS ||
@@ -109,6 +110,7 @@ function SettingsPage(): JSX.Element {
isEnabled:
item.key === ROUTES.BILLING ||
item.key === ROUTES.ROLES_SETTINGS ||
item.key === ROUTES.ROLE_DETAILS ||
item.key === ROUTES.INTEGRATIONS ||
item.key === ROUTES.API_KEYS ||
item.key === ROUTES.ORG_SETTINGS ||
@@ -138,7 +140,8 @@ function SettingsPage(): JSX.Element {
isEnabled:
item.key === ROUTES.API_KEYS ||
item.key === ROUTES.ORG_SETTINGS ||
item.key === ROUTES.ROLES_SETTINGS
item.key === ROUTES.ROLES_SETTINGS ||
item.key === ROUTES.ROLE_DETAILS
? true
: item.isEnabled,
}));
@@ -230,6 +233,14 @@ function SettingsPage(): JSX.Element {
return true;
}
if (
(pathname.startsWith(ROUTES.ROLES_SETTINGS) &&
key === ROUTES.ROLES_SETTINGS) ||
(pathname.startsWith(ROUTES.ROLE_DETAILS) && key === ROUTES.ROLE_DETAILS)
) {
return true;
}
return pathname === key;
};

View File

@@ -13,6 +13,7 @@ import MultiIngestionSettings from 'container/IngestionSettings/MultiIngestionSe
import MySettings from 'container/MySettings';
import OrganizationSettings from 'container/OrganizationSettings';
import RolesSettings from 'container/RolesSettings';
import RoleDetailsPage from 'container/RolesSettings/RoleDetails';
import { TFunction } from 'i18next';
import {
Backpack,
@@ -163,6 +164,15 @@ export const rolesSettings = (t: TFunction): RouteTabProps['routes'] => [
},
];
export const roleDetails = (): RouteTabProps['routes'] => [
{
Component: RoleDetailsPage,
name: <div className="periscope-tab">Role Details</div>,
route: ROUTES.ROLE_DETAILS,
key: ROUTES.ROLE_DETAILS,
},
];
export const keyboardShortcuts = (t: TFunction): RouteTabProps['routes'] => [
{
Component: Shortcuts,

View File

@@ -15,6 +15,7 @@ import {
multiIngestionSettings,
mySettings,
organizationSettings,
roleDetails,
rolesSettings,
} from './config';
@@ -76,6 +77,7 @@ export const getRoutes = (
...createAlertChannels(t),
...editAlertChannels(t),
...keyboardShortcuts(t),
...roleDetails(),
);
return settings;

View File

@@ -98,6 +98,7 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
WORKSPACE_LOCKED: ['ADMIN', 'EDITOR', 'VIEWER'],
WORKSPACE_SUSPENDED: ['ADMIN', 'EDITOR', 'VIEWER'],
ROLES_SETTINGS: ['ADMIN'],
ROLE_DETAILS: ['ADMIN'],
BILLING: ['ADMIN'],
SUPPORT: ['ADMIN', 'EDITOR', 'VIEWER'],
SOMETHING_WENT_WRONG: ['ADMIN', 'EDITOR', 'VIEWER'],

View File

@@ -3,7 +3,6 @@ package configflagger
import (
"context"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/flagger"
"github.com/SigNoz/signoz/pkg/types/featuretypes"
@@ -33,10 +32,6 @@ func New(ctx context.Context, ps factory.ProviderSettings, c flagger.Config, reg
for name, value := range c.Config.Boolean {
feature, _, err := registry.GetByString(name)
if err != nil {
if errors.Ast(err, errors.TypeNotFound) {
settings.Logger().WarnContext(ctx, "skipping unknown feature flag", "name", name, "kind", "boolean")
continue
}
return nil, err
}
@@ -51,10 +46,6 @@ func New(ctx context.Context, ps factory.ProviderSettings, c flagger.Config, reg
for name, value := range c.Config.String {
feature, _, err := registry.GetByString(name)
if err != nil {
if errors.Ast(err, errors.TypeNotFound) {
settings.Logger().WarnContext(ctx, "skipping unknown feature flag", "name", name, "kind", "string")
continue
}
return nil, err
}
@@ -69,10 +60,6 @@ func New(ctx context.Context, ps factory.ProviderSettings, c flagger.Config, reg
for name, value := range c.Config.Float {
feature, _, err := registry.GetByString(name)
if err != nil {
if errors.Ast(err, errors.TypeNotFound) {
settings.Logger().WarnContext(ctx, "skipping unknown feature flag", "name", name, "kind", "float")
continue
}
return nil, err
}
@@ -87,10 +74,6 @@ func New(ctx context.Context, ps factory.ProviderSettings, c flagger.Config, reg
for name, value := range c.Config.Integer {
feature, _, err := registry.GetByString(name)
if err != nil {
if errors.Ast(err, errors.TypeNotFound) {
settings.Logger().WarnContext(ctx, "skipping unknown feature flag", "name", name, "kind", "integer")
continue
}
return nil, err
}
@@ -105,10 +88,6 @@ func New(ctx context.Context, ps factory.ProviderSettings, c flagger.Config, reg
for name, value := range c.Config.Object {
feature, _, err := registry.GetByString(name)
if err != nil {
if errors.Ast(err, errors.TypeNotFound) {
settings.Logger().WarnContext(ctx, "skipping unknown feature flag", "name", name, "kind", "object")
continue
}
return nil, err
}

View File

@@ -5,7 +5,6 @@ import "github.com/SigNoz/signoz/pkg/types/featuretypes"
var (
FeatureUseSpanMetrics = featuretypes.MustNewName("use_span_metrics")
FeatureKafkaSpanEval = featuretypes.MustNewName("kafka_span_eval")
FeatureHideRootUser = featuretypes.MustNewName("hide_root_user")
)
func MustNewRegistry() featuretypes.Registry {
@@ -26,14 +25,6 @@ func MustNewRegistry() featuretypes.Registry {
DefaultVariant: featuretypes.MustNewName("disabled"),
Variants: featuretypes.NewBooleanVariants(),
},
&featuretypes.Feature{
Name: FeatureHideRootUser,
Kind: featuretypes.KindBoolean,
Stage: featuretypes.StageStable,
Description: "Controls whether root admin user is hidden or not",
DefaultVariant: featuretypes.MustNewName("disabled"),
Variants: featuretypes.NewBooleanVariants(),
},
)
if err != nil {
panic(err)

View File

@@ -120,8 +120,6 @@ func FilterResponse(results []*qbtypes.QueryRangeResponse) []*qbtypes.QueryRange
}
}
resultData.Rows = filteredRows
case *qbtypes.ScalarData:
resultData.Data = filterScalarDataIPs(resultData.Columns, resultData.Data)
}
filteredData = append(filteredData, result)
@@ -147,39 +145,6 @@ func shouldIncludeSeries(series *qbtypes.TimeSeries) bool {
return true
}
func filterScalarDataIPs(columns []*qbtypes.ColumnDescriptor, data [][]any) [][]any {
// Find column indices for server address fields
serverColIndices := make([]int, 0)
for i, col := range columns {
if col.Name == derivedKeyHTTPHost {
serverColIndices = append(serverColIndices, i)
}
}
if len(serverColIndices) == 0 {
return data
}
filtered := make([][]any, 0, len(data))
for _, row := range data {
includeRow := true
for _, colIdx := range serverColIndices {
if colIdx < len(row) {
if strVal, ok := row[colIdx].(string); ok {
if net.ParseIP(strVal) != nil {
includeRow = false
break
}
}
}
}
if includeRow {
filtered = append(filtered, row)
}
}
return filtered
}
func shouldIncludeRow(row *qbtypes.RawRow) bool {
if row.Data != nil {
if domainVal, ok := row.Data[derivedKeyHTTPHost]; ok {

View File

@@ -117,59 +117,6 @@ func TestFilterResponse(t *testing.T) {
},
},
},
{
name: "should filter out IP addresses from scalar data",
input: []*qbtypes.QueryRangeResponse{
{
Data: qbtypes.QueryData{
Results: []any{
&qbtypes.ScalarData{
QueryName: "endpoints",
Columns: []*qbtypes.ColumnDescriptor{
{
TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: derivedKeyHTTPHost},
Type: qbtypes.ColumnTypeGroup,
},
{
TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "endpoints"},
Type: qbtypes.ColumnTypeAggregation,
},
},
Data: [][]any{
{"192.168.1.1", 10},
{"example.com", 20},
{"10.0.0.1", 5},
},
},
},
},
},
},
expected: []*qbtypes.QueryRangeResponse{
{
Data: qbtypes.QueryData{
Results: []any{
&qbtypes.ScalarData{
QueryName: "endpoints",
Columns: []*qbtypes.ColumnDescriptor{
{
TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: derivedKeyHTTPHost},
Type: qbtypes.ColumnTypeGroup,
},
{
TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "endpoints"},
Type: qbtypes.ColumnTypeAggregation,
},
},
Data: [][]any{
{"example.com", 20},
},
},
},
},
},
},
},
}
for _, tt := range tests {

View File

@@ -2,22 +2,18 @@ package impluser
import (
"context"
"slices"
"github.com/SigNoz/signoz/pkg/flagger"
"github.com/SigNoz/signoz/pkg/modules/user"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/featuretypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
type getter struct {
store types.UserStore
flagger flagger.Flagger
store types.UserStore
}
func NewGetter(store types.UserStore, flagger flagger.Flagger) user.Getter {
return &getter{store: store, flagger: flagger}
func NewGetter(store types.UserStore) user.Getter {
return &getter{store: store}
}
func (module *getter) GetRootUserByOrgID(ctx context.Context, orgID valuer.UUID) (*types.User, error) {
@@ -30,14 +26,6 @@ func (module *getter) ListByOrgID(ctx context.Context, orgID valuer.UUID) ([]*ty
return nil, err
}
// filter root users if feature flag `hide_root_users` is true
evalCtx := featuretypes.NewFlaggerEvaluationContext(orgID)
hideRootUsers := module.flagger.BooleanOrEmpty(ctx, flagger.FeatureHideRootUser, evalCtx)
if hideRootUsers {
users = slices.DeleteFunc(users, func(user *types.User) bool { return user.IsRoot })
}
return users, nil
}

View File

@@ -3,7 +3,7 @@ package formatter
import (
"fmt"
"github.com/SigNoz/signoz/pkg/converter"
"github.com/SigNoz/signoz/pkg/query-service/converter"
"github.com/dustin/go-humanize"
)

View File

@@ -3,7 +3,7 @@ package formatter
import (
"fmt"
"github.com/SigNoz/signoz/pkg/converter"
"github.com/SigNoz/signoz/pkg/query-service/converter"
"github.com/dustin/go-humanize"
)

View File

@@ -78,8 +78,9 @@ func toFixed(value float64, decimals DecimalCount) string {
}
decimalPos := strings.Index(formatted, ".")
precision := 0
if decimalPos != -1 {
precision := len(formatted) - decimalPos - 1
precision = len(formatted) - decimalPos - 1
if precision < *decimals {
return formatted + strings.Repeat("0", *decimals-precision)
}
@@ -88,8 +89,8 @@ func toFixed(value float64, decimals DecimalCount) string {
return formatted
}
func toFixedScaled(value float64, scaleFormat string) string {
return toFixed(value, nil) + scaleFormat
func toFixedScaled(value float64, decimals DecimalCount, scaleFormat string) string {
return toFixed(value, decimals) + scaleFormat
}
func getDecimalsForValue(value float64) int {

View File

@@ -13,35 +13,35 @@ func (*throughputFormatter) Name() string {
return "throughput"
}
func simpleCountUnit(value float64, symbol string) string {
func simpleCountUnit(value float64, decimals *int, symbol string) string {
units := []string{"", "K", "M", "B", "T"}
scaler := scaledUnits(1000, units, 0)
return scaler(value, nil) + " " + symbol
return scaler(value, decimals) + " " + symbol
}
func (f *throughputFormatter) Format(value float64, unit string) string {
switch unit {
case "cps", "{count}/s":
return simpleCountUnit(value, "c/s")
return simpleCountUnit(value, nil, "c/s")
case "ops", "{ops}/s":
return simpleCountUnit(value, "op/s")
return simpleCountUnit(value, nil, "op/s")
case "reqps", "{req}/s":
return simpleCountUnit(value, "req/s")
return simpleCountUnit(value, nil, "req/s")
case "rps", "{read}/s":
return simpleCountUnit(value, "r/s")
return simpleCountUnit(value, nil, "r/s")
case "wps", "{write}/s":
return simpleCountUnit(value, "w/s")
return simpleCountUnit(value, nil, "w/s")
case "iops", "{iops}/s":
return simpleCountUnit(value, "iops")
return simpleCountUnit(value, nil, "iops")
case "cpm", "{count}/min":
return simpleCountUnit(value, "c/m")
return simpleCountUnit(value, nil, "c/m")
case "opm", "{ops}/min":
return simpleCountUnit(value, "op/m")
return simpleCountUnit(value, nil, "op/m")
case "rpm", "{read}/min":
return simpleCountUnit(value, "r/m")
return simpleCountUnit(value, nil, "r/m")
case "wpm", "{write}/min":
return simpleCountUnit(value, "w/m")
return simpleCountUnit(value, nil, "w/m")
}
// When unit is not matched, return the value as it is.
return fmt.Sprintf("%v", value)

View File

@@ -46,17 +46,17 @@ func toNanoSeconds(value float64) string {
if absValue < 1000 {
return toFixed(value, nil) + " ns"
} else if absValue < 1000000 { // 2000 ns is better represented as 2 µs
return toFixedScaled(value/1000, " µs")
return toFixedScaled(value/1000, nil, " µs")
} else if absValue < 1000000000 { // 2000000 ns is better represented as 2 ms
return toFixedScaled(value/1000000, " ms")
return toFixedScaled(value/1000000, nil, " ms")
} else if absValue < 60000000000 {
return toFixedScaled(value/1000000000, " s")
return toFixedScaled(value/1000000000, nil, " s")
} else if absValue < 3600000000000 {
return toFixedScaled(value/60000000000, " min")
return toFixedScaled(value/60000000000, nil, " min")
} else if absValue < 86400000000000 {
return toFixedScaled(value/3600000000000, " hour")
return toFixedScaled(value/3600000000000, nil, " hour")
} else {
return toFixedScaled(value/86400000000000, " day")
return toFixedScaled(value/86400000000000, nil, " day")
}
}
@@ -66,9 +66,9 @@ func toMicroSeconds(value float64) string {
if absValue < 1000 {
return toFixed(value, nil) + " µs"
} else if absValue < 1000000 { // 2000 µs is better represented as 2 ms
return toFixedScaled(value/1000, " ms")
return toFixedScaled(value/1000, nil, " ms")
} else {
return toFixedScaled(value/1000000, " s")
return toFixedScaled(value/1000000, nil, " s")
}
}
@@ -80,16 +80,16 @@ func toMilliSeconds(value float64) string {
if absValue < 1000 {
return toFixed(value, nil) + " ms"
} else if absValue < 60000 {
return toFixedScaled(value/1000, " s")
return toFixedScaled(value/1000, nil, " s")
} else if absValue < 3600000 {
return toFixedScaled(value/60000, " min")
return toFixedScaled(value/60000, nil, " min")
} else if absValue < 86400000 { // 172800000 ms is better represented as 2 day
return toFixedScaled(value/3600000, " hour")
return toFixedScaled(value/3600000, nil, " hour")
} else if absValue < 31536000000 {
return toFixedScaled(value/86400000, " day")
return toFixedScaled(value/86400000, nil, " day")
}
return toFixedScaled(value/31536000000, " year")
return toFixedScaled(value/31536000000, nil, " year")
}
// toSeconds returns a easy to read string representation of the given value in seconds
@@ -97,24 +97,24 @@ func toSeconds(value float64) string {
absValue := math.Abs(value)
if absValue < 0.000001 {
return toFixedScaled(value*1e9, " ns")
return toFixedScaled(value*1e9, nil, " ns")
} else if absValue < 0.001 {
return toFixedScaled(value*1e6, " µs")
return toFixedScaled(value*1e6, nil, " µs")
} else if absValue < 1 {
return toFixedScaled(value*1e3, " ms")
return toFixedScaled(value*1e3, nil, " ms")
} else if absValue < 60 {
return toFixed(value, nil) + " s"
} else if absValue < 3600 {
return toFixedScaled(value/60, " min")
return toFixedScaled(value/60, nil, " min")
} else if absValue < 86400 { // 56000 s is better represented as 15.56 hour
return toFixedScaled(value/3600, " hour")
return toFixedScaled(value/3600, nil, " hour")
} else if absValue < 604800 {
return toFixedScaled(value/86400, " day")
return toFixedScaled(value/86400, nil, " day")
} else if absValue < 31536000 {
return toFixedScaled(value/604800, " week")
return toFixedScaled(value/604800, nil, " week")
}
return toFixedScaled(value/3.15569e7, " year")
return toFixedScaled(value/3.15569e7, nil, " year")
}
// toMinutes returns a easy to read string representation of the given value in minutes
@@ -124,13 +124,13 @@ func toMinutes(value float64) string {
if absValue < 60 {
return toFixed(value, nil) + " min"
} else if absValue < 1440 {
return toFixedScaled(value/60, " hour")
return toFixedScaled(value/60, nil, " hour")
} else if absValue < 10080 {
return toFixedScaled(value/1440, " day")
return toFixedScaled(value/1440, nil, " day")
} else if absValue < 604800 {
return toFixedScaled(value/10080, " week")
return toFixedScaled(value/10080, nil, " week")
} else {
return toFixedScaled(value/5.25948e5, " year")
return toFixedScaled(value/5.25948e5, nil, " year")
}
}
@@ -142,11 +142,11 @@ func toHours(value float64) string {
if absValue < 24 {
return toFixed(value, nil) + " hour"
} else if absValue < 168 {
return toFixedScaled(value/24, " day")
return toFixedScaled(value/24, nil, " day")
} else if absValue < 8760 {
return toFixedScaled(value/168, " week")
return toFixedScaled(value/168, nil, " week")
} else {
return toFixedScaled(value/8760, " year")
return toFixedScaled(value/8760, nil, " year")
}
}
@@ -157,9 +157,9 @@ func toDays(value float64) string {
if absValue < 7 {
return toFixed(value, nil) + " day"
} else if absValue < 365 {
return toFixedScaled(value/7, " week")
return toFixedScaled(value/7, nil, " week")
} else {
return toFixedScaled(value/365, " year")
return toFixedScaled(value/365, nil, " year")
}
}
@@ -170,6 +170,6 @@ func toWeeks(value float64) string {
if absValue < 52 {
return toFixed(value, nil) + " week"
} else {
return toFixedScaled(value/52, " year")
return toFixedScaled(value/52, nil, " year")
}
}

View File

@@ -9,7 +9,7 @@ import (
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/prometheus"
"github.com/SigNoz/signoz/pkg/formatter"
"github.com/SigNoz/signoz/pkg/query-service/formatter"
"github.com/SigNoz/signoz/pkg/query-service/interfaces"
"github.com/SigNoz/signoz/pkg/query-service/model"
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"

View File

@@ -33,7 +33,7 @@ import (
logsv3 "github.com/SigNoz/signoz/pkg/query-service/app/logs/v3"
tracesV4 "github.com/SigNoz/signoz/pkg/query-service/app/traces/v4"
"github.com/SigNoz/signoz/pkg/formatter"
"github.com/SigNoz/signoz/pkg/query-service/formatter"
querierV5 "github.com/SigNoz/signoz/pkg/querier"

View File

@@ -11,11 +11,8 @@ import (
"github.com/SigNoz/signoz/pkg/alertmanager/signozalertmanager"
"github.com/SigNoz/signoz/pkg/emailing/emailingtest"
"github.com/SigNoz/signoz/pkg/factory/factorytest"
"github.com/SigNoz/signoz/pkg/flagger"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/modules/dashboard/impldashboard"
"github.com/SigNoz/signoz/pkg/modules/organization/implorganization"
"github.com/SigNoz/signoz/pkg/modules/user/impluser"
"github.com/SigNoz/signoz/pkg/querier"
"github.com/SigNoz/signoz/pkg/queryparser"
"github.com/SigNoz/signoz/pkg/sharder"
@@ -44,13 +41,7 @@ func TestNewHandlers(t *testing.T) {
queryParser := queryparser.New(providerSettings)
require.NoError(t, err)
dashboardModule := impldashboard.NewModule(impldashboard.NewStore(sqlstore), providerSettings, nil, orgGetter, queryParser)
flagger, err := flagger.New(context.Background(), instrumentationtest.New().ToProviderSettings(), flagger.Config{}, flagger.MustNewRegistry())
require.NoError(t, err)
userGetter := impluser.NewGetter(impluser.NewStore(sqlstore, providerSettings), flagger)
modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, nil, nil, nil, nil, nil, nil, nil, queryParser, Config{}, dashboardModule, userGetter)
modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, nil, nil, nil, nil, nil, nil, nil, queryParser, Config{}, dashboardModule)
querierHandler := querier.NewHandler(providerSettings, nil, nil)
handlers := NewHandlers(modules, providerSettings, nil, querierHandler, nil, nil, nil, nil, nil, nil, nil)

View File

@@ -85,11 +85,11 @@ func NewModules(
queryParser queryparser.QueryParser,
config Config,
dashboard dashboard.Module,
userGetter user.Getter,
) Modules {
quickfilter := implquickfilter.NewModule(implquickfilter.NewStore(sqlstore))
orgSetter := implorganization.NewSetter(implorganization.NewStore(sqlstore), alertmanager, quickfilter)
user := impluser.NewModule(impluser.NewStore(sqlstore, providerSettings), tokenizer, emailing, providerSettings, orgSetter, authz, analytics, config.User)
userGetter := impluser.NewGetter(impluser.NewStore(sqlstore, providerSettings))
ruleStore := sqlrulestore.NewRuleStore(sqlstore, queryParser, providerSettings)
return Modules{

View File

@@ -11,11 +11,8 @@ import (
"github.com/SigNoz/signoz/pkg/alertmanager/signozalertmanager"
"github.com/SigNoz/signoz/pkg/emailing/emailingtest"
"github.com/SigNoz/signoz/pkg/factory/factorytest"
"github.com/SigNoz/signoz/pkg/flagger"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/modules/dashboard/impldashboard"
"github.com/SigNoz/signoz/pkg/modules/organization/implorganization"
"github.com/SigNoz/signoz/pkg/modules/user/impluser"
"github.com/SigNoz/signoz/pkg/queryparser"
"github.com/SigNoz/signoz/pkg/sharder"
"github.com/SigNoz/signoz/pkg/sharder/noopsharder"
@@ -43,13 +40,7 @@ func TestNewModules(t *testing.T) {
queryParser := queryparser.New(providerSettings)
require.NoError(t, err)
dashboardModule := impldashboard.NewModule(impldashboard.NewStore(sqlstore), providerSettings, nil, orgGetter, queryParser)
flagger, err := flagger.New(context.Background(), instrumentationtest.New().ToProviderSettings(), flagger.Config{}, flagger.MustNewRegistry())
require.NoError(t, err)
userGetter := impluser.NewGetter(impluser.NewStore(sqlstore, providerSettings), flagger)
modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, nil, nil, nil, nil, nil, nil, nil, queryParser, Config{}, dashboardModule, userGetter)
modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, nil, nil, nil, nil, nil, nil, nil, queryParser, Config{}, dashboardModule)
reflectVal := reflect.ValueOf(modules)
for i := 0; i < reflectVal.NumField(); i++ {

View File

@@ -169,7 +169,6 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewAddAnonymousPublicDashboardTransactionFactory(sqlstore),
sqlmigration.NewAddRootUserFactory(sqlstore, sqlschema),
sqlmigration.NewAddUserEmailOrgIDIndexFactory(sqlstore, sqlschema),
sqlmigration.NewMigrateRulesV4ToV5Factory(sqlstore, telemetryStore),
)
}

View File

@@ -1,13 +1,11 @@
package signoz
import (
"context"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/SigNoz/signoz/pkg/alertmanager/nfmanager/nfmanagertest"
"github.com/SigNoz/signoz/pkg/analytics"
"github.com/SigNoz/signoz/pkg/flagger"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/modules/organization/implorganization"
"github.com/SigNoz/signoz/pkg/modules/user/impluser"
@@ -77,12 +75,7 @@ func TestNewProviderFactories(t *testing.T) {
})
assert.NotPanics(t, func() {
flagger, err := flagger.New(context.Background(), instrumentationtest.New().ToProviderSettings(), flagger.Config{}, flagger.MustNewRegistry())
if err != nil {
panic(err)
}
userGetter := impluser.NewGetter(impluser.NewStore(sqlstoretest.New(sqlstore.Config{Provider: "sqlite"}, sqlmock.QueryMatcherEqual), instrumentationtest.New().ToProviderSettings()), flagger)
userGetter := impluser.NewGetter(impluser.NewStore(sqlstoretest.New(sqlstore.Config{Provider: "sqlite"}, sqlmock.QueryMatcherEqual), instrumentationtest.New().ToProviderSettings()))
orgGetter := implorganization.NewGetter(implorganization.NewStore(sqlstoretest.New(sqlstore.Config{Provider: "sqlite"}, sqlmock.QueryMatcherEqual)), nil)
telemetryStore := telemetrystoretest.New(telemetrystore.Config{Provider: "clickhouse"}, sqlmock.QueryMatcherEqual)
NewStatsReporterProviderFactories(telemetryStore, []statsreporter.StatsCollector{}, orgGetter, userGetter, tokenizertest.NewMockTokenizer(t), version.Build{}, analytics.Config{Enabled: true})

View File

@@ -280,7 +280,7 @@ func New(
}
// Initialize user getter
userGetter := impluser.NewGetter(impluser.NewStore(sqlstore, providerSettings), flagger)
userGetter := impluser.NewGetter(impluser.NewStore(sqlstore, providerSettings))
licensingProviderFactory := licenseProviderFactory(sqlstore, zeus, orgGetter, analytics)
licensing, err := licensingProviderFactory.New(
@@ -388,7 +388,7 @@ func New(
}
// Initialize all modules
modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, analytics, querier, telemetrystore, telemetryMetadataStore, authNs, authz, cache, queryParser, config, dashboard, userGetter)
modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, analytics, querier, telemetrystore, telemetryMetadataStore, authNs, authz, cache, queryParser, config, dashboard)
userService := impluser.NewService(providerSettings, impluser.NewStore(sqlstore, providerSettings), modules.User, orgGetter, authz, config.User.Root)

View File

@@ -1,209 +0,0 @@
package sqlmigration
import (
"context"
"database/sql"
"encoding/json"
"log/slog"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/transition"
"github.com/uptrace/bun"
"github.com/uptrace/bun/migrate"
)
type migrateRulesV4ToV5 struct {
store sqlstore.SQLStore
telemetryStore telemetrystore.TelemetryStore
logger *slog.Logger
}
func NewMigrateRulesV4ToV5Factory(
store sqlstore.SQLStore,
telemetryStore telemetrystore.TelemetryStore,
) factory.ProviderFactory[SQLMigration, Config] {
return factory.NewProviderFactory(
factory.MustNewName("migrate_rules_post_deprecation"),
func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
return &migrateRulesV4ToV5{
store: store,
telemetryStore: telemetryStore,
logger: ps.Logger,
}, nil
})
}
func (migration *migrateRulesV4ToV5) Register(migrations *migrate.Migrations) error {
if err := migrations.Register(migration.Up, migration.Down); err != nil {
return err
}
return nil
}
func (migration *migrateRulesV4ToV5) getLogDuplicateKeys(ctx context.Context) ([]string, error) {
query := `
SELECT name
FROM (
SELECT DISTINCT name FROM signoz_logs.distributed_logs_attribute_keys
INTERSECT
SELECT DISTINCT name FROM signoz_logs.distributed_logs_resource_keys
)
ORDER BY name
`
rows, err := migration.telemetryStore.ClickhouseDB().Query(ctx, query)
if err != nil {
migration.logger.WarnContext(ctx, "failed to query log duplicate keys", "error", err)
return nil, nil
}
defer rows.Close()
var keys []string
for rows.Next() {
var key string
if err := rows.Scan(&key); err != nil {
migration.logger.WarnContext(ctx, "failed to scan log duplicate key", "error", err)
continue
}
keys = append(keys, key)
}
return keys, nil
}
func (migration *migrateRulesV4ToV5) getTraceDuplicateKeys(ctx context.Context) ([]string, error) {
query := `
SELECT tagKey
FROM signoz_traces.distributed_span_attributes_keys
WHERE tagType IN ('tag', 'resource')
GROUP BY tagKey
HAVING COUNT(DISTINCT tagType) > 1
ORDER BY tagKey
`
rows, err := migration.telemetryStore.ClickhouseDB().Query(ctx, query)
if err != nil {
migration.logger.WarnContext(ctx, "failed to query trace duplicate keys", "error", err)
return nil, nil
}
defer rows.Close()
var keys []string
for rows.Next() {
var key string
if err := rows.Scan(&key); err != nil {
migration.logger.WarnContext(ctx, "failed to scan trace duplicate key", "error", err)
continue
}
keys = append(keys, key)
}
return keys, nil
}
func (migration *migrateRulesV4ToV5) Up(ctx context.Context, db *bun.DB) error {
logsKeys, err := migration.getLogDuplicateKeys(ctx)
if err != nil {
return err
}
tracesKeys, err := migration.getTraceDuplicateKeys(ctx)
if err != nil {
return err
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() {
_ = tx.Rollback()
}()
var rules []struct {
ID string `bun:"id"`
Data map[string]any `bun:"data"`
}
err = tx.NewSelect().
Table("rule").
Column("id", "data").
Scan(ctx, &rules)
if err != nil {
if err == sql.ErrNoRows {
return nil
}
return err
}
alertsMigrator := transition.NewAlertMigrateV5(migration.logger, logsKeys, tracesKeys)
count := 0
for _, rule := range rules {
version, _ := rule.Data["version"].(string)
if version == "v5" {
continue
}
if version == "" {
migration.logger.WarnContext(ctx, "unexpected empty version for rule", "rule_id", rule.ID)
}
migration.logger.InfoContext(ctx, "migrating rule v4 to v5", "rule_id", rule.ID, "current_version", version)
// Check if the queries envelope already exists and is non-empty
hasQueriesEnvelope := false
if condition, ok := rule.Data["condition"].(map[string]any); ok {
if compositeQuery, ok := condition["compositeQuery"].(map[string]any); ok {
if queries, ok := compositeQuery["queries"].([]any); ok && len(queries) > 0 {
hasQueriesEnvelope = true
}
}
}
if hasQueriesEnvelope {
// already has queries envelope, just bump version
// this is because user made a mistake of choosing version
migration.logger.InfoContext(ctx, "rule already has queries envelope, bumping version", "rule_id", rule.ID)
rule.Data["version"] = "v5"
} else {
// old format, run full migration
migration.logger.InfoContext(ctx, "rule has old format, running full migration", "rule_id", rule.ID)
updated := alertsMigrator.Migrate(ctx, rule.Data)
if !updated {
migration.logger.WarnContext(ctx, "expected updated to be true but got false", "rule_id", rule.ID)
continue
}
rule.Data["version"] = "v5"
}
dataJSON, err := json.Marshal(rule.Data)
if err != nil {
return err
}
_, err = tx.NewUpdate().
Table("rule").
Set("data = ?", string(dataJSON)).
Where("id = ?", rule.ID).
Exec(ctx)
if err != nil {
return err
}
count++
}
if count != 0 {
migration.logger.InfoContext(ctx, "migrate v4 alerts", "count", count)
}
return tx.Commit()
}
func (migration *migrateRulesV4ToV5) Down(ctx context.Context, db *bun.DB) error {
return nil
}

View File

@@ -355,10 +355,6 @@ func (r *PostableRule) validate() error {
errs = append(errs, signozError.NewInvalidInputf(signozError.CodeInvalidInput, "composite query is required"))
}
if r.Version != "v5" {
errs = append(errs, signozError.NewInvalidInputf(signozError.CodeInvalidInput, "only version v5 is supported, got %q", r.Version))
}
if isAllQueriesDisabled(r.RuleCondition.CompositeQuery) {
errs = append(errs, signozError.NewInvalidInputf(signozError.CodeInvalidInput, "all queries are disabled in rule condition"))
}

View File

@@ -108,7 +108,6 @@ func TestParseIntoRule(t *testing.T) {
"ruleType": "threshold_rule",
"evalWindow": "5m",
"frequency": "1m",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -151,7 +150,6 @@ func TestParseIntoRule(t *testing.T) {
content: []byte(`{
"alert": "DefaultsRule",
"ruleType": "threshold_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -189,7 +187,6 @@ func TestParseIntoRule(t *testing.T) {
initRule: PostableRule{},
content: []byte(`{
"alert": "PromQLRule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "promql",
@@ -259,7 +256,6 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {
content: []byte(`{
"alert": "SeverityLabelTest",
"schemaVersion": "v1",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -348,7 +344,6 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {
content: []byte(`{
"alert": "NoLabelsTest",
"schemaVersion": "v1",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -389,7 +384,6 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {
content: []byte(`{
"alert": "OverwriteTest",
"schemaVersion": "v1",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -480,7 +474,6 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {
content: []byte(`{
"alert": "V2Test",
"schemaVersion": "v2",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -524,7 +517,6 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {
initRule: PostableRule{},
content: []byte(`{
"alert": "DefaultSchemaTest",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -577,7 +569,6 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {
func TestParseIntoRuleThresholdGeneration(t *testing.T) {
content := []byte(`{
"alert": "TestThresholds",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -648,7 +639,6 @@ func TestParseIntoRuleMultipleThresholds(t *testing.T) {
"schemaVersion": "v2",
"alert": "MultiThresholdAlert",
"ruleType": "threshold_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -742,7 +732,6 @@ func TestAnomalyNegationEval(t *testing.T) {
ruleJSON: []byte(`{
"alert": "AnomalyBelowTest",
"ruleType": "anomaly_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -777,7 +766,6 @@ func TestAnomalyNegationEval(t *testing.T) {
ruleJSON: []byte(`{
"alert": "AnomalyBelowTest",
"ruleType": "anomaly_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -811,7 +799,6 @@ func TestAnomalyNegationEval(t *testing.T) {
ruleJSON: []byte(`{
"alert": "AnomalyAboveTest",
"ruleType": "anomaly_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -846,7 +833,6 @@ func TestAnomalyNegationEval(t *testing.T) {
ruleJSON: []byte(`{
"alert": "AnomalyAboveTest",
"ruleType": "anomaly_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -880,7 +866,6 @@ func TestAnomalyNegationEval(t *testing.T) {
ruleJSON: []byte(`{
"alert": "AnomalyBelowAllTest",
"ruleType": "anomaly_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -916,7 +901,6 @@ func TestAnomalyNegationEval(t *testing.T) {
ruleJSON: []byte(`{
"alert": "AnomalyBelowAllTest",
"ruleType": "anomaly_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -951,7 +935,6 @@ func TestAnomalyNegationEval(t *testing.T) {
ruleJSON: []byte(`{
"alert": "AnomalyOutOfBoundsTest",
"ruleType": "anomaly_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -986,7 +969,6 @@ func TestAnomalyNegationEval(t *testing.T) {
ruleJSON: []byte(`{
"alert": "ThresholdTest",
"ruleType": "threshold_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",
@@ -1021,7 +1003,6 @@ func TestAnomalyNegationEval(t *testing.T) {
ruleJSON: []byte(`{
"alert": "ThresholdTest",
"ruleType": "threshold_rule",
"version": "v5",
"condition": {
"compositeQuery": {
"queryType": "builder",

View File

@@ -7,7 +7,7 @@ import (
"strings"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/converter"
"github.com/SigNoz/signoz/pkg/query-service/converter"
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
"github.com/SigNoz/signoz/pkg/query-service/utils/labels"
"github.com/SigNoz/signoz/pkg/valuer"