mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-17 22:00:42 +00:00
Compare commits
14 Commits
main
...
feat/servi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
043cb3f64d | ||
|
|
2e7b42e734 | ||
|
|
934866ab9d | ||
|
|
91900ea04e | ||
|
|
7ccc4bff6b | ||
|
|
11f6f7b0e1 | ||
|
|
5c2c814e8a | ||
|
|
0c1560514d | ||
|
|
47e2486639 | ||
|
|
fdd4d8d078 | ||
|
|
079ce982c6 | ||
|
|
de1edd1f2d | ||
|
|
6429c7a3ea | ||
|
|
82d7243ad9 |
@@ -299,6 +299,10 @@ export function createAggregation(
|
||||
reduceTo: haveReduceTo
|
||||
? queryData?.aggregations?.[0]?.reduceTo || queryData?.reduceTo
|
||||
: undefined,
|
||||
...(queryData?.aggregations?.[0]?.comparisonSpaceAggregationParam && {
|
||||
comparisonSpaceAggregationParam:
|
||||
queryData.aggregations[0].comparisonSpaceAggregationParam,
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { QueryKey } from 'react-query';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { Button, Select, Skeleton, Table } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
getQueryRangeRequestData,
|
||||
@@ -36,10 +36,12 @@ import { openInNewTab } from 'utils/navigation';
|
||||
import triangleRulerUrl from '@/assets/Icons/triangle-ruler.svg';
|
||||
|
||||
import { DOCS_LINKS } from '../constants';
|
||||
import { columns, TIME_PICKER_OPTIONS } from './constants';
|
||||
import { getColumns, TIME_PICKER_OPTIONS } from './constants';
|
||||
|
||||
const homeInterval = 30 * 60 * 1000;
|
||||
|
||||
const columns = getColumns(true);
|
||||
|
||||
// Extracted EmptyState component
|
||||
const EmptyState = memo(
|
||||
({
|
||||
@@ -69,7 +71,7 @@ const EmptyState = memo(
|
||||
type="default"
|
||||
className="periscope-btn secondary"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: Get Started clicked', {
|
||||
void logEvent('Homepage: Get Started clicked', {
|
||||
source: 'Service Metrics',
|
||||
});
|
||||
|
||||
@@ -90,7 +92,7 @@ const EmptyState = memo(
|
||||
type="link"
|
||||
className="learn-more-link"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: Learn more clicked', {
|
||||
void logEvent('Homepage: Learn more clicked', {
|
||||
source: 'Service Metrics',
|
||||
});
|
||||
window.open(
|
||||
@@ -118,7 +120,10 @@ const ServicesListTable = memo(
|
||||
services: ServicesList[];
|
||||
onRowClick: (record: ServicesList, event: React.MouseEvent) => void;
|
||||
}): JSX.Element => (
|
||||
<div className="services-list-container home-data-item-container metrics-services-list">
|
||||
<div
|
||||
className="services-list-container home-data-item-container metrics-services-list"
|
||||
data-testid="home-services-table"
|
||||
>
|
||||
<div className="services-list">
|
||||
<Table<ServicesList>
|
||||
columns={columns}
|
||||
@@ -197,7 +202,7 @@ function ServiceMetrics({
|
||||
(option) => option.value === value,
|
||||
);
|
||||
|
||||
logEvent('Homepage: Services time interval updated', {
|
||||
void logEvent('Homepage: Services time interval updated', {
|
||||
updatedTimeInterval: timeInterval?.label,
|
||||
});
|
||||
|
||||
@@ -222,7 +227,7 @@ function ServiceMetrics({
|
||||
|
||||
const dataQueries = useGetQueriesRange(
|
||||
queryRangeRequestData,
|
||||
ENTITY_VERSION_V4,
|
||||
ENTITY_VERSION_V5,
|
||||
{
|
||||
queryKey: useMemo(
|
||||
() => [
|
||||
@@ -258,12 +263,7 @@ function ServiceMetrics({
|
||||
);
|
||||
|
||||
const sortedServices = useMemo(
|
||||
() =>
|
||||
services?.sort((a, b) => {
|
||||
const aUpdateAt = new Date(a.p99).getTime();
|
||||
const bUpdateAt = new Date(b.p99).getTime();
|
||||
return bUpdateAt - aUpdateAt;
|
||||
}) || [],
|
||||
() => [...services].sort((a, b) => b.p99 - a.p99),
|
||||
[services],
|
||||
);
|
||||
|
||||
@@ -281,7 +281,7 @@ function ServiceMetrics({
|
||||
|
||||
const handleRowClick = useCallback(
|
||||
(record: ServicesList, event: React.MouseEvent) => {
|
||||
logEvent('Homepage: Service clicked', {
|
||||
void logEvent('Homepage: Service clicked', {
|
||||
serviceName: record.serviceName,
|
||||
});
|
||||
safeNavigate(`${ROUTES.APPLICATION}/${record.serviceName}`, {
|
||||
@@ -348,7 +348,7 @@ function ServiceMetrics({
|
||||
type="link"
|
||||
className="periscope-btn link learn-more-link"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: All Services clicked', {});
|
||||
void logEvent('Homepage: All Services clicked', {});
|
||||
}}
|
||||
>
|
||||
All Services <ArrowRight size={12} />
|
||||
|
||||
@@ -22,10 +22,12 @@ import { openInNewTab } from 'utils/navigation';
|
||||
import triangleRulerUrl from '@/assets/Icons/triangle-ruler.svg';
|
||||
|
||||
import { DOCS_LINKS } from '../constants';
|
||||
import { columns, TIME_PICKER_OPTIONS } from './constants';
|
||||
import { getColumns, TIME_PICKER_OPTIONS } from './constants';
|
||||
|
||||
const homeInterval = 30 * 60 * 1000;
|
||||
|
||||
const columns = getColumns(false);
|
||||
|
||||
export default function ServiceTraces({
|
||||
onUpdateChecklistDoneItem,
|
||||
loadingUserPreferences,
|
||||
@@ -91,7 +93,7 @@ export default function ServiceTraces({
|
||||
(option) => option.value === value,
|
||||
);
|
||||
|
||||
logEvent('Homepage: Services time interval updated', {
|
||||
void logEvent('Homepage: Services time interval updated', {
|
||||
updatedTimeInterval: timeInterval?.label,
|
||||
});
|
||||
|
||||
@@ -126,7 +128,7 @@ export default function ServiceTraces({
|
||||
type="default"
|
||||
className="periscope-btn secondary"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: Get Started clicked', {
|
||||
void logEvent('Homepage: Get Started clicked', {
|
||||
source: 'Service Traces',
|
||||
});
|
||||
|
||||
@@ -147,7 +149,7 @@ export default function ServiceTraces({
|
||||
type="link"
|
||||
className="learn-more-link"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: Learn more clicked', {
|
||||
void logEvent('Homepage: Learn more clicked', {
|
||||
source: 'Service Traces',
|
||||
});
|
||||
window.open(
|
||||
@@ -168,7 +170,10 @@ export default function ServiceTraces({
|
||||
|
||||
const renderDashboardsList = useCallback(
|
||||
() => (
|
||||
<div className="services-list-container home-data-item-container traces-services-list">
|
||||
<div
|
||||
className="services-list-container home-data-item-container traces-services-list"
|
||||
data-testid="home-services-table"
|
||||
>
|
||||
<div className="services-list">
|
||||
<Table<ServicesList>
|
||||
columns={columns}
|
||||
@@ -178,7 +183,7 @@ export default function ServiceTraces({
|
||||
className="services-table"
|
||||
onRow={(record: ServicesList): Record<string, unknown> => ({
|
||||
onClick: (event: React.MouseEvent): void => {
|
||||
logEvent('Homepage: Service clicked', {
|
||||
void logEvent('Homepage: Service clicked', {
|
||||
serviceName: record.serviceName,
|
||||
});
|
||||
|
||||
@@ -246,7 +251,7 @@ export default function ServiceTraces({
|
||||
type="link"
|
||||
className="periscope-btn link learn-more-link"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: All Services clicked', {});
|
||||
void logEvent('Homepage: All Services clicked', {});
|
||||
}}
|
||||
>
|
||||
All Services <ArrowRight size={12} />
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
|
||||
import {
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type QueryRangeV5200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import ServiceMetrics from '../ServiceMetrics';
|
||||
|
||||
const topLevelOperations: ServiceDataProps = { SampleApp: ['GET'] };
|
||||
|
||||
// A = p99 (ms), D = ops/s, F1 = error rate
|
||||
const scalarTable: QueryRangeV5200 = {
|
||||
status: 'success',
|
||||
data: {
|
||||
type: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
columns: ['A', 'D', 'F1'].map((queryName) => ({
|
||||
name: '__result_0',
|
||||
queryName,
|
||||
aggregationIndex: 0,
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
|
||||
})),
|
||||
data: [[148.25, 12.4, 1.8]],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe('Home ServiceMetrics', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.post(
|
||||
'http://localhost/api/v1/service/top_level_operations',
|
||||
(_, res, ctx) => res(ctx.status(200), ctx.json(topLevelOperations)),
|
||||
),
|
||||
rest.post('http://localhost/api/v5/query_range', (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(scalarTable)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the span-metrics p99 in ms as sent', async () => {
|
||||
render(
|
||||
<ServiceMetrics
|
||||
onUpdateChecklistDoneItem={jest.fn()}
|
||||
loadingUserPreferences={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
Array.from(
|
||||
screen.getByTestId('home-services-table').querySelectorAll('tbody tr td'),
|
||||
).map((cell) => cell.textContent),
|
||||
).toStrictEqual(['SampleApp', '148.25', '1.80', '12.40']),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
import { ServicesList } from 'types/api/metrics/getService';
|
||||
|
||||
import ServiceTraces from '../ServiceTraces';
|
||||
|
||||
const services: ServicesList[] = [
|
||||
{
|
||||
serviceName: 'SampleApp',
|
||||
p99: 148_250_000,
|
||||
avgDuration: 0,
|
||||
numCalls: 100,
|
||||
callRate: 12.4,
|
||||
numErrors: 2,
|
||||
errorRate: 1.8,
|
||||
},
|
||||
];
|
||||
|
||||
describe('Home ServiceTraces', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.post('http://localhost/api/v2/services', (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: services })),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the traces p99 in ms from ns', async () => {
|
||||
render(
|
||||
<ServiceTraces
|
||||
onUpdateChecklistDoneItem={jest.fn()}
|
||||
loadingUserPreferences={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
Array.from(
|
||||
screen.getByTestId('home-services-table').querySelectorAll('tbody tr td'),
|
||||
).map((cell) => cell.textContent),
|
||||
).toStrictEqual(['SampleApp', '148.25', '1.80', '12.40']),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import { TableProps } from 'antd';
|
||||
import { ServicesList } from 'types/api/metrics/getService';
|
||||
|
||||
export const columns: TableProps<ServicesList>['columns'] = [
|
||||
export const getColumns = (
|
||||
isMetricData: boolean,
|
||||
): TableProps<ServicesList>['columns'] => [
|
||||
{
|
||||
title: 'APPLICATION',
|
||||
dataIndex: 'serviceName',
|
||||
@@ -11,7 +13,8 @@ export const columns: TableProps<ServicesList>['columns'] = [
|
||||
title: 'P99 LATENCY (in ms)',
|
||||
dataIndex: 'p99',
|
||||
key: 'p99',
|
||||
render: (value: number): string => (value / 1000000).toFixed(2),
|
||||
render: (value: number): string =>
|
||||
isMetricData ? value.toFixed(2) : (value / 1000000).toFixed(2),
|
||||
},
|
||||
{
|
||||
title: 'ERROR RATE (% of total)',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
alphabet,
|
||||
initialFormulaBuilderFormValues,
|
||||
@@ -6,7 +7,9 @@ import {
|
||||
import getStep from 'lib/getStep';
|
||||
import store from 'store';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { SpaceAggregation, TimeAggregation } from 'types/api/v5/queryRange';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
ReduceOperators,
|
||||
@@ -18,6 +21,38 @@ import {
|
||||
BuilderQuerieswithFormulaProps,
|
||||
} from '../Tabs/types';
|
||||
|
||||
// The query spreads in default `aggregations` (avg / sum, or count() for traces),
|
||||
// and v5 reads those before the top-level time / space fields, so set them here.
|
||||
const getAggregations = ({
|
||||
dataSource,
|
||||
key,
|
||||
aggregateOperator,
|
||||
timeAggregation,
|
||||
spaceAggregation,
|
||||
comparisonSpaceAggregationParam,
|
||||
}: {
|
||||
dataSource: DataSource;
|
||||
key: string;
|
||||
aggregateOperator: string;
|
||||
timeAggregation: MetricAggregateOperator;
|
||||
spaceAggregation: MetricAggregateOperator;
|
||||
comparisonSpaceAggregationParam?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
}): IBuilderQuery['aggregations'] =>
|
||||
dataSource === DataSource.TRACES
|
||||
? [{ expression: `${aggregateOperator}(${key})` }]
|
||||
: [
|
||||
{
|
||||
metricName: key,
|
||||
temporality: '',
|
||||
timeAggregation: timeAggregation as TimeAggregation,
|
||||
spaceAggregation: spaceAggregation as SpaceAggregation,
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
...(comparisonSpaceAggregationParam && {
|
||||
comparisonSpaceAggregationParam,
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
||||
export const getQueryBuilderQueries = ({
|
||||
autocompleteData,
|
||||
groupBy = [],
|
||||
@@ -31,23 +66,33 @@ export const getQueryBuilderQueries = ({
|
||||
}: BuilderQueriesProps): QueryBuilderData => ({
|
||||
queryFormulas: [],
|
||||
queryData: autocompleteData.map((item, index) => {
|
||||
const operator = aggregateOperator
|
||||
? aggregateOperator[index]
|
||||
: MetricAggregateOperator.SUM_RATE;
|
||||
const newQueryData: IBuilderQuery = {
|
||||
...initialQueryBuilderFormValuesMap.metrics,
|
||||
aggregateOperator: ((): string => {
|
||||
if (aggregateOperator) {
|
||||
return aggregateOperator[index];
|
||||
}
|
||||
return MetricAggregateOperator.SUM_RATE;
|
||||
})(),
|
||||
aggregateOperator: operator,
|
||||
aggregations: getAggregations({
|
||||
dataSource,
|
||||
key: item.key,
|
||||
aggregateOperator: operator,
|
||||
timeAggregation: timeAggregateOperators[index],
|
||||
spaceAggregation: spaceAggregateOperators[index],
|
||||
}),
|
||||
disabled: false,
|
||||
groupBy,
|
||||
aggregateAttribute: item,
|
||||
legend: legends[index],
|
||||
stepInterval: getStep({
|
||||
end: store.getState().globalTime.maxTime,
|
||||
inputFormat: 'ns',
|
||||
start: store.getState().globalTime.minTime,
|
||||
}),
|
||||
// v5 sets the metrics step (multiples of 300s from 1 day up); its traces
|
||||
// default is ~300 points, far denser than these cards
|
||||
stepInterval:
|
||||
dataSource === DataSource.METRICS
|
||||
? null
|
||||
: getStep({
|
||||
end: store.getState().globalTime.maxTime,
|
||||
inputFormat: 'ns',
|
||||
start: store.getState().globalTime.minTime,
|
||||
}),
|
||||
filters: {
|
||||
items: filterItems[index],
|
||||
op: 'AND',
|
||||
@@ -78,6 +123,8 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
legendFormulas,
|
||||
timeAggregateOperators,
|
||||
spaceAggregateOperators,
|
||||
comparisonSpaceAggregationParams = [],
|
||||
stepInterval,
|
||||
dataSource,
|
||||
}: BuilderQuerieswithFormulaProps): QueryBuilderData => ({
|
||||
queryFormulas: expressions.map((expression, index) => ({
|
||||
@@ -87,6 +134,14 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
})),
|
||||
queryData: autocompleteData.map((_, index) => ({
|
||||
...initialQueryBuilderFormValuesMap.metrics,
|
||||
aggregations: getAggregations({
|
||||
dataSource,
|
||||
key: autocompleteData[index].key,
|
||||
aggregateOperator: timeAggregateOperators[index],
|
||||
timeAggregation: timeAggregateOperators[index],
|
||||
spaceAggregation: spaceAggregateOperators[index],
|
||||
comparisonSpaceAggregationParam: comparisonSpaceAggregationParams[index],
|
||||
}),
|
||||
timeAggregation: timeAggregateOperators[index],
|
||||
spaceAggregation: spaceAggregateOperators[index],
|
||||
temporality: Temporality.Delta,
|
||||
@@ -101,11 +156,7 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
items: additionalItems[index],
|
||||
op: 'AND',
|
||||
},
|
||||
stepInterval: getStep({
|
||||
end: store.getState().globalTime.maxTime,
|
||||
inputFormat: 'ns',
|
||||
start: store.getState().globalTime.minTime,
|
||||
}),
|
||||
stepInterval: stepInterval ?? null,
|
||||
dataSource,
|
||||
})),
|
||||
queryTraceOperator: [],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
@@ -22,11 +23,10 @@ import {
|
||||
} from '../constant';
|
||||
import {
|
||||
ApDexMetricsQueryBuilderQueriesProps,
|
||||
ApDexProps,
|
||||
LatencyProps,
|
||||
OperationPerSecProps,
|
||||
} from '../Tabs/types';
|
||||
import { convertMilSecToNanoSec, getNearestHighestBucketValue } from '../utils';
|
||||
import { getNearestHighestBucketValue } from '../utils';
|
||||
import {
|
||||
getQueryBuilderQueries,
|
||||
getQueryBuilderQuerieswithFormula,
|
||||
@@ -40,11 +40,10 @@ export const latency = ({
|
||||
}: LatencyProps): QueryBuilderData => {
|
||||
const signozLatencyBucketMetrics = WidgetKeys.SignozLatencyBucket;
|
||||
|
||||
const signozMetricsServiceName = WidgetKeys.OTelServiceName;
|
||||
const newAutoCompleteData: BaseAutocompleteData = {
|
||||
key: isSpanMetricEnable
|
||||
? signozLatencyBucketMetrics
|
||||
: WidgetKeys.DurationNano,
|
||||
: WidgetKeys.SpanDurationNano,
|
||||
dataType: DataTypes.Float64,
|
||||
type: isSpanMetricEnable ? '' : MetricsType.Tag,
|
||||
};
|
||||
@@ -55,7 +54,7 @@ export const latency = ({
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: isSpanMetricEnable ? signozMetricsServiceName : WidgetKeys.ServiceName,
|
||||
key: WidgetKeys.OTelServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: isSpanMetricEnable ? MetricsType.Resource : MetricsType.Tag,
|
||||
},
|
||||
@@ -106,175 +105,6 @@ export const latency = ({
|
||||
});
|
||||
};
|
||||
|
||||
export const apDexTracesQueryBuilderQueries = ({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
topLevelOperationsRoute,
|
||||
threashold,
|
||||
}: ApDexProps): QueryBuilderData => {
|
||||
const autoCompleteDataA: BaseAutocompleteData = {
|
||||
dataType: DataTypes.Float64,
|
||||
key: '',
|
||||
type: '',
|
||||
};
|
||||
|
||||
const autoCompleteDataB: BaseAutocompleteData = {
|
||||
dataType: DataTypes.Float64,
|
||||
key: '',
|
||||
type: '',
|
||||
};
|
||||
|
||||
const autoCompleteDataC: BaseAutocompleteData = {
|
||||
dataType: DataTypes.Float64,
|
||||
key: '',
|
||||
type: '',
|
||||
};
|
||||
|
||||
const filterItemA: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.ServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: servicename,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Name,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS.IN,
|
||||
value: [...topLevelOperationsRoute],
|
||||
},
|
||||
...tagFilterItems,
|
||||
];
|
||||
|
||||
const filterItemB: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.HasError,
|
||||
dataType: DataTypes.bool,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: false,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.DurationNano,
|
||||
dataType: DataTypes.Float64,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['<='],
|
||||
value: convertMilSecToNanoSec(threashold),
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.ServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: servicename,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Name,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS.IN,
|
||||
value: [...topLevelOperationsRoute],
|
||||
},
|
||||
];
|
||||
|
||||
const filterItemC: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.DurationNano,
|
||||
dataType: DataTypes.Float64,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['<='],
|
||||
value: convertMilSecToNanoSec(threashold * 4),
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.HasError,
|
||||
dataType: DataTypes.bool,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: false,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.ServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: servicename,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Name,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS.IN,
|
||||
value: [...topLevelOperationsRoute],
|
||||
},
|
||||
];
|
||||
|
||||
const autocompleteData = [
|
||||
autoCompleteDataA,
|
||||
autoCompleteDataB,
|
||||
autoCompleteDataC,
|
||||
];
|
||||
const additionalItems = [filterItemA, filterItemB, filterItemC];
|
||||
const legends = [GraphTitle.APDEX];
|
||||
const disabled = Array(3).fill(true);
|
||||
const expressions = [FORMULA.APDEX_TRACES];
|
||||
const legendFormulas = [GraphTitle.APDEX];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.COUNT,
|
||||
MetricAggregateOperator.COUNT,
|
||||
MetricAggregateOperator.COUNT,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
];
|
||||
const dataSource = DataSource.TRACES;
|
||||
|
||||
return getQueryBuilderQuerieswithFormula({
|
||||
autocompleteData,
|
||||
additionalItems,
|
||||
legends,
|
||||
disabled,
|
||||
expressions,
|
||||
legendFormulas,
|
||||
timeAggregateOperators,
|
||||
spaceAggregateOperators,
|
||||
dataSource,
|
||||
});
|
||||
};
|
||||
|
||||
export const apDexMetricsQueryBuilderQueries = ({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
@@ -283,6 +113,30 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
delta,
|
||||
metricsBuckets,
|
||||
}: ApDexMetricsQueryBuilderQueriesProps): QueryBuilderData => {
|
||||
// the comparison count stops at the largest finite bucket, so a threshold past it
|
||||
// reads the count metric, which is the +Inf bucket
|
||||
const countAtOrBelow = (
|
||||
ms: number,
|
||||
): {
|
||||
key: string;
|
||||
spaceAggregation: MetricAggregateOperator;
|
||||
param?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
} => {
|
||||
const bucket = getNearestHighestBucketValue(ms, metricsBuckets);
|
||||
return bucket === '+Inf'
|
||||
? {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
spaceAggregation: MetricAggregateOperator.SUM,
|
||||
}
|
||||
: {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
spaceAggregation: MetricAggregateOperator.COUNT,
|
||||
param: { operator: '<=', threshold: Number(bucket) },
|
||||
};
|
||||
};
|
||||
const satisfied = countAtOrBelow(threashold * 1000);
|
||||
const tolerating = countAtOrBelow(threashold * 1000 * 4);
|
||||
|
||||
const autoCompleteDataA: BaseAutocompleteData = {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
dataType: DataTypes.Float64,
|
||||
@@ -290,13 +144,13 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
};
|
||||
|
||||
const autoCompleteDataB: BaseAutocompleteData = {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
key: satisfied.key,
|
||||
dataType: DataTypes.Float64,
|
||||
type: '',
|
||||
};
|
||||
|
||||
const autoCompleteDataC: BaseAutocompleteData = {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
key: tolerating.key,
|
||||
dataType: DataTypes.Float64,
|
||||
type: '',
|
||||
};
|
||||
@@ -336,16 +190,6 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
op: OPERATORS['!='],
|
||||
value: 'STATUS_CODE_ERROR',
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Le,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: getNearestHighestBucketValue(threashold * 1000, metricsBuckets),
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
@@ -370,16 +214,6 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
];
|
||||
|
||||
const filterItemC: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Le,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: getNearestHighestBucketValue(threashold * 1000 * 4, metricsBuckets),
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
@@ -426,16 +260,23 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
? [FORMULA.APDEX_DELTA_SPAN_METRICS]
|
||||
: [FORMULA.APDEX_CUMULATIVE_SPAN_METRICS];
|
||||
const legendFormulas = [GraphTitle.APDEX];
|
||||
// v5 forces increase on histograms, so the total matches it
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
];
|
||||
|
||||
// a plain sum keeps the le label on B and C, and the formula then cannot join them
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
satisfied.spaceAggregation,
|
||||
tolerating.spaceAggregation,
|
||||
];
|
||||
const comparisonSpaceAggregationParams = [
|
||||
undefined,
|
||||
satisfied.param,
|
||||
tolerating.param,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
@@ -448,6 +289,7 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
legendFormulas,
|
||||
timeAggregateOperators,
|
||||
spaceAggregateOperators,
|
||||
comparisonSpaceAggregationParams,
|
||||
dataSource,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import { QueryEnvelope } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import {
|
||||
apDexMetricsQueryBuilderQueries,
|
||||
errorPercentage,
|
||||
latency,
|
||||
} from '../OverviewQueries';
|
||||
|
||||
const toV5Queries = (builder: QueryBuilderData): QueryEnvelope[] =>
|
||||
prepareQueryRangePayloadV5({
|
||||
query: {
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
promql: [],
|
||||
builder,
|
||||
clickhouse_sql: [],
|
||||
id: 'query',
|
||||
},
|
||||
graphType: PANEL_TYPES.TIME_SERIES,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
}).queryPayload.compositeQuery.queries;
|
||||
|
||||
const getAggregations = (queries: QueryEnvelope[]): unknown[] =>
|
||||
queries.map(
|
||||
(query) => (query.spec as { aggregations?: unknown[] }).aggregations,
|
||||
);
|
||||
|
||||
const getFilters = (queries: QueryEnvelope[]): unknown[] =>
|
||||
queries.map((query) => (query.spec as { filter?: unknown }).filter);
|
||||
|
||||
describe('service details queries on v5', () => {
|
||||
it('keeps the latency percentiles on the span metrics histogram', () => {
|
||||
const queries = toV5Queries(
|
||||
latency({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
isSpanMetricEnable: true,
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries)).toStrictEqual(
|
||||
['p50', 'p90', 'p99'].map((spaceAggregation) => [
|
||||
{
|
||||
metricName: 'signoz_latency.bucket',
|
||||
temporality: undefined,
|
||||
timeAggregation: '',
|
||||
spaceAggregation,
|
||||
reduceTo: undefined,
|
||||
},
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('builds the traces latency percentiles from span duration', () => {
|
||||
const queries = toV5Queries(
|
||||
latency({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries)).toStrictEqual([
|
||||
[{ expression: 'p50(duration_nano)' }],
|
||||
[{ expression: 'p90(duration_nano)' }],
|
||||
[{ expression: 'p99(duration_nano)' }],
|
||||
]);
|
||||
expect(getFilters(queries)[0]).toStrictEqual({
|
||||
expression: "service.name = 'frontend' AND name in ['GET /']",
|
||||
});
|
||||
});
|
||||
|
||||
it('rates the error and total calls behind the error percentage', () => {
|
||||
const queries = toV5Queries(
|
||||
errorPercentage({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperations: ['GET /'],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries).slice(0, 2)).toStrictEqual(
|
||||
Array(2).fill([
|
||||
{
|
||||
metricName: 'signoz_calls_total',
|
||||
temporality: undefined,
|
||||
timeAggregation: 'rate',
|
||||
spaceAggregation: 'sum',
|
||||
reduceTo: undefined,
|
||||
},
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('counts the apdex buckets at the threshold instead of filtering on le', () => {
|
||||
const queries = toV5Queries(
|
||||
apDexMetricsQueryBuilderQueries({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
metricsBuckets: [100, 250, 500, 1000, 2000, 5000],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries).slice(0, 3)).toStrictEqual([
|
||||
[
|
||||
{
|
||||
metricName: 'signoz_latency.count',
|
||||
temporality: undefined,
|
||||
timeAggregation: 'increase',
|
||||
spaceAggregation: 'sum',
|
||||
reduceTo: undefined,
|
||||
},
|
||||
],
|
||||
...[500, 2000].map((threshold) => [
|
||||
{
|
||||
metricName: 'signoz_latency.bucket',
|
||||
temporality: undefined,
|
||||
timeAggregation: 'increase',
|
||||
spaceAggregation: 'count',
|
||||
reduceTo: undefined,
|
||||
comparisonSpaceAggregationParam: { operator: '<=', threshold },
|
||||
},
|
||||
]),
|
||||
]);
|
||||
expect(getFilters(queries).slice(1, 3)).toStrictEqual([
|
||||
{
|
||||
expression:
|
||||
"status.code != 'STATUS_CODE_ERROR' AND service.name = 'frontend' AND operation in ['GET /']",
|
||||
},
|
||||
{
|
||||
expression:
|
||||
"status.code != 'STATUS_CODE_ERROR' AND service.name = 'frontend' AND operation in ['GET /']",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('reads the count metric when the apdex threshold is past the largest bucket', () => {
|
||||
const queries = toV5Queries(
|
||||
apDexMetricsQueryBuilderQueries({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
metricsBuckets: [100, 250, 500, 1000],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries)[2]).toStrictEqual([
|
||||
{
|
||||
metricName: 'signoz_latency.count',
|
||||
temporality: undefined,
|
||||
timeAggregation: 'increase',
|
||||
spaceAggregation: 'sum',
|
||||
reduceTo: undefined,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('leaves the metrics step to v5 on single and formula queries', () => {
|
||||
const queries = [
|
||||
...toV5Queries(
|
||||
latency({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
isSpanMetricEnable: true,
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
}),
|
||||
),
|
||||
...toV5Queries(
|
||||
errorPercentage({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperations: ['GET /'],
|
||||
}),
|
||||
),
|
||||
].filter((query) => query.type === 'builder_query');
|
||||
|
||||
expect(
|
||||
queries.map(
|
||||
(query) => (query.spec as { stepInterval?: unknown }).stepInterval,
|
||||
),
|
||||
).toStrictEqual(Array(queries.length).fill(null));
|
||||
});
|
||||
|
||||
it('keeps the card step on the traces latency', () => {
|
||||
const [p50] = toV5Queries(
|
||||
latency({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
}),
|
||||
);
|
||||
|
||||
expect((p50.spec as { stepInterval?: unknown }).stepInterval).toBe(60);
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { Col } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
@@ -201,7 +201,7 @@ function DBCall(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
@@ -240,7 +240,7 @@ function DBCall(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { Col } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
@@ -273,7 +273,7 @@ function External(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
@@ -317,7 +317,7 @@ function External(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
@@ -362,7 +362,7 @@ function External(): JSX.Element {
|
||||
)
|
||||
}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
@@ -406,7 +406,7 @@ function External(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
apDexToolTipUrl,
|
||||
apDexToolTipUrlText,
|
||||
} from 'constants/apDex';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
import DisplayThreshold from 'container/WidgetCard/Header/DisplayThreshold';
|
||||
@@ -95,7 +95,7 @@ function ApDexMetrics({
|
||||
onClickHandler={handleGraphClick('ApDex')}
|
||||
threshold={threshold}
|
||||
isQueryEnabled={isQueryEnabled}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { FeatureKeys } from 'constants/features';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
@@ -13,7 +13,10 @@ import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsAppli
|
||||
import { latency } from 'container/MetricsApplication/MetricsPageQueries/OverviewQueries';
|
||||
import { Card, GraphContainer } from 'container/MetricsApplication/styles';
|
||||
import useResourceAttribute from 'hooks/useResourceAttribute';
|
||||
import { resourceAttributesToTagFilterItems } from 'hooks/useResourceAttribute/utils';
|
||||
import {
|
||||
resourceAttributesToTagFilterItems,
|
||||
resourceAttributesToTracesFilterItems,
|
||||
} from 'hooks/useResourceAttribute/utils';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
@@ -49,9 +52,9 @@ function ServiceOverview({
|
||||
|
||||
const tagFilterItems = useMemo(
|
||||
() =>
|
||||
handleNonInQueryRange(
|
||||
resourceAttributesToTagFilterItems(queries, !isSpanMetricEnable),
|
||||
) || [],
|
||||
isSpanMetricEnable
|
||||
? handleNonInQueryRange(resourceAttributesToTagFilterItems(queries))
|
||||
: resourceAttributesToTracesFilterItems(queries),
|
||||
[isSpanMetricEnable, queries],
|
||||
);
|
||||
|
||||
@@ -72,7 +75,7 @@ function ServiceOverview({
|
||||
},
|
||||
title: GraphTitle.LATENCY,
|
||||
panelTypes: PANEL_TYPES.TIME_SERIES,
|
||||
yAxisUnit: 'ns',
|
||||
yAxisUnit: isSpanMetricEnable ? 'ms' : 'ns',
|
||||
id: SERVICE_CHART_ID.latency,
|
||||
}),
|
||||
[isSpanMetricEnable, servicename, tagFilterItems, topLevelOperationsRoute],
|
||||
@@ -116,7 +119,7 @@ function ServiceOverview({
|
||||
widget={latencyWidget}
|
||||
onClickHandler={handleGraphClick('Service')}
|
||||
isQueryEnabled={isQueryEnabled}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import axios from 'axios';
|
||||
import { SOMETHING_WENT_WRONG } from 'constants/api';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
import { SERVICE_DETAIL_DRILLDOWN_ENABLED } from 'container/MetricsApplication/constant';
|
||||
import { Card, GraphContainer } from 'container/MetricsApplication/styles';
|
||||
@@ -33,7 +33,7 @@ function TopLevelOperation({
|
||||
onClickHandler={handleGraphClick(opName)}
|
||||
onDragSelect={onDragSelect}
|
||||
isQueryEnabled={!topLevelOperationsIsLoading}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ReactNode, useMemo } from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { topOperationMetricsDownloadOptions } from 'container/MetricsApplication/constant';
|
||||
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
|
||||
@@ -15,6 +15,7 @@ import useResourceAttribute from 'hooks/useResourceAttribute';
|
||||
import { convertRawQueriesToTraceSelectedTags } from 'hooks/useResourceAttribute/utils';
|
||||
import { RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { QueryDataV3 } from 'types/api/widgets/getQuery';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
@@ -70,7 +71,7 @@ function TopOperationMetrics(): JSX.Element {
|
||||
globalSelectedInterval,
|
||||
variables: {},
|
||||
},
|
||||
ENTITY_VERSION_V4,
|
||||
ENTITY_VERSION_V5,
|
||||
{
|
||||
queryKey: [
|
||||
`GetMetricsQueryRange-${keyOperationWidget?.timePreferance}-${globalSelectedInterval}-${keyOperationWidget?.id}`,
|
||||
@@ -88,7 +89,9 @@ function TopOperationMetrics(): JSX.Element {
|
||||
},
|
||||
);
|
||||
|
||||
const queryTableData = data?.payload?.data?.newResult?.data?.result || [];
|
||||
const queryTableData = (data?.payload?.data?.newResult?.data?.result ||
|
||||
data?.payload?.data?.result ||
|
||||
[]) as QueryDataV3[];
|
||||
|
||||
const renderColumnCell = useMemo(
|
||||
() =>
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
|
||||
import { FeatureKeys } from 'constants/features';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
import { IResourceAttribute } from 'hooks/useResourceAttribute/types';
|
||||
import { encode } from 'js-base64';
|
||||
import { defaultFeatureFlags, render } from 'tests/test-utils';
|
||||
|
||||
import ServiceOverview from '../ServiceOverview';
|
||||
|
||||
jest.mock('container/WidgetCard/Card', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(() => null),
|
||||
}));
|
||||
|
||||
const resourceAttributes: IResourceAttribute[] = [
|
||||
{
|
||||
id: 'env',
|
||||
tagKey: 'resource_deployment.environment',
|
||||
operator: 'Not IN',
|
||||
tagValue: ['prod'],
|
||||
},
|
||||
];
|
||||
|
||||
describe('ServiceOverview', () => {
|
||||
it('filters the traces latency on the resource attribute with its operator', () => {
|
||||
render(
|
||||
<ServiceOverview
|
||||
stepInterval={60}
|
||||
selectedTimeStamp={0}
|
||||
selectedTraceTags="[]"
|
||||
onDragSelect={jest.fn()}
|
||||
handleGraphClick={jest.fn()}
|
||||
topLevelOperationsRoute={['GET /']}
|
||||
topLevelOperationsIsLoading={false}
|
||||
/>,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: `/services/frontend?${QueryParams.resourceAttributes}=${encodeURIComponent(
|
||||
encode(JSON.stringify(resourceAttributes)),
|
||||
)}`,
|
||||
routePath: ROUTES.SERVICE_METRICS,
|
||||
},
|
||||
);
|
||||
|
||||
const { widget } = jest.mocked(Graph).mock.calls[0][0];
|
||||
const [latencyQuery] = prepareQueryRangePayloadV5({
|
||||
query: widget.query,
|
||||
graphType: widget.panelTypes,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
}).queryPayload.compositeQuery.queries;
|
||||
|
||||
expect(latencyQuery.spec).toMatchObject({
|
||||
filter: {
|
||||
expression:
|
||||
"service.name = 'frontend' AND name in ['GET /'] AND deployment.environment NOT IN ['prod']",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ spanMetrics: false, unit: 'ns' },
|
||||
{ spanMetrics: true, unit: 'ms' },
|
||||
])(
|
||||
'reads the latency in $unit when span metrics is $spanMetrics',
|
||||
({ spanMetrics, unit }) => {
|
||||
render(
|
||||
<ServiceOverview
|
||||
stepInterval={60}
|
||||
selectedTimeStamp={0}
|
||||
selectedTraceTags="[]"
|
||||
onDragSelect={jest.fn()}
|
||||
handleGraphClick={jest.fn()}
|
||||
topLevelOperationsRoute={['GET /']}
|
||||
topLevelOperationsIsLoading={false}
|
||||
/>,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: '/services/frontend',
|
||||
routePath: ROUTES.SERVICE_METRICS,
|
||||
appContextOverrides: {
|
||||
featureFlags: defaultFeatureFlags.map((flag) =>
|
||||
flag.name === FeatureKeys.USE_SPAN_METRICS
|
||||
? { ...flag, active: spanMetrics }
|
||||
: flag,
|
||||
),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(jest.mocked(Graph).mock.calls[0][0].widget.yAxisUnit).toBe(unit);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -43,6 +44,12 @@ export interface BuilderQuerieswithFormulaProps {
|
||||
additionalItems: TagFilterItem[][];
|
||||
timeAggregateOperators: MetricAggregateOperator[];
|
||||
spaceAggregateOperators: MetricAggregateOperator[];
|
||||
comparisonSpaceAggregationParams?: (
|
||||
| MetrictypesComparisonSpaceAggregationParamDTO
|
||||
| undefined
|
||||
)[];
|
||||
// v5 picks its own step when none is sent; v4 needs one
|
||||
stepInterval?: number;
|
||||
dataSource: DataSource;
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ export enum WidgetKeys {
|
||||
HasError = 'hasError',
|
||||
Address = 'address',
|
||||
DurationNano = 'durationNano',
|
||||
SpanDurationNano = 'duration_nano',
|
||||
StatusCode = 'status.code',
|
||||
Operation = 'operation',
|
||||
OperationName = 'operationName',
|
||||
|
||||
@@ -54,9 +54,6 @@ export const getNearestHighestBucketValue = (
|
||||
return nearestBucket?.toString() || '+Inf';
|
||||
};
|
||||
|
||||
export const convertMilSecToNanoSec = (value: number): number =>
|
||||
value * 1000000000;
|
||||
|
||||
export const convertedTracesToDownloadData = (
|
||||
originalData: TopOperationList[],
|
||||
): Record<string, string>[] =>
|
||||
|
||||
@@ -23,9 +23,7 @@ export const getColumns = (
|
||||
{
|
||||
key: ColumnKey.P99,
|
||||
columnOption: {
|
||||
title: `${ColumnTitle[ColumnKey.P99]}${
|
||||
isMetricData ? ' (in ns)' : ' (in ms)'
|
||||
}`,
|
||||
title: `${ColumnTitle[ColumnKey.P99]} (in ms)`,
|
||||
sorter: (a: ServicesList, b: ServicesList): number => a.p99 - b.p99,
|
||||
render: (value: number): string => {
|
||||
if (Number.isNaN(value)) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { SolidAlertTriangle } from '@signozhq/icons';
|
||||
import { Flex } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { ResizeTable } from 'components/ResizeTable';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { MAX_RPS_LIMIT } from 'constants/global';
|
||||
import ResourceAttributesFilter from 'container/ResourceAttributesFilter';
|
||||
import { useGetQueriesRange } from 'hooks/queryBuilder/useGetQueriesRange';
|
||||
@@ -40,9 +40,9 @@ function ServiceMetricTable({
|
||||
const { isFetchingActiveLicense, trialInfo } = useAppContext();
|
||||
const { isCloudUser: isCloudUserVal } = useGetTenantLicense();
|
||||
|
||||
const queries = useGetQueriesRange(queryRangeRequestData, ENTITY_VERSION_V4, {
|
||||
const queries = useGetQueriesRange(queryRangeRequestData, ENTITY_VERSION_V5, {
|
||||
queryKey: [
|
||||
`GetMetricsQueryRange-${queryRangeRequestData[0].selectedTime}-${globalSelectedInterval}`,
|
||||
`GetMetricsQueryRange-${queryRangeRequestData[0]?.selectedTime}-${globalSelectedInterval}`,
|
||||
maxTime,
|
||||
minTime,
|
||||
globalSelectedInterval,
|
||||
|
||||
@@ -1,193 +1,123 @@
|
||||
import useGetTopLevelOperations from 'hooks/useGetTopLevelOperations';
|
||||
import { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
|
||||
import {
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type QueryRangeV5200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { act, render, screen } from 'tests/test-utils';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import ServicesUsingMetrics from './index';
|
||||
|
||||
// Mock the useGetTopLevelOperations hook
|
||||
jest.mock('hooks/useGetTopLevelOperations', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(),
|
||||
}));
|
||||
const topLevelOperations: ServiceDataProps = {
|
||||
SampleApp: ['GET'],
|
||||
TestApp: ['POST'],
|
||||
};
|
||||
|
||||
const mockUseGetTopLevelOperations =
|
||||
useGetTopLevelOperations as jest.MockedFunction<
|
||||
typeof useGetTopLevelOperations
|
||||
>;
|
||||
// A = p99, D = ops/s, F1 = error rate
|
||||
const metricsByService: Record<string, [number, number, number]> = {
|
||||
SampleApp: [100, 50, 2.5],
|
||||
TestApp: [200, 10, 0],
|
||||
};
|
||||
|
||||
const scalarTable = (service: string): QueryRangeV5200 => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
type: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
columns: [
|
||||
{
|
||||
name: 'service.name',
|
||||
queryName: 'A',
|
||||
aggregationIndex: 0,
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.group,
|
||||
},
|
||||
...['A', 'D', 'F1'].map((queryName) => ({
|
||||
name: '__result_0',
|
||||
queryName,
|
||||
aggregationIndex: 0,
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
|
||||
})),
|
||||
],
|
||||
data: [[service, ...metricsByService[service]]],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const mockTopLevelOperations = (operations: ServiceDataProps): void => {
|
||||
server.use(
|
||||
rest.post(
|
||||
'http://localhost/api/v1/service/top_level_operations',
|
||||
(_, res, ctx) => res(ctx.status(200), ctx.json(operations)),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const table = (): HTMLElement => screen.getByTestId('services-table');
|
||||
|
||||
const rowCells = (service: string): (string | null)[] =>
|
||||
Array.from(table().querySelectorAll(`tr[data-row-key="${service}"] td`)).map(
|
||||
(cell) => cell.textContent,
|
||||
);
|
||||
|
||||
describe('ServicesUsingMetrics', () => {
|
||||
beforeEach(() => {
|
||||
// Reset all mocks before each test
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should render the ServicesUsingMetrics component', async () => {
|
||||
// Mock successful API response
|
||||
mockUseGetTopLevelOperations.mockReturnValue({
|
||||
data: {
|
||||
SampleApp: ['GET'],
|
||||
TestApp: ['POST'],
|
||||
},
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
isIdle: false,
|
||||
isLoadingError: false,
|
||||
isRefetchError: false,
|
||||
isSuccess: true,
|
||||
status: 'success',
|
||||
dataUpdatedAt: 0,
|
||||
errorUpdatedAt: 0,
|
||||
failureCount: 0,
|
||||
failureReason: null,
|
||||
isFetching: false,
|
||||
isFetchingNextPage: false,
|
||||
isFetchingPreviousPage: false,
|
||||
isPlaceholderData: false,
|
||||
isPreviousData: false,
|
||||
isStale: false,
|
||||
refetch: jest.fn(),
|
||||
remove: jest.fn(),
|
||||
} as any);
|
||||
|
||||
// Mock the query range API responses
|
||||
server.use(
|
||||
rest.post('*/api/v1/query_range', (req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
resultType: 'matrix',
|
||||
result: [
|
||||
{
|
||||
metric: { __name__: 'A' },
|
||||
values: [[Date.now() / 1000, '100']],
|
||||
},
|
||||
{
|
||||
metric: { __name__: 'D' },
|
||||
values: [[Date.now() / 1000, '50']],
|
||||
},
|
||||
{
|
||||
metric: { __name__: 'F1' },
|
||||
values: [[Date.now() / 1000, '2.5']],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
rest.post('http://localhost/api/v5/query_range', async (req, res, ctx) => {
|
||||
const body = JSON.stringify(await req.json());
|
||||
const service = Object.keys(metricsByService).find((name) =>
|
||||
body.includes(`'${name}'`),
|
||||
);
|
||||
|
||||
return res(ctx.status(200), ctx.json(scalarTable(service ?? '')));
|
||||
}),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
render(<ServicesUsingMetrics />);
|
||||
});
|
||||
|
||||
// Wait for the component to load and render
|
||||
await screen.findByText(/application/i);
|
||||
expect(screen.getByText(/p99 latency \(in ns\)/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/error rate \(% of total\)/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render the ServicesUsingMetrics component with loading', async () => {
|
||||
// Mock loading state
|
||||
mockUseGetTopLevelOperations.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
isError: false,
|
||||
error: null,
|
||||
isIdle: false,
|
||||
isLoadingError: false,
|
||||
isRefetchError: false,
|
||||
isSuccess: false,
|
||||
status: 'loading',
|
||||
dataUpdatedAt: 0,
|
||||
errorUpdatedAt: 0,
|
||||
failureCount: 0,
|
||||
failureReason: null,
|
||||
isFetching: true,
|
||||
isFetchingNextPage: false,
|
||||
isFetchingPreviousPage: false,
|
||||
isPlaceholderData: false,
|
||||
isPreviousData: false,
|
||||
isStale: false,
|
||||
refetch: jest.fn(),
|
||||
remove: jest.fn(),
|
||||
} as any);
|
||||
it('fills each row from the v5 table', async () => {
|
||||
mockTopLevelOperations(topLevelOperations);
|
||||
render(<ServicesUsingMetrics />);
|
||||
|
||||
await act(async () => {
|
||||
render(<ServicesUsingMetrics />);
|
||||
});
|
||||
|
||||
// Should show loading spinner
|
||||
expect(screen.getByLabelText(/loading/i)).toBeInTheDocument();
|
||||
await waitFor(() =>
|
||||
expect(rowCells('SampleApp')).toStrictEqual([
|
||||
'SampleApp',
|
||||
'100.00',
|
||||
'2.50',
|
||||
'50.00',
|
||||
]),
|
||||
);
|
||||
expect(rowCells('TestApp')).toStrictEqual([
|
||||
'TestApp',
|
||||
'200.00',
|
||||
'0.00',
|
||||
'10.00',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should not render if the data is not present', async () => {
|
||||
// Mock successful API response with data
|
||||
mockUseGetTopLevelOperations.mockReturnValue({
|
||||
data: {
|
||||
SampleApp: ['GET'],
|
||||
TestApp: ['GET'],
|
||||
},
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
isIdle: false,
|
||||
isLoadingError: false,
|
||||
isRefetchError: false,
|
||||
isSuccess: true,
|
||||
status: 'success',
|
||||
dataUpdatedAt: 0,
|
||||
errorUpdatedAt: 0,
|
||||
failureCount: 0,
|
||||
failureReason: null,
|
||||
isFetching: false,
|
||||
isFetchingNextPage: false,
|
||||
isFetchingPreviousPage: false,
|
||||
isPlaceholderData: false,
|
||||
isPreviousData: false,
|
||||
isStale: false,
|
||||
refetch: jest.fn(),
|
||||
remove: jest.fn(),
|
||||
} as any);
|
||||
it('labels the span-metrics p99 in ms', async () => {
|
||||
mockTopLevelOperations(topLevelOperations);
|
||||
render(<ServicesUsingMetrics />);
|
||||
|
||||
// Mock the query range API responses
|
||||
server.use(
|
||||
rest.post('*/api/v1/query_range', (req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
resultType: 'matrix',
|
||||
result: [
|
||||
{
|
||||
metric: { __name__: 'A' },
|
||||
values: [[Date.now() / 1000, '100']],
|
||||
},
|
||||
{
|
||||
metric: { __name__: 'D' },
|
||||
values: [[Date.now() / 1000, '50']],
|
||||
},
|
||||
{
|
||||
metric: { __name__: 'F1' },
|
||||
values: [[Date.now() / 1000, '2.5']],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
Array.from(table().querySelectorAll('thead th')).map(
|
||||
(cell) => cell.textContent,
|
||||
),
|
||||
),
|
||||
).toContain('P99 latency (in ms)'),
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
render(<ServicesUsingMetrics />);
|
||||
});
|
||||
it('renders an empty list when no service has top level operations', async () => {
|
||||
mockTopLevelOperations({});
|
||||
render(<ServicesUsingMetrics />);
|
||||
|
||||
// Wait for the services to be rendered
|
||||
await screen.findByText(/SampleApp/i);
|
||||
expect(screen.getByText(/TestApp/i)).toBeInTheDocument();
|
||||
await waitFor(() =>
|
||||
expect(table().querySelectorAll('tr[data-row-key]')).toHaveLength(0),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { getQueryRangeRequestData } from '../utils';
|
||||
|
||||
describe('getQueryRangeRequestData', () => {
|
||||
it('leaves the step of the services list queries to v5', () => {
|
||||
const [request] = getQueryRangeRequestData({
|
||||
topLevelOperations: [['frontend', ['GET /']]],
|
||||
globalSelectedInterval: '15m',
|
||||
});
|
||||
|
||||
const steps = request.query.builder.queryData.map(
|
||||
(query) => query.stepInterval,
|
||||
);
|
||||
|
||||
expect(steps).toStrictEqual(Array(steps.length).fill(null));
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,6 @@ import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsAppli
|
||||
import { updateStepInterval } from 'hooks/queryBuilder/useStepInterval';
|
||||
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
|
||||
import { ServicesList } from 'types/api/metrics/getService';
|
||||
import { QueryDataV3 } from 'types/api/widgets/getQuery';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
@@ -13,13 +12,12 @@ import {
|
||||
GetServiceListFromQueryProps,
|
||||
} from './types';
|
||||
|
||||
export function getSeriesValue(
|
||||
queryArray: QueryDataV3[] | undefined,
|
||||
function getRowValue(
|
||||
row: Record<string, unknown> | undefined,
|
||||
queryName: string,
|
||||
): string {
|
||||
const queryObject = queryArray?.find((item) => item?.queryName === queryName);
|
||||
const series = queryObject ? queryObject.series : 0;
|
||||
return series ? series[0].values[0].value : '0';
|
||||
): number {
|
||||
const value = Number(row?.[queryName]);
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
export const getQueryRangeRequestData = ({
|
||||
@@ -71,14 +69,13 @@ export const getServiceListFromQuery = ({
|
||||
numErrors: 0,
|
||||
};
|
||||
services.push(serviceData);
|
||||
}
|
||||
if (query.data) {
|
||||
const queryArray = query.data?.payload?.data?.newResult?.data?.result;
|
||||
} else if (query.data) {
|
||||
const row = query.data?.payload?.data?.result?.[0]?.table?.rows?.[0]?.data;
|
||||
const serviceData: ServicesList = {
|
||||
serviceName: topLevelOperations[index][0].toString(),
|
||||
p99: parseFloat(getSeriesValue(queryArray, 'A')),
|
||||
callRate: parseFloat(getSeriesValue(queryArray, 'D')),
|
||||
errorRate: parseFloat(getSeriesValue(queryArray, 'F1')),
|
||||
p99: getRowValue(row, 'A'),
|
||||
callRate: getRowValue(row, 'D'),
|
||||
errorRate: getRowValue(row, 'F1'),
|
||||
avgDuration: 0,
|
||||
numCalls: 0,
|
||||
numErrors: 0,
|
||||
|
||||
@@ -96,22 +96,8 @@ export const convertRawQueriesToTraceSelectedTags = (
|
||||
/* Convert resource attributes to tagFilter items for queryBuilder */
|
||||
export const resourceAttributesToTagFilterItems = (
|
||||
queries: IResourceAttribute[],
|
||||
isTraceDataSource = false,
|
||||
): TagFilterItem[] => {
|
||||
if (isTraceDataSource) {
|
||||
return convertRawQueriesToTraceSelectedTags(queries).map((e) => ({
|
||||
id: e.Key,
|
||||
op: e.Operator,
|
||||
value: e.StringValues,
|
||||
key: {
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Resource,
|
||||
key: e.Key,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
return queries.map((res) => ({
|
||||
): TagFilterItem[] =>
|
||||
queries.map((res) => ({
|
||||
id: `${res.id}`,
|
||||
key: {
|
||||
key: res.tagKey,
|
||||
@@ -121,7 +107,6 @@ export const resourceAttributesToTagFilterItems = (
|
||||
op: `${res.operator}`,
|
||||
value: `${res.tagValue}`.split(','),
|
||||
}));
|
||||
};
|
||||
/* Convert resource attributes to trace filters items for queryBuilder */
|
||||
export const resourceAttributesToTracesFilterItems = (
|
||||
queries: IResourceAttribute[],
|
||||
|
||||
@@ -51,7 +51,8 @@ interface QueryRangeV5Body {
|
||||
|
||||
/**
|
||||
* Home detects logs and traces with one `query_range` call each, told apart by
|
||||
* the signal on the query spec.
|
||||
* the signal on the query spec. The span-metrics services card queries metrics
|
||||
* and falls through to its own handler, which follows the data state.
|
||||
*/
|
||||
const signalOf = (body: QueryRangeV5Body): string | undefined =>
|
||||
body.compositeQuery?.queries?.[0]?.spec?.signal;
|
||||
@@ -129,6 +130,10 @@ export const homeMocks = defineStoryMocks({
|
||||
rest.post('http://localhost/api/v5/query_range', async (req, res, ctx) => {
|
||||
const signal = signalOf((await req.json()) as QueryRangeV5Body);
|
||||
|
||||
if (signal === 'metrics') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const isActive =
|
||||
signal === 'traces' ? values.tracesIngestion : values.logsIngestion;
|
||||
|
||||
@@ -138,6 +143,11 @@ export const homeMocks = defineStoryMocks({
|
||||
);
|
||||
}),
|
||||
|
||||
rest.post(
|
||||
'http://localhost/api/v5/query_range',
|
||||
response.json(() => spanMetricsResponse()),
|
||||
),
|
||||
|
||||
rest.get('http://localhost/api/v1/user/preferences', (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
@@ -191,11 +201,6 @@ export const homeMocks = defineStoryMocks({
|
||||
'http://localhost/api/v1/service/top_level_operations',
|
||||
response.json(() => topLevelOperationsResponse(values.services)),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
'http://localhost/api/v4/query_range',
|
||||
response.json(() => spanMetricsResponse()),
|
||||
),
|
||||
],
|
||||
config: ({ servicesSource }) => ({
|
||||
appContext: { featureFlags: homeFeatureFlags(servicesSource) },
|
||||
|
||||
@@ -23,12 +23,15 @@ import type { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
|
||||
import { alertRulesFixture } from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { defaultFeatureFlags } from 'tests/fixtures/appContextMock';
|
||||
import type { FeatureFlagProps } from 'types/api/features/getFeaturesFlags';
|
||||
import type { MetricRangePayloadV3 } from 'types/api/metrics/getQueryRange';
|
||||
import type { ServicesList } from 'types/api/metrics/getService';
|
||||
import type { UserPreference } from 'types/api/preferences/preference';
|
||||
import type { MetricRangePayloadV5 } from 'types/api/v5/queryRange';
|
||||
|
||||
import { baseUserPreferences } from '@/storybook/msw/__story_mockdata__/appShell';
|
||||
import { queryRangeV5ScalarResponse } from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
import {
|
||||
queryRangeV5ScalarResponse,
|
||||
queryRangeV5ScalarTableResponse,
|
||||
} from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
|
||||
export { queryRangeV5ScalarResponse };
|
||||
|
||||
@@ -328,33 +331,11 @@ export const topLevelOperationsResponse = (count: number): ServiceDataProps =>
|
||||
);
|
||||
|
||||
/**
|
||||
* Span-metrics latency, error rate and ops per second come off a table panel.
|
||||
* The page reads them from `newResult`, which the table branch of
|
||||
* `GetMetricQueryRange` never adds, so the columns render as zero however
|
||||
* complete this body is. That is the app's gap, not the mock's.
|
||||
* The span-metrics card sends one table query per service; `A` is p99 (ms), `D`
|
||||
* ops per second and `F1` the error rate.
|
||||
*/
|
||||
export const spanMetricsResponse = (): {
|
||||
status: string;
|
||||
data: MetricRangePayloadV3['data'];
|
||||
} => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
resultType: 'table',
|
||||
result: [
|
||||
{
|
||||
queryName: '',
|
||||
legend: '',
|
||||
series: null,
|
||||
list: null,
|
||||
table: {
|
||||
columns: [
|
||||
{ name: 'A', queryName: 'A', isValueColumn: true },
|
||||
{ name: 'D', queryName: 'D', isValueColumn: true },
|
||||
{ name: 'F1', queryName: 'F1', isValueColumn: true },
|
||||
],
|
||||
rows: [{ data: { A: 148_000_000, D: 12.4, F1: 1.8 } }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
export const spanMetricsResponse = (): MetricRangePayloadV5 =>
|
||||
queryRangeV5ScalarTableResponse({
|
||||
aggregations: ['A', 'D', 'F1'],
|
||||
rows: [[148, 12.4, 1.8]],
|
||||
});
|
||||
|
||||
@@ -3,8 +3,13 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { FeatureKeys } from 'constants/features';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { rest } from 'msw';
|
||||
import { createAppContextMock } from 'tests/fixtures/appContextMock';
|
||||
import type { FeatureFlagProps } from 'types/api/features/getFeaturesFlags';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
import { choiceControl, countControl } from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
@@ -12,18 +17,20 @@ import {
|
||||
attributeKeysResponse,
|
||||
attributeValuesResponse,
|
||||
} from '@/storybook/msw/__story_mockdata__/attributes';
|
||||
import { queryRangeV3ForRequest } from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
import { queryRangeV5ForRequest } from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
|
||||
import {
|
||||
apDexSettingsResponse,
|
||||
METRICS_APPLICATION_TABS,
|
||||
METRICS_LABEL_VALUES,
|
||||
metricMetaResponse,
|
||||
SERVICE_MODES,
|
||||
SERVICE_NAME,
|
||||
TOP_OPERATION_MAX,
|
||||
topLevelOperationsResponse,
|
||||
topOperationsResponse,
|
||||
type MetricsApplicationTabKey,
|
||||
type ServiceMode,
|
||||
} from './__story_mockdata__/metricsApplication';
|
||||
|
||||
const VIEW = 'Service · view';
|
||||
@@ -40,6 +47,17 @@ const RESOURCE_ATTRIBUTE_KEYS = [
|
||||
|
||||
const APDEX_THRESHOLD = 0.5;
|
||||
|
||||
const { featureFlags: baseFeatureFlags } = createAppContextMock(
|
||||
USER_ROLES.ADMIN,
|
||||
);
|
||||
|
||||
const featureFlagsFor = (mode: ServiceMode): FeatureFlagProps[] =>
|
||||
(baseFeatureFlags ?? []).map((flag) =>
|
||||
flag.name === FeatureKeys.USE_SPAN_METRICS
|
||||
? { ...flag, active: mode === 'span-metrics' }
|
||||
: flag,
|
||||
);
|
||||
|
||||
export const metricsApplicationMocks = defineStoryMocks({
|
||||
controls: {
|
||||
tab: choiceControl<MetricsApplicationTabKey>('Tab', {
|
||||
@@ -48,6 +66,13 @@ export const metricsApplicationMocks = defineStoryMocks({
|
||||
options: METRICS_APPLICATION_TABS,
|
||||
value: 'OVER_METRICS',
|
||||
}),
|
||||
mode: choiceControl<ServiceMode>('Source', {
|
||||
group: VIEW,
|
||||
description:
|
||||
'Where latency and the key operations table read from: traces, or the span metrics the `use_span_metrics` flag switches them to.',
|
||||
options: SERVICE_MODES,
|
||||
value: 'traces',
|
||||
}),
|
||||
operations: countControl('Key operations', {
|
||||
group: DATA,
|
||||
description: 'Rows in the key operations table below the graphs.',
|
||||
@@ -63,16 +88,22 @@ export const metricsApplicationMocks = defineStoryMocks({
|
||||
}),
|
||||
},
|
||||
handlers: (values, response) => {
|
||||
const queryRange = response.json(async (req) =>
|
||||
queryRangeV3ForRequest(await req.json(), {
|
||||
count: values.series,
|
||||
labelValues: METRICS_LABEL_VALUES,
|
||||
}),
|
||||
);
|
||||
|
||||
return [
|
||||
rest.post('http://localhost/api/v3/query_range', queryRange),
|
||||
rest.post('http://localhost/api/v4/query_range', queryRange),
|
||||
rest.post(
|
||||
'http://localhost/api/v5/query_range',
|
||||
response.json(async (req) => {
|
||||
const body = await req.json();
|
||||
|
||||
// the only scalar request is the span-metrics key operations table
|
||||
return queryRangeV5ForRequest(body, {
|
||||
count:
|
||||
body.requestType === Querybuildertypesv5RequestTypeDTO.scalar
|
||||
? values.operations
|
||||
: values.series,
|
||||
labelValues: METRICS_LABEL_VALUES,
|
||||
});
|
||||
}),
|
||||
),
|
||||
rest.post(
|
||||
'http://localhost/api/v1/service/top_level_operations',
|
||||
response.json(() => topLevelOperationsResponse(SERVICE_NAME)),
|
||||
@@ -132,5 +163,6 @@ export const metricsApplicationMocks = defineStoryMocks({
|
||||
},
|
||||
config: (values) => ({
|
||||
route: `/services/${SERVICE_NAME}?${QueryParams.tab}=${values.tab}`,
|
||||
appContext: { featureFlags: featureFlagsFor(values.mode) },
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { renderAtRoute } from '@/storybook/renderAtRoute';
|
||||
import { screen, userEvent, within } from 'storybook/test';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import MetricsApplication from '../MetricsApplication';
|
||||
import { openDownloadMenu } from './__story_mockdata__/metricsApplication.play';
|
||||
import { metricsApplicationMocks } from './MetricsApplication.stories.mocks';
|
||||
|
||||
type MetricsApplicationArgs = PageStoryArgs<typeof metricsApplicationMocks>;
|
||||
@@ -40,6 +40,14 @@ type Story = StoryObj<MetricsApplicationArgs>;
|
||||
*/
|
||||
export const Default: Story = {};
|
||||
|
||||
/**
|
||||
* The overview read from span metrics, which the `use_span_metrics` flag
|
||||
* switches it to: histogram latency and the metrics key operations table.
|
||||
*/
|
||||
export const SpanMetrics: Story = {
|
||||
args: { mode: 'span-metrics' },
|
||||
};
|
||||
|
||||
/** The database calls the service makes, by system and by upstream. */
|
||||
export const DatabaseCalls: Story = {
|
||||
args: { tab: 'DB_CALL_METRICS' },
|
||||
@@ -65,14 +73,5 @@ export const NoOperations: Story = {
|
||||
* be taken away in.
|
||||
*/
|
||||
export const DownloadMenu: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'download-menu-trigger',
|
||||
{},
|
||||
{ timeout: 15000 },
|
||||
),
|
||||
);
|
||||
await screen.findByRole('menu');
|
||||
},
|
||||
play: openDownloadMenu,
|
||||
};
|
||||
|
||||
23
frontend/src/pages/MetricsApplication/stories/__story_mockdata__/metricsApplication.play.ts
generated
Normal file
23
frontend/src/pages/MetricsApplication/stories/__story_mockdata__/metricsApplication.play.ts
generated
Normal file
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import { screen, userEvent, within } from 'storybook/test';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
}
|
||||
|
||||
export const openDownloadMenu = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByTestId(
|
||||
'download-menu-trigger',
|
||||
{},
|
||||
{ timeout: 15000 },
|
||||
),
|
||||
);
|
||||
await screen.findByRole('menu');
|
||||
};
|
||||
@@ -27,6 +27,10 @@ export const METRICS_APPLICATION_TABS = [
|
||||
export type MetricsApplicationTabKey =
|
||||
(typeof METRICS_APPLICATION_TABS)[number];
|
||||
|
||||
export const SERVICE_MODES = ['traces', 'span-metrics'] as const;
|
||||
|
||||
export type ServiceMode = (typeof SERVICE_MODES)[number];
|
||||
|
||||
const OPERATION_NAMES = [
|
||||
'POST /api/checkout',
|
||||
'GET /api/cart',
|
||||
|
||||
@@ -47,12 +47,6 @@ const featureFlagsFor = (mode: ServiceMode): FeatureFlagProps[] =>
|
||||
: flag,
|
||||
);
|
||||
|
||||
/**
|
||||
* The span-metrics table derives one point per series, so every request answers
|
||||
* on the same timestamp and a refetch redraws the same numbers.
|
||||
*/
|
||||
const POINT_AT = 1_735_689_600_000;
|
||||
|
||||
export const servicesMocks = defineStoryMocks({
|
||||
controls: {
|
||||
mode: choiceControl<ServiceMode>('Source', {
|
||||
@@ -95,14 +89,13 @@ export const servicesMocks = defineStoryMocks({
|
||||
response.json(() => topLevelOperationsResponse(values.services)),
|
||||
),
|
||||
rest.post(
|
||||
'http://localhost/api/v4/query_range',
|
||||
'http://localhost/api/v5/query_range',
|
||||
response.json(async (req) =>
|
||||
serviceMetricsResponse(
|
||||
(await req.json()) as Record<string, unknown>,
|
||||
values.services,
|
||||
values.health,
|
||||
values.traffic,
|
||||
POINT_AT,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -37,7 +37,7 @@ type Story = StoryObj<ServicesArgs>;
|
||||
*/
|
||||
export const Default: Story = {};
|
||||
|
||||
/** The same list read from span metrics instead of traces, so p99 is in ns. */
|
||||
/** The same list read from span metrics instead of traces. */
|
||||
export const SpanMetrics: Story = {
|
||||
args: { mode: 'span-metrics' },
|
||||
};
|
||||
|
||||
@@ -4,14 +4,10 @@
|
||||
*/
|
||||
|
||||
import type { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
|
||||
import type { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
|
||||
import type { ServicesList } from 'types/api/metrics/getService';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type { MetricRangePayloadV5 } from 'types/api/v5/queryRange';
|
||||
|
||||
import {
|
||||
queryRangeV3TimeSeriesResponse,
|
||||
v3Series,
|
||||
} from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
import { queryRangeV5ScalarTableResponse } from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
|
||||
export const SERVICE_MODES = ['traces', 'span-metrics'] as const;
|
||||
|
||||
@@ -64,7 +60,7 @@ export const RESOURCE_ATTRIBUTE_KEYS = [
|
||||
const namesFor = (count: number): string[] =>
|
||||
SERVICE_NAMES.slice(0, Math.min(count, SERVICE_MAX));
|
||||
|
||||
/** Latency in nanoseconds, which is what both the table columns divide down from. */
|
||||
/** Latency in nanoseconds, as `/v2/services` sends it. */
|
||||
const p99Of = (index: number, health: ServiceHealth): number => {
|
||||
const base = 118_000_000 + index * 11_500_000;
|
||||
|
||||
@@ -161,28 +157,31 @@ const serviceOf = (
|
||||
names: string[],
|
||||
): string | undefined => {
|
||||
const composite = body.compositeQuery as
|
||||
| { builderQueries?: Record<string, IBuilderQuery> }
|
||||
| {
|
||||
queries?: {
|
||||
spec?: { name?: string; filter?: { expression?: string } };
|
||||
}[];
|
||||
}
|
||||
| undefined;
|
||||
const item = composite?.builderQueries?.A?.filters?.items?.find(
|
||||
(filter) => filter.key?.key === 'service.name',
|
||||
);
|
||||
const value = Array.isArray(item?.value) ? item?.value[0] : item?.value;
|
||||
const expression =
|
||||
composite?.queries?.find((query) => query.spec?.name === 'A')?.spec?.filter
|
||||
?.expression ?? '';
|
||||
|
||||
return names.find((name) => name === value);
|
||||
return names.find((name) => expression.includes(`'${name}'`));
|
||||
};
|
||||
|
||||
/**
|
||||
* One request per service, so the row a response fills is the one named in its
|
||||
* own `service.name` filter. `A` is p99, `D` the call rate and `F1` the error
|
||||
* rate formula, which is the only three values the table reads back.
|
||||
* own `service.name` filter. `A` is p99 in ms (span metrics, unlike the ns of
|
||||
* `/v2/services`), `D` the call rate and `F1` the error rate formula, which is
|
||||
* the only three values the table reads back.
|
||||
*/
|
||||
export const serviceMetricsResponse = (
|
||||
body: Record<string, unknown>,
|
||||
count: number,
|
||||
health: ServiceHealth,
|
||||
traffic: ServiceTraffic,
|
||||
timestamp: number,
|
||||
): MetricRangePayloadProps => {
|
||||
): MetricRangePayloadV5 => {
|
||||
const names = namesFor(count);
|
||||
const service = serviceOf(body, names);
|
||||
const index = service ? names.indexOf(service) : 0;
|
||||
@@ -193,20 +192,11 @@ export const serviceMetricsResponse = (
|
||||
traffic,
|
||||
);
|
||||
|
||||
const point = (value: number): { timestamp: number; value: string } => ({
|
||||
timestamp,
|
||||
value: String(Number(value.toFixed(4))),
|
||||
});
|
||||
const round = (value: number): number => Number(value.toFixed(4));
|
||||
|
||||
return {
|
||||
data: {
|
||||
result: [],
|
||||
resultType: '',
|
||||
newResult: queryRangeV3TimeSeriesResponse([
|
||||
{ queryName: 'A', series: [v3Series({}, [point(p99)])] },
|
||||
{ queryName: 'D', series: [v3Series({}, [point(callRate)])] },
|
||||
{ queryName: 'F1', series: [v3Series({}, [point(errorRate)])] },
|
||||
]),
|
||||
},
|
||||
};
|
||||
return queryRangeV5ScalarTableResponse({
|
||||
groupBy: ['service.name'],
|
||||
aggregations: ['A', 'D', 'F1'],
|
||||
rows: [[service, round(p99 / 1_000_000), round(callRate), round(errorRate)]],
|
||||
});
|
||||
};
|
||||
|
||||
@@ -4,8 +4,13 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
Querybuildertypesv5QueryEnvelopeFormulaDTOType,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type QueryRangeV5200,
|
||||
type Querybuildertypesv5ColumnDescriptorDTO,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
type Querybuildertypesv5TimeSeriesDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { Warning } from 'types/api';
|
||||
@@ -346,21 +351,6 @@ interface BuilderQueryShape {
|
||||
groupBy?: Array<{ key: string }>;
|
||||
}
|
||||
|
||||
interface BuilderRequestShape {
|
||||
start: number;
|
||||
end: number;
|
||||
compositeQuery: {
|
||||
panelType?: string;
|
||||
builderQueries?: Record<string, BuilderQueryShape>;
|
||||
};
|
||||
}
|
||||
|
||||
const allQueries = (body: BuilderRequestShape): BuilderQueryShape[] =>
|
||||
Object.values(body.compositeQuery.builderQueries ?? {});
|
||||
|
||||
const enabledQueries = (body: BuilderRequestShape): BuilderQueryShape[] =>
|
||||
allQueries(body).filter((query) => !query.disabled);
|
||||
|
||||
/**
|
||||
* A formula carries no `groupBy` of its own: it is grouped by whatever the
|
||||
* queries it combines were, so its series take the same labels and a `{{key}}`
|
||||
@@ -382,89 +372,6 @@ const keysFor = (
|
||||
),
|
||||
];
|
||||
|
||||
export const builderTimeSeriesResponse = (
|
||||
body: BuilderRequestShape,
|
||||
{ count = 1, labelValues = {} }: BuilderResponseOptions = {},
|
||||
): QueryRangeV3Body => {
|
||||
const { start, end } = body;
|
||||
const isValue = body.compositeQuery.panelType === 'value';
|
||||
|
||||
const queries = allQueries(body);
|
||||
|
||||
return queryRangeV3TimeSeriesResponse(
|
||||
enabledQueries(body).map((query, queryIndex) => {
|
||||
const keys = keysFor(query, queries);
|
||||
const seriesCount = isValue || !keys.length ? Math.min(count, 1) : count;
|
||||
|
||||
return {
|
||||
queryName: query.queryName,
|
||||
legend: query.legend,
|
||||
series: Array.from({ length: seriesCount }, (_unused, seriesIndex) =>
|
||||
v3Series(
|
||||
Object.fromEntries(
|
||||
keys.map((key) => [
|
||||
key,
|
||||
builderLabelValue(key, seriesIndex, labelValues),
|
||||
]),
|
||||
),
|
||||
v3TimeSeriesValues({
|
||||
start,
|
||||
end,
|
||||
points: isValue ? 1 : 30,
|
||||
base: 40 + queryIndex * 15 + seriesIndex * 8,
|
||||
amplitude: 12 + seriesIndex * 3,
|
||||
seed: queryIndex * 5 + seriesIndex,
|
||||
}),
|
||||
),
|
||||
),
|
||||
};
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const builderTableResponse = (
|
||||
body: BuilderRequestShape,
|
||||
{ count = 1, labelValues = {} }: BuilderResponseOptions = {},
|
||||
): QueryRangeV3Body => {
|
||||
const queries = enabledQueries(body);
|
||||
const keys = [
|
||||
...new Set(queries.flatMap((query) => keysFor(query, allQueries(body)))),
|
||||
];
|
||||
|
||||
const columns: Column[] = [
|
||||
...keys.map((name) => ({ name, queryName: '', isValueColumn: false })),
|
||||
...queries.map((query) => ({
|
||||
name: query.queryName,
|
||||
queryName: query.queryName,
|
||||
isValueColumn: true,
|
||||
})),
|
||||
];
|
||||
|
||||
const rows = Array.from({ length: count }, (_unused, index) => ({
|
||||
data: {
|
||||
...Object.fromEntries(
|
||||
keys.map((key) => [key, builderLabelValue(key, index, labelValues)]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
queries.map((query, queryIndex) => [
|
||||
query.queryName,
|
||||
seededMetricValue(index + queryIndex, 20 + queryIndex * 30, 60),
|
||||
]),
|
||||
),
|
||||
},
|
||||
}));
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
data: {
|
||||
resultType: 'table',
|
||||
result: [
|
||||
{ queryName: 'A', series: null, list: null, table: { columns, rows } },
|
||||
],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Derived from the index rather than random, so a refetch redraws the same values. */
|
||||
export const seededMetricValue = (
|
||||
index: number,
|
||||
@@ -472,14 +379,6 @@ export const seededMetricValue = (
|
||||
spread: number,
|
||||
): number => Number((base + (spread * ((index * 37) % 100)) / 100).toFixed(2));
|
||||
|
||||
export const queryRangeV3ForRequest = (
|
||||
body: BuilderRequestShape,
|
||||
options: BuilderResponseOptions = {},
|
||||
): QueryRangeV3Body =>
|
||||
body.compositeQuery.panelType === 'table'
|
||||
? builderTableResponse(body, options)
|
||||
: builderTimeSeriesResponse(body, options);
|
||||
|
||||
interface HeatmapResponseSpec {
|
||||
/** Ascending bucket upper bounds; each point carries one count per bound plus the open-above overflow. */
|
||||
buckets: number[];
|
||||
@@ -517,3 +416,131 @@ export const queryRangeV5HeatmapResponse = ({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/** The v5 request's builder queries and formulas in the shape `keysFor` reads them. */
|
||||
const v5QueryShapes = (
|
||||
body: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
): (BuilderQueryShape & { aggregations: number })[] =>
|
||||
(body.compositeQuery?.queries ?? []).flatMap((envelope) => {
|
||||
if (
|
||||
envelope.type ===
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
|
||||
) {
|
||||
const { spec } = envelope;
|
||||
return [
|
||||
{
|
||||
queryName: spec?.name ?? '',
|
||||
legend: spec?.legend,
|
||||
disabled: spec?.disabled,
|
||||
groupBy: (spec?.groupBy ?? []).map(({ name }) => ({ key: name })),
|
||||
aggregations: Math.max(spec?.aggregations?.length ?? 0, 1),
|
||||
},
|
||||
];
|
||||
}
|
||||
if (
|
||||
envelope.type ===
|
||||
Querybuildertypesv5QueryEnvelopeFormulaDTOType.builder_formula
|
||||
) {
|
||||
const { spec } = envelope;
|
||||
return [
|
||||
{
|
||||
queryName: spec?.name ?? '',
|
||||
legend: spec?.legend,
|
||||
disabled: spec?.disabled,
|
||||
aggregations: 1,
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
/**
|
||||
* Answers a v5 request from the request itself: a time-series request gets one
|
||||
* series per group-by combination, a scalar request one row per combination with
|
||||
* a column per aggregation.
|
||||
*/
|
||||
export const queryRangeV5ForRequest = (
|
||||
body: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
{ count = 1, labelValues = {} }: BuilderResponseOptions = {},
|
||||
): QueryRangeV5200 => {
|
||||
const queries = v5QueryShapes(body);
|
||||
const enabled = queries.filter((query) => !query.disabled);
|
||||
const start = body.start ?? 0;
|
||||
const end = body.end ?? 0;
|
||||
|
||||
if (body.requestType === Querybuildertypesv5RequestTypeDTO.scalar) {
|
||||
const keys = [
|
||||
...new Set(enabled.flatMap((query) => keysFor(query, queries))),
|
||||
];
|
||||
const columns: Querybuildertypesv5ColumnDescriptorDTO[] = [
|
||||
...keys.map((name) => ({
|
||||
name,
|
||||
queryName: '',
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.group,
|
||||
})),
|
||||
...enabled.flatMap((query) =>
|
||||
Array.from({ length: query.aggregations }, (_unused, aggregationIndex) => ({
|
||||
name: `__result_${aggregationIndex}`,
|
||||
queryName: query.queryName,
|
||||
aggregationIndex,
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
|
||||
})),
|
||||
),
|
||||
];
|
||||
const rows = Array.from({ length: count }, (_unused, index) => [
|
||||
...keys.map((key) => builderLabelValue(key, index, labelValues)),
|
||||
...columns
|
||||
.slice(keys.length)
|
||||
.map((_column, columnIndex) =>
|
||||
seededMetricValue(index + columnIndex, 20 + columnIndex * 30, 60),
|
||||
),
|
||||
]);
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
data: {
|
||||
type: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
data: { results: [{ columns, data: rows }] },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
data: {
|
||||
type: Querybuildertypesv5RequestTypeDTO.time_series,
|
||||
data: {
|
||||
results: enabled.map((query, queryIndex) => {
|
||||
const keys = keysFor(query, queries);
|
||||
const seriesCount = keys.length ? count : Math.min(count, 1);
|
||||
|
||||
return {
|
||||
queryName: query.queryName,
|
||||
aggregations: [
|
||||
{
|
||||
index: 0,
|
||||
alias: '',
|
||||
series: Array.from(
|
||||
{ length: seriesCount },
|
||||
(_unused, seriesIndex): Querybuildertypesv5TimeSeriesDTO => ({
|
||||
labels: keys.map((key) => ({
|
||||
key: { name: key },
|
||||
value: builderLabelValue(key, seriesIndex, labelValues),
|
||||
})),
|
||||
values: timeSeriesPoints({
|
||||
start,
|
||||
end,
|
||||
base: 40 + queryIndex * 15 + seriesIndex * 8,
|
||||
amplitude: 12 + seriesIndex * 3,
|
||||
seed: queryIndex * 5 + seriesIndex,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
}),
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// ===================== Base Types =====================
|
||||
|
||||
import { Querybuildertypesv5BucketOptionsDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
MetrictypesComparisonSpaceAggregationParamDTO,
|
||||
Querybuildertypesv5BucketOptionsDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { ReduceOperators } from 'types/common/queryBuilder';
|
||||
|
||||
import { Warning } from '..';
|
||||
@@ -201,6 +204,7 @@ export interface MetricAggregation {
|
||||
timeAggregation: TimeAggregation;
|
||||
spaceAggregation: SpaceAggregation;
|
||||
reduceTo?: ReduceOperators;
|
||||
comparisonSpaceAggregationParam?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
}
|
||||
|
||||
export interface SecondaryAggregation {
|
||||
|
||||
Reference in New Issue
Block a user