Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

refactor: migrate External API's top 10 errors query_range request to v5 (#9476)

Shaheer Kochai287558dc9d3c
diff --git a/frontend/src/api/v5/queryRange/getQueryRange.ts b/frontend/src/api/v5/queryRange/getQueryRange.ts
index 35aa474e6c..82afa1e9ee 100644
--- a/frontend/src/api/v5/queryRange/getQueryRange.ts
+++ b/frontend/src/api/v5/queryRange/getQueryRange.ts
@@ -11,7 +11,7 @@ import {
export const getQueryRangeV5 = async (
props: QueryRangePayloadV5,
version: string,
- signal: AbortSignal,
+ signal?: AbortSignal,
headers?: Record<string, string>,
): Promise<SuccessResponseV2<MetricRangePayloadV5>> => {
try {
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx
index bc9c839e64..9bfd355e6c 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx
@@ -1,8 +1,10 @@
import { LoadingOutlined } from '@ant-design/icons';
import { Spin, Switch, Table, Tooltip, Typography } from 'antd';
+import { getQueryRangeV5 } from 'api/v5/queryRange/getQueryRange';
+import { MetricRangePayloadV5, ScalarData } from 'api/v5/v5';
import { useNavigateToExplorer } from 'components/CeleryTask/useNavigateToExplorer';
import { withErrorBoundary } from 'components/ErrorBoundaryHOC';
-import { DEFAULT_ENTITY_VERSION, ENTITY_VERSION_V4 } from 'constants/app';
+import { ENTITY_VERSION_V4, ENTITY_VERSION_V5 } from 'constants/app';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import {
END_POINT_DETAILS_QUERY_KEYS_ARRAY,
@@ -11,13 +13,12 @@ import {
getTopErrorsColumnsConfig,
getTopErrorsCoRelationQueryFilters,
getTopErrorsQueryPayload,
- TopErrorsResponseRow,
} from 'container/ApiMonitoring/utils';
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
import { Info } from 'lucide-react';
import { useMemo, useState } from 'react';
-import { useQueries } from 'react-query';
-import { SuccessResponse } from 'types/api';
+import { QueryFunctionContext, useQueries, useQuery } from 'react-query';
+import { SuccessResponse, SuccessResponseV2 } from 'types/api';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
@@ -46,7 +47,7 @@ function TopErrors({
true,
);
- const queryPayloads = useMemo(
+ const queryPayload = useMemo(
() =>
getTopErrorsQueryPayload(
domainName,
@@ -82,37 +83,34 @@ function TopErrors({
],
);
- const topErrorsDataQueries = useQueries(
- queryPayloads.map((payload) => ({
- queryKey: [
- REACT_QUERY_KEY.GET_TOP_ERRORS_BY_DOMAIN,
- payload,
- DEFAULT_ENTITY_VERSION,
- showStatusCodeErrors,
- ],
- queryFn: (): Promise<SuccessResponse<MetricRangePayloadProps>> =>
- GetMetricQueryRange(payload, DEFAULT_ENTITY_VERSION),
- enabled: !!payload,
- staleTime: 0,
- cacheTime: 0,
- })),
- );
-
- const topErrorsDataQuery = topErrorsDataQueries[0];
const {
data: topErrorsData,
isLoading,
isRefetching,
isError,
refetch,
- } = topErrorsDataQuery;
+ } = useQuery({
+ queryKey: [
+ REACT_QUERY_KEY.GET_TOP_ERRORS_BY_DOMAIN,
+ queryPayload,
+ ENTITY_VERSION_V5,
+ showStatusCodeErrors,
+ ],
+ queryFn: ({
+ signal,
+ }: QueryFunctionContext): Promise<SuccessResponseV2<MetricRangePayloadV5>> =>
+ getQueryRangeV5(queryPayload, ENTITY_VERSION_V5, signal),
+ enabled: !!queryPayload,
+ staleTime: 0,
+ cacheTime: 0,
+ });
const topErrorsColumnsConfig = useMemo(() => getTopErrorsColumnsConfig(), []);
const formattedTopErrorsData = useMemo(
() =>
formatTopErrorsDataForTable(
- topErrorsData?.payload?.data?.result as TopErrorsResponseRow[],
+ topErrorsData?.data?.data?.data?.results[0] as ScalarData,
),
[topErrorsData],
);
diff --git a/frontend/src/container/ApiMonitoring/__tests__/APIMonitoringUtils.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/APIMonitoringUtils.test.tsx
index e2507282bc..2afb0f2e81 100644
--- a/frontend/src/container/ApiMonitoring/__tests__/APIMonitoringUtils.test.tsx
+++ b/frontend/src/container/ApiMonitoring/__tests__/APIMonitoringUtils.test.tsx
@@ -8,7 +8,6 @@ import {
endPointStatusCodeColumns,
extractPortAndEndpoint,
formatDataForTable,
- formatTopErrorsDataForTable,
getAllEndpointsWidgetData,
getCustomFiltersForBarChart,
getEndPointDetailsQueryPayload,
@@ -23,8 +22,6 @@ import {
getStatusCodeBarChartWidgetData,
getTopErrorsColumnsConfig,
getTopErrorsCoRelationQueryFilters,
- getTopErrorsQueryPayload,
- TopErrorsResponseRow,
} from '../utils';
import { APIMonitoringColumnsMock } from './mock';
@@ -344,49 +341,6 @@ describe('API Monitoring Utils', () => {
});
});
- describe('formatTopErrorsDataForTable', () => {
- it('should format top errors data correctly', () => {
- // Arrange
- const inputData = [
- {
- metric: {
- [SPAN_ATTRIBUTES.URL_PATH]: '/api/test',
- [SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE]: '500',
- status_message: 'Internal Server Error',
- },
- values: [[1000000100, '10']],
- queryName: 'A',
- legend: 'Test Legend',
- },
- ];
-
- // Act
- const result = formatTopErrorsDataForTable(
- inputData as TopErrorsResponseRow[],
- );
-
- // Assert
- expect(result).toBeDefined();
- expect(result.length).toBe(1);
-
- // Check first item is formatted correctly
- expect(result[0].endpointName).toBe('/api/test');
- expect(result[0].statusCode).toBe('500');
- expect(result[0].statusMessage).toBe('Internal Server Error');
- expect(result[0].count).toBe('10');
- expect(result[0].key).toBeDefined();
- });
-
- it('should handle empty input', () => {
- // Act
- const result = formatTopErrorsDataForTable(undefined);
-
- // Assert
- expect(result).toBeDefined();
- expect(result).toEqual([]);
- });
- });
-
describe('getTopErrorsColumnsConfig', () => {
it('should return column configuration with expected fields', () => {
// Act
@@ -453,72 +407,6 @@ describe('API Monitoring Utils', () => {
});
});
- describe('getTopErrorsQueryPayload', () => {
- it('should create correct query payload with filters', () => {
- // Arrange
- const domainName = 'test-domain';
- const start = 1000000000;
- const end = 1000010000;
- const filters = {
- items: [
- {
- id: 'test-filter',
- key: {
- dataType: DataTypes.String,
- key: 'test-key',
- type: '',
- },
- op: '=',
- value: 'test-value',
- },
- ],
- op: 'AND',
- };
-
- // Act
- const result = getTopErrorsQueryPayload(
- domainName,
- start,
- end,
- filters as IBuilderQuery['filters'],
- );
-
- // Assert
- expect(result).toBeDefined();
- expect(result.length).toBeGreaterThan(0);
-
- // Verify query params
- expect(result[0].start).toBe(start);
- expect(result[0].end).toBe(end);
-
- // Verify correct structure
- expect(result[0].graphType).toBeDefined();
- expect(result[0].query).toBeDefined();
- expect(result[0].query.builder).toBeDefined();
- expect(result[0].query.builder.queryData).toBeDefined();
-
- // Verify domain filter is included
- const queryData = result[0].query.builder.queryData[0];
- expect(queryData.filters).toBeDefined();
-
- // Check for domain filter
- const domainFilter = queryData.filters?.items?.find(
- // eslint-disable-next-line sonarjs/no-identical-functions
- (item) =>
- item.key &&
- item.key.key === SPAN_ATTRIBUTES.SERVER_NAME &&
- item.value === domainName,
- );
- expect(domainFilter).toBeDefined();
-
- // Check that custom filters were included
- const testFilter = queryData.filters?.items?.find(
- (item) => item.id === 'test-filter',
- );
- expect(testFilter).toBeDefined();
- });
- });
-
// Add new tests for EndPointDetails utility functions
describe('extractPortAndEndpoint', () => {
it('should extract port and endpoint from a valid URL', () => {
diff --git a/frontend/src/container/ApiMonitoring/__tests__/TopErrors.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/TopErrors.test.tsx
index 5150cd319f..def3b589be 100644
--- a/frontend/src/container/ApiMonitoring/__tests__/TopErrors.test.tsx
+++ b/frontend/src/container/ApiMonitoring/__tests__/TopErrors.test.tsx
@@ -1,14 +1,6 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
import { useNavigateToExplorer } from 'components/CeleryTask/useNavigateToExplorer';
-import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import {
- formatTopErrorsDataForTable,
- getEndPointDetailsQueryPayload,
- getTopErrorsColumnsConfig,
- getTopErrorsCoRelationQueryFilters,
- getTopErrorsQueryPayload,
-} from 'container/ApiMonitoring/utils';
-import { useQueries } from 'react-query';
+import { rest, server } from 'mocks-server/server';
+import { fireEvent, render, screen, waitFor, within } from 'tests/test-utils';
import { DataSource } from 'types/common/queryBuilder';
import TopErrors from '../Explorer/Domains/DomainDetails/TopErrors';
@@ -35,28 +27,15 @@ jest.mock(
}),
);
-// Mock dependencies
-jest.mock('react-query', () => ({
- ...jest.requireActual('react-query'),
- useQueries: jest.fn(),
-}));
-
jest.mock('components/CeleryTask/useNavigateToExplorer', () => ({
useNavigateToExplorer: jest.fn(),
}));
-jest.mock('container/ApiMonitoring/utils', () => ({
- END_POINT_DETAILS_QUERY_KEYS_ARRAY: ['key1', 'key2', 'key3', 'key4', 'key5'],
- formatTopErrorsDataForTable: jest.fn(),
- getEndPointDetailsQueryPayload: jest.fn(),
- getTopErrorsColumnsConfig: jest.fn(),
- getTopErrorsCoRelationQueryFilters: jest.fn(),
- getTopErrorsQueryPayload: jest.fn(),
-}));
-
describe('TopErrors', () => {
+ const TABLE_BODY_SELECTOR = '.ant-table-tbody';
+ const V5_QUERY_RANGE_API_PATH = '*/api/v5/query_range';
+
const mockProps = {
- // eslint-disable-next-line sonarjs/no-duplicate-string
domainName: 'test-domain',
timeRange: {
startTime: 1000000000,
@@ -68,75 +47,72 @@ describe('TopErrors', () => {
},
};
- // Setup basic mocks
+ // Helper function to wait for table data to load
+ const waitForTableDataToLoad = async (
+ container: HTMLElement,
+ ): Promise<void> => {
+ await waitFor(() => {
+ const tableBody = container.querySelector(TABLE_BODY_SELECTOR);
+ expect(tableBody).not.toBeNull();
+ if (tableBody) {
+ expect(
+ within(tableBody as HTMLElement).queryByText('/api/test'),
+ ).toBeInTheDocument();
+ }
+ });
+ };
+
beforeEach(() => {
jest.clearAllMocks();
- // Mock getTopErrorsColumnsConfig
- (getTopErrorsColumnsConfig as jest.Mock).mockReturnValue([
- {
- title: 'Endpoint',
- dataIndex: 'endpointName',
- key: 'endpointName',
- },
- {
- title: 'Status Code',
- dataIndex: 'statusCode',
- key: 'statusCode',
- },
- {
- title: 'Status Message',
- dataIndex: 'statusMessage',
- key: 'statusMessage',
- },
- {
- title: 'Count',
- dataIndex: 'count',
- key: 'count',
- },
- ]);
-
- // Mock useQueries
- (useQueries as jest.Mock).mockImplementation((queryConfigs) => {
- // For topErrorsDataQueries
- if (
- queryConfigs.length === 1 &&
- queryConfigs[0].queryKey &&
- queryConfigs[0].queryKey[0] === REACT_QUERY_KEY.GET_TOP_ERRORS_BY_DOMAIN
- ) {
- return [
- {
+ // Mock useNavigateToExplorer
+ (useNavigateToExplorer as jest.Mock).mockReturnValue(jest.fn());
+
+ // Mock V5 API endpoint for top errors
+ server.use(
+ rest.post(V5_QUERY_RANGE_API_PATH, (_req, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({
data: {
- payload: {
- data: {
- result: [
- {
- metric: {
- 'http.url': '/api/test',
- status_code: '500',
- // eslint-disable-next-line sonarjs/no-duplicate-string
- status_message: 'Internal Server Error',
+ data: {
+ results: [
+ {
+ columns: [
+ {
+ name: 'http.url',
+ fieldDataType: 'string',
+ fieldContext: 'attribute',
},
- values: [[1000000100, '10']],
- queryName: 'A',
- legend: 'Test Legend',
- },
- ],
- },
+ {
+ name: 'response_status_code',
+ fieldDataType: 'string',
+ fieldContext: 'span',
+ },
+ {
+ name: 'status_message',
+ fieldDataType: 'string',
+ fieldContext: 'span',
+ },
+ { name: 'count()', fieldDataType: 'int64', fieldContext: '' },
+ ],
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ data: [['/api/test', '500', 'Internal Server Error', 10]],
+ },
+ ],
},
},
- isLoading: false,
- isRefetching: false,
- isError: false,
- refetch: jest.fn(),
- },
- ];
- }
+ }),
+ ),
+ ),
+ );
- // For endPointDropDownDataQueries
- return [
- {
- data: {
+ // Mock V4 API endpoint for dropdown data
+ server.use(
+ rest.post('*/api/v1/query_range', (_req, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({
payload: {
data: {
result: [
@@ -153,62 +129,13 @@ describe('TopErrors', () => {
],
},
},
- },
- isLoading: false,
- isRefetching: false,
- isError: false,
- },
- ];
- });
-
- // Mock formatTopErrorsDataForTable
- (formatTopErrorsDataForTable as jest.Mock).mockReturnValue([
- {
- key: '1',
- endpointName: '/api/test',
- statusCode: '500',
- statusMessage: 'Internal Server Error',
- count: 10,
- },
- ]);
-
- // Mock getTopErrorsQueryPayload
- (getTopErrorsQueryPayload as jest.Mock).mockReturnValue([
- {
- queryName: 'TopErrorsQuery',
- start: mockProps.timeRange.startTime,
- end: mockProps.timeRange.endTime,
- step: 60,
- },
- ]);
-
- // Mock getEndPointDetailsQueryPayload
- (getEndPointDetailsQueryPayload as jest.Mock).mockReturnValue([
- {},
- {},
- {
- queryName: 'EndpointDropdownQuery',
- start: mockProps.timeRange.startTime,
- end: mockProps.timeRange.endTime,
- step: 60,
- },
- ]);
-
- // Mock useNavigateToExplorer
- (useNavigateToExplorer as jest.Mock).mockReturnValue(jest.fn());
-
- // Mock getTopErrorsCoRelationQueryFilters
- (getTopErrorsCoRelationQueryFilters as jest.Mock).mockReturnValue({
- items: [
- { id: 'test1', key: { key: 'domain' }, op: '=', value: 'test-domain' },
- { id: 'test2', key: { key: 'endpoint' }, op: '=', value: '/api/test' },
- { id: 'test3', key: { key: 'status' }, op: '=', value: '500' },
- ],
- op: 'AND',
- });
+ }),
+ ),
+ ),
+ );
});
- it('renders component correctly', () => {
+ it('renders component correctly', async () => {
// eslint-disable-next-line react/jsx-props-no-spreading
const { container } = render(<TopErrors {...mockProps} />);
@@ -216,10 +143,11 @@ describe('TopErrors', () => {
expect(screen.getByText('Errors with Status Message')).toBeInTheDocument();
expect(screen.getByText('Status Message Exists')).toBeInTheDocument();
- // Find the table row and verify content
- const tableBody = container.querySelector('.ant-table-tbody');
- expect(tableBody).not.toBeNull();
+ // Wait for data to load
+ await waitForTableDataToLoad(container);
+ // Find the table row and verify content
+ const tableBody = container.querySelector(TABLE_BODY_SELECTOR);
if (tableBody) {
const row = within(tableBody as HTMLElement).getByRole('row');
expect(within(row).getByText('/api/test')).toBeInTheDocument();
@@ -228,35 +156,40 @@ describe('TopErrors', () => {
}
});
- it('renders error state when isError is true', () => {
- // Mock useQueries to return isError: true
- (useQueries as jest.Mock).mockImplementationOnce(() => [
- {
- isError: true,
- refetch: jest.fn(),
- },
- ]);
+ it('renders error state when API fails', async () => {
+ // Mock API to return error
+ server.use(
+ rest.post(V5_QUERY_RANGE_API_PATH, (_req, res, ctx) =>
+ res(ctx.status(500), ctx.json({ error: 'Internal Server Error' })),
+ ),
+ );
// eslint-disable-next-line react/jsx-props-no-spreading
render(<TopErrors {...mockProps} />);
- // Error state should be shown with the actual text displayed in the UI
- expect(
- screen.getByText('Uh-oh :/ We ran into an error.'),
- ).toBeInTheDocument();
+ // Wait for error state
+ await waitFor(() => {
+ expect(
+ screen.getByText('Uh-oh :/ We ran into an error.'),
+ ).toBeInTheDocument();
+ });
+
expect(screen.getByText('Please refresh this panel.')).toBeInTheDocument();
expect(screen.getByText('Refresh this panel')).toBeInTheDocument();
});
- it('handles row click correctly', () => {
+ it('handles row click correctly', async () => {
const navigateMock = jest.fn();
(useNavigateToExplorer as jest.Mock).mockReturnValue(navigateMock);
// eslint-disable-next-line react/jsx-props-no-spreading
const { container } = render(<TopErrors {...mockProps} />);
+ // Wait for data to load
+ await waitForTableDataToLoad(container);
+
// Find and click on the table cell containing the endpoint
- const tableBody = container.querySelector('.ant-table-tbody');
+ const tableBody = container.querySelector(TABLE_BODY_SELECTOR);
expect(tableBody).not.toBeNull();
if (tableBody) {
@@ -267,11 +200,28 @@ describe('TopErrors', () => {
// Check if navigateToExplorer was called with correct params
expect(navigateMock).toHaveBeenCalledWith({
- filters: [
- { id: 'test1', key: { key: 'domain' }, op: '=', value: 'test-domain' },
- { id: 'test2', key: { key: 'endpoint' }, op: '=', value: '/api/test' },
- { id: 'test3', key: { key: 'status' }, op: '=', value: '500' },
- ],
+ filters: expect.arrayContaining([
+ expect.objectContaining({
+ key: expect.objectContaining({ key: 'http.url' }),
+ op: '=',
+ value: '/api/test',
+ }),
+ expect.objectContaining({
+ key: expect.objectContaining({ key: 'has_error' }),
+ op: '=',
+ value: 'true',
+ }),
+ expect.objectContaining({
+ key: expect.objectContaining({ key: 'net.peer.name' }),
+ op: '=',
+ value: 'test-domain',
+ }),
+ expect.objectContaining({
+ key: expect.objectContaining({ key: 'response_status_code' }),
+ op: '=',
+ value: '500',
+ }),
+ ]),
dataSource: DataSource.TRACES,
startTime: mockProps.timeRange.startTime,
endTime: mockProps.timeRange.endTime,
@@ -279,24 +229,34 @@ describe('TopErrors', () => {
});
});
- it('updates endpoint filter when dropdown value changes', () => {
+ it('updates endpoint filter when dropdown value changes', async () => {
// eslint-disable-next-line react/jsx-props-no-spreading
render(<TopErrors {...mockProps} />);
+ // Wait for initial load
+ await waitFor(() => {
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ });
+
// Find the dropdown
const dropdown = screen.getByRole('combobox');
// Mock the change
fireEvent.change(dropdown, { target: { value: '/api/new-endpoint' } });
- // Check if getTopErrorsQueryPayload was called with updated parameters
- expect(getTopErrorsQueryPayload).toHaveBeenCalled();
+ // Component should re-render with new filter
+ expect(dropdown).toBeInTheDocument();
});
- it('handles status message toggle correctly', () => {
+ it('handles status message toggle correctly', async () => {
// eslint-disable-next-line react/jsx-props-no-spreading
render(<TopErrors {...mockProps} />);
+ // Wait for initial load
+ await waitFor(() => {
+ expect(screen.getByRole('switch')).toBeInTheDocument();
+ });
+
// Find the toggle switch
const toggle = screen.getByRole('switch');
expect(toggle).toBeInTheDocument();
@@ -307,69 +267,104 @@ describe('TopErrors', () => {
// Click the toggle to turn it off
fireEvent.click(toggle);
- // Check if getTopErrorsQueryPayload was called with showStatusCodeErrors=false
- expect(getTopErrorsQueryPayload).toHaveBeenCalledWith(
- mockProps.domainName,
- mockProps.timeRange.startTime,
- mockProps.timeRange.endTime,
- expect.any(Object),
- false,
- );
-
// Title should change
- expect(screen.getByText('All Errors')).toBeInTheDocument();
+ await waitFor(() => {
+ expect(screen.getByText('All Errors')).toBeInTheDocument();
+ });
// Click the toggle to turn it back on
fireEvent.click(toggle);
- // Check if getTopErrorsQueryPayload was called with showStatusCodeErrors=true
- expect(getTopErrorsQueryPayload).toHaveBeenCalledWith(
- mockProps.domainName,
- mockProps.timeRange.startTime,
- mockProps.timeRange.endTime,
- expect.any(Object),
- true,
- );
-
// Title should change back
- expect(screen.getByText('Errors with Status Message')).toBeInTheDocument();
+ await waitFor(() => {
+ expect(screen.getByText('Errors with Status Message')).toBeInTheDocument();
+ });
});
- it('includes toggle state in query key for cache busting', () => {
+ it('includes toggle state in query key for cache busting', async () => {
// eslint-disable-next-line react/jsx-props-no-spreading
render(<TopErrors {...mockProps} />);
- const toggle = screen.getByRole('switch');
+ // Wait for initial load
+ await waitFor(() => {
+ expect(screen.getByRole('switch')).toBeInTheDocument();
+ });
- // Initial query should include showStatusCodeErrors=true
- expect(useQueries).toHaveBeenCalledWith(
- expect.arrayContaining([
- expect.objectContaining({
- queryKey: expect.arrayContaining([
- REACT_QUERY_KEY.GET_TOP_ERRORS_BY_DOMAIN,
- expect.any(Object),
- expect.any(String),
- true,
- ]),
- }),
- ]),
- );
+ const toggle = screen.getByRole('switch');
// Click toggle
fireEvent.click(toggle);
- // Query should be called with showStatusCodeErrors=false in key
- expect(useQueries).toHaveBeenCalledWith(
- expect.arrayContaining([
- expect.objectContaining({
- queryKey: expect.arrayContaining([
- REACT_QUERY_KEY.GET_TOP_ERRORS_BY_DOMAIN,
- expect.any(Object),
- expect.any(String),
- false,
- ]),
- }),
- ]),
+ // Wait for title to change, indicating query was refetched with new key
+ await waitFor(() => {
+ expect(screen.getByText('All Errors')).toBeInTheDocument();
+ });
+
+ // The fact that data refetches when toggle changes proves the query key includes the toggle state
+ expect(toggle).toBeInTheDocument();
+ });
+
+ it('sends query_range v5 API call with required filters including has_error', async () => {
+ let capturedRequest: any;
+
+ // Override the v5 API mock to capture the request
+ server.use(
+ rest.post(V5_QUERY_RANGE_API_PATH, async (req, res, ctx) => {
+ capturedRequest = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json({
+ data: {
+ data: {
+ results: [
+ {
+ columns: [
+ {
+ name: 'http.url',
+ fieldDataType: 'string',
+ fieldContext: 'attribute',
+ },
+ {
+ name: 'response_status_code',
+ fieldDataType: 'string',
+ fieldContext: 'span',
+ },
+ {
+ name: 'status_message',
+ fieldDataType: 'string',
+ fieldContext: 'span',
+ },
+ { name: 'count()', fieldDataType: 'int64', fieldContext: '' },
+ ],
+ data: [['/api/test', '500', 'Internal Server Error', 10]],
+ },
+ ],
+ },
+ },
+ }),
+ );
+ }),
+ );
+
+ // eslint-disable-next-line react/jsx-props-no-spreading
+ render(<TopErrors {...mockProps} />);
+
+ // Wait for the API call to be made
+ await waitFor(() => {
+ expect(capturedRequest).toBeDefined();
+ });
+
+ // Extract the filter expression from the captured request
+ const filterExpression =
+ capturedRequest.compositeQuery.queries[0].spec.filter.expression;
+
+ // Verify all required filters are present
+ expect(filterExpression).toContain(`kind_string = 'Client'`);
+ expect(filterExpression).toContain(`(http.url EXISTS OR url.full EXISTS)`);
+ expect(filterExpression).toContain(
+ `(net.peer.name = 'test-domain' OR server.address = 'test-domain')`,
);
+ expect(filterExpression).toContain(`has_error = true`);
+ expect(filterExpression).toContain(`status_message EXISTS`); // toggle is on by default
});
});
diff --git a/frontend/src/container/ApiMonitoring/utils.tsx b/frontend/src/container/ApiMonitoring/utils.tsx
index 136dc937f1..565094246a 100644
--- a/frontend/src/container/ApiMonitoring/utils.tsx
+++ b/frontend/src/container/ApiMonitoring/utils.tsx
@@ -2,6 +2,7 @@
import { Color } from '@signozhq/design-tokens';
import { Progress, Tag, Tooltip } from 'antd';
import { ColumnType } from 'antd/es/table';
+import { convertFiltersToExpressionWithExistingQuery } from 'components/QueryBuilderV2/utils';
import {
FiltersType,
IQuickFiltersConfig,
@@ -27,6 +28,11 @@ import {
OrderByPayload,
TagFilterItem,
} from 'types/api/queryBuilder/queryBuilderData';
+import {
+ ColumnDescriptor,
+ QueryRangePayloadV5,
+ ScalarData,
+} from 'types/api/v5/queryRange';
import { QueryData } from 'types/api/widgets/getQuery';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
@@ -40,6 +46,9 @@ import {
EndPointsResponseRow,
} from './types';
+export const isEmptyFilterValue = (value: unknown): boolean =>
+ value === '' || value === null || value === undefined || value === 'n/a';
+
export const ApiMonitoringQuickFiltersConfig: IQuickFiltersConfig[] = [
{
type: FiltersType.CHECKBOX,
@@ -816,153 +825,100 @@ export const getEndPointsQueryPayload = (
];
};
+// eslint-disable-next-line sonarjs/cognitive-complexity
+function buildFilterExpression(
+ domainName: string,
+ filters: IBuilderQuery['filters'],
+ showStatusCodeErrors: boolean,
+): string {
+ const baseFilterParts = [
+ `kind_string = 'Client'`,
+ `(http.url EXISTS OR url.full EXISTS)`,
+ `(net.peer.name = '${domainName}' OR server.address = '${domainName}')`,
+ `has_error = true`,
+ ];
+ if (showStatusCodeErrors) {
+ baseFilterParts.push('status_message EXISTS');
+ }
+ const filterExpression = baseFilterParts.join(' AND ');
+ if (!filters) {
+ return filterExpression;
+ }
+ const { filter } = convertFiltersToExpressionWithExistingQuery(
+ filters,
+ filterExpression,
+ );
+ return filter.expression;
+}
+
export const getTopErrorsQueryPayload = (
domainName: string,
start: number,
end: number,
filters: IBuilderQuery['filters'],
showStatusCodeErrors = true,
-): GetQueryResultsProps[] => [
- {
- selectedTime: 'GLOBAL_TIME',
- graphType: PANEL_TYPES.TABLE,
- query: {
- builder: {
- queryData: [
- {
- dataSource: DataSource.TRACES,
- queryName: 'A',
- aggregateOperator: 'count',
- aggregateAttribute: {
- id: '------false',
- dataType: DataTypes.String,
- key: '',
- type: '',
- },
- timeAggregation: 'rate',
- spaceAggregation: 'sum',
- functions: [],
- filters: {
- op: 'AND',
- items: [
- {
- id: '04da97bd',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- {
- id: 'b1af6bdb',
- key: {
- key: SPAN_ATTRIBUTES.URL_PATH,
- dataType: DataTypes.String,
- type: 'tag',
- },
- op: 'exists',
- value: '',
- },
- ...(showStatusCodeErrors
- ? [
- {
- id: '75d65388',
- key: {
- key: 'status_message',
- dataType: DataTypes.String,
- type: '',
- },
- op: 'exists',
- value: '',
- },
- ]
- : []),
- {
- id: '4872bf91',
- key: {
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- dataType: DataTypes.String,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: 'ab4c885d',
- key: {
- key: 'has_error',
- dataType: DataTypes.bool,
- type: '',
- },
- op: '=',
- value: true,
- },
- ...(filters?.items || []),
- ],
- },
- expression: 'A',
- disabled: false,
+): QueryRangePayloadV5 => {
+ const filterExpression = buildFilterExpression(
+ domainName,
+ filters,
+ showStatusCodeErrors,
+ );
+
+ return {
+ schemaVersion: 'v1',
+ start,
+ end,
+ requestType: 'scalar',
+ compositeQuery: {
+ queries: [
+ {
+ type: 'builder_query',
+ spec: {
+ name: 'A',
+ signal: 'traces',
stepInterval: 60,
- having: [],
- limit: 10,
- orderBy: [
+ disabled: false,
+ aggregations: [{ expression: 'count()' }],
+ filter: { expression: filterExpression },
+ groupBy: [
{
- columnName: 'timestamp',
- order: 'desc',
+ name: 'http.url',
+ fieldDataType: 'string',
+ fieldContext: 'attribute',
},
- ],
- groupBy: [
{
- key: SPAN_ATTRIBUTES.URL_PATH,
- dataType: DataTypes.String,
- type: 'tag',
+ name: 'url.full',
+ fieldDataType: 'string',
+ fieldContext: 'attribute',
},
{
- dataType: DataTypes.String,
- key: 'response_status_code',
- type: '',
- id: 'response_status_code--string----true',
+ name: 'response_status_code',
+ fieldDataType: 'string',
+ fieldContext: 'span',
},
{
- key: 'status_message',
- dataType: DataTypes.String,
- type: '',
+ name: 'status_message',
+ fieldDataType: 'string',
+ fieldContext: 'span',
+ },
+ ],
+ limit: 10,
+ order: [
+ {
+ key: {
+ name: 'count()',
+ },
+ direction: 'desc',
},
],
- legend: '',
- reduceTo: 'avg',
},
- ],
- queryFormulas: [],
- queryTraceOperator: [],
- },
- clickhouse_sql: [
- {
- disabled: false,
- legend: '',
- name: 'A',
- query: '',
- },
- ],
- id: '315b15fa-ff0c-442f-89f8-2bf4fb1af2f2',
- promql: [
- {
- disabled: false,
- legend: '',
- name: 'A',
- query: '',
},
],
- queryType: EQueryType.QUERY_BUILDER,
},
+ formatOptions: { formatTableResultForUI: true, fillGaps: false },
variables: {},
- start,
- end,
- step: 240,
- },
-];
+ };
+};
export interface EndPointsTableRowData {
key: string;
@@ -1242,63 +1198,55 @@ export const formatEndPointsDataForTable = (
return formattedData;
};
-export interface TopErrorsResponseRow {
- metric: {
- [SPAN_ATTRIBUTES.URL_PATH]: string;
- [SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE]: string;
- status_message: string;
- };
- values: [number, string][];
- queryName: string;
- legend: string;
-}
+export type TopErrorsResponseRow = ScalarData;
export interface TopErrorsTableRowData {
key: string;
endpointName: string;
statusCode: string;
statusMessage: string;
- count: number | string;
+ count: string;
+}
+
+/**
+ * Returns '-' if value is empty, otherwise returns value as string
+ */
+export function getDisplayValue(value: unknown): string {
+ return isEmptyFilterValue(value) ? '-' : String(value);
}
export const formatTopErrorsDataForTable = (
- data: TopErrorsResponseRow[] | undefined,
+ scalarResult: TopErrorsResponseRow | undefined,
): TopErrorsTableRowData[] => {
- if (!data) return [];
+ if (!scalarResult?.data) return [];
- return data.map((row) => ({
- key: v4(),
- endpointName:
- row.metric[SPAN_ATTRIBUTES.URL_PATH] === 'n/a' ||
- row.metric[SPAN_ATTRIBUTES.URL_PATH] === undefined
- ? '-'
- : row.metric[SPAN_ATTRIBUTES.URL_PATH],
- statusCode:
- row.metric[SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE] === 'n/a' ||
- row.metric[SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE] === undefined
- ? '-'
- : row.metric[SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE],
- statusMessage:
- row.metric.status_message === 'n/a' ||
- row.metric.status_message === undefined
- ? '-'
- : row.metric.status_message,
- count:
- row.values &&
- row.values[0] &&
- row.values[0][1] !== undefined &&
- row.values[0][1] !== 'n/a'
- ? row.values[0][1]
- : '-',
- }));
+ const columns = scalarResult.columns || [];
+ const rows = scalarResult.data || [];
+
+ return rows.map((rowData: unknown[]) => {
+ const rowObj: Record<string, unknown> = {};
+ columns.forEach((col: ColumnDescriptor, index: number) => {
+ rowObj[col.name] = rowData[index];
+ });
+
+ return {
+ key: v4(),
+ endpointName: getDisplayValue(
+ rowObj[SPAN_ATTRIBUTES.URL_PATH] || rowObj['url.full'],
+ ),
+ statusCode: getDisplayValue(rowObj[SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE]),
+ statusMessage: getDisplayValue(rowObj.status_message),
+ count: getDisplayValue(rowObj.__result_0),
+ };
+ });
};
export const getTopErrorsCoRelationQueryFilters = (
domainName: string,
endPointName: string,
statusCode: string,
-): IBuilderQuery['filters'] => ({
- items: [
+): IBuilderQuery['filters'] => {
+ const items: TagFilterItem[] = [
{
id: 'ea16470b',
key: {
@@ -1330,7 +1278,10 @@ export const getTopErrorsCoRelationQueryFilters = (
op: '=',
value: domainName,
},
- {
+ ];
+
+ if (statusCode !== '-') {
+ items.push({
id: 'f6891e27',
key: {
key: 'response_status_code',
@@ -1340,10 +1291,14 @@ export const getTopErrorsCoRelationQueryFilters = (
},
op: '=',
value: statusCode,
- },
- ],
- op: 'AND',
-});
+ });
+ }
+
+ return {
+ items,
+ op: 'AND',
+ };
+};
export const getTopErrorsColumnsConfig = (): ColumnType<TopErrorsTableRowData>[] => [
{