mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-03 21:51:22 +00:00
Compare commits
5 Commits
chore/dead
...
refactor/q
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8aa32ffa1a | ||
|
|
757475b2ff | ||
|
|
e88990e464 | ||
|
|
cbe325f652 | ||
|
|
86da2471f2 |
@@ -1,53 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
|
||||
export interface QueueOverviewPayload {
|
||||
start: number;
|
||||
end: number;
|
||||
filters: {
|
||||
items: {
|
||||
key: {
|
||||
key: string;
|
||||
dataType: string;
|
||||
};
|
||||
op: string;
|
||||
value: string[];
|
||||
}[];
|
||||
op: 'AND' | 'OR';
|
||||
};
|
||||
}
|
||||
|
||||
export interface QueueOverviewResponse {
|
||||
status: string;
|
||||
data: {
|
||||
timestamp?: string;
|
||||
data: {
|
||||
destination?: string;
|
||||
error_percentage?: number;
|
||||
kind_string?: string;
|
||||
messaging_system?: string;
|
||||
p95_latency?: number;
|
||||
service_name?: string;
|
||||
span_name?: string;
|
||||
throughput?: number;
|
||||
}[];
|
||||
}[];
|
||||
}
|
||||
|
||||
export const getQueueOverview = async (
|
||||
props: QueueOverviewPayload,
|
||||
): Promise<SuccessResponse<QueueOverviewResponse['data']> | ErrorResponse> => {
|
||||
const { start, end, filters } = props;
|
||||
const response = await axios.post(`messaging-queues/queue-overview`, {
|
||||
start,
|
||||
end,
|
||||
filters,
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
};
|
||||
@@ -1,55 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { MessagingQueueServiceDetailType } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
|
||||
export interface MessagingQueueServicePayload {
|
||||
start?: number | string;
|
||||
end?: number | string;
|
||||
variables?: {
|
||||
partition?: string;
|
||||
topic?: string;
|
||||
consumer_group?: string;
|
||||
service_name?: string;
|
||||
};
|
||||
detailType?: MessagingQueueServiceDetailType | 'producer' | 'consumer';
|
||||
}
|
||||
|
||||
export interface MessagingQueuesPayloadProps {
|
||||
status: string;
|
||||
payload: {
|
||||
resultType: string;
|
||||
result: {
|
||||
table: {
|
||||
columns: {
|
||||
name: string;
|
||||
queryName: string;
|
||||
isValueColumn: boolean;
|
||||
}[];
|
||||
rows: {
|
||||
data: Record<string, string>;
|
||||
}[];
|
||||
};
|
||||
}[];
|
||||
};
|
||||
}
|
||||
|
||||
export const getConsumerLagDetails = async (
|
||||
props: MessagingQueueServicePayload,
|
||||
): Promise<
|
||||
SuccessResponse<MessagingQueuesPayloadProps['payload']> | ErrorResponse
|
||||
> => {
|
||||
const { detailType, ...restProps } = props;
|
||||
const response = await axios.post(
|
||||
`/messaging-queues/kafka/consumer-lag/${detailType}`,
|
||||
{
|
||||
...restProps,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { MessagingQueueServiceDetailType } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
|
||||
import {
|
||||
MessagingQueueServicePayload,
|
||||
MessagingQueuesPayloadProps,
|
||||
} from './getConsumerLagDetails';
|
||||
|
||||
export const getPartitionLatencyDetails = async (
|
||||
props: MessagingQueueServicePayload,
|
||||
): Promise<
|
||||
SuccessResponse<MessagingQueuesPayloadProps['payload']> | ErrorResponse
|
||||
> => {
|
||||
const { detailType, ...rest } = props;
|
||||
let endpoint = '';
|
||||
if (detailType === MessagingQueueServiceDetailType.ConsumerDetails) {
|
||||
endpoint = `/messaging-queues/kafka/partition-latency/consumer`;
|
||||
} else {
|
||||
endpoint = `/messaging-queues/kafka/consumer-lag/producer-details`;
|
||||
}
|
||||
|
||||
const response = await axios.post(endpoint, {
|
||||
...rest,
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
|
||||
import {
|
||||
MessagingQueueServicePayload,
|
||||
MessagingQueuesPayloadProps,
|
||||
} from './getConsumerLagDetails';
|
||||
|
||||
export const getPartitionLatencyOverview = async (
|
||||
props: Omit<MessagingQueueServicePayload, 'detailType' | 'variables'>,
|
||||
): Promise<
|
||||
SuccessResponse<MessagingQueuesPayloadProps['payload']> | ErrorResponse
|
||||
> => {
|
||||
const response = await axios.post(
|
||||
`/messaging-queues/kafka/partition-latency/overview`,
|
||||
{
|
||||
...props,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
};
|
||||
@@ -1,26 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
|
||||
import {
|
||||
MessagingQueueServicePayload,
|
||||
MessagingQueuesPayloadProps,
|
||||
} from './getConsumerLagDetails';
|
||||
|
||||
export const getTopicThroughputDetails = async (
|
||||
props: MessagingQueueServicePayload,
|
||||
): Promise<
|
||||
SuccessResponse<MessagingQueuesPayloadProps['payload']> | ErrorResponse
|
||||
> => {
|
||||
const { detailType, ...rest } = props;
|
||||
const endpoint = `/messaging-queues/kafka/topic-throughput/${detailType}`;
|
||||
const response = await axios.post(endpoint, {
|
||||
...rest,
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
};
|
||||
@@ -1,29 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
|
||||
import {
|
||||
MessagingQueueServicePayload,
|
||||
MessagingQueuesPayloadProps,
|
||||
} from './getConsumerLagDetails';
|
||||
|
||||
export const getTopicThroughputOverview = async (
|
||||
props: Omit<MessagingQueueServicePayload, 'variables'>,
|
||||
): Promise<
|
||||
SuccessResponse<MessagingQueuesPayloadProps['payload']> | ErrorResponse
|
||||
> => {
|
||||
const { detailType, start, end } = props;
|
||||
const response = await axios.post(
|
||||
`messaging-queues/kafka/topic-throughput/${detailType}`,
|
||||
{
|
||||
start,
|
||||
end,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
};
|
||||
@@ -1,39 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { SOMETHING_WENT_WRONG } from 'constants/api';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
|
||||
export interface OnboardingStatusResponse {
|
||||
status: string;
|
||||
data: {
|
||||
attribute?: string;
|
||||
error_message?: string;
|
||||
status?: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
const getOnboardingStatus = async (props: {
|
||||
start: number;
|
||||
end: number;
|
||||
endpointService?: string;
|
||||
}): Promise<SuccessResponse<OnboardingStatusResponse> | ErrorResponse> => {
|
||||
const { endpointService, ...rest } = props;
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`/messaging-queues/kafka/onboarding/${endpointService || 'consumers'}`,
|
||||
rest,
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler((error as AxiosError) || SOMETHING_WENT_WRONG);
|
||||
}
|
||||
};
|
||||
|
||||
export default getOnboardingStatus;
|
||||
@@ -1,7 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useMutation } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { Loader, Search } from '@signozhq/icons';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import {
|
||||
@@ -19,21 +16,14 @@ import { Progress } from '@signozhq/ui/progress';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import type { FilterDropdownProps } from 'antd/lib/table/interface';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import {
|
||||
getQueueOverview,
|
||||
QueueOverviewResponse,
|
||||
} from 'api/messagingQueues/celery/getQueueOverview';
|
||||
import { ResizeTable } from 'components/ResizeTable';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import useDragColumns from 'hooks/useDragColumns';
|
||||
import { getDraggedColumns } from 'hooks/useDragColumns/utils';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import { formatNumericValue } from 'utils/numericUtils';
|
||||
|
||||
import { useQueueOverview } from './useQueueOverview';
|
||||
|
||||
import './CeleryOverviewTable.styles.scss';
|
||||
|
||||
const INITIAL_PAGE_SIZE = 20;
|
||||
@@ -277,126 +267,13 @@ function getColumns(data: RowData[]): TableColumnsType<RowData> {
|
||||
];
|
||||
}
|
||||
|
||||
function getTableData(data: QueueOverviewResponse['data']): RowData[] {
|
||||
if (data?.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const columnOrder = [
|
||||
'service_name',
|
||||
'span_name',
|
||||
'messaging_system',
|
||||
'destination',
|
||||
'kind_string',
|
||||
'error_percentage',
|
||||
'p95_latency',
|
||||
'throughput',
|
||||
];
|
||||
|
||||
const tableData: RowData[] =
|
||||
data?.map((row, index: number): RowData => {
|
||||
const rowData: Record<string, string | number> = {};
|
||||
columnOrder.forEach((key) => {
|
||||
const value = row.data[key as keyof typeof row.data];
|
||||
if (typeof value === 'string' || typeof value === 'number') {
|
||||
rowData[key] = value;
|
||||
}
|
||||
});
|
||||
Object.entries(row.data).forEach(([key, value]) => {
|
||||
if (
|
||||
!columnOrder.includes(key) &&
|
||||
(typeof value === 'string' || typeof value === 'number')
|
||||
) {
|
||||
rowData[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
...rowData,
|
||||
key: index,
|
||||
};
|
||||
}) || [];
|
||||
|
||||
return tableData;
|
||||
}
|
||||
|
||||
type Filter = {
|
||||
key: {
|
||||
key: string;
|
||||
dataType: string;
|
||||
};
|
||||
op: string;
|
||||
value: string[];
|
||||
};
|
||||
|
||||
type FilterConfig = {
|
||||
paramName: string;
|
||||
operator: string;
|
||||
key: string;
|
||||
};
|
||||
|
||||
function makeFilters(urlQuery: URLSearchParams): Filter[] {
|
||||
const filterConfigs: FilterConfig[] = [
|
||||
{ paramName: QueryParams.destination, key: 'destination', operator: 'in' },
|
||||
{ paramName: QueryParams.msgSystem, key: 'queue', operator: 'in' },
|
||||
{ paramName: QueryParams.kindString, key: 'kind_string', operator: 'in' },
|
||||
{ paramName: QueryParams.service, key: 'service.name', operator: 'in' },
|
||||
{ paramName: QueryParams.spanName, key: 'name', operator: 'in' },
|
||||
];
|
||||
|
||||
return filterConfigs
|
||||
.map(({ paramName, operator, key }) => {
|
||||
const value = urlQuery.get(paramName);
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
key: {
|
||||
key,
|
||||
dataType: 'string',
|
||||
},
|
||||
op: operator,
|
||||
value: value.split(','),
|
||||
};
|
||||
})
|
||||
.filter((filter): filter is Filter => filter !== null);
|
||||
}
|
||||
|
||||
export default function CeleryOverviewTable({
|
||||
onRowClick,
|
||||
}: {
|
||||
onRowClick: (record: RowData) => void;
|
||||
}): JSX.Element {
|
||||
const [tableData, setTableData] = useState<RowData[]>([]);
|
||||
|
||||
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
|
||||
const { mutate: getOverviewData, isLoading } = useMutation(getQueueOverview, {
|
||||
onSuccess: (data) => {
|
||||
if (data?.payload) {
|
||||
setTableData(getTableData(data?.payload));
|
||||
} else if (isEmpty(data?.payload)) {
|
||||
setTableData([]);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const urlQuery = useUrlQuery();
|
||||
const filters = useMemo(() => makeFilters(urlQuery), [urlQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
getOverviewData({
|
||||
start: minTime,
|
||||
end: maxTime,
|
||||
filters: {
|
||||
items: filters,
|
||||
op: 'AND',
|
||||
},
|
||||
});
|
||||
}, [getOverviewData, minTime, maxTime, filters]);
|
||||
const { data, isFetching: isLoading } = useQueueOverview();
|
||||
const tableData = useMemo(() => data ?? [], [data]);
|
||||
|
||||
const { draggedColumns, onDragColumns } = useDragColumns<RowData>(
|
||||
LOCALSTORAGE.CELERY_OVERVIEW_COLUMNS,
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import {
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
type Querybuildertypesv5ScalarDataDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
|
||||
import {
|
||||
getQueueOverviewFilterExpression,
|
||||
getQueueOverviewRequest,
|
||||
getQueueOverviewRows,
|
||||
} from '../queueOverviewQuery';
|
||||
|
||||
const { group, aggregation } = Querybuildertypesv5ColumnTypeDTO;
|
||||
|
||||
const QUEUE_SPANS =
|
||||
"(messaging.system = 'kafka' OR celery.action EXISTS OR celery.task_name EXISTS)";
|
||||
|
||||
describe('getQueueOverviewFilterExpression', () => {
|
||||
it('keeps only kafka and celery spans when no filter is set', () => {
|
||||
expect(getQueueOverviewFilterExpression(new URLSearchParams())).toBe(
|
||||
QUEUE_SPANS,
|
||||
);
|
||||
});
|
||||
|
||||
it('matches celery spans by their attributes and destinations on either key', () => {
|
||||
const urlQuery = new URLSearchParams({
|
||||
[QueryParams.msgSystem]: 'kafka,celery',
|
||||
[QueryParams.destination]: 'orders',
|
||||
[QueryParams.service]: 'billing-worker',
|
||||
});
|
||||
|
||||
expect(getQueueOverviewFilterExpression(urlQuery)).toBe(
|
||||
[
|
||||
QUEUE_SPANS,
|
||||
"service.name IN ['billing-worker']",
|
||||
"(messaging.system IN ['kafka', 'celery'] OR (messaging.system NOT EXISTS AND (celery.action EXISTS OR celery.task_name EXISTS)))",
|
||||
"(messaging.destination.name IN ['orders'] OR (messaging.destination.name NOT EXISTS AND messaging.destination IN ['orders']))",
|
||||
].join(' AND '),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getQueueOverviewRequest', () => {
|
||||
it('groups by the keys the legacy SQL derived its columns from', () => {
|
||||
expect(getQueueOverviewRequest(1000.7, 2000.2, QUEUE_SPANS)).toStrictEqual({
|
||||
schemaVersion: 'v1',
|
||||
start: 1000,
|
||||
end: 2000,
|
||||
requestType: 'scalar',
|
||||
compositeQuery: {
|
||||
queries: [
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: 'traces',
|
||||
filter: { expression: QUEUE_SPANS },
|
||||
groupBy: [
|
||||
{ name: 'service.name' },
|
||||
{ name: 'name' },
|
||||
{ name: 'messaging.system' },
|
||||
{ name: 'messaging.destination.name' },
|
||||
{ name: 'messaging.destination' },
|
||||
{ name: 'kind_string' },
|
||||
],
|
||||
aggregations: [
|
||||
{ expression: 'p95(duration_nano)' },
|
||||
{ expression: 'count()' },
|
||||
{ expression: 'countIf(has_error = true)' },
|
||||
{ expression: 'rate()' },
|
||||
],
|
||||
order: [
|
||||
{ key: { name: 'service.name' }, direction: 'asc' },
|
||||
{ key: { name: 'name' }, direction: 'asc' },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getQueueOverviewRows', () => {
|
||||
const RESULT_COLUMNS: Querybuildertypesv5ScalarDataDTO['columns'] = [
|
||||
{ name: 'service.name', columnType: group },
|
||||
{ name: 'name', columnType: group },
|
||||
{ name: 'messaging.system', columnType: group },
|
||||
{ name: 'messaging.destination.name', columnType: group },
|
||||
{ name: 'messaging.destination', columnType: group },
|
||||
{ name: 'kind_string', columnType: group },
|
||||
{ name: '__result_0', columnType: aggregation, aggregationIndex: 0 },
|
||||
{ name: '__result_1', columnType: aggregation, aggregationIndex: 1 },
|
||||
{ name: '__result_2', columnType: aggregation, aggregationIndex: 2 },
|
||||
{ name: '__result_3', columnType: aggregation, aggregationIndex: 3 },
|
||||
];
|
||||
|
||||
it('names spans without a messaging system celery and falls back to messaging.destination', () => {
|
||||
const result: Querybuildertypesv5ScalarDataDTO = {
|
||||
queryName: 'A',
|
||||
columns: RESULT_COLUMNS,
|
||||
data: [
|
||||
[
|
||||
'billing-worker',
|
||||
'run/charge',
|
||||
null,
|
||||
null,
|
||||
'billing',
|
||||
'Consumer',
|
||||
148e6,
|
||||
200,
|
||||
5,
|
||||
0.4,
|
||||
],
|
||||
],
|
||||
};
|
||||
|
||||
expect(getQueueOverviewRows(result)).toStrictEqual([
|
||||
{
|
||||
key: 0,
|
||||
service_name: 'billing-worker',
|
||||
span_name: 'run/charge',
|
||||
messaging_system: 'celery',
|
||||
destination: 'billing',
|
||||
kind_string: 'Consumer',
|
||||
error_percentage: 2.5,
|
||||
p95_latency: 148,
|
||||
throughput: 0.4,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('merges groups that show the same queue, keeping the highest p95', () => {
|
||||
const queue = ['celery-worker', 'analytics.tasks.rollup_hourly'];
|
||||
const result: Querybuildertypesv5ScalarDataDTO = {
|
||||
queryName: 'A',
|
||||
columns: RESULT_COLUMNS,
|
||||
data: [
|
||||
[...queue, 'celery', 'default', 'default', 'Consumer', 7700e6, 73, 0, 0.1],
|
||||
[...queue, null, 'default', 'default', 'Consumer', 9000e6, 2, 1, 0.2],
|
||||
[...queue, 'celery', 'default', null, 'Consumer', 5000e6, 3, 0, 0.004],
|
||||
[...queue, 'celery', 'reports', null, 'Consumer', 6000e6, 4, 0, 0.5],
|
||||
],
|
||||
};
|
||||
|
||||
expect(getQueueOverviewRows(result)).toStrictEqual([
|
||||
{
|
||||
key: 0,
|
||||
service_name: 'celery-worker',
|
||||
span_name: 'analytics.tasks.rollup_hourly',
|
||||
messaging_system: 'celery',
|
||||
destination: 'default',
|
||||
kind_string: 'Consumer',
|
||||
error_percentage: 1.2820512820512822,
|
||||
p95_latency: 9000,
|
||||
throughput: 0.304,
|
||||
},
|
||||
{
|
||||
key: 1,
|
||||
service_name: 'celery-worker',
|
||||
span_name: 'analytics.tasks.rollup_hourly',
|
||||
messaging_system: 'celery',
|
||||
destination: 'reports',
|
||||
kind_string: 'Consumer',
|
||||
error_percentage: 0,
|
||||
p95_latency: 6000,
|
||||
throughput: 0.5,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import {
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
Querybuildertypesv5OrderDirectionDTO,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal as TraceSignal,
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type Querybuildertypesv5ScalarDataDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { formatValueForExpression } from 'components/QueryBuilderV2/utils';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import {
|
||||
NS_PER_MS,
|
||||
toGroupText,
|
||||
} from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
import { toFiniteNumber } from 'utils/numericUtils';
|
||||
|
||||
import type { RowData } from './CeleryOverviewTable';
|
||||
|
||||
const CELERY = 'celery';
|
||||
|
||||
const SERVICE_NAME = 'service.name';
|
||||
const SPAN_NAME = 'name';
|
||||
const MESSAGING_SYSTEM = 'messaging.system';
|
||||
const DESTINATION_NAME = 'messaging.destination.name';
|
||||
const DESTINATION = 'messaging.destination';
|
||||
const KIND = 'kind_string';
|
||||
|
||||
const GROUP_BY = [
|
||||
SERVICE_NAME,
|
||||
SPAN_NAME,
|
||||
MESSAGING_SYSTEM,
|
||||
DESTINATION_NAME,
|
||||
DESTINATION,
|
||||
KIND,
|
||||
];
|
||||
|
||||
const AGGREGATIONS = [
|
||||
'p95(duration_nano)',
|
||||
'count()',
|
||||
'countIf(has_error = true)',
|
||||
'rate()',
|
||||
];
|
||||
|
||||
const CELERY_SPANS = `(${MESSAGING_SYSTEM} NOT EXISTS AND (celery.action EXISTS OR celery.task_name EXISTS))`;
|
||||
const QUEUE_SPANS = `(${MESSAGING_SYSTEM} = 'kafka' OR celery.action EXISTS OR celery.task_name EXISTS)`;
|
||||
|
||||
const inList = (key: string, values: string[]): string =>
|
||||
`${key} IN ${formatValueForExpression(values)}`;
|
||||
|
||||
const getUrlValues = (
|
||||
urlQuery: URLSearchParams,
|
||||
param: QueryParams,
|
||||
): string[] => urlQuery.get(param)?.split(',').filter(Boolean) ?? [];
|
||||
|
||||
/** A span's destination is `messaging.destination.name`, else `messaging.destination`. */
|
||||
const getDestinationFilter = (values: string[]): string =>
|
||||
`(${inList(DESTINATION_NAME, values)} OR (${DESTINATION_NAME} NOT EXISTS AND ${inList(DESTINATION, values)}))`;
|
||||
|
||||
/** Spans without `messaging.system` but with celery attributes count as `celery`. */
|
||||
const getMessagingSystemFilter = (values: string[]): string =>
|
||||
values.includes(CELERY)
|
||||
? `(${inList(MESSAGING_SYSTEM, values)} OR ${CELERY_SPANS})`
|
||||
: inList(MESSAGING_SYSTEM, values);
|
||||
|
||||
export const getQueueOverviewFilterExpression = (
|
||||
urlQuery: URLSearchParams,
|
||||
): string => {
|
||||
const filters: [QueryParams, (values: string[]) => string][] = [
|
||||
[QueryParams.service, (values): string => inList(SERVICE_NAME, values)],
|
||||
[QueryParams.spanName, (values): string => inList(SPAN_NAME, values)],
|
||||
[QueryParams.msgSystem, getMessagingSystemFilter],
|
||||
[QueryParams.destination, getDestinationFilter],
|
||||
[QueryParams.kindString, (values): string => inList(KIND, values)],
|
||||
];
|
||||
|
||||
return [
|
||||
QUEUE_SPANS,
|
||||
...filters.flatMap(([param, toExpression]) => {
|
||||
const values = getUrlValues(urlQuery, param);
|
||||
return values.length ? [toExpression(values)] : [];
|
||||
}),
|
||||
].join(' AND ');
|
||||
};
|
||||
|
||||
export const getQueueOverviewRequest = (
|
||||
startMs: number,
|
||||
endMs: number,
|
||||
filterExpression: string,
|
||||
): Querybuildertypesv5QueryRangeRequestDTO => ({
|
||||
schemaVersion: 'v1',
|
||||
start: Math.floor(startMs),
|
||||
end: Math.floor(endMs),
|
||||
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
compositeQuery: {
|
||||
queries: [
|
||||
{
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: TraceSignal.traces,
|
||||
filter: { expression: filterExpression },
|
||||
groupBy: GROUP_BY.map((name) => ({ name })),
|
||||
aggregations: AGGREGATIONS.map((expression) => ({ expression })),
|
||||
order: [SERVICE_NAME, SPAN_NAME].map((name) => ({
|
||||
key: { name },
|
||||
direction: Querybuildertypesv5OrderDirectionDTO.asc,
|
||||
})),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
/** Service, span name, messaging system, destination and kind, as displayed. */
|
||||
type QueueValues = [string, string, string, string, string];
|
||||
|
||||
interface QueueTotals {
|
||||
values: QueueValues;
|
||||
count: number;
|
||||
errors: number;
|
||||
rate: number;
|
||||
p95: number;
|
||||
}
|
||||
|
||||
export const getQueueOverviewRows = (
|
||||
result: Querybuildertypesv5ScalarDataDTO | undefined,
|
||||
): RowData[] => {
|
||||
const columns = result?.columns ?? [];
|
||||
const groupIndex = (name: string): number =>
|
||||
columns.findIndex(
|
||||
(column) =>
|
||||
column.columnType === Querybuildertypesv5ColumnTypeDTO.group &&
|
||||
column.name === name,
|
||||
);
|
||||
const aggregationIndex = (index: number): number =>
|
||||
columns.findIndex(
|
||||
(column) =>
|
||||
column.columnType === Querybuildertypesv5ColumnTypeDTO.aggregation &&
|
||||
column.aggregationIndex === index,
|
||||
);
|
||||
const [p95Index, countIndex, errorsIndex, rateIndex] = AGGREGATIONS.map(
|
||||
(_, index) => aggregationIndex(index),
|
||||
);
|
||||
|
||||
/**
|
||||
* v5 groups by the raw keys, so spans that differ only in which keys they
|
||||
* carry come back as separate groups. Groups showing the same values are one
|
||||
* queue. A p95 can't be combined, so a merged row keeps the highest.
|
||||
*/
|
||||
const queues = new Map<string, QueueTotals>();
|
||||
(result?.data ?? []).forEach((row) => {
|
||||
const text = (name: string): string => toGroupText(row[groupIndex(name)]);
|
||||
const values: QueueValues = [
|
||||
text(SERVICE_NAME),
|
||||
text(SPAN_NAME),
|
||||
text(MESSAGING_SYSTEM) || CELERY,
|
||||
text(DESTINATION_NAME) || text(DESTINATION),
|
||||
text(KIND),
|
||||
];
|
||||
const key = JSON.stringify(values);
|
||||
const queue = queues.get(key) ?? {
|
||||
values,
|
||||
count: 0,
|
||||
errors: 0,
|
||||
rate: 0,
|
||||
p95: 0,
|
||||
};
|
||||
queue.count += toFiniteNumber(row[countIndex]);
|
||||
queue.errors += toFiniteNumber(row[errorsIndex]);
|
||||
queue.rate += toFiniteNumber(row[rateIndex]);
|
||||
queue.p95 = Math.max(queue.p95, toFiniteNumber(row[p95Index]));
|
||||
queues.set(key, queue);
|
||||
});
|
||||
|
||||
return [...queues.values()].map(
|
||||
({ values, count, errors, rate, p95 }, index): RowData => {
|
||||
const [service, span, system, destination, kind] = values;
|
||||
return {
|
||||
key: index,
|
||||
service_name: service,
|
||||
span_name: span,
|
||||
messaging_system: system,
|
||||
destination,
|
||||
kind_string: kind,
|
||||
error_percentage: count ? (errors * 100) / count : 0,
|
||||
p95_latency: p95 / NS_PER_MS,
|
||||
// Drops the float noise a sum of rounded rates picks up.
|
||||
throughput: Number(rate.toPrecision(12)),
|
||||
};
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useQuery, UseQueryResult } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { queryRangeV5 } from 'api/generated/services/querier';
|
||||
import type {
|
||||
QueryRangeV5200,
|
||||
RenderErrorResponseDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { ErrorType } from 'api/generatedAPIInstance';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { getScalarResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
|
||||
import { NS_PER_MS } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import type { RowData } from './CeleryOverviewTable';
|
||||
import {
|
||||
getQueueOverviewFilterExpression,
|
||||
getQueueOverviewRequest,
|
||||
getQueueOverviewRows,
|
||||
} from './queueOverviewQuery';
|
||||
|
||||
export function useQueueOverview(): UseQueryResult<
|
||||
RowData[],
|
||||
ErrorType<RenderErrorResponseDTO>
|
||||
> {
|
||||
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
const urlQuery = useUrlQuery();
|
||||
const filterExpression = getQueueOverviewFilterExpression(urlQuery);
|
||||
|
||||
const request = useMemo(
|
||||
() =>
|
||||
getQueueOverviewRequest(
|
||||
minTime / NS_PER_MS,
|
||||
maxTime / NS_PER_MS,
|
||||
filterExpression,
|
||||
),
|
||||
[minTime, maxTime, filterExpression],
|
||||
);
|
||||
|
||||
return useQuery<QueryRangeV5200, ErrorType<RenderErrorResponseDTO>, RowData[]>(
|
||||
{
|
||||
queryKey: [REACT_QUERY_KEY.GET_QUEUE_OVERVIEW, request],
|
||||
queryFn: ({ signal }) => queryRangeV5(request, signal),
|
||||
select: (response) => getQueueOverviewRows(getScalarResults(response)[0]),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
X,
|
||||
} from '@signozhq/icons';
|
||||
import { Modal, Select, Spin, Tooltip, Tree, TreeDataNode } from 'antd';
|
||||
import { OnboardingStatusResponse } from 'api/messagingQueues/onboarding/getOnboardingStatus';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
@@ -22,6 +21,8 @@ import {
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
import { OnboardingCheck } from './onboardingStatusQuery';
|
||||
|
||||
import './MessagingQueueHealthCheck.styles.scss';
|
||||
|
||||
interface AttributeCheckListProps {
|
||||
@@ -29,7 +30,7 @@ interface AttributeCheckListProps {
|
||||
onClose: () => void;
|
||||
onboardingStatusResponses: {
|
||||
title: string;
|
||||
data: OnboardingStatusResponse['data'];
|
||||
data: OnboardingCheck[];
|
||||
errorMsg?: string;
|
||||
}[];
|
||||
loading: boolean;
|
||||
@@ -161,28 +162,20 @@ function renderSwitcherIcon(props: { expanded?: boolean }): JSX.Element {
|
||||
}
|
||||
|
||||
function generateTreeDataNodes(
|
||||
response: OnboardingStatusResponse['data'],
|
||||
response: OnboardingCheck[],
|
||||
parentTitle: string,
|
||||
isCloudUserVal: boolean,
|
||||
): TreeDataNode[] {
|
||||
return response
|
||||
.map((item) => {
|
||||
if (item.attribute) {
|
||||
if (item.status === '1') {
|
||||
return treeTitleAndKey({ title: item.attribute, isLeaf: true });
|
||||
}
|
||||
if (item.status === '0') {
|
||||
return ErrorTitleAndKey({
|
||||
title: item.attribute,
|
||||
errorMsg: item.error_message || '',
|
||||
parentTitle,
|
||||
isCloudUserVal,
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Boolean) as TreeDataNode[];
|
||||
return response.map((item) =>
|
||||
item.passed
|
||||
? treeTitleAndKey({ title: item.attribute, isLeaf: true })
|
||||
: ErrorTitleAndKey({
|
||||
title: item.attribute,
|
||||
errorMsg: item.errorMessage || '',
|
||||
parentTitle,
|
||||
isCloudUserVal,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function AttributeCheckList({
|
||||
@@ -213,9 +206,9 @@ function AttributeCheckList({
|
||||
let filteredData = response.data;
|
||||
|
||||
if (filter === AttributesFilters.SUCCESS) {
|
||||
filteredData = response.data.filter((item) => item.status === '1');
|
||||
filteredData = response.data.filter((item) => item.passed);
|
||||
} else if (filter === AttributesFilters.ERROR) {
|
||||
filteredData = response.data.filter((item) => item.status === '0');
|
||||
filteredData = response.data.filter((item) => !item.passed);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Button } from 'antd';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import cx from 'classnames';
|
||||
import { useOnboardingStatus } from 'hooks/messagingQueue/useOnboardingStatus';
|
||||
import { Bolt, FolderTree } from '@signozhq/icons';
|
||||
@@ -19,18 +20,17 @@ function MessagingQueueHealthCheck({
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [checkListOpen, setCheckListOpen] = useState(false);
|
||||
|
||||
const isIncluded = (service: MessagingQueueHealthCheckService): boolean =>
|
||||
serviceToInclude.includes(service);
|
||||
|
||||
// Consumer Data
|
||||
const {
|
||||
data: consumerData,
|
||||
error: consumerError,
|
||||
isFetching: consumerLoading,
|
||||
} = useOnboardingStatus(
|
||||
{
|
||||
enabled: !!serviceToInclude.filter(
|
||||
(service) => service === MessagingQueueHealthCheckService.Consumers,
|
||||
).length,
|
||||
},
|
||||
MessagingQueueHealthCheckService.Consumers,
|
||||
isIncluded(MessagingQueueHealthCheckService.Consumers),
|
||||
);
|
||||
|
||||
// Producer Data
|
||||
@@ -39,12 +39,8 @@ function MessagingQueueHealthCheck({
|
||||
error: producerError,
|
||||
isFetching: producerLoading,
|
||||
} = useOnboardingStatus(
|
||||
{
|
||||
enabled: !!serviceToInclude.filter(
|
||||
(service) => service === MessagingQueueHealthCheckService.Producers,
|
||||
).length,
|
||||
},
|
||||
MessagingQueueHealthCheckService.Producers,
|
||||
isIncluded(MessagingQueueHealthCheckService.Producers),
|
||||
);
|
||||
|
||||
// Kafka Data
|
||||
@@ -53,12 +49,8 @@ function MessagingQueueHealthCheck({
|
||||
error: kafkaError,
|
||||
isFetching: kafkaLoading,
|
||||
} = useOnboardingStatus(
|
||||
{
|
||||
enabled: !!serviceToInclude.filter(
|
||||
(service) => service === MessagingQueueHealthCheckService.Kafka,
|
||||
).length,
|
||||
},
|
||||
MessagingQueueHealthCheckService.Kafka,
|
||||
isIncluded(MessagingQueueHealthCheckService.Kafka),
|
||||
);
|
||||
|
||||
// combined loading and update state
|
||||
@@ -66,24 +58,21 @@ function MessagingQueueHealthCheck({
|
||||
setLoading(consumerLoading || producerLoading || kafkaLoading);
|
||||
}, [consumerLoading, producerLoading, kafkaLoading]);
|
||||
|
||||
const missingConfiguration = useMemo(() => {
|
||||
const consumerMissing =
|
||||
(serviceToInclude.includes(MessagingQueueHealthCheckService.Consumers) &&
|
||||
consumerData?.payload?.data?.filter((item) => item.status === '0')
|
||||
.length) ||
|
||||
0;
|
||||
const producerMissing =
|
||||
(serviceToInclude.includes(MessagingQueueHealthCheckService.Producers) &&
|
||||
producerData?.payload?.data?.filter((item) => item.status === '0')
|
||||
.length) ||
|
||||
0;
|
||||
const kafkaMissing =
|
||||
(serviceToInclude.includes(MessagingQueueHealthCheckService.Kafka) &&
|
||||
kafkaData?.payload?.data?.filter((item) => item.status === '0').length) ||
|
||||
0;
|
||||
|
||||
return consumerMissing + producerMissing + kafkaMissing;
|
||||
}, [consumerData, producerData, kafkaData, serviceToInclude]);
|
||||
const missingConfiguration = useMemo(
|
||||
() =>
|
||||
[
|
||||
{ service: MessagingQueueHealthCheckService.Consumers, data: consumerData },
|
||||
{ service: MessagingQueueHealthCheckService.Producers, data: producerData },
|
||||
{ service: MessagingQueueHealthCheckService.Kafka, data: kafkaData },
|
||||
]
|
||||
.filter(({ service }) => serviceToInclude.includes(service))
|
||||
.reduce(
|
||||
(total, { data }) =>
|
||||
total + (data?.filter((check) => !check.passed).length ?? 0),
|
||||
0,
|
||||
),
|
||||
[consumerData, producerData, kafkaData, serviceToInclude],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -109,18 +98,18 @@ function MessagingQueueHealthCheck({
|
||||
onboardingStatusResponses={[
|
||||
{
|
||||
title: 'Consumers',
|
||||
data: consumerData?.payload?.data || [],
|
||||
errorMsg: (consumerError || consumerData?.error) as string,
|
||||
data: consumerData || [],
|
||||
errorMsg: convertToApiError(consumerError)?.getErrorMessage(),
|
||||
},
|
||||
{
|
||||
title: 'Producers',
|
||||
data: producerData?.payload?.data || [],
|
||||
errorMsg: (producerError || producerData?.error) as string,
|
||||
data: producerData || [],
|
||||
errorMsg: convertToApiError(producerError)?.getErrorMessage(),
|
||||
},
|
||||
{
|
||||
title: 'Kafka',
|
||||
data: kafkaData?.payload?.data || [],
|
||||
errorMsg: (kafkaError || kafkaData?.error) as string,
|
||||
data: kafkaData || [],
|
||||
errorMsg: convertToApiError(kafkaError)?.getErrorMessage(),
|
||||
},
|
||||
].filter((item) => serviceToInclude.includes(item.title.toLowerCase()))}
|
||||
loading={loading}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import {
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
type Querybuildertypesv5ScalarDataDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { MessagingQueueHealthCheckService } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
|
||||
import {
|
||||
getOnboardingChecks,
|
||||
getOnboardingStatusRequest,
|
||||
} from '../onboardingStatusQuery';
|
||||
|
||||
const counts = (
|
||||
queryName: string,
|
||||
values: number[],
|
||||
): Querybuildertypesv5ScalarDataDTO => ({
|
||||
queryName,
|
||||
columns: values.map((_, aggregationIndex) => ({
|
||||
name: `__result_${aggregationIndex}`,
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
|
||||
aggregationIndex,
|
||||
})),
|
||||
data: [values],
|
||||
});
|
||||
|
||||
describe('getOnboardingChecks', () => {
|
||||
it('reports only missing telemetry when no span arrived', () => {
|
||||
expect(
|
||||
getOnboardingChecks(MessagingQueueHealthCheckService.Producers, [
|
||||
counts('B', [0]),
|
||||
counts('A', [0, 0, 0, 0]),
|
||||
]),
|
||||
).toStrictEqual([
|
||||
{
|
||||
attribute: 'telemetry ingestion',
|
||||
passed: false,
|
||||
errorMessage: 'No data available in the given time range',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('checks each producer attribute and the kafka system, sorted by attribute', () => {
|
||||
expect(
|
||||
getOnboardingChecks(MessagingQueueHealthCheckService.Producers, [
|
||||
counts('B', [0]),
|
||||
counts('A', [40, 40, 0, 40]),
|
||||
]),
|
||||
).toStrictEqual([
|
||||
{ attribute: 'kind', passed: true },
|
||||
{
|
||||
attribute: 'messaging.destination.name',
|
||||
passed: false,
|
||||
errorMessage:
|
||||
'messaging.destination.name attribute is not present in your spans',
|
||||
},
|
||||
{ attribute: 'messaging.destination.partition.id', passed: true },
|
||||
{
|
||||
attribute: 'messaging.system',
|
||||
passed: false,
|
||||
errorMessage:
|
||||
'messaging.system attribute is not present or not equal to kafka in your spans',
|
||||
},
|
||||
{ attribute: 'telemetry ingestion', passed: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it('pairs each consumer count with its own check', () => {
|
||||
expect(
|
||||
getOnboardingChecks(MessagingQueueHealthCheckService.Consumers, [
|
||||
counts('A', [50, 50, 50, 50, 50, 0, 50, 50, 50]),
|
||||
counts('B', [50]),
|
||||
]),
|
||||
).toStrictEqual([
|
||||
{ attribute: 'kind', passed: true },
|
||||
{ attribute: 'messaging.client_id', passed: true },
|
||||
{ attribute: 'messaging.destination.name', passed: true },
|
||||
{ attribute: 'messaging.destination.partition.id', passed: true },
|
||||
{
|
||||
attribute: 'messaging.kafka.consumer.group',
|
||||
passed: false,
|
||||
errorMessage:
|
||||
'messaging.kafka.consumer.group attribute is not present in your spans',
|
||||
},
|
||||
{ attribute: 'messaging.message.body.size', passed: true },
|
||||
{ attribute: 'messaging.system', passed: true },
|
||||
{ attribute: 'service.instance.id', passed: true },
|
||||
{ attribute: 'service_name', passed: true },
|
||||
{ attribute: 'telemetry ingestion', passed: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it('adds missing telemetry when neither kafka metric arrived', () => {
|
||||
expect(
|
||||
getOnboardingChecks(MessagingQueueHealthCheckService.Kafka, [
|
||||
counts('A', [0]),
|
||||
{ queryName: 'B', columns: null, data: [] },
|
||||
]).map(({ attribute, passed }) => [attribute, passed]),
|
||||
).toStrictEqual([
|
||||
['telemetry ingestion', false],
|
||||
['kafka.consumer.fetch_latency_avg', false],
|
||||
['kafka.consumer_group.lag', false],
|
||||
]);
|
||||
});
|
||||
|
||||
it('leaves out missing telemetry when one kafka metric arrived', () => {
|
||||
expect(
|
||||
getOnboardingChecks(MessagingQueueHealthCheckService.Kafka, [
|
||||
counts('A', [12]),
|
||||
{ queryName: 'B', columns: null, data: [] },
|
||||
]).map(({ attribute, passed }) => [attribute, passed]),
|
||||
).toStrictEqual([
|
||||
['kafka.consumer.fetch_latency_avg', true],
|
||||
['kafka.consumer_group.lag', false],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getOnboardingStatusRequest', () => {
|
||||
it('counts every consumer check in query A and kafka spans in query B', () => {
|
||||
expect(
|
||||
getOnboardingStatusRequest(
|
||||
MessagingQueueHealthCheckService.Consumers,
|
||||
1000,
|
||||
2000,
|
||||
).compositeQuery?.queries,
|
||||
).toStrictEqual([
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: 'traces',
|
||||
aggregations: [
|
||||
{ expression: 'count()' },
|
||||
{ expression: "countIf(kind_string = 'Consumer')" },
|
||||
{ expression: 'countIf(service.name EXISTS)' },
|
||||
{ expression: 'countIf(messaging.destination.name EXISTS)' },
|
||||
{ expression: 'countIf(messaging.destination.partition.id EXISTS)' },
|
||||
{ expression: 'countIf(messaging.kafka.consumer.group EXISTS)' },
|
||||
{ expression: 'countIf(messaging.message.body.size EXISTS)' },
|
||||
{ expression: 'countIf(messaging.client_id EXISTS)' },
|
||||
{ expression: 'countIf(service.instance.id EXISTS)' },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: 'B',
|
||||
signal: 'traces',
|
||||
filter: { expression: "messaging.system = 'kafka'" },
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('counts the two kafka metrics for the kafka group', () => {
|
||||
expect(
|
||||
getOnboardingStatusRequest(
|
||||
MessagingQueueHealthCheckService.Kafka,
|
||||
1000,
|
||||
2000,
|
||||
).compositeQuery?.queries,
|
||||
).toStrictEqual(
|
||||
['kafka.consumer.fetch_latency_avg', 'kafka.consumer_group.lag'].map(
|
||||
(metricName, index) => ({
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: index === 0 ? 'A' : 'B',
|
||||
signal: 'metrics',
|
||||
aggregations: [
|
||||
{
|
||||
metricName,
|
||||
timeAggregation: 'count',
|
||||
spaceAggregation: 'sum',
|
||||
reduceTo: 'sum',
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal as TraceSignal,
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
type Querybuildertypesv5QueryEnvelopeDTO,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
Querybuildertypesv5ReduceToDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type Querybuildertypesv5ScalarDataDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { MessagingQueueHealthCheckService } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
import { toFiniteNumber } from 'utils/numericUtils';
|
||||
|
||||
export interface OnboardingCheck {
|
||||
attribute: string;
|
||||
passed: boolean;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
interface SpanCheck {
|
||||
attribute: string;
|
||||
condition: string;
|
||||
errorMessage: string;
|
||||
}
|
||||
|
||||
const SPAN_CHECKS_QUERY = 'A';
|
||||
const KAFKA_SPANS_QUERY = 'B';
|
||||
|
||||
const TELEMETRY_INGESTION = 'telemetry ingestion';
|
||||
const NO_DATA_MESSAGE = 'No data available in the given time range';
|
||||
|
||||
const notPresent = (attribute: string): SpanCheck => ({
|
||||
attribute,
|
||||
condition: `${attribute} EXISTS`,
|
||||
errorMessage: `${attribute} attribute is not present in your spans`,
|
||||
});
|
||||
|
||||
const DESTINATION_CHECKS = [
|
||||
notPresent('messaging.destination.name'),
|
||||
notPresent('messaging.destination.partition.id'),
|
||||
];
|
||||
|
||||
const PRODUCER_CHECKS: SpanCheck[] = [
|
||||
{
|
||||
attribute: 'kind',
|
||||
condition: "kind_string = 'Producer'",
|
||||
errorMessage: 'check if your producer spans has kind=4 as attribute',
|
||||
},
|
||||
...DESTINATION_CHECKS,
|
||||
];
|
||||
|
||||
const CONSUMER_CHECKS: SpanCheck[] = [
|
||||
{
|
||||
attribute: 'kind',
|
||||
condition: "kind_string = 'Consumer'",
|
||||
errorMessage: 'check if your consumer spans has kind=5 as attribute',
|
||||
},
|
||||
{
|
||||
attribute: 'service_name',
|
||||
condition: 'service.name EXISTS',
|
||||
errorMessage: 'service_name attribute is not present in your spans',
|
||||
},
|
||||
...DESTINATION_CHECKS,
|
||||
notPresent('messaging.kafka.consumer.group'),
|
||||
notPresent('messaging.message.body.size'),
|
||||
notPresent('messaging.client_id'),
|
||||
notPresent('service.instance.id'),
|
||||
];
|
||||
|
||||
/**
|
||||
* `countIf(messaging.system = 'kafka')` fails on the materialized column,
|
||||
* so this check counts with a filter in its own query.
|
||||
*/
|
||||
const KAFKA_SPANS_CHECK: Omit<SpanCheck, 'condition'> = {
|
||||
attribute: 'messaging.system',
|
||||
errorMessage:
|
||||
'messaging.system attribute is not present or not equal to kafka in your spans',
|
||||
};
|
||||
|
||||
const KAFKA_METRIC_CHECKS = [
|
||||
{
|
||||
queryName: 'A',
|
||||
metricName: 'kafka.consumer.fetch_latency_avg',
|
||||
errorMessage:
|
||||
'Metric kafka_consumer_fetch_latency_avg is not present in the given time range.',
|
||||
},
|
||||
{
|
||||
queryName: 'B',
|
||||
metricName: 'kafka.consumer_group.lag',
|
||||
errorMessage:
|
||||
'Metric kafka_consumer_group_lag is not present in the given time range.',
|
||||
},
|
||||
];
|
||||
|
||||
const getSpanChecks = (
|
||||
service: MessagingQueueHealthCheckService,
|
||||
): SpanCheck[] =>
|
||||
service === MessagingQueueHealthCheckService.Producers
|
||||
? PRODUCER_CHECKS
|
||||
: CONSUMER_CHECKS;
|
||||
|
||||
const getSpanQueries = (
|
||||
service: MessagingQueueHealthCheckService,
|
||||
): Querybuildertypesv5QueryEnvelopeDTO[] => [
|
||||
{
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
spec: {
|
||||
name: SPAN_CHECKS_QUERY,
|
||||
signal: TraceSignal.traces,
|
||||
aggregations: [
|
||||
{ expression: 'count()' },
|
||||
...getSpanChecks(service).map(({ condition }) => ({
|
||||
expression: `countIf(${condition})`,
|
||||
})),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
spec: {
|
||||
name: KAFKA_SPANS_QUERY,
|
||||
signal: TraceSignal.traces,
|
||||
filter: { expression: "messaging.system = 'kafka'" },
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const getMetricQueries = (): Querybuildertypesv5QueryEnvelopeDTO[] =>
|
||||
KAFKA_METRIC_CHECKS.map(({ queryName, metricName }) => ({
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
spec: {
|
||||
name: queryName,
|
||||
signal: MetricSignal.metrics,
|
||||
aggregations: [
|
||||
{
|
||||
metricName,
|
||||
timeAggregation: MetrictypesTimeAggregationDTO.count,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
|
||||
reduceTo: Querybuildertypesv5ReduceToDTO.sum,
|
||||
},
|
||||
],
|
||||
},
|
||||
}));
|
||||
|
||||
export const getOnboardingStatusRequest = (
|
||||
service: MessagingQueueHealthCheckService,
|
||||
startMs: number,
|
||||
endMs: number,
|
||||
): Querybuildertypesv5QueryRangeRequestDTO => ({
|
||||
schemaVersion: 'v1',
|
||||
start: Math.floor(startMs),
|
||||
end: Math.floor(endMs),
|
||||
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
compositeQuery: {
|
||||
queries:
|
||||
service === MessagingQueueHealthCheckService.Kafka
|
||||
? getMetricQueries()
|
||||
: getSpanQueries(service),
|
||||
},
|
||||
});
|
||||
|
||||
const getCounts = (
|
||||
results: Querybuildertypesv5ScalarDataDTO[],
|
||||
queryName: string,
|
||||
): number[] => {
|
||||
const result = results.find((item) => item.queryName === queryName);
|
||||
const row = result?.data?.[0] ?? [];
|
||||
return (result?.columns ?? []).map((_, index) => toFiniteNumber(row[index]));
|
||||
};
|
||||
|
||||
const toCheck = (
|
||||
attribute: string,
|
||||
count: number,
|
||||
errorMessage: string,
|
||||
): OnboardingCheck =>
|
||||
count > 0
|
||||
? { attribute, passed: true }
|
||||
: { attribute, passed: false, errorMessage };
|
||||
|
||||
const NO_DATA_CHECK: OnboardingCheck = {
|
||||
attribute: TELEMETRY_INGESTION,
|
||||
passed: false,
|
||||
errorMessage: NO_DATA_MESSAGE,
|
||||
};
|
||||
|
||||
const getSpanOnboardingChecks = (
|
||||
service: MessagingQueueHealthCheckService,
|
||||
results: Querybuildertypesv5ScalarDataDTO[],
|
||||
): OnboardingCheck[] => {
|
||||
const [total = 0, ...checkCounts] = getCounts(results, SPAN_CHECKS_QUERY);
|
||||
if (!total) {
|
||||
return [NO_DATA_CHECK];
|
||||
}
|
||||
const [kafkaSpans = 0] = getCounts(results, KAFKA_SPANS_QUERY);
|
||||
|
||||
return [
|
||||
{ attribute: TELEMETRY_INGESTION, passed: true },
|
||||
toCheck(
|
||||
KAFKA_SPANS_CHECK.attribute,
|
||||
kafkaSpans,
|
||||
KAFKA_SPANS_CHECK.errorMessage,
|
||||
),
|
||||
...getSpanChecks(service).map(({ attribute, errorMessage }, index) =>
|
||||
toCheck(attribute, checkCounts[index] ?? 0, errorMessage),
|
||||
),
|
||||
].sort((a, b) => (a.attribute < b.attribute ? -1 : 1));
|
||||
};
|
||||
|
||||
const getKafkaOnboardingChecks = (
|
||||
results: Querybuildertypesv5ScalarDataDTO[],
|
||||
): OnboardingCheck[] => {
|
||||
const checks = KAFKA_METRIC_CHECKS.map(
|
||||
({ queryName, metricName, errorMessage }) =>
|
||||
toCheck(metricName, getCounts(results, queryName)[0] ?? 0, errorMessage),
|
||||
);
|
||||
return checks.some((check) => check.passed)
|
||||
? checks
|
||||
: [NO_DATA_CHECK, ...checks];
|
||||
};
|
||||
|
||||
export const getOnboardingChecks = (
|
||||
service: MessagingQueueHealthCheckService,
|
||||
results: Querybuildertypesv5ScalarDataDTO[],
|
||||
): OnboardingCheck[] =>
|
||||
service === MessagingQueueHealthCheckService.Kafka
|
||||
? getKafkaOnboardingChecks(results)
|
||||
: getSpanOnboardingChecks(service, results);
|
||||
@@ -113,6 +113,11 @@ export const REACT_QUERY_KEY = {
|
||||
// Celery Query Keys
|
||||
GET_CELERY_WORKER_COUNT: 'GET_CELERY_WORKER_COUNT',
|
||||
|
||||
// Messaging Queues Query Keys
|
||||
GET_KAFKA_TABLE_ROWS: 'GET_KAFKA_TABLE_ROWS',
|
||||
GET_QUEUE_OVERVIEW: 'GET_QUEUE_OVERVIEW',
|
||||
GET_KAFKA_ONBOARDING_STATUS: 'GET_KAFKA_ONBOARDING_STATUS',
|
||||
|
||||
// AI Assistant Query Keys
|
||||
AI_ASSISTANT_EMPTY_STATE_CHIPS: 'AI_ASSISTANT_EMPTY_STATE_CHIPS',
|
||||
} as const;
|
||||
|
||||
@@ -1,29 +1,39 @@
|
||||
import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
|
||||
import getOnboardingStatus, {
|
||||
OnboardingStatusResponse,
|
||||
} from 'api/messagingQueues/onboarding/getOnboardingStatus';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { useQuery, UseQueryResult } from 'react-query';
|
||||
import { queryRangeV5 } from 'api/generated/services/querier';
|
||||
import type {
|
||||
QueryRangeV5200,
|
||||
RenderErrorResponseDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { ErrorType } from 'api/generatedAPIInstance';
|
||||
import {
|
||||
getOnboardingChecks,
|
||||
getOnboardingStatusRequest,
|
||||
OnboardingCheck,
|
||||
} from 'components/MessagingQueueHealthCheck/onboardingStatusQuery';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { getScalarResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
|
||||
import { MessagingQueueHealthCheckService } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
|
||||
type UseOnboardingStatus = (
|
||||
options?: UseQueryOptions<
|
||||
SuccessResponse<OnboardingStatusResponse> | ErrorResponse
|
||||
>,
|
||||
endpointService?: string,
|
||||
queryKey?: string,
|
||||
) => UseQueryResult<SuccessResponse<OnboardingStatusResponse> | ErrorResponse>;
|
||||
const CHECK_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
export const useOnboardingStatus: UseOnboardingStatus = (
|
||||
options,
|
||||
endpointService,
|
||||
queryKey,
|
||||
) =>
|
||||
useQuery<SuccessResponse<OnboardingStatusResponse> | ErrorResponse>({
|
||||
queryKey: [queryKey || `onboardingStatus-${endpointService}`],
|
||||
queryFn: () =>
|
||||
getOnboardingStatus({
|
||||
start: (Date.now() - 15 * 60 * 1000) * 1_000_000,
|
||||
end: Date.now() * 1_000_000,
|
||||
endpointService,
|
||||
}),
|
||||
...options,
|
||||
export const useOnboardingStatus = (
|
||||
service: MessagingQueueHealthCheckService,
|
||||
enabled: boolean,
|
||||
): UseQueryResult<OnboardingCheck[], ErrorType<RenderErrorResponseDTO>> =>
|
||||
useQuery<
|
||||
QueryRangeV5200,
|
||||
ErrorType<RenderErrorResponseDTO>,
|
||||
OnboardingCheck[]
|
||||
>({
|
||||
queryKey: [REACT_QUERY_KEY.GET_KAFKA_ONBOARDING_STATUS, service],
|
||||
queryFn: ({ signal }) => {
|
||||
const end = Date.now();
|
||||
return queryRangeV5(
|
||||
getOnboardingStatusRequest(service, end - CHECK_WINDOW_MS, end),
|
||||
signal,
|
||||
);
|
||||
},
|
||||
select: (response) =>
|
||||
getOnboardingChecks(service, getScalarResults(response)),
|
||||
enabled,
|
||||
});
|
||||
|
||||
@@ -23,13 +23,10 @@ import {
|
||||
timeRangeState,
|
||||
} from '../../stories/__story_mockdata__/messagingQueues';
|
||||
import {
|
||||
consumerLagDetails,
|
||||
isKafkaTableRequest,
|
||||
KAFKA_VIEWS,
|
||||
kafkaDetailRoute,
|
||||
partitionLatencyDetails,
|
||||
partitionLatencyOverview,
|
||||
topicThroughputDetails,
|
||||
topicThroughputOverview,
|
||||
kafkaTableResponse,
|
||||
} from './__story_mockdata__/kafkaDetail';
|
||||
|
||||
const VIEWS = 'Kafka detail · views';
|
||||
@@ -67,42 +64,18 @@ export const kafkaDetailMocks = defineStoryMocks({
|
||||
}),
|
||||
},
|
||||
handlers: (values, response) => [
|
||||
rest.post(
|
||||
'http://localhost/api/v1/messaging-queues/kafka/consumer-lag/:detailType',
|
||||
response.json((req) =>
|
||||
consumerLagDetails(String(req.params.detailType), values.rows),
|
||||
),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
'http://localhost/api/v1/messaging-queues/kafka/partition-latency/overview',
|
||||
response.json(() => partitionLatencyOverview(values.rows)),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
'http://localhost/api/v1/messaging-queues/kafka/partition-latency/consumer',
|
||||
response.json(() => partitionLatencyDetails(values.rows)),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
'http://localhost/api/v1/messaging-queues/kafka/topic-throughput/:detailType',
|
||||
response.json((req) => {
|
||||
const detailType = String(req.params.detailType);
|
||||
|
||||
return detailType.endsWith('-details')
|
||||
? topicThroughputDetails(values.rows)
|
||||
: topicThroughputOverview(detailType, values.rows);
|
||||
}),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
'http://localhost/api/v5/query_range',
|
||||
response.json(async (req) =>
|
||||
queryRangeV5ForRequest(
|
||||
(await req.json()) as Querybuildertypesv5QueryRangeRequestDTO,
|
||||
{ count: values.series, labelValues: LABEL_VALUES },
|
||||
),
|
||||
),
|
||||
response.json(async (req) => {
|
||||
const body = (await req.json()) as Querybuildertypesv5QueryRangeRequestDTO;
|
||||
|
||||
return isKafkaTableRequest(body)
|
||||
? kafkaTableResponse(body, values.rows)
|
||||
: queryRangeV5ForRequest(body, {
|
||||
count: values.series,
|
||||
labelValues: LABEL_VALUES,
|
||||
});
|
||||
}),
|
||||
),
|
||||
|
||||
rest.get(
|
||||
|
||||
@@ -57,9 +57,6 @@ export const showConsumers = async ({
|
||||
await userEvent.click(
|
||||
await canvas.findByText('Consumers', undefined, untilLoaded),
|
||||
);
|
||||
// Byte Rate is the column only the producer table has.
|
||||
await waitFor(
|
||||
() => expect(canvas.queryByText('Byte Rate')).not.toBeInTheDocument(),
|
||||
untilLoaded,
|
||||
);
|
||||
// Ingestion Rate is the column only the consumer table has.
|
||||
await canvas.findByText('Ingestion Rate', undefined, untilLoaded);
|
||||
};
|
||||
|
||||
@@ -3,18 +3,24 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import type { MessagingQueuesPayloadProps } from 'api/messagingQueues/getConsumerLagDetails';
|
||||
import {
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type QueryRangeV5200,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { MessagingQueuesViewTypeOptions } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
|
||||
import {
|
||||
MessagingQueueServiceDetailType,
|
||||
MessagingQueuesViewTypeOptions,
|
||||
} from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
queryRangeV5ScalarResultsResponse,
|
||||
type ScalarQueryResult,
|
||||
} from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
|
||||
import {
|
||||
CONSUMER_GROUPS,
|
||||
KAFKA_SERVICES,
|
||||
kafkaTableResponse,
|
||||
PARTITIONS,
|
||||
RELATIVE_TIME,
|
||||
seeded,
|
||||
@@ -90,149 +96,134 @@ export const kafkaDetailRoute = (
|
||||
return `${ROUTES.MESSAGING_QUEUES_KAFKA_DETAIL}?${params.toString()}`;
|
||||
};
|
||||
|
||||
type KafkaTable = {
|
||||
status: string;
|
||||
data: MessagingQueuesPayloadProps['payload'];
|
||||
const CLIENT_IDS = CONSUMER_GROUPS.map((group) => `${group}-client`);
|
||||
|
||||
const INSTANCES = KAFKA_SERVICES.map((service) => `${service}-0`);
|
||||
|
||||
/**
|
||||
* Each pool is one thing a row can be grouped by. A span key and the metric
|
||||
* label that joins to it (`messaging.client_id` and `client-id`) share a pool,
|
||||
* so a metric row lines up with the span row the page joins it to.
|
||||
*/
|
||||
const POOLS: Record<string, { family: string; values: string[] }> = {
|
||||
'messaging.destination.name': { family: 'a-topic', values: TOPICS },
|
||||
topic: { family: 'a-topic', values: TOPICS },
|
||||
'messaging.destination.partition.id': {
|
||||
family: 'b-partition',
|
||||
values: PARTITIONS,
|
||||
},
|
||||
'messaging.kafka.consumer.group': {
|
||||
family: 'c-group',
|
||||
values: CONSUMER_GROUPS,
|
||||
},
|
||||
'service.name': { family: 'd-service', values: KAFKA_SERVICES },
|
||||
'messaging.client_id': { family: 'e-client', values: CLIENT_IDS },
|
||||
'client-id': { family: 'e-client', values: CLIENT_IDS },
|
||||
'service.instance.id': { family: 'f-instance', values: INSTANCES },
|
||||
};
|
||||
|
||||
const rowsOf = (
|
||||
count: number,
|
||||
build: (index: number) => Record<string, string>,
|
||||
): Array<Record<string, string>> =>
|
||||
Array.from({ length: count }, (_u, i) => build(i));
|
||||
/**
|
||||
* The row-th combination of the keys' pools. Keys are walked in family order,
|
||||
* not the order the query lists them, so two queries grouping by the same
|
||||
* families under different names and orders produce the same combination.
|
||||
*/
|
||||
const groupValues = (keys: string[], row: number): string[] => {
|
||||
const ordered = [...keys].sort((a, b) =>
|
||||
(POOLS[a]?.family ?? a).localeCompare(POOLS[b]?.family ?? b),
|
||||
);
|
||||
const combination: Record<string, string> = {};
|
||||
let rest = row;
|
||||
[...ordered].reverse().forEach((key) => {
|
||||
const values = POOLS[key]?.values ?? [`${key}-${row + 1}`];
|
||||
combination[key] = values[rest % values.length];
|
||||
rest = Math.floor(rest / values.length);
|
||||
});
|
||||
return keys.map((key) => combination[key]);
|
||||
};
|
||||
|
||||
const metric = (index: number, base: number, spread: number): string =>
|
||||
String(seeded(index, base, spread));
|
||||
const NS_PER_MS = 1e6;
|
||||
|
||||
const serviceRows = (
|
||||
count: number,
|
||||
offset = 0,
|
||||
): Array<Record<string, string>> =>
|
||||
rowsOf(count, (index) => ({
|
||||
service_name: KAFKA_SERVICES[(index + offset) % KAFKA_SERVICES.length],
|
||||
p99: metric(index, 120, 400),
|
||||
error_rate: metric(index, 0, 12),
|
||||
throughput: metric(index, 30, 250),
|
||||
}));
|
||||
/** What each aggregation the tables ask for answers, in its own unit. */
|
||||
const aggregationValue = (aggregation: string, row: number): number => {
|
||||
const total = Math.round(seeded(row, 800, 4000));
|
||||
|
||||
/** The three tabs under the consumer lag graph, each on its own detail type. */
|
||||
export const consumerLagDetails = (
|
||||
detailType: string,
|
||||
count: number,
|
||||
): KafkaTable => {
|
||||
if (detailType === MessagingQueueServiceDetailType.NetworkLatency) {
|
||||
return kafkaTableResponse(
|
||||
[
|
||||
'consumer_service',
|
||||
'service_instance_id',
|
||||
'client_id',
|
||||
'p99',
|
||||
'throughput',
|
||||
],
|
||||
rowsOf(count, (index) => ({
|
||||
consumer_service: KAFKA_SERVICES[index % KAFKA_SERVICES.length],
|
||||
service_instance_id: `instance-${index % 4}`,
|
||||
client_id: `${CONSUMER_GROUPS[index % CONSUMER_GROUPS.length]}-${index % 3}`,
|
||||
p99: metric(index, 90, 320),
|
||||
throughput: metric(index, 20, 180),
|
||||
})),
|
||||
['p99', 'throughput'],
|
||||
);
|
||||
if (aggregation.startsWith('p99(') || aggregation.startsWith('p95(')) {
|
||||
return seeded(row, 20, 380) * NS_PER_MS;
|
||||
}
|
||||
|
||||
const isConsumer =
|
||||
detailType === MessagingQueueServiceDetailType.ConsumerDetails;
|
||||
|
||||
return kafkaTableResponse(
|
||||
isConsumer
|
||||
? ['service_name', 'p99', 'error_rate', 'throughput', 'avg_msg_size']
|
||||
: ['service_name', 'p99', 'error_rate', 'throughput'],
|
||||
serviceRows(count, isConsumer ? 1 : 0).map((row, index) =>
|
||||
isConsumer ? { ...row, avg_msg_size: metric(index, 400, 2400) } : row,
|
||||
),
|
||||
['p99', 'error_rate', 'throughput', 'avg_msg_size'],
|
||||
);
|
||||
if (aggregation === 'count()') {
|
||||
return total;
|
||||
}
|
||||
if (aggregation.startsWith('countIf(')) {
|
||||
return Math.round((total * seeded(row, 0, 8)) / 100);
|
||||
}
|
||||
if (aggregation === 'rate()') {
|
||||
return seeded(row, 0.5, 6);
|
||||
}
|
||||
if (aggregation.startsWith('avg(')) {
|
||||
return seeded(row, 300, 2400);
|
||||
}
|
||||
if (aggregation === 'kafka.consumer.fetch_latency_avg') {
|
||||
return seeded(row, 10, 60);
|
||||
}
|
||||
return seeded(row, 1200, 8600);
|
||||
};
|
||||
|
||||
/** The partition latency overview, whose rows carry the topic and partition
|
||||
* the details tables below it need. */
|
||||
export const partitionLatencyOverview = (count: number): KafkaTable =>
|
||||
kafkaTableResponse(
|
||||
['topic', 'partition', 'p99', 'error_rate', 'throughput'],
|
||||
rowsOf(count, (index) => ({
|
||||
topic: TOPICS[index % TOPICS.length],
|
||||
partition: PARTITIONS[index % PARTITIONS.length],
|
||||
p99: metric(index, 150, 380),
|
||||
error_rate: metric(index, 0, 9),
|
||||
throughput: metric(index, 40, 300),
|
||||
})),
|
||||
['p99', 'error_rate', 'throughput'],
|
||||
);
|
||||
/** Metric rows the joined column finds no match for, so it shows its fallback. */
|
||||
const hasMetricRow = (row: number): boolean => row % 5 !== 4;
|
||||
|
||||
export const partitionLatencyDetails = (count: number): KafkaTable =>
|
||||
kafkaTableResponse(
|
||||
['service_name', 'p99', 'error_rate', 'throughput'],
|
||||
serviceRows(count),
|
||||
['p99', 'error_rate', 'throughput'],
|
||||
export const isKafkaTableRequest = (
|
||||
body: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
): boolean =>
|
||||
body.requestType === Querybuildertypesv5RequestTypeDTO.scalar &&
|
||||
(body.compositeQuery?.queries ?? []).some(
|
||||
(envelope) =>
|
||||
envelope.type ===
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query &&
|
||||
envelope.spec?.signal === 'traces',
|
||||
);
|
||||
|
||||
/**
|
||||
* The producer side of the topic throughput overview answers two tables: the
|
||||
* page merges `byte_rate` from the second onto the first, keyed by
|
||||
* `service_name--topic`, and renders it as a column the first table never had.
|
||||
* The tables under every view are one span query, plus a metric query the
|
||||
* page joins on for byte rate and network latency. Rows are built from what the
|
||||
* request groups by and aggregates, so each table gets the columns it asked for.
|
||||
*/
|
||||
export const topicThroughputOverview = (
|
||||
detailType: string,
|
||||
export const kafkaTableResponse = (
|
||||
body: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
count: number,
|
||||
): KafkaTable => {
|
||||
const rows = rowsOf(count, (index) => ({
|
||||
service_name: KAFKA_SERVICES[index % KAFKA_SERVICES.length],
|
||||
topic: TOPICS[index % TOPICS.length],
|
||||
p99: metric(index, 110, 360),
|
||||
error_rate: metric(index, 0, 7),
|
||||
throughput: metric(index, 25, 210),
|
||||
ingestion_rate: metric(index, 500, 4200),
|
||||
}));
|
||||
): QueryRangeV5200 =>
|
||||
queryRangeV5ScalarResultsResponse(
|
||||
(body.compositeQuery?.queries ?? []).flatMap(
|
||||
(envelope): ScalarQueryResult[] => {
|
||||
if (
|
||||
envelope.type !==
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const { spec } = envelope;
|
||||
const groupBy = (spec?.groupBy ?? []).map(({ name }) => name);
|
||||
const aggregations = (spec?.aggregations ?? []).map(
|
||||
(aggregation) =>
|
||||
('metricName' in aggregation && aggregation.metricName) ||
|
||||
('expression' in aggregation && aggregation.expression) ||
|
||||
'',
|
||||
);
|
||||
const isMetric = spec?.signal === 'metrics';
|
||||
const rows = Array.from({ length: count }, (_unused, row) => row)
|
||||
.filter((row) => !isMetric || hasMetricRow(row))
|
||||
.map((row) => [
|
||||
...groupValues(groupBy, row),
|
||||
...aggregations.map((aggregation) => aggregationValue(aggregation, row)),
|
||||
]);
|
||||
|
||||
const overview = kafkaTableResponse(
|
||||
[
|
||||
'service_name',
|
||||
'topic',
|
||||
'p99',
|
||||
'error_rate',
|
||||
'throughput',
|
||||
'ingestion_rate',
|
||||
],
|
||||
rows,
|
||||
['p99', 'error_rate', 'throughput', 'ingestion_rate'],
|
||||
);
|
||||
|
||||
if (detailType !== 'producer') {
|
||||
return overview;
|
||||
}
|
||||
|
||||
const byteRate = kafkaTableResponse(
|
||||
['service_name', 'topic', 'byte_rate'],
|
||||
rows.map((row, index) => ({
|
||||
service_name: row.service_name,
|
||||
topic: row.topic,
|
||||
byte_rate: metric(index, 1200, 8600),
|
||||
})),
|
||||
['byte_rate'],
|
||||
);
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
data: {
|
||||
resultType: 'table',
|
||||
result: [...overview.data.result, ...byteRate.data.result],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const topicThroughputDetails = (count: number): KafkaTable =>
|
||||
kafkaTableResponse(
|
||||
['service_name', 'p99', 'error_rate', 'throughput'],
|
||||
serviceRows(count, 2),
|
||||
['p99', 'error_rate', 'throughput'],
|
||||
return [
|
||||
{
|
||||
queryName: spec?.name ?? '',
|
||||
groupBy,
|
||||
aggregations: aggregations.length,
|
||||
rows,
|
||||
},
|
||||
];
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
@@ -10,13 +10,14 @@ import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import {
|
||||
ConsumerLagDetailTitle,
|
||||
getMetaDataAndAPIPerView,
|
||||
MessagingQueueServiceDetailType,
|
||||
MessagingQueuesViewType,
|
||||
MessagingQueuesViewTypeOptions,
|
||||
NS_PER_MS,
|
||||
ProducerLatencyOptions,
|
||||
SelectedTimelineQuery,
|
||||
} from '../MessagingQueuesUtils';
|
||||
import { getDetailTableSpec } from './MQTables/kafkaTableSpecs';
|
||||
import MessagingQueuesTable from './MQTables/MQTables';
|
||||
|
||||
import './MQDetails.style.scss';
|
||||
@@ -164,18 +165,20 @@ function MessagingQueuesDetails({
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
|
||||
const serviceConfigDetails = useMemo(
|
||||
const spec = useMemo(
|
||||
() =>
|
||||
getMetaDataAndAPIPerView({
|
||||
getDetailTableSpec({
|
||||
selectedView,
|
||||
detailType: currentTab,
|
||||
minTime,
|
||||
maxTime,
|
||||
selectedTimelineQuery: timelineQueryData,
|
||||
timelineQuery: timelineQueryData,
|
||||
configDetails: configDetailQueryData,
|
||||
}),
|
||||
[configDetailQueryData, currentTab, maxTime, minTime, timelineQueryData],
|
||||
[selectedView, currentTab, timelineQueryData, configDetailQueryData],
|
||||
);
|
||||
|
||||
const isConsumerLag =
|
||||
selectedView === MessagingQueuesViewType.consumerLag.value;
|
||||
|
||||
return (
|
||||
<div className="mq-details">
|
||||
<MessagingQueuesOptions
|
||||
@@ -187,14 +190,17 @@ function MessagingQueuesDetails({
|
||||
<MessagingQueuesTable
|
||||
currentTab={currentTab}
|
||||
selectedView={selectedView}
|
||||
tableApi={serviceConfigDetails[selectedView]?.tableApi}
|
||||
spec={spec}
|
||||
startMs={
|
||||
isConsumerLag ? (timelineQueryData.start ?? 0) : minTime / NS_PER_MS
|
||||
}
|
||||
endMs={isConsumerLag ? (timelineQueryData.end ?? 0) : maxTime / NS_PER_MS}
|
||||
validConfigPresent={checkValidityOfDetailConfigs(
|
||||
timelineQueryData,
|
||||
selectedView,
|
||||
currentTab,
|
||||
configDetailQueryData,
|
||||
)}
|
||||
tableApiPayload={serviceConfigDetails[selectedView]?.tableApiPayload}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { MessagingQueuesPayloadProps } from 'api/messagingQueues/getConsumerLagDetails';
|
||||
import { RowData } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
|
||||
export function getTableDataForProducerLatencyOverview(
|
||||
data: MessagingQueuesPayloadProps['payload'],
|
||||
): RowData[] {
|
||||
if (data?.result?.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const firstTableData = data.result[0].table.rows || [];
|
||||
const secondTableData = data.result[1]?.table.rows || [];
|
||||
|
||||
// Create a map for quick lookup of byte_rate using service_name and topic
|
||||
const byteRateMap = new Map(
|
||||
secondTableData.map((row) => [
|
||||
`${row.data.service_name}--${row.data.topic}`,
|
||||
row.data.byte_rate,
|
||||
]),
|
||||
);
|
||||
|
||||
// Merge the data from both tables
|
||||
const mergedTableData: RowData[] =
|
||||
firstTableData.map((row, index): RowData => ({
|
||||
...row.data,
|
||||
byte_rate:
|
||||
byteRateMap.get(`${row.data.service_name}--${row.data.topic}`) || 0,
|
||||
key: index,
|
||||
})) || [];
|
||||
|
||||
return mergedTableData;
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useMutation } from 'react-query';
|
||||
import { Skeleton, Table } from 'antd';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import {
|
||||
MessagingQueueServicePayload,
|
||||
MessagingQueuesPayloadProps,
|
||||
} from 'api/messagingQueues/getConsumerLagDetails';
|
||||
import axios from 'axios';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { ErrorType } from 'api/generatedAPIInstance';
|
||||
import cx from 'classnames';
|
||||
import { ColumnTypeRender } from 'components/Logs/TableView/types';
|
||||
import { SOMETHING_WENT_WRONG } from 'constants/api';
|
||||
@@ -29,54 +26,32 @@ import {
|
||||
SelectedTimelineQuery,
|
||||
setConfigDetail,
|
||||
} from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { isModifierKeyPressed } from 'utils/app';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
import { formatNumericValue } from 'utils/numericUtils';
|
||||
|
||||
import { getTableDataForProducerLatencyOverview } from './MQTableUtils';
|
||||
import { formatKafkaValueCell, getKafkaTableColumns } from './kafkaTableQuery';
|
||||
import { KafkaTableSpec } from './kafkaTableQuery.types';
|
||||
import { useKafkaTableRows } from './useKafkaTableRows';
|
||||
|
||||
import './MQTables.styles.scss';
|
||||
|
||||
const INITIAL_PAGE_SIZE = 10;
|
||||
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
export function getColumns(
|
||||
data: MessagingQueuesPayloadProps['payload'],
|
||||
isProducerOverview?: boolean,
|
||||
): RowData[] {
|
||||
if (data?.result?.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const mergedColumns = isProducerOverview
|
||||
? [
|
||||
...(data?.result?.[0]?.table?.columns || []),
|
||||
{ name: 'byte_rate', queryName: 'byte_rate' },
|
||||
]
|
||||
: data?.result?.[0]?.table?.columns;
|
||||
|
||||
const columns: {
|
||||
title: string;
|
||||
dataIndex: string;
|
||||
key: string;
|
||||
}[] = mergedColumns.map((column) => ({
|
||||
title: convertToTitleCase(column.name),
|
||||
dataIndex: column.name,
|
||||
key: column.name,
|
||||
render: [
|
||||
'p99',
|
||||
'error_rate',
|
||||
'throughput',
|
||||
'avg_msg_size',
|
||||
'error_percentage',
|
||||
'ingestion_rate',
|
||||
'byte_rate',
|
||||
].includes(column.name)
|
||||
? formatNumericValue
|
||||
function getColumns(spec: KafkaTableSpec): {
|
||||
title: string;
|
||||
dataIndex: string;
|
||||
key: string;
|
||||
}[] {
|
||||
const groupColumns = new Set<string>(spec.groupBy);
|
||||
return getKafkaTableColumns(spec).map((name) => ({
|
||||
title: convertToTitleCase(name),
|
||||
dataIndex: name,
|
||||
key: name,
|
||||
render: !groupColumns.has(name)
|
||||
? formatKafkaValueCell
|
||||
: (text: string): ColumnTypeRender<Record<string, unknown>> => ({
|
||||
children:
|
||||
column.name === 'service_name' ? (
|
||||
name === 'service_name' ? (
|
||||
<Button
|
||||
variant="link"
|
||||
color="primary"
|
||||
@@ -108,24 +83,6 @@ export function getColumns(
|
||||
),
|
||||
}),
|
||||
}));
|
||||
|
||||
return columns;
|
||||
}
|
||||
|
||||
export function getTableData(
|
||||
data: MessagingQueuesPayloadProps['payload'],
|
||||
): RowData[] {
|
||||
if (data?.result?.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const tableData: RowData[] =
|
||||
data?.result?.[0]?.table?.rows?.map((row, index: number): RowData => ({
|
||||
...row.data,
|
||||
key: index,
|
||||
})) || [];
|
||||
|
||||
return tableData;
|
||||
}
|
||||
|
||||
const showPaginationItem = (total: number, range: number[]): JSX.Element => (
|
||||
@@ -158,26 +115,22 @@ const showPaginationItem = (total: number, range: number[]): JSX.Element => (
|
||||
function MessagingQueuesTable({
|
||||
currentTab,
|
||||
selectedView,
|
||||
tableApiPayload,
|
||||
tableApi,
|
||||
spec,
|
||||
startMs,
|
||||
endMs,
|
||||
validConfigPresent = false,
|
||||
type = 'Detail',
|
||||
option = ProducerLatencyOptions.Producers,
|
||||
}: {
|
||||
currentTab?: MessagingQueueServiceDetailType;
|
||||
selectedView: MessagingQueuesViewTypeOptions;
|
||||
tableApiPayload?: MessagingQueueServicePayload;
|
||||
tableApi: (
|
||||
props: MessagingQueueServicePayload,
|
||||
) => Promise<
|
||||
SuccessResponse<MessagingQueuesPayloadProps['payload']> | ErrorResponse
|
||||
>;
|
||||
spec: KafkaTableSpec;
|
||||
startMs: number;
|
||||
endMs: number;
|
||||
validConfigPresent?: boolean;
|
||||
type?: 'Detail' | 'Overview';
|
||||
option?: ProducerLatencyOptions;
|
||||
}): JSX.Element {
|
||||
const [columns, setColumns] = useState<any[]>([]);
|
||||
const [tableData, setTableData] = useState<any[]>([]);
|
||||
const { notifications } = useNotifications();
|
||||
const urlQuery = useUrlQuery();
|
||||
const timelineQuery = decodeURIComponent(
|
||||
@@ -200,6 +153,25 @@ function MessagingQueuesTable({
|
||||
[configDetails],
|
||||
);
|
||||
|
||||
const handleConsumerDetailsOnError = (
|
||||
error: ErrorType<RenderErrorResponseDTO>,
|
||||
): void => {
|
||||
notifications.error({
|
||||
message: convertToApiError(error)?.getErrorMessage() || SOMETHING_WENT_WRONG,
|
||||
});
|
||||
};
|
||||
|
||||
const { data, isFetching, error, isError } = useKafkaTableRows({
|
||||
spec,
|
||||
startMs,
|
||||
endMs,
|
||||
enabled: validConfigPresent,
|
||||
onError: handleConsumerDetailsOnError,
|
||||
});
|
||||
|
||||
const tableData = useMemo(() => data ?? [], [data]);
|
||||
const columns = useMemo(() => getColumns(spec), [spec]);
|
||||
|
||||
const paginationConfig = useMemo(
|
||||
() =>
|
||||
tableData?.length > INITIAL_PAGE_SIZE && {
|
||||
@@ -211,61 +183,12 @@ function MessagingQueuesTable({
|
||||
[tableData],
|
||||
);
|
||||
|
||||
const handleConsumerDetailsOnError = (error: Error): void => {
|
||||
notifications.error({
|
||||
message: axios.isAxiosError(error) ? error?.message : SOMETHING_WENT_WRONG,
|
||||
});
|
||||
};
|
||||
|
||||
const isProducerOverview = useMemo(
|
||||
() =>
|
||||
type === 'Overview' &&
|
||||
selectedView === MessagingQueuesViewType.producerLatency.value &&
|
||||
tableApiPayload?.detailType === 'producer',
|
||||
[type, selectedView, tableApiPayload],
|
||||
);
|
||||
|
||||
const {
|
||||
mutate: getViewDetails,
|
||||
isLoading,
|
||||
error,
|
||||
isError,
|
||||
} = useMutation(tableApi, {
|
||||
onSuccess: (data) => {
|
||||
if (data.payload) {
|
||||
setColumns(getColumns(data?.payload, isProducerOverview));
|
||||
setTableData(
|
||||
isProducerOverview
|
||||
? getTableDataForProducerLatencyOverview(data?.payload)
|
||||
: getTableData(data?.payload),
|
||||
);
|
||||
}
|
||||
},
|
||||
onError: handleConsumerDetailsOnError,
|
||||
});
|
||||
|
||||
useEffect(
|
||||
() => {
|
||||
if (validConfigPresent && tableApiPayload) {
|
||||
getViewDetails(tableApiPayload);
|
||||
}
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[currentTab, selectedView, tableApiPayload],
|
||||
);
|
||||
|
||||
const [selectedRowKey, setSelectedRowKey] = useState<React.Key>();
|
||||
const [, setSelectedRows] = useState<any>();
|
||||
const location = useAppLocation();
|
||||
|
||||
const selectedRowKeyGenerator = (record: {
|
||||
[key: string]: string;
|
||||
}): React.Key => {
|
||||
if (!isEmpty(tableApiPayload?.detailType)) {
|
||||
return `${record.key}_${selectedView}_${tableApiPayload?.detailType}`;
|
||||
}
|
||||
return `${record.key}_${selectedView}`;
|
||||
};
|
||||
const selectedRowKeyGenerator = (record: RowData): React.Key =>
|
||||
`${record.key}_${selectedView}_${spec.kind}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (isEmpty(configDetailQueryData)) {
|
||||
@@ -274,7 +197,7 @@ function MessagingQueuesTable({
|
||||
}
|
||||
}, [configDetailQueryData]);
|
||||
|
||||
const onRowClick = (record: { [key: string]: string }): void => {
|
||||
const onRowClick = (record: RowData): void => {
|
||||
if (selectedRowKeyGenerator(record) === selectedRowKey) {
|
||||
setSelectedRowKey(undefined);
|
||||
setSelectedRows({});
|
||||
@@ -363,7 +286,7 @@ function MessagingQueuesTable({
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{error?.message || SOMETHING_WENT_WRONG}
|
||||
{convertToApiError(error)?.getErrorMessage() || SOMETHING_WENT_WRONG}
|
||||
</Typography>
|
||||
</div>
|
||||
) : (
|
||||
@@ -385,7 +308,7 @@ function MessagingQueuesTable({
|
||||
columns={columns}
|
||||
dataSource={tableData}
|
||||
bordered={false}
|
||||
loading={isLoading}
|
||||
loading={isFetching}
|
||||
onRow={(record): any =>
|
||||
type !== 'Detail'
|
||||
? {
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import {
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
Querybuildertypesv5OrderDirectionDTO,
|
||||
type Querybuildertypesv5ScalarDataDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
MessagingQueueServiceDetailType,
|
||||
MessagingQueuesViewTypeOptions,
|
||||
ProducerLatencyOptions,
|
||||
} from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
|
||||
import {
|
||||
getKafkaTableColumns,
|
||||
getKafkaTableRequest,
|
||||
getKafkaTableRows,
|
||||
} from '../kafkaTableQuery';
|
||||
import { KafkaSpanKind, KafkaTableSpec } from '../kafkaTableQuery.types';
|
||||
import { getDetailTableSpec, getOverviewTableSpec } from '../kafkaTableSpecs';
|
||||
|
||||
const { group, aggregation } = Querybuildertypesv5ColumnTypeDTO;
|
||||
|
||||
const networkLatencySpec: KafkaTableSpec = {
|
||||
kind: KafkaSpanKind.Consumer,
|
||||
filters: { consumer_group: 'fraud-consumer', partition: '0' },
|
||||
groupBy: ['client_id', 'service_instance_id', 'service_name'],
|
||||
values: ['throughput'],
|
||||
order: {
|
||||
by: 'throughput',
|
||||
direction: Querybuildertypesv5OrderDirectionDTO.desc,
|
||||
},
|
||||
metricJoin: {
|
||||
metricName: 'kafka.consumer.fetch_latency_avg',
|
||||
column: 'latency',
|
||||
labels: {
|
||||
service_name: 'service.name',
|
||||
client_id: 'client-id',
|
||||
service_instance_id: 'service.instance.id',
|
||||
},
|
||||
missingValue: 'n/a',
|
||||
},
|
||||
};
|
||||
|
||||
const consumerDetailsSpec: KafkaTableSpec = {
|
||||
kind: KafkaSpanKind.Consumer,
|
||||
filters: {
|
||||
topic: "o'rders",
|
||||
partition: '0',
|
||||
consumer_group: 'fraud-consumer',
|
||||
},
|
||||
groupBy: ['service_name'],
|
||||
values: ['p99', 'error_rate', 'throughput', 'avg_msg_size'],
|
||||
order: {
|
||||
by: 'service_name',
|
||||
direction: Querybuildertypesv5OrderDirectionDTO.asc,
|
||||
},
|
||||
};
|
||||
|
||||
describe('getKafkaTableRequest', () => {
|
||||
it('builds one traces scalar query from the selected row', () => {
|
||||
expect(
|
||||
getKafkaTableRequest(consumerDetailsSpec, 1000.7, 2000.2),
|
||||
).toStrictEqual({
|
||||
schemaVersion: 'v1',
|
||||
start: 1000,
|
||||
end: 2000,
|
||||
requestType: 'scalar',
|
||||
compositeQuery: {
|
||||
queries: [
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: 'traces',
|
||||
filter: {
|
||||
expression:
|
||||
"kind_string = 'Consumer' AND messaging.system = 'kafka' AND messaging.destination.name = 'o\\'rders' AND messaging.destination.partition.id = '0' AND messaging.kafka.consumer.group = 'fraud-consumer'",
|
||||
},
|
||||
groupBy: [{ name: 'service.name' }],
|
||||
aggregations: [
|
||||
{ expression: 'p99(duration_nano)' },
|
||||
{ expression: 'count()' },
|
||||
{ expression: 'countIf(has_error = true)' },
|
||||
{ expression: 'rate()' },
|
||||
{ expression: 'avg(messaging.message.body.size)' },
|
||||
],
|
||||
order: [{ key: { name: 'service.name' }, direction: 'asc' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('adds the joined metric as a second query grouped by its labels', () => {
|
||||
const [spanQuery, metricQuery] =
|
||||
getKafkaTableRequest(networkLatencySpec, 0, 1).compositeQuery?.queries ?? [];
|
||||
|
||||
expect(spanQuery.spec).toMatchObject({
|
||||
order: [{ key: { name: 'rate()' }, direction: 'desc' }],
|
||||
});
|
||||
expect(metricQuery).toStrictEqual({
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: 'B',
|
||||
signal: 'metrics',
|
||||
aggregations: [
|
||||
{
|
||||
metricName: 'kafka.consumer.fetch_latency_avg',
|
||||
timeAggregation: 'avg',
|
||||
spaceAggregation: 'avg',
|
||||
reduceTo: 'avg',
|
||||
},
|
||||
],
|
||||
groupBy: [
|
||||
{ name: 'service.name' },
|
||||
{ name: 'client-id' },
|
||||
{ name: 'service.instance.id' },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getKafkaTableRows', () => {
|
||||
it('reads p99 in ms, error rate in percent and an empty group as blank', () => {
|
||||
const results: Querybuildertypesv5ScalarDataDTO[] = [
|
||||
{
|
||||
queryName: 'A',
|
||||
columns: [
|
||||
{ name: 'service.name', columnType: group },
|
||||
{ name: '__result_0', columnType: aggregation, aggregationIndex: 0 },
|
||||
{ name: '__result_1', columnType: aggregation, aggregationIndex: 1 },
|
||||
{ name: '__result_2', columnType: aggregation, aggregationIndex: 2 },
|
||||
{ name: '__result_3', columnType: aggregation, aggregationIndex: 3 },
|
||||
{ name: '__result_4', columnType: aggregation, aggregationIndex: 4 },
|
||||
],
|
||||
data: [
|
||||
['order-consumer', 39000000, 534, 7, 0.593, 812.5],
|
||||
[null, 1000000, 0, 0, 0, null],
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
expect(getKafkaTableRows(consumerDetailsSpec, results)).toStrictEqual([
|
||||
{
|
||||
key: 0,
|
||||
service_name: 'order-consumer',
|
||||
p99: 39,
|
||||
error_rate: 1.3108614232209739,
|
||||
throughput: 0.593,
|
||||
avg_msg_size: 812.5,
|
||||
},
|
||||
{
|
||||
key: 1,
|
||||
service_name: '',
|
||||
p99: 1,
|
||||
error_rate: 0,
|
||||
throughput: 0,
|
||||
avg_msg_size: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('joins the metric on its own label names, whatever order the results come in, and marks unmatched rows', () => {
|
||||
const results: Querybuildertypesv5ScalarDataDTO[] = [
|
||||
{
|
||||
queryName: 'B',
|
||||
columns: [
|
||||
{ name: 'service.name', columnType: group },
|
||||
{ name: 'client-id', columnType: group },
|
||||
{ name: 'service.instance.id', columnType: group },
|
||||
{ name: '__result_0', columnType: aggregation, aggregationIndex: 0 },
|
||||
],
|
||||
data: [
|
||||
['fraud-consumer', 'fraud-consumer-client-3', 'fraud-consumer-3', 35.234],
|
||||
],
|
||||
},
|
||||
{
|
||||
queryName: 'A',
|
||||
columns: [
|
||||
{ name: 'messaging.client_id', columnType: group },
|
||||
{ name: 'service.instance.id', columnType: group },
|
||||
{ name: 'service.name', columnType: group },
|
||||
{ name: '__result_0', columnType: aggregation, aggregationIndex: 0 },
|
||||
],
|
||||
data: [
|
||||
['fraud-consumer-client-3', 'fraud-consumer-3', 'fraud-consumer', 0.186],
|
||||
['order-consumer-client-1', 'order-consumer-1', 'order-consumer', 0.25],
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
expect(getKafkaTableRows(networkLatencySpec, results)).toStrictEqual([
|
||||
{
|
||||
key: 0,
|
||||
client_id: 'fraud-consumer-client-3',
|
||||
service_instance_id: 'fraud-consumer-3',
|
||||
service_name: 'fraud-consumer',
|
||||
throughput: 0.186,
|
||||
latency: 35.234,
|
||||
},
|
||||
{
|
||||
key: 1,
|
||||
client_id: 'order-consumer-client-1',
|
||||
service_instance_id: 'order-consumer-1',
|
||||
service_name: 'order-consumer',
|
||||
throughput: 0.25,
|
||||
latency: 'n/a',
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getKafkaTableColumns', () => {
|
||||
it("puts Network Latency's latency before throughput, as it always was", () => {
|
||||
expect(
|
||||
getKafkaTableColumns(
|
||||
getDetailTableSpec({
|
||||
selectedView: MessagingQueuesViewTypeOptions.ConsumerLag,
|
||||
detailType: MessagingQueueServiceDetailType.NetworkLatency,
|
||||
timelineQuery: {},
|
||||
configDetails: {},
|
||||
}),
|
||||
),
|
||||
).toStrictEqual([
|
||||
'client_id',
|
||||
'service_instance_id',
|
||||
'service_name',
|
||||
'latency',
|
||||
'throughput',
|
||||
]);
|
||||
});
|
||||
|
||||
it('puts the producers byte rate after the span values', () => {
|
||||
expect(
|
||||
getKafkaTableColumns(
|
||||
getOverviewTableSpec(
|
||||
MessagingQueuesViewTypeOptions.ProducerLatency,
|
||||
ProducerLatencyOptions.Producers,
|
||||
),
|
||||
),
|
||||
).toStrictEqual([
|
||||
'topic',
|
||||
'service_name',
|
||||
'p99',
|
||||
'error_rate',
|
||||
'throughput',
|
||||
'byte_rate',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,271 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
Querybuildertypesv5OrderDirectionDTO,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal as TraceSignal,
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
type Querybuildertypesv5QueryEnvelopeDTO,
|
||||
Querybuildertypesv5ReduceToDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
MessagingQueueServiceDetailType,
|
||||
MessagingQueuesViewTypeOptions,
|
||||
ProducerLatencyOptions,
|
||||
} from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
|
||||
import { getKafkaTableRequest } from '../kafkaTableQuery';
|
||||
import { KafkaTableSpec } from '../kafkaTableQuery.types';
|
||||
import { getDetailTableSpec, getOverviewTableSpec } from '../kafkaTableSpecs';
|
||||
|
||||
const { asc, desc } = Querybuildertypesv5OrderDirectionDTO;
|
||||
const BUILDER_QUERY =
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query;
|
||||
|
||||
const P99 = 'p99(duration_nano)';
|
||||
const COUNT = 'count()';
|
||||
const ERRORS = 'countIf(has_error = true)';
|
||||
const RATE = 'rate()';
|
||||
|
||||
const TOPIC = 'messaging.destination.name';
|
||||
const PARTITION = 'messaging.destination.partition.id';
|
||||
const GROUP = 'messaging.kafka.consumer.group';
|
||||
const SERVICE = 'service.name';
|
||||
|
||||
const PRODUCER_SPANS =
|
||||
"kind_string = 'Producer' AND messaging.system = 'kafka'";
|
||||
const CONSUMER_SPANS =
|
||||
"kind_string = 'Consumer' AND messaging.system = 'kafka'";
|
||||
|
||||
const timelineQuery = {
|
||||
topic: 'orders',
|
||||
partition: '2',
|
||||
group: 'fraud-consumer',
|
||||
};
|
||||
const configDetails = {
|
||||
topic: 'orders',
|
||||
partition: '2',
|
||||
service_name: 'order-producer',
|
||||
};
|
||||
|
||||
const detail = (
|
||||
selectedView: MessagingQueuesViewTypeOptions,
|
||||
detailType: MessagingQueueServiceDetailType,
|
||||
): KafkaTableSpec =>
|
||||
getDetailTableSpec({ selectedView, detailType, timelineQuery, configDetails });
|
||||
|
||||
const spanQuery = ({
|
||||
filter,
|
||||
groupBy,
|
||||
aggregations,
|
||||
order,
|
||||
}: {
|
||||
filter: string;
|
||||
groupBy: string[];
|
||||
aggregations: string[];
|
||||
order?: { name: string; direction: Querybuildertypesv5OrderDirectionDTO };
|
||||
}): Querybuildertypesv5QueryEnvelopeDTO => ({
|
||||
type: BUILDER_QUERY,
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: TraceSignal.traces,
|
||||
filter: { expression: filter },
|
||||
groupBy: groupBy.map((name) => ({ name })),
|
||||
aggregations: aggregations.map((expression) => ({ expression })),
|
||||
order: order && [{ key: { name: order.name }, direction: order.direction }],
|
||||
},
|
||||
});
|
||||
|
||||
const metricQuery = (
|
||||
metricName: string,
|
||||
labels: string[],
|
||||
): Querybuildertypesv5QueryEnvelopeDTO => ({
|
||||
type: BUILDER_QUERY,
|
||||
spec: {
|
||||
name: 'B',
|
||||
signal: MetricSignal.metrics,
|
||||
aggregations: [
|
||||
{
|
||||
metricName,
|
||||
timeAggregation: MetrictypesTimeAggregationDTO.avg,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.avg,
|
||||
reduceTo: Querybuildertypesv5ReduceToDTO.avg,
|
||||
},
|
||||
],
|
||||
groupBy: labels.map((name) => ({ name })),
|
||||
},
|
||||
});
|
||||
|
||||
describe('Kafka table specs, one per legacy messaging-queues route', () => {
|
||||
it.each<[string, KafkaTableSpec, Querybuildertypesv5QueryEnvelopeDTO[]]>([
|
||||
[
|
||||
'partition-latency/overview',
|
||||
getOverviewTableSpec(
|
||||
MessagingQueuesViewTypeOptions.PartitionLatency,
|
||||
ProducerLatencyOptions.Producers,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: PRODUCER_SPANS,
|
||||
groupBy: [TOPIC, PARTITION],
|
||||
aggregations: [P99, RATE],
|
||||
order: { name: TOPIC, direction: asc },
|
||||
}),
|
||||
],
|
||||
],
|
||||
[
|
||||
'topic-throughput/producer',
|
||||
getOverviewTableSpec(
|
||||
MessagingQueuesViewTypeOptions.ProducerLatency,
|
||||
ProducerLatencyOptions.Producers,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: PRODUCER_SPANS,
|
||||
groupBy: [TOPIC, SERVICE],
|
||||
aggregations: [P99, COUNT, ERRORS, RATE],
|
||||
}),
|
||||
metricQuery('kafka.producer.byte-rate', [SERVICE, 'topic']),
|
||||
],
|
||||
],
|
||||
[
|
||||
'topic-throughput/consumer',
|
||||
getOverviewTableSpec(
|
||||
MessagingQueuesViewTypeOptions.ProducerLatency,
|
||||
ProducerLatencyOptions.Consumers,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: CONSUMER_SPANS,
|
||||
groupBy: [TOPIC, SERVICE],
|
||||
aggregations: [
|
||||
P99,
|
||||
COUNT,
|
||||
ERRORS,
|
||||
RATE,
|
||||
'rate_sum(messaging.message.body.size)',
|
||||
],
|
||||
order: { name: TOPIC, direction: asc },
|
||||
}),
|
||||
],
|
||||
],
|
||||
[
|
||||
'consumer-lag/producer-details',
|
||||
detail(
|
||||
MessagingQueuesViewTypeOptions.ConsumerLag,
|
||||
MessagingQueueServiceDetailType.ProducerDetails,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: `${PRODUCER_SPANS} AND ${TOPIC} = 'orders' AND ${PARTITION} = '2'`,
|
||||
groupBy: [SERVICE],
|
||||
aggregations: [P99, COUNT, ERRORS, RATE],
|
||||
order: { name: SERVICE, direction: asc },
|
||||
}),
|
||||
],
|
||||
],
|
||||
[
|
||||
'consumer-lag/consumer-details',
|
||||
detail(
|
||||
MessagingQueuesViewTypeOptions.ConsumerLag,
|
||||
MessagingQueueServiceDetailType.ConsumerDetails,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: `${CONSUMER_SPANS} AND ${TOPIC} = 'orders' AND ${PARTITION} = '2' AND ${GROUP} = 'fraud-consumer'`,
|
||||
groupBy: [SERVICE],
|
||||
aggregations: [
|
||||
P99,
|
||||
COUNT,
|
||||
ERRORS,
|
||||
RATE,
|
||||
'avg(messaging.message.body.size)',
|
||||
],
|
||||
order: { name: SERVICE, direction: asc },
|
||||
}),
|
||||
],
|
||||
],
|
||||
[
|
||||
'consumer-lag/network-latency',
|
||||
detail(
|
||||
MessagingQueuesViewTypeOptions.ConsumerLag,
|
||||
MessagingQueueServiceDetailType.NetworkLatency,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: `${CONSUMER_SPANS} AND ${GROUP} = 'fraud-consumer' AND ${PARTITION} = '2'`,
|
||||
groupBy: ['messaging.client_id', 'service.instance.id', SERVICE],
|
||||
aggregations: [RATE],
|
||||
order: { name: RATE, direction: desc },
|
||||
}),
|
||||
metricQuery('kafka.consumer.fetch_latency_avg', [
|
||||
'client-id',
|
||||
'service.instance.id',
|
||||
SERVICE,
|
||||
]),
|
||||
],
|
||||
],
|
||||
[
|
||||
'partition-latency/consumer',
|
||||
detail(
|
||||
MessagingQueuesViewTypeOptions.PartitionLatency,
|
||||
MessagingQueueServiceDetailType.ConsumerDetails,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: `${CONSUMER_SPANS} AND ${TOPIC} = 'orders' AND ${PARTITION} = '2'`,
|
||||
groupBy: [GROUP, SERVICE],
|
||||
aggregations: [P99, COUNT, ERRORS, RATE],
|
||||
order: { name: GROUP, direction: asc },
|
||||
}),
|
||||
],
|
||||
],
|
||||
[
|
||||
'consumer-lag/producer-details, from the Partition Latency view',
|
||||
detail(
|
||||
MessagingQueuesViewTypeOptions.PartitionLatency,
|
||||
MessagingQueueServiceDetailType.ProducerDetails,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: `${PRODUCER_SPANS} AND ${TOPIC} = 'orders' AND ${PARTITION} = '2'`,
|
||||
groupBy: [SERVICE],
|
||||
aggregations: [P99, COUNT, ERRORS, RATE],
|
||||
order: { name: SERVICE, direction: asc },
|
||||
}),
|
||||
],
|
||||
],
|
||||
[
|
||||
'topic-throughput/producer-details',
|
||||
detail(
|
||||
MessagingQueuesViewTypeOptions.ProducerLatency,
|
||||
MessagingQueueServiceDetailType.ProducerDetails,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: `${PRODUCER_SPANS} AND ${TOPIC} = 'orders' AND ${SERVICE} = 'order-producer'`,
|
||||
groupBy: [PARTITION],
|
||||
aggregations: [P99, COUNT, ERRORS, RATE],
|
||||
}),
|
||||
],
|
||||
],
|
||||
[
|
||||
'topic-throughput/consumer-details',
|
||||
detail(
|
||||
MessagingQueuesViewTypeOptions.ProducerLatency,
|
||||
MessagingQueueServiceDetailType.ConsumerDetails,
|
||||
),
|
||||
[
|
||||
spanQuery({
|
||||
filter: `${CONSUMER_SPANS} AND ${TOPIC} = 'orders' AND ${SERVICE} = 'order-producer'`,
|
||||
groupBy: [PARTITION],
|
||||
aggregations: [P99, COUNT, ERRORS, RATE],
|
||||
}),
|
||||
],
|
||||
],
|
||||
])('%s sends the query the legacy SQL ran', (_route, spec, queries) => {
|
||||
expect(
|
||||
getKafkaTableRequest(spec, 0, 1).compositeQuery?.queries,
|
||||
).toStrictEqual(queries);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import {
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal as TraceSignal,
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
type Querybuildertypesv5QueryEnvelopeDTO,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
Querybuildertypesv5ReduceToDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type Querybuildertypesv5ScalarDataDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { formatValueForExpression } from 'components/QueryBuilderV2/utils';
|
||||
import {
|
||||
NS_PER_MS,
|
||||
RowData,
|
||||
toGroupText,
|
||||
} from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
import { toFiniteNumber } from 'utils/numericUtils';
|
||||
|
||||
import {
|
||||
KafkaGroupColumn,
|
||||
KafkaMetricJoin,
|
||||
KafkaTableSpec,
|
||||
KafkaValueColumn,
|
||||
} from './kafkaTableQuery.types';
|
||||
|
||||
const SPAN_QUERY = 'A';
|
||||
const METRIC_QUERY = 'B';
|
||||
|
||||
const GROUP_COLUMN_KEYS: Record<KafkaGroupColumn, string> = {
|
||||
topic: 'messaging.destination.name',
|
||||
partition: 'messaging.destination.partition.id',
|
||||
consumer_group: 'messaging.kafka.consumer.group',
|
||||
service_name: 'service.name',
|
||||
client_id: 'messaging.client_id',
|
||||
service_instance_id: 'service.instance.id',
|
||||
};
|
||||
|
||||
type SpanAggregation =
|
||||
| 'p99'
|
||||
| 'count'
|
||||
| 'errors'
|
||||
| 'rate'
|
||||
| 'avgBodySize'
|
||||
| 'bodySizeRate';
|
||||
|
||||
const SPAN_AGGREGATION_EXPRESSIONS: Record<SpanAggregation, string> = {
|
||||
p99: 'p99(duration_nano)',
|
||||
count: 'count()',
|
||||
errors: 'countIf(has_error = true)',
|
||||
rate: 'rate()',
|
||||
avgBodySize: 'avg(messaging.message.body.size)',
|
||||
bodySizeRate: 'rate_sum(messaging.message.body.size)',
|
||||
};
|
||||
|
||||
type ReadAggregation = (aggregation: SpanAggregation) => number;
|
||||
|
||||
const getErrorPercentage = (read: ReadAggregation): number => {
|
||||
const count = read('count');
|
||||
return count ? (read('errors') * 100) / count : 0;
|
||||
};
|
||||
|
||||
const VALUE_COLUMNS: Record<
|
||||
KafkaValueColumn,
|
||||
{ aggregations: SpanAggregation[]; read: (read: ReadAggregation) => number }
|
||||
> = {
|
||||
p99: { aggregations: ['p99'], read: (read) => read('p99') / NS_PER_MS },
|
||||
error_rate: { aggregations: ['count', 'errors'], read: getErrorPercentage },
|
||||
error_percentage: {
|
||||
aggregations: ['count', 'errors'],
|
||||
read: getErrorPercentage,
|
||||
},
|
||||
throughput: { aggregations: ['rate'], read: (read) => read('rate') },
|
||||
ingestion_rate: { aggregations: ['rate'], read: (read) => read('rate') },
|
||||
avg_msg_size: {
|
||||
aggregations: ['avgBodySize'],
|
||||
read: (read) => read('avgBodySize'),
|
||||
},
|
||||
byte_rate: {
|
||||
aggregations: ['bodySizeRate'],
|
||||
read: (read) => read('bodySizeRate'),
|
||||
},
|
||||
};
|
||||
|
||||
const getSpanAggregations = (spec: KafkaTableSpec): SpanAggregation[] => [
|
||||
...new Set(
|
||||
spec.values.flatMap((column) => VALUE_COLUMNS[column].aggregations),
|
||||
),
|
||||
];
|
||||
|
||||
const getFilterExpression = ({ kind, filters }: KafkaTableSpec): string =>
|
||||
[
|
||||
`kind_string = ${formatValueForExpression(kind)}`,
|
||||
`messaging.system = 'kafka'`,
|
||||
...(Object.keys(filters) as KafkaGroupColumn[]).flatMap((column) => {
|
||||
const value = filters[column];
|
||||
return value
|
||||
? [`${GROUP_COLUMN_KEYS[column]} = ${formatValueForExpression(value)}`]
|
||||
: [];
|
||||
}),
|
||||
].join(' AND ');
|
||||
|
||||
const getMetricQuery = (
|
||||
join: KafkaMetricJoin,
|
||||
): Querybuildertypesv5QueryEnvelopeDTO => ({
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
spec: {
|
||||
name: METRIC_QUERY,
|
||||
signal: MetricSignal.metrics,
|
||||
aggregations: [
|
||||
{
|
||||
metricName: join.metricName,
|
||||
timeAggregation: MetrictypesTimeAggregationDTO.avg,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.avg,
|
||||
reduceTo: Querybuildertypesv5ReduceToDTO.avg,
|
||||
},
|
||||
],
|
||||
groupBy: Object.values(join.labels).map((name) => ({ name })),
|
||||
},
|
||||
});
|
||||
|
||||
export const getKafkaTableRequest = (
|
||||
spec: KafkaTableSpec,
|
||||
startMs: number,
|
||||
endMs: number,
|
||||
): Querybuildertypesv5QueryRangeRequestDTO => {
|
||||
const { order, metricJoin } = spec;
|
||||
const queries: Querybuildertypesv5QueryEnvelopeDTO[] = [
|
||||
{
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
spec: {
|
||||
name: SPAN_QUERY,
|
||||
signal: TraceSignal.traces,
|
||||
filter: { expression: getFilterExpression(spec) },
|
||||
groupBy: spec.groupBy.map((column) => ({
|
||||
name: GROUP_COLUMN_KEYS[column],
|
||||
})),
|
||||
aggregations: getSpanAggregations(spec).map((aggregation) => ({
|
||||
expression: SPAN_AGGREGATION_EXPRESSIONS[aggregation],
|
||||
})),
|
||||
order: order && [
|
||||
{
|
||||
key: {
|
||||
name:
|
||||
order.by === 'throughput'
|
||||
? SPAN_AGGREGATION_EXPRESSIONS.rate
|
||||
: GROUP_COLUMN_KEYS[order.by],
|
||||
},
|
||||
direction: order.direction,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
if (metricJoin) {
|
||||
queries.push(getMetricQuery(metricJoin));
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 'v1',
|
||||
start: Math.floor(startMs),
|
||||
end: Math.floor(endMs),
|
||||
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
compositeQuery: { queries },
|
||||
};
|
||||
};
|
||||
|
||||
const getJoinKey = (values: string[]): string => JSON.stringify(values);
|
||||
|
||||
const getMetricValues = (
|
||||
join: KafkaMetricJoin,
|
||||
result: Querybuildertypesv5ScalarDataDTO | undefined,
|
||||
): Map<string, number> => {
|
||||
const columns = result?.columns ?? [];
|
||||
const labelIndexes = Object.values(join.labels).map((label) =>
|
||||
columns.findIndex(
|
||||
(column) =>
|
||||
column.columnType === Querybuildertypesv5ColumnTypeDTO.group &&
|
||||
column.name === label,
|
||||
),
|
||||
);
|
||||
const valueIndex = columns.findIndex(
|
||||
(column) =>
|
||||
column.columnType === Querybuildertypesv5ColumnTypeDTO.aggregation,
|
||||
);
|
||||
|
||||
return new Map(
|
||||
(result?.data ?? []).map((row) => [
|
||||
getJoinKey(labelIndexes.map((index) => toGroupText(row[index]))),
|
||||
toFiniteNumber(row[valueIndex]),
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
export const getKafkaTableRows = (
|
||||
spec: KafkaTableSpec,
|
||||
results: Querybuildertypesv5ScalarDataDTO[],
|
||||
): RowData[] => {
|
||||
const spanResult = results.find((result) => result.queryName === SPAN_QUERY);
|
||||
const columns = spanResult?.columns ?? [];
|
||||
const aggregations = getSpanAggregations(spec);
|
||||
const { metricJoin } = spec;
|
||||
const metricValues =
|
||||
metricJoin &&
|
||||
getMetricValues(
|
||||
metricJoin,
|
||||
results.find((result) => result.queryName === METRIC_QUERY),
|
||||
);
|
||||
|
||||
const groupIndexes = spec.groupBy.map((groupColumn) =>
|
||||
columns.findIndex(
|
||||
(column) =>
|
||||
column.columnType === Querybuildertypesv5ColumnTypeDTO.group &&
|
||||
column.name === GROUP_COLUMN_KEYS[groupColumn],
|
||||
),
|
||||
);
|
||||
const aggregationIndexes = aggregations.map((_aggregation, index) =>
|
||||
columns.findIndex(
|
||||
(column) =>
|
||||
column.columnType === Querybuildertypesv5ColumnTypeDTO.aggregation &&
|
||||
column.aggregationIndex === index,
|
||||
),
|
||||
);
|
||||
|
||||
return (spanResult?.data ?? []).map((row, rowIndex): RowData => {
|
||||
const groupValues = Object.fromEntries(
|
||||
spec.groupBy.map((column, index) => [
|
||||
column,
|
||||
toGroupText(row[groupIndexes[index]]),
|
||||
]),
|
||||
) as Record<KafkaGroupColumn, string>;
|
||||
const read: ReadAggregation = (aggregation) =>
|
||||
toFiniteNumber(row[aggregationIndexes[aggregations.indexOf(aggregation)]]);
|
||||
const values = Object.fromEntries(
|
||||
spec.values.map((column) => [column, VALUE_COLUMNS[column].read(read)]),
|
||||
);
|
||||
const joined =
|
||||
metricJoin &&
|
||||
metricValues?.get(
|
||||
getJoinKey(
|
||||
(Object.keys(metricJoin.labels) as KafkaGroupColumn[]).map(
|
||||
(column) => groupValues[column] ?? '',
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
key: rowIndex,
|
||||
...groupValues,
|
||||
...values,
|
||||
...(metricJoin && {
|
||||
[metricJoin.column]: joined ?? metricJoin.missingValue,
|
||||
}),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
export const getKafkaTableColumns = ({
|
||||
groupBy,
|
||||
values,
|
||||
metricJoin,
|
||||
}: KafkaTableSpec): string[] => {
|
||||
const joined = metricJoin ? [metricJoin.column] : [];
|
||||
return metricJoin?.beforeValues
|
||||
? [...groupBy, ...joined, ...values]
|
||||
: [...groupBy, ...values, ...joined];
|
||||
};
|
||||
|
||||
/** A value cell to 3 decimals; a join's `n/a` fallback passes through. */
|
||||
export const formatKafkaValueCell = (value: number | string): string =>
|
||||
typeof value === 'number' ? value.toFixed(3) : value;
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Querybuildertypesv5OrderDirectionDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export enum KafkaSpanKind {
|
||||
Producer = 'Producer',
|
||||
Consumer = 'Consumer',
|
||||
}
|
||||
|
||||
/** Row keys the tables render and their row clicks write to the URL. */
|
||||
export type KafkaGroupColumn =
|
||||
| 'topic'
|
||||
| 'partition'
|
||||
| 'consumer_group'
|
||||
| 'service_name'
|
||||
| 'client_id'
|
||||
| 'service_instance_id';
|
||||
|
||||
export type KafkaValueColumn =
|
||||
| 'p99'
|
||||
| 'error_rate'
|
||||
| 'error_percentage'
|
||||
| 'throughput'
|
||||
| 'ingestion_rate'
|
||||
| 'avg_msg_size'
|
||||
| 'byte_rate';
|
||||
|
||||
export interface KafkaMetricJoin {
|
||||
metricName: string;
|
||||
column: 'byte_rate' | 'latency';
|
||||
/** The metric label each group column joins on. */
|
||||
labels: Partial<Record<KafkaGroupColumn, string>>;
|
||||
/** Shown when no metric series matches the row. */
|
||||
missingValue: number | string;
|
||||
/** Puts the joined column ahead of the span values instead of after them. */
|
||||
beforeValues?: boolean;
|
||||
}
|
||||
|
||||
export interface KafkaTableSpec {
|
||||
kind: KafkaSpanKind;
|
||||
filters: Partial<Record<KafkaGroupColumn, string>>;
|
||||
groupBy: KafkaGroupColumn[];
|
||||
values: KafkaValueColumn[];
|
||||
order?: {
|
||||
by: KafkaGroupColumn | 'throughput';
|
||||
direction: Querybuildertypesv5OrderDirectionDTO;
|
||||
};
|
||||
metricJoin?: KafkaMetricJoin;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Querybuildertypesv5OrderDirectionDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
MessagingQueueServiceDetailType,
|
||||
MessagingQueuesViewType,
|
||||
MessagingQueuesViewTypeOptions,
|
||||
ProducerLatencyOptions,
|
||||
SelectedTimelineQuery,
|
||||
} from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
|
||||
import { KafkaSpanKind, KafkaTableSpec } from './kafkaTableQuery.types';
|
||||
|
||||
const { asc, desc } = Querybuildertypesv5OrderDirectionDTO;
|
||||
|
||||
const PARTITION_LATENCY_OVERVIEW: KafkaTableSpec = {
|
||||
kind: KafkaSpanKind.Producer,
|
||||
filters: {},
|
||||
groupBy: ['topic', 'partition'],
|
||||
values: ['p99', 'throughput'],
|
||||
order: { by: 'topic', direction: asc },
|
||||
};
|
||||
|
||||
const PRODUCERS_OVERVIEW: KafkaTableSpec = {
|
||||
kind: KafkaSpanKind.Producer,
|
||||
filters: {},
|
||||
groupBy: ['topic', 'service_name'],
|
||||
values: ['p99', 'error_rate', 'throughput'],
|
||||
metricJoin: {
|
||||
metricName: 'kafka.producer.byte-rate',
|
||||
column: 'byte_rate',
|
||||
labels: { service_name: 'service.name', topic: 'topic' },
|
||||
missingValue: 0,
|
||||
},
|
||||
};
|
||||
|
||||
const CONSUMERS_OVERVIEW: KafkaTableSpec = {
|
||||
kind: KafkaSpanKind.Consumer,
|
||||
filters: {},
|
||||
groupBy: ['topic', 'service_name'],
|
||||
values: ['p99', 'error_rate', 'ingestion_rate', 'byte_rate'],
|
||||
order: { by: 'topic', direction: asc },
|
||||
};
|
||||
|
||||
export const getOverviewTableSpec = (
|
||||
selectedView: MessagingQueuesViewTypeOptions,
|
||||
option: ProducerLatencyOptions,
|
||||
): KafkaTableSpec => {
|
||||
if (selectedView !== MessagingQueuesViewType.producerLatency.value) {
|
||||
return PARTITION_LATENCY_OVERVIEW;
|
||||
}
|
||||
return option === ProducerLatencyOptions.Producers
|
||||
? PRODUCERS_OVERVIEW
|
||||
: CONSUMERS_OVERVIEW;
|
||||
};
|
||||
|
||||
const getProducersOfPartitionSpec = (
|
||||
topic?: string,
|
||||
partition?: string,
|
||||
): KafkaTableSpec => ({
|
||||
kind: KafkaSpanKind.Producer,
|
||||
filters: { topic, partition },
|
||||
groupBy: ['service_name'],
|
||||
values: ['p99', 'error_percentage', 'throughput'],
|
||||
order: { by: 'service_name', direction: asc },
|
||||
});
|
||||
|
||||
const getConsumerLagSpec = (
|
||||
detailType: MessagingQueueServiceDetailType,
|
||||
{ group, topic, partition }: SelectedTimelineQuery,
|
||||
): KafkaTableSpec => {
|
||||
switch (detailType) {
|
||||
case MessagingQueueServiceDetailType.ConsumerDetails:
|
||||
return {
|
||||
kind: KafkaSpanKind.Consumer,
|
||||
filters: { topic, partition, consumer_group: group },
|
||||
groupBy: ['service_name'],
|
||||
values: ['p99', 'error_rate', 'throughput', 'avg_msg_size'],
|
||||
order: { by: 'service_name', direction: asc },
|
||||
};
|
||||
case MessagingQueueServiceDetailType.NetworkLatency:
|
||||
return {
|
||||
kind: KafkaSpanKind.Consumer,
|
||||
filters: { consumer_group: group, partition },
|
||||
groupBy: ['client_id', 'service_instance_id', 'service_name'],
|
||||
values: ['throughput'],
|
||||
order: { by: 'throughput', direction: desc },
|
||||
metricJoin: {
|
||||
metricName: 'kafka.consumer.fetch_latency_avg',
|
||||
column: 'latency',
|
||||
labels: {
|
||||
client_id: 'client-id',
|
||||
service_instance_id: 'service.instance.id',
|
||||
service_name: 'service.name',
|
||||
},
|
||||
missingValue: 'n/a',
|
||||
beforeValues: true,
|
||||
},
|
||||
};
|
||||
default:
|
||||
return getProducersOfPartitionSpec(topic, partition);
|
||||
}
|
||||
};
|
||||
|
||||
const getPartitionLatencySpec = (
|
||||
detailType: MessagingQueueServiceDetailType,
|
||||
{ topic, partition }: Record<string, string>,
|
||||
): KafkaTableSpec =>
|
||||
detailType === MessagingQueueServiceDetailType.ConsumerDetails
|
||||
? {
|
||||
kind: KafkaSpanKind.Consumer,
|
||||
filters: { topic, partition },
|
||||
groupBy: ['consumer_group', 'service_name'],
|
||||
values: ['p99', 'error_rate', 'throughput'],
|
||||
order: { by: 'consumer_group', direction: asc },
|
||||
}
|
||||
: getProducersOfPartitionSpec(topic, partition);
|
||||
|
||||
const getProducerLatencySpec = (
|
||||
detailType: MessagingQueueServiceDetailType,
|
||||
{ topic, service_name }: Record<string, string>,
|
||||
): KafkaTableSpec => ({
|
||||
kind:
|
||||
detailType === MessagingQueueServiceDetailType.ConsumerDetails
|
||||
? KafkaSpanKind.Consumer
|
||||
: KafkaSpanKind.Producer,
|
||||
filters: { topic, service_name },
|
||||
groupBy: ['partition'],
|
||||
values: ['p99', 'error_rate', 'throughput'],
|
||||
});
|
||||
|
||||
export const getDetailTableSpec = ({
|
||||
selectedView,
|
||||
detailType,
|
||||
timelineQuery,
|
||||
configDetails,
|
||||
}: {
|
||||
selectedView: MessagingQueuesViewTypeOptions;
|
||||
detailType: MessagingQueueServiceDetailType;
|
||||
timelineQuery: SelectedTimelineQuery;
|
||||
configDetails: Record<string, string>;
|
||||
}): KafkaTableSpec => {
|
||||
switch (selectedView) {
|
||||
case MessagingQueuesViewType.consumerLag.value:
|
||||
return getConsumerLagSpec(detailType, timelineQuery);
|
||||
case MessagingQueuesViewType.producerLatency.value:
|
||||
return getProducerLatencySpec(detailType, configDetails);
|
||||
default:
|
||||
return getPartitionLatencySpec(detailType, configDetails);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useQuery, UseQueryResult } from 'react-query';
|
||||
import { queryRangeV5 } from 'api/generated/services/querier';
|
||||
import type {
|
||||
QueryRangeV5200,
|
||||
RenderErrorResponseDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { ErrorType } from 'api/generatedAPIInstance';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { getScalarResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
|
||||
import { RowData } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
|
||||
import { getKafkaTableRequest, getKafkaTableRows } from './kafkaTableQuery';
|
||||
import { KafkaTableSpec } from './kafkaTableQuery.types';
|
||||
|
||||
interface UseKafkaTableRowsArgs {
|
||||
spec: KafkaTableSpec;
|
||||
startMs: number;
|
||||
endMs: number;
|
||||
enabled: boolean;
|
||||
onError: (error: ErrorType<RenderErrorResponseDTO>) => void;
|
||||
}
|
||||
|
||||
export function useKafkaTableRows({
|
||||
spec,
|
||||
startMs,
|
||||
endMs,
|
||||
enabled,
|
||||
onError,
|
||||
}: UseKafkaTableRowsArgs): UseQueryResult<
|
||||
RowData[],
|
||||
ErrorType<RenderErrorResponseDTO>
|
||||
> {
|
||||
const request = useMemo(
|
||||
() => getKafkaTableRequest(spec, startMs, endMs),
|
||||
[spec, startMs, endMs],
|
||||
);
|
||||
|
||||
return useQuery<QueryRangeV5200, ErrorType<RenderErrorResponseDTO>, RowData[]>(
|
||||
{
|
||||
queryKey: [REACT_QUERY_KEY.GET_KAFKA_TABLE_ROWS, request],
|
||||
queryFn: ({ signal }) => queryRangeV5(request, signal),
|
||||
select: (response) => getKafkaTableRows(spec, getScalarResults(response)),
|
||||
enabled,
|
||||
onError,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -3,9 +3,6 @@ import { Dispatch, SetStateAction, useMemo } from 'react';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { ToggleGroup } from '@signozhq/ui/toggle-group';
|
||||
import { MessagingQueueServicePayload } from 'api/messagingQueues/getConsumerLagDetails';
|
||||
import { getPartitionLatencyOverview } from 'api/messagingQueues/getPartitionLatencyOverview';
|
||||
import { getTopicThroughputOverview } from 'api/messagingQueues/getTopicThroughputOverview';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
@@ -13,9 +10,11 @@ import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import {
|
||||
MessagingQueuesViewType,
|
||||
MessagingQueuesViewTypeOptions,
|
||||
NS_PER_MS,
|
||||
ProducerLatencyOptions,
|
||||
setConfigDetail,
|
||||
} from '../MessagingQueuesUtils';
|
||||
import { getOverviewTableSpec } from './MQTables/kafkaTableSpecs';
|
||||
import MessagingQueuesTable from './MQTables/MQTables';
|
||||
|
||||
import './MQDetails.style.scss';
|
||||
@@ -58,13 +57,6 @@ function ProducerLatencyTabs({
|
||||
);
|
||||
}
|
||||
|
||||
const getTableApi = (selectedView: MessagingQueuesViewTypeOptions): any => {
|
||||
if (selectedView === MessagingQueuesViewType.producerLatency.value) {
|
||||
return getTopicThroughputOverview;
|
||||
}
|
||||
return getPartitionLatencyOverview;
|
||||
};
|
||||
|
||||
function MessagingQueueOverview({
|
||||
selectedView,
|
||||
option,
|
||||
@@ -78,19 +70,9 @@ function MessagingQueueOverview({
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
|
||||
const tableApiPayload: MessagingQueueServicePayload = useMemo(
|
||||
() => ({
|
||||
variables: {},
|
||||
start: minTime,
|
||||
end: maxTime,
|
||||
detailType:
|
||||
selectedView === MessagingQueuesViewType.producerLatency.value
|
||||
? option === ProducerLatencyOptions.Producers
|
||||
? 'producer'
|
||||
: 'consumer'
|
||||
: undefined,
|
||||
}),
|
||||
[minTime, maxTime, selectedView, option],
|
||||
const spec = useMemo(
|
||||
() => getOverviewTableSpec(selectedView, option),
|
||||
[selectedView, option],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -104,8 +86,9 @@ function MessagingQueueOverview({
|
||||
)}
|
||||
<MessagingQueuesTable
|
||||
selectedView={selectedView}
|
||||
tableApiPayload={tableApiPayload}
|
||||
tableApi={getTableApi(selectedView)}
|
||||
spec={spec}
|
||||
startMs={minTime / NS_PER_MS}
|
||||
endMs={maxTime / NS_PER_MS}
|
||||
validConfigPresent
|
||||
type="Overview"
|
||||
option={option}
|
||||
|
||||
@@ -1,21 +1,14 @@
|
||||
import {
|
||||
getConsumerLagDetails,
|
||||
MessagingQueueServicePayload,
|
||||
MessagingQueuesPayloadProps,
|
||||
} from 'api/messagingQueues/getConsumerLagDetails';
|
||||
import { getPartitionLatencyDetails } from 'api/messagingQueues/getPartitionLatencyDetails';
|
||||
import { getTopicThroughputDetails } from 'api/messagingQueues/getTopicThroughputDetails';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetWidgetQueryBuilderProps } from 'container/MetricsApplication/types';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import type { AppLocation } from 'lib/router/types';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
import { isScalarFieldValue } from 'utils/stringUtils';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
export const KAFKA_SETUP_DOC_LINK =
|
||||
@@ -28,6 +21,12 @@ export function convertToTitleCase(text: string): string {
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
export const NS_PER_MS = 1e6;
|
||||
|
||||
/** A scalar group cell as text; a missing group value is blank. */
|
||||
export const toGroupText = (value: unknown): string =>
|
||||
isScalarFieldValue(value) ? String(value) : '';
|
||||
|
||||
export type RowData = {
|
||||
key: string | number;
|
||||
[key: string]: string | number;
|
||||
@@ -252,9 +251,7 @@ export const MessagingQueuesViewType = {
|
||||
export function setConfigDetail(
|
||||
urlQuery: URLSearchParams,
|
||||
location: AppLocation,
|
||||
paramsToSet?: {
|
||||
[key: string]: string;
|
||||
},
|
||||
paramsToSet?: Record<string, string | number>,
|
||||
): void {
|
||||
// remove "key" and its value from the paramsToSet object
|
||||
const { key: _key, ...restParamsToSet } = paramsToSet || {};
|
||||
@@ -279,72 +276,6 @@ export enum ProducerLatencyOptions {
|
||||
Consumers = 'Consumers',
|
||||
}
|
||||
|
||||
interface MetaDataAndAPI {
|
||||
tableApiPayload: MessagingQueueServicePayload;
|
||||
tableApi: (
|
||||
props: MessagingQueueServicePayload,
|
||||
) => Promise<
|
||||
SuccessResponse<MessagingQueuesPayloadProps['payload']> | ErrorResponse
|
||||
>;
|
||||
}
|
||||
interface MetaDataAndAPIPerView {
|
||||
detailType: MessagingQueueServiceDetailType;
|
||||
selectedTimelineQuery: SelectedTimelineQuery;
|
||||
configDetails?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
minTime: number;
|
||||
maxTime: number;
|
||||
}
|
||||
|
||||
export const getMetaDataAndAPIPerView = (
|
||||
metaDataProps: MetaDataAndAPIPerView,
|
||||
): Record<string, MetaDataAndAPI> => {
|
||||
const { detailType, minTime, maxTime, selectedTimelineQuery, configDetails } =
|
||||
metaDataProps;
|
||||
return {
|
||||
[MessagingQueuesViewType.consumerLag.value]: {
|
||||
tableApiPayload: {
|
||||
start: (selectedTimelineQuery?.start || 0) * 1e6,
|
||||
end: (selectedTimelineQuery?.end || 0) * 1e6,
|
||||
variables: {
|
||||
partition: selectedTimelineQuery?.partition,
|
||||
topic: selectedTimelineQuery?.topic,
|
||||
consumer_group: selectedTimelineQuery?.group,
|
||||
},
|
||||
detailType,
|
||||
},
|
||||
tableApi: getConsumerLagDetails,
|
||||
},
|
||||
[MessagingQueuesViewType.partitionLatency.value]: {
|
||||
tableApiPayload: {
|
||||
start: minTime,
|
||||
end: maxTime,
|
||||
variables: {
|
||||
partition: configDetails?.partition,
|
||||
topic: configDetails?.topic,
|
||||
consumer_group: configDetails?.group,
|
||||
},
|
||||
detailType,
|
||||
},
|
||||
tableApi: getPartitionLatencyDetails,
|
||||
},
|
||||
[MessagingQueuesViewType.producerLatency.value]: {
|
||||
tableApiPayload: {
|
||||
start: minTime,
|
||||
end: maxTime,
|
||||
variables: {
|
||||
partition: configDetails?.partition,
|
||||
topic: configDetails?.topic,
|
||||
service_name: configDetails?.service_name,
|
||||
},
|
||||
detailType,
|
||||
},
|
||||
tableApi: getTopicThroughputDetails,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export enum MessagingQueueHealthCheckService {
|
||||
Consumers = 'consumers',
|
||||
Producers = 'producers',
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
timeRangeState,
|
||||
} from '../../stories/__story_mockdata__/messagingQueues';
|
||||
import {
|
||||
isQueueOverviewRequest,
|
||||
MESSAGING_SYSTEMS,
|
||||
type MessagingSystemFilter,
|
||||
overviewValueResponse,
|
||||
@@ -62,28 +63,15 @@ export const queueOverviewMocks = defineStoryMocks({
|
||||
}),
|
||||
},
|
||||
handlers: (values, response) => [
|
||||
rest.post(
|
||||
'http://localhost/api/v1/messaging-queues/queue-overview',
|
||||
response.json(async (req) => {
|
||||
const body = (await req.json()) as { end: number };
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
data: queueOverviewResponse(
|
||||
values.queues,
|
||||
values.system,
|
||||
values.failing,
|
||||
body.end / 1e6,
|
||||
),
|
||||
};
|
||||
}),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
'http://localhost/api/v5/query_range',
|
||||
response.json(async (req) => {
|
||||
const body = (await req.json()) as Querybuildertypesv5QueryRangeRequestDTO;
|
||||
|
||||
if (isQueueOverviewRequest(body)) {
|
||||
return queueOverviewResponse(values.queues, values.system, values.failing);
|
||||
}
|
||||
|
||||
return (
|
||||
overviewValueResponse(body, values.failing) ??
|
||||
queryRangeV5ForRequest(body, {
|
||||
|
||||
@@ -6,11 +6,16 @@
|
||||
import {
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type QueryRangeV5200,
|
||||
type Querybuildertypesv5QueryEnvelopeDTO,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { MetricRangePayloadV5 } from 'types/api/v5/queryRange';
|
||||
|
||||
import { queryRangeV5ScalarResponse } from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
import {
|
||||
queryRangeV5ScalarResponse,
|
||||
queryRangeV5ScalarResultsResponse,
|
||||
} from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
|
||||
import {
|
||||
KAFKA_SERVICES,
|
||||
@@ -121,48 +126,78 @@ const errorPercentage = (index: number, failing: boolean): number => {
|
||||
return index % 3 === 0 ? seeded(index, 60, 40) : seeded(index, 5, 45);
|
||||
};
|
||||
|
||||
/**
|
||||
* `QueueOverviewResponse` declares each entry's `data` as an array of column
|
||||
* objects, but `getTableData` indexes it as a single object and casts the key to
|
||||
* get past the compiler, so the builder follows what the page reads.
|
||||
*/
|
||||
export interface QueueOverviewEntry {
|
||||
timestamp: string;
|
||||
data: {
|
||||
service_name: string;
|
||||
span_name: string;
|
||||
messaging_system: string;
|
||||
destination: string;
|
||||
kind_string: string;
|
||||
error_percentage: number;
|
||||
p95_latency: number;
|
||||
throughput: number;
|
||||
};
|
||||
}
|
||||
const NS_PER_MS = 1e6;
|
||||
|
||||
type BuilderSpec = Extract<
|
||||
Querybuildertypesv5QueryEnvelopeDTO,
|
||||
{ type: typeof Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query }
|
||||
>['spec'];
|
||||
|
||||
const builderSpec = (
|
||||
body: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
): BuilderSpec | undefined => {
|
||||
const query = body.compositeQuery?.queries?.find(
|
||||
(envelope) =>
|
||||
envelope.type ===
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
);
|
||||
return query?.type ===
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
|
||||
? query.spec
|
||||
: undefined;
|
||||
};
|
||||
|
||||
/** The table's request is the only one grouped by `messaging.destination`. */
|
||||
export const isQueueOverviewRequest = (
|
||||
body: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
): boolean =>
|
||||
(builderSpec(body)?.groupBy ?? []).some(
|
||||
({ name }) => name === 'messaging.destination',
|
||||
);
|
||||
|
||||
/**
|
||||
* Celery spans carry no `messaging.system` and name their queue on
|
||||
* `messaging.destination`; kafka spans set the system and the topic on
|
||||
* `messaging.destination.name`. The page derives the system and destination
|
||||
* columns from those raw groups.
|
||||
*/
|
||||
export const queueOverviewResponse = (
|
||||
count: number,
|
||||
system: MessagingSystemFilter,
|
||||
failing: boolean,
|
||||
timestamp: number,
|
||||
): QueueOverviewEntry[] =>
|
||||
Array.from({ length: count }, (_unused, index) => {
|
||||
const row = rowFor(index, system);
|
||||
): QueryRangeV5200 =>
|
||||
queryRangeV5ScalarResultsResponse([
|
||||
{
|
||||
queryName: 'A',
|
||||
groupBy: [
|
||||
'service.name',
|
||||
'name',
|
||||
'messaging.system',
|
||||
'messaging.destination.name',
|
||||
'messaging.destination',
|
||||
'kind_string',
|
||||
],
|
||||
aggregations: 4,
|
||||
rows: Array.from({ length: count }, (_unused, index) => {
|
||||
const row = rowFor(index, system);
|
||||
const isCelery = row.system === 'celery';
|
||||
const total = Math.round(seeded(index, 400, 6000));
|
||||
|
||||
return {
|
||||
timestamp: new Date(timestamp).toISOString(),
|
||||
data: {
|
||||
service_name: row.service,
|
||||
span_name: row.span,
|
||||
messaging_system: row.system,
|
||||
destination: row.destination,
|
||||
kind_string: row.kind,
|
||||
error_percentage: errorPercentage(index, failing),
|
||||
p95_latency: seeded(index, 80, 900),
|
||||
throughput: seeded(index, 5, 120),
|
||||
},
|
||||
};
|
||||
});
|
||||
return [
|
||||
row.service,
|
||||
row.span,
|
||||
isCelery ? null : row.system,
|
||||
isCelery ? null : row.destination,
|
||||
isCelery ? row.destination : null,
|
||||
row.kind,
|
||||
seeded(index, 80, 900) * NS_PER_MS,
|
||||
total,
|
||||
Math.round((total * errorPercentage(index, failing)) / 100),
|
||||
seeded(index, 5, 120),
|
||||
];
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
/**
|
||||
* The three tiles at the top of the detail panel are three `VALUE` requests that
|
||||
@@ -178,15 +213,7 @@ export const overviewValueResponse = (
|
||||
return null;
|
||||
}
|
||||
|
||||
const query = body.compositeQuery?.queries?.find(
|
||||
(envelope) =>
|
||||
envelope.type ===
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
);
|
||||
const spec =
|
||||
query?.type === Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
|
||||
? query.spec
|
||||
: undefined;
|
||||
const spec = builderSpec(body);
|
||||
|
||||
const isError = (spec?.filter?.expression ?? '').includes('has_error');
|
||||
const isLatency = (spec?.aggregations ?? []).some(
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import type { Querybuildertypesv5QueryRangeRequestDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { rest } from 'msw';
|
||||
import { MessagingQueueHealthCheckService } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
|
||||
import { choiceControl } from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
@@ -31,10 +31,10 @@ export const kafkaOverviewMocks = defineStoryMocks({
|
||||
},
|
||||
handlers: (values, response) => [
|
||||
rest.post(
|
||||
'http://localhost/api/v1/messaging-queues/kafka/onboarding/:service',
|
||||
response.json((req) =>
|
||||
'http://localhost/api/v5/query_range',
|
||||
response.json(async (req) =>
|
||||
onboardingStatusResponse(
|
||||
req.params.service as MessagingQueueHealthCheckService,
|
||||
(await req.json()) as Querybuildertypesv5QueryRangeRequestDTO,
|
||||
values.configuration,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -3,76 +3,68 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import type { OnboardingStatusResponse } from 'api/messagingQueues/onboarding/getOnboardingStatus';
|
||||
import { MessagingQueueHealthCheckService } from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
import {
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
type QueryRangeV5200,
|
||||
type Querybuildertypesv5QueryRangeRequestDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { queryRangeV5ScalarResultsResponse } from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
|
||||
export const CONFIGURATION_STATES = ['complete', 'partial', 'missing'] as const;
|
||||
|
||||
export type ConfigurationState = (typeof CONFIGURATION_STATES)[number];
|
||||
|
||||
/**
|
||||
* What each onboarding endpoint checks for. The page never reads the names, so
|
||||
* the only thing that matters is that they are the span attributes the kafka
|
||||
* instrumentation is supposed to emit.
|
||||
*/
|
||||
const CHECKED_ATTRIBUTES: Record<MessagingQueueHealthCheckService, string[]> = {
|
||||
[MessagingQueueHealthCheckService.Consumers]: [
|
||||
'messaging.system',
|
||||
'messaging.destination.name',
|
||||
'messaging.kafka.consumer.group',
|
||||
'messaging.kafka.message.offset',
|
||||
'messaging.destination.partition.id',
|
||||
'service.name',
|
||||
],
|
||||
[MessagingQueueHealthCheckService.Producers]: [
|
||||
'messaging.system',
|
||||
'messaging.destination.name',
|
||||
'messaging.destination.partition.id',
|
||||
'messaging.message.body.size',
|
||||
'service.name',
|
||||
],
|
||||
[MessagingQueueHealthCheckService.Kafka]: [
|
||||
'kafka.consumer_group.lag',
|
||||
'kafka.partition.current_offset',
|
||||
'kafka.partition.oldest_offset',
|
||||
'kafka.topic.partitions',
|
||||
'kafka.brokers',
|
||||
],
|
||||
};
|
||||
const SPANS_IN_RANGE = 1200;
|
||||
|
||||
/**
|
||||
* `'1'` is a checked attribute the backend saw, `'0'` one it did not: the
|
||||
* header button counts the zeroes and the checklist tree renders their
|
||||
* `error_message` behind the Fix link.
|
||||
* How many spans or metric points one check counts. A check passes on any
|
||||
* count above zero, so `partial` zeroes every third and `missing` all of them
|
||||
* while spans still arrive, which keeps the checklist rather than the no-data row.
|
||||
*/
|
||||
const attributeStatus = (
|
||||
state: ConfigurationState,
|
||||
index: number,
|
||||
): '0' | '1' => {
|
||||
const checkCount = (state: ConfigurationState, index: number): number => {
|
||||
if (state === 'complete') {
|
||||
return '1';
|
||||
return SPANS_IN_RANGE;
|
||||
}
|
||||
|
||||
if (state === 'missing') {
|
||||
return '0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
return index % 3 === 0 ? '0' : '1';
|
||||
return index % 3 === 0 ? 0 : SPANS_IN_RANGE;
|
||||
};
|
||||
|
||||
/**
|
||||
* Each health check group is one request: the span groups count every span and
|
||||
* then one count per check, the kafka group counts each metric in its own
|
||||
* query. The first aggregation of a span query is the total, never a check.
|
||||
*/
|
||||
export const onboardingStatusResponse = (
|
||||
service: MessagingQueueHealthCheckService,
|
||||
body: Querybuildertypesv5QueryRangeRequestDTO,
|
||||
state: ConfigurationState,
|
||||
): OnboardingStatusResponse => ({
|
||||
status: 'success',
|
||||
data: CHECKED_ATTRIBUTES[service].map((attribute, index) => {
|
||||
const status = attributeStatus(state, index);
|
||||
): QueryRangeV5200 => {
|
||||
let checkIndex = 0;
|
||||
|
||||
return {
|
||||
attribute,
|
||||
status,
|
||||
error_message:
|
||||
status === '0' ? `No span in the selected range carried ${attribute}.` : '',
|
||||
};
|
||||
}),
|
||||
});
|
||||
return queryRangeV5ScalarResultsResponse(
|
||||
(body.compositeQuery?.queries ?? []).flatMap((envelope) => {
|
||||
if (
|
||||
envelope.type !==
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const { spec } = envelope;
|
||||
const aggregations = spec?.aggregations?.length ?? 0;
|
||||
const isTotal = (index: number): boolean =>
|
||||
spec?.signal === 'traces' && !spec.filter && index === 0;
|
||||
const row = Array.from({ length: aggregations }, (_unused, index) => {
|
||||
if (isTotal(index)) {
|
||||
return SPANS_IN_RANGE;
|
||||
}
|
||||
const count = checkCount(state, checkIndex);
|
||||
checkIndex += 1;
|
||||
return count;
|
||||
});
|
||||
|
||||
return [{ queryName: spec?.name ?? '', aggregations, rows: [row] }];
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import type { MessagingQueuesPayloadProps } from 'api/messagingQueues/getConsumerLagDetails';
|
||||
import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';
|
||||
import type { AppState } from 'store/reducers';
|
||||
import type { Column } from 'types/api/widgets/getQuery';
|
||||
|
||||
export const RELATIVE_TIME: Time = '30m';
|
||||
|
||||
@@ -103,31 +101,6 @@ export const attributeValues = (
|
||||
searchText: string,
|
||||
): string[] => matching(ATTRIBUTE_VALUES[attributeKey] ?? [], searchText);
|
||||
|
||||
/**
|
||||
* The kafka detail tables all answer on this one shape: a single result whose
|
||||
* `table` carries the columns the page turns into headers and the rows it
|
||||
* renders. `isValueColumn` is what tells a metric column from a grouping one.
|
||||
*/
|
||||
export const kafkaTableResponse = (
|
||||
columnNames: string[],
|
||||
rows: Array<Record<string, string>>,
|
||||
valueColumns: string[] = [],
|
||||
): { status: string; data: MessagingQueuesPayloadProps['payload'] } => {
|
||||
const columns: Column[] = columnNames.map((name) => ({
|
||||
name,
|
||||
queryName: name,
|
||||
isValueColumn: valueColumns.includes(name),
|
||||
}));
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
data: {
|
||||
resultType: 'table',
|
||||
result: [{ table: { columns, rows: rows.map((data) => ({ data })) } }],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* A metric value derived from the row index rather than random, so a refetch
|
||||
* redraws the same table.
|
||||
|
||||
@@ -122,6 +122,47 @@ export const queryRangeV5ScalarTableResponse = ({
|
||||
};
|
||||
};
|
||||
|
||||
export interface ScalarQueryResult {
|
||||
queryName: string;
|
||||
/** Group-by columns, in the order each row carries their values. */
|
||||
groupBy?: string[];
|
||||
/** Aggregation columns after the group columns, in the query's order. */
|
||||
aggregations: number;
|
||||
rows: unknown[][];
|
||||
}
|
||||
|
||||
/**
|
||||
* A scalar answer with one result per query, each keyed by its `queryName`, the
|
||||
* way the backend answers a request that holds several queries.
|
||||
*/
|
||||
export const queryRangeV5ScalarResultsResponse = (
|
||||
results: ScalarQueryResult[],
|
||||
): QueryRangeV5200 => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
type: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
data: {
|
||||
results: results.map(({ queryName, groupBy = [], aggregations, rows }) => ({
|
||||
queryName,
|
||||
columns: [
|
||||
...groupBy.map((name) => ({
|
||||
name,
|
||||
queryName,
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.group,
|
||||
})),
|
||||
...Array.from({ length: aggregations }, (_unused, aggregationIndex) => ({
|
||||
name: `__result_${aggregationIndex}`,
|
||||
queryName,
|
||||
aggregationIndex,
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
|
||||
})),
|
||||
],
|
||||
data: rows,
|
||||
})),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const queryRangeV5EmptyResponse = (
|
||||
queryName = 'A',
|
||||
): MetricRangePayloadV5 => ({
|
||||
|
||||
Reference in New Issue
Block a user