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: external apis query range v5 migration (#9550)

Shaheer Kochai3763794531c6
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/AllEndPoints.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/AllEndPoints.tsx
index 926ed8aef0..94bc416a68 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/AllEndPoints.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/AllEndPoints.tsx
@@ -1,4 +1,5 @@
import { Select } from 'antd';
+import { ENTITY_VERSION_V5 } from 'constants/app';
import { initialQueriesMap } from 'constants/queryBuilder';
import {
getAllEndpointsWidgetData,
@@ -264,6 +265,7 @@ function AllEndPoints({
customOnDragSelect={(): void => {}}
customTimeRange={timeRange}
customOnRowClick={onRowClick}
+ version={ENTITY_VERSION_V5}
/>
</div>
</div>
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/EndPointDetails.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/EndPointDetails.tsx
index fc56856209..acf928d06d 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/EndPointDetails.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/EndPointDetails.tsx
@@ -179,7 +179,14 @@ function EndPointDetails({
[domainName, filters, minTime, maxTime],
);
- const V5_QUERIES = [REACT_QUERY_KEY.GET_ENDPOINT_STATUS_CODE_DATA] as const;
+ const V5_QUERIES = [
+ REACT_QUERY_KEY.GET_ENDPOINT_STATUS_CODE_DATA,
+ REACT_QUERY_KEY.GET_ENDPOINT_STATUS_CODE_BAR_CHARTS_DATA,
+ REACT_QUERY_KEY.GET_ENDPOINT_STATUS_CODE_LATENCY_BAR_CHARTS_DATA,
+ REACT_QUERY_KEY.GET_ENDPOINT_METRICS_DATA,
+ REACT_QUERY_KEY.GET_ENDPOINT_DEPENDENT_SERVICES_DATA,
+ REACT_QUERY_KEY.GET_ENDPOINT_DROPDOWN_DATA,
+ ] as const;
const endPointDetailsDataQueries = useQueries(
endPointDetailsQueryPayload.map((payload, index) => {
@@ -191,7 +198,7 @@ function EndPointDetails({
queryKey: [
END_POINT_DETAILS_QUERY_KEYS_ARRAY[index],
payload,
- filters?.items, // Include filters.items in queryKey for better caching
+ ...(filters?.items?.length ? filters.items : []), // Include filters.items in queryKey for better caching
version,
],
queryFn: (): Promise<SuccessResponse<MetricRangePayloadProps>> =>
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx
index 9bfd355e6c..51ac767403 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx
@@ -4,7 +4,7 @@ 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 { ENTITY_VERSION_V4, ENTITY_VERSION_V5 } from 'constants/app';
+import { ENTITY_VERSION_V5 } from 'constants/app';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import {
END_POINT_DETAILS_QUERY_KEYS_ARRAY,
@@ -56,6 +56,10 @@ function TopErrors({
{
items: endPointName
? [
+ // Remove any existing http.url filters from initialFilters to avoid duplicates
+ ...(initialFilters?.items?.filter(
+ (item) => item.key?.key !== SPAN_ATTRIBUTES.URL_PATH,
+ ) || []),
{
id: '92b8a1c1',
key: {
@@ -66,7 +70,6 @@ function TopErrors({
op: '=',
value: endPointName,
},
- ...(initialFilters?.items || []),
]
: [...(initialFilters?.items || [])],
op: 'AND',
@@ -128,12 +131,12 @@ function TopErrors({
const endPointDropDownDataQueries = useQueries(
endPointDropDownQueryPayload.map((payload) => ({
queryKey: [
- END_POINT_DETAILS_QUERY_KEYS_ARRAY[4],
+ END_POINT_DETAILS_QUERY_KEYS_ARRAY[2],
payload,
- ENTITY_VERSION_V4,
+ ENTITY_VERSION_V5,
],
queryFn: (): Promise<SuccessResponse<MetricRangePayloadProps>> =>
- GetMetricQueryRange(payload, ENTITY_VERSION_V4),
+ GetMetricQueryRange(payload, ENTITY_VERSION_V5),
enabled: !!payload,
staleTime: 60 * 1000,
})),
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.test.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.test.tsx
new file mode 100644
index 0000000000..6e07ff40bc
--- /dev/null
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.test.tsx
@@ -0,0 +1,337 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/* eslint-disable react/jsx-props-no-spreading */
+/* eslint-disable prefer-destructuring */
+/* eslint-disable sonarjs/no-duplicate-string */
+import { render, screen, waitFor } from '@testing-library/react';
+import { TraceAggregation } from 'api/v5/v5';
+import { ENTITY_VERSION_V5 } from 'constants/app';
+import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+import DomainMetrics from './DomainMetrics';
+
+// Mock the API call
+jest.mock('lib/dashboard/getQueryResults', () => ({
+ GetMetricQueryRange: jest.fn(),
+}));
+
+// Mock ErrorState component
+jest.mock('./ErrorState', () => ({
+ __esModule: true,
+ default: jest.fn(({ refetch }) => (
+ <div data-testid="error-state">
+ <button type="button" onClick={refetch} data-testid="retry-button">
+ Retry
+ </button>
+ </div>
+ )),
+}));
+
+describe('DomainMetrics - V5 Query Payload Tests', () => {
+ let queryClient: QueryClient;
+
+ const mockProps = {
+ domainName: '0.0.0.0',
+ timeRange: {
+ startTime: 1758259531000,
+ endTime: 1758261331000,
+ },
+ domainListFilters: {
+ items: [],
+ op: 'AND' as const,
+ } as IBuilderQuery['filters'],
+ };
+
+ const mockSuccessResponse = {
+ statusCode: 200,
+ error: null,
+ payload: {
+ data: {
+ result: [
+ {
+ table: {
+ rows: [
+ {
+ data: {
+ A: '150',
+ B: '125000000',
+ D: '2021-01-01T23:00:00Z',
+ F1: '5.5',
+ },
+ },
+ ],
+ },
+ },
+ ],
+ },
+ },
+ };
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ cacheTime: 0,
+ },
+ },
+ });
+ jest.clearAllMocks();
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ });
+
+ const renderComponent = (props = mockProps): ReturnType<typeof render> =>
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DomainMetrics {...props} />
+ </QueryClientProvider>,
+ );
+
+ describe('1. V5 Query Payload with Filters', () => {
+ it('sends correct V5 payload structure with domain name filters', async () => {
+ (GetMetricQueryRange as jest.Mock).mockResolvedValue(mockSuccessResponse);
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(GetMetricQueryRange).toHaveBeenCalledTimes(1);
+ });
+
+ const [payload, version] = (GetMetricQueryRange as jest.Mock).mock.calls[0];
+
+ // Verify it's using V5
+ expect(version).toBe(ENTITY_VERSION_V5);
+
+ // Verify time range
+ expect(payload.start).toBe(1758259531000);
+ expect(payload.end).toBe(1758261331000);
+
+ // Verify V3 payload structure (getDomainMetricsQueryPayload returns V3 format)
+ expect(payload.query).toBeDefined();
+ expect(payload.query.builder).toBeDefined();
+ expect(payload.query.builder.queryData).toBeDefined();
+
+ const queryData = payload.query.builder.queryData;
+
+ // Verify Query A - count with URL filter
+ const queryA = queryData.find((q: any) => q.queryName === 'A');
+ expect(queryA).toBeDefined();
+ expect(queryA.dataSource).toBe('traces');
+ expect(queryA.aggregations?.[0]).toBeDefined();
+ expect((queryA.aggregations?.[0] as TraceAggregation)?.expression).toBe(
+ 'count()',
+ );
+ // Verify exact domain filter expression structure
+ expect(queryA.filter.expression).toContain(
+ "(net.peer.name = '0.0.0.0' OR server.address = '0.0.0.0')",
+ );
+ expect(queryA.filter.expression).toContain(
+ 'url.full EXISTS OR http.url EXISTS',
+ );
+
+ // Verify Query B - p99 latency
+ const queryB = queryData.find((q: any) => q.queryName === 'B');
+ expect(queryB).toBeDefined();
+ expect(queryB.aggregateOperator).toBe('p99');
+ expect(queryB.aggregations?.[0]).toBeDefined();
+ expect((queryB.aggregations?.[0] as TraceAggregation)?.expression).toBe(
+ 'p99(duration_nano)',
+ );
+ // Verify exact domain filter expression structure
+ expect(queryB.filter.expression).toContain(
+ "(net.peer.name = '0.0.0.0' OR server.address = '0.0.0.0')",
+ );
+
+ // Verify Query C - error count (disabled)
+ const queryC = queryData.find((q: any) => q.queryName === 'C');
+ expect(queryC).toBeDefined();
+ expect(queryC.disabled).toBe(true);
+ expect(queryC.filter.expression).toContain(
+ "(net.peer.name = '0.0.0.0' OR server.address = '0.0.0.0')",
+ );
+ expect(queryC.aggregations?.[0]).toBeDefined();
+ expect((queryC.aggregations?.[0] as TraceAggregation)?.expression).toBe(
+ 'count()',
+ );
+
+ expect(queryC.filter.expression).toContain('has_error = true');
+
+ // Verify Query D - max timestamp
+ const queryD = queryData.find((q: any) => q.queryName === 'D');
+ expect(queryD).toBeDefined();
+ expect(queryD.aggregateOperator).toBe('max');
+ expect(queryD.aggregations?.[0]).toBeDefined();
+ expect((queryD.aggregations?.[0] as TraceAggregation)?.expression).toBe(
+ 'max(timestamp)',
+ );
+ // Verify exact domain filter expression structure
+ expect(queryD.filter.expression).toContain(
+ "(net.peer.name = '0.0.0.0' OR server.address = '0.0.0.0')",
+ );
+
+ // Verify Formula F1 - error rate calculation
+ const formulas = payload.query.builder.queryFormulas;
+ expect(formulas).toBeDefined();
+ expect(formulas.length).toBeGreaterThan(0);
+ const formulaF1 = formulas.find((f: any) => f.queryName === 'F1');
+ expect(formulaF1).toBeDefined();
+ expect(formulaF1.expression).toBe('(C/A)*100');
+ });
+
+ it('includes custom filters in filter expressions', async () => {
+ (GetMetricQueryRange as jest.Mock).mockResolvedValue(mockSuccessResponse);
+
+ const customFilters: IBuilderQuery['filters'] = {
+ items: [
+ {
+ id: 'test-1',
+ key: {
+ key: 'service.name',
+ dataType: 'string' as any,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'my-service',
+ },
+ {
+ id: 'test-2',
+ key: {
+ key: 'deployment.environment',
+ dataType: 'string' as any,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'production',
+ },
+ ],
+ op: 'AND' as const,
+ };
+
+ renderComponent({
+ ...mockProps,
+ domainListFilters: customFilters,
+ });
+
+ await waitFor(() => {
+ expect(GetMetricQueryRange).toHaveBeenCalled();
+ });
+
+ const [payload] = (GetMetricQueryRange as jest.Mock).mock.calls[0];
+ const queryData = payload.query.builder.queryData;
+
+ // Verify all queries include the custom filters
+ queryData.forEach((query: any) => {
+ if (query.filter && query.filter.expression) {
+ expect(query.filter.expression).toContain('service.name');
+ expect(query.filter.expression).toContain('my-service');
+ expect(query.filter.expression).toContain('deployment.environment');
+ expect(query.filter.expression).toContain('production');
+ }
+ });
+ });
+ });
+
+ describe('2. Data Display State', () => {
+ it('displays metrics when data is successfully loaded', async () => {
+ (GetMetricQueryRange as jest.Mock).mockResolvedValue(mockSuccessResponse);
+
+ renderComponent();
+
+ // Wait for skeletons to disappear
+ await waitFor(() => {
+ const skeletons = document.querySelectorAll('.ant-skeleton-button');
+ expect(skeletons.length).toBe(0);
+ });
+
+ // Verify all metric labels are displayed
+ expect(screen.getByText('EXTERNAL API')).toBeInTheDocument();
+ expect(screen.getByText('AVERAGE LATENCY')).toBeInTheDocument();
+ expect(screen.getByText('ERROR %')).toBeInTheDocument();
+ expect(screen.getByText('LAST USED')).toBeInTheDocument();
+
+ // Verify metric values are displayed
+ expect(screen.getByText('150')).toBeInTheDocument();
+ expect(screen.getByText('0.125s')).toBeInTheDocument();
+ });
+ });
+
+ describe('3. Empty/Missing Data State', () => {
+ it('displays "-" for missing data values', async () => {
+ const emptyResponse = {
+ statusCode: 200,
+ error: null,
+ payload: {
+ data: {
+ result: [
+ {
+ table: {
+ rows: [],
+ },
+ },
+ ],
+ },
+ },
+ };
+
+ (GetMetricQueryRange as jest.Mock).mockResolvedValue(emptyResponse);
+
+ renderComponent();
+
+ await waitFor(() => {
+ const skeletons = document.querySelectorAll('.ant-skeleton-button');
+ expect(skeletons.length).toBe(0);
+ });
+
+ // When no data, all values should show "-"
+ const dashValues = screen.getAllByText('-');
+ expect(dashValues.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('4. Error State', () => {
+ it('displays error state when API call fails', async () => {
+ (GetMetricQueryRange as jest.Mock).mockRejectedValue(new Error('API Error'));
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(screen.getByTestId('error-state')).toBeInTheDocument();
+ });
+
+ expect(screen.getByTestId('retry-button')).toBeInTheDocument();
+ });
+
+ it('retries API call when retry button is clicked', async () => {
+ let callCount = 0;
+ (GetMetricQueryRange as jest.Mock).mockImplementation(() => {
+ callCount += 1;
+ if (callCount === 1) {
+ return Promise.reject(new Error('API Error'));
+ }
+ return Promise.resolve(mockSuccessResponse);
+ });
+
+ renderComponent();
+
+ // Wait for error state
+ await waitFor(() => {
+ expect(screen.getByTestId('error-state')).toBeInTheDocument();
+ });
+
+ // Click retry
+ const retryButton = screen.getByTestId('retry-button');
+ retryButton.click();
+
+ // Wait for successful load
+ await waitFor(() => {
+ expect(screen.getByText('150')).toBeInTheDocument();
+ });
+
+ expect(callCount).toBe(2);
+ });
+ });
+});
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.tsx
index 722ae3b67e..0411e0437e 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.tsx
@@ -1,6 +1,6 @@
import { Color } from '@signozhq/design-tokens';
import { Progress, Skeleton, Tooltip, Typography } from 'antd';
-import { ENTITY_VERSION_V4 } from 'constants/app';
+import { ENTITY_VERSION_V5 } from 'constants/app';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import {
DomainMetricsResponseRow,
@@ -44,10 +44,10 @@ function DomainMetrics({
queryKey: [
REACT_QUERY_KEY.GET_DOMAIN_METRICS_DATA,
payload,
- ENTITY_VERSION_V4,
+ ENTITY_VERSION_V5,
],
queryFn: (): Promise<SuccessResponse<MetricRangePayloadProps>> =>
- GetMetricQueryRange(payload, ENTITY_VERSION_V4),
+ GetMetricQueryRange(payload, ENTITY_VERSION_V5),
enabled: !!payload,
staleTime: 60 * 1000, // 1 minute stale time : optimize this part
})),
@@ -132,7 +132,9 @@ function DomainMetrics({
) : (
<Tooltip title={formattedDomainMetricsData.latency}>
<span className="round-metric-tag">
- {(Number(formattedDomainMetricsData.latency) / 1000).toFixed(3)}s
+ {formattedDomainMetricsData.latency !== '-'
+ ? `${(Number(formattedDomainMetricsData.latency) / 1000).toFixed(3)}s`
+ : '-'}
</span>
</Tooltip>
)}
@@ -143,23 +145,27 @@ function DomainMetrics({
<Skeleton.Button active size="small" />
) : (
<Tooltip title={formattedDomainMetricsData.errorRate}>
- <Progress
- status="active"
- percent={Number(
- Number(formattedDomainMetricsData.errorRate).toFixed(2),
- )}
- strokeLinecap="butt"
- size="small"
- strokeColor={((): string => {
- const errorRatePercent = Number(
+ {formattedDomainMetricsData.errorRate !== '-' ? (
+ <Progress
+ status="active"
+ percent={Number(
Number(formattedDomainMetricsData.errorRate).toFixed(2),
- );
- if (errorRatePercent >= 90) return Color.BG_SAKURA_500;
- if (errorRatePercent >= 60) return Color.BG_AMBER_500;
- return Color.BG_FOREST_500;
- })()}
- className="progress-bar"
- />
+ )}
+ strokeLinecap="butt"
+ size="small"
+ strokeColor={((): string => {
+ const errorRatePercent = Number(
+ Number(formattedDomainMetricsData.errorRate).toFixed(2),
+ );
+ if (errorRatePercent >= 90) return Color.BG_SAKURA_500;
+ if (errorRatePercent >= 60) return Color.BG_AMBER_500;
+ return Color.BG_FOREST_500;
+ })()}
+ className="progress-bar"
+ />
+ ) : (
+ '-'
+ )}
</Tooltip>
)}
</Typography.Text>
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/EndPointMetrics.test.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/EndPointMetrics.test.tsx
new file mode 100644
index 0000000000..3584e847f0
--- /dev/null
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/EndPointMetrics.test.tsx
@@ -0,0 +1,419 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/* eslint-disable react/jsx-props-no-spreading */
+/* eslint-disable prefer-destructuring */
+/* eslint-disable sonarjs/no-duplicate-string */
+import { render, screen, waitFor } from '@testing-library/react';
+import { getEndPointDetailsQueryPayload } from 'container/ApiMonitoring/utils';
+import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
+import { QueryClient, QueryClientProvider, UseQueryResult } from 'react-query';
+import { SuccessResponse } from 'types/api';
+
+import EndPointMetrics from './EndPointMetrics';
+
+// Mock the API call
+jest.mock('lib/dashboard/getQueryResults', () => ({
+ GetMetricQueryRange: jest.fn(),
+}));
+
+// Mock ErrorState component
+jest.mock('./ErrorState', () => ({
+ __esModule: true,
+ default: jest.fn(({ refetch }) => (
+ <div data-testid="error-state">
+ <button type="button" onClick={refetch} data-testid="retry-button">
+ Retry
+ </button>
+ </div>
+ )),
+}));
+
+describe('EndPointMetrics - V5 Query Payload Tests', () => {
+ let queryClient: QueryClient;
+
+ const mockSuccessResponse = {
+ statusCode: 200,
+ error: null,
+ payload: {
+ data: {
+ result: [
+ {
+ table: {
+ rows: [
+ {
+ data: {
+ A: '85.5',
+ B: '245000000',
+ D: '2021-01-01T22:30:00Z',
+ F1: '3.2',
+ },
+ },
+ ],
+ },
+ },
+ ],
+ },
+ },
+ };
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ cacheTime: 0,
+ },
+ },
+ });
+ jest.clearAllMocks();
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ });
+
+ // Helper to create mock query result
+ const createMockQueryResult = (
+ response: any,
+ overrides?: Partial<UseQueryResult<SuccessResponse<any>, unknown>>,
+ ): UseQueryResult<SuccessResponse<any>, unknown> =>
+ ({
+ data: response,
+ error: null,
+ isError: false,
+ isIdle: false,
+ isLoading: false,
+ isLoadingError: false,
+ isRefetchError: false,
+ isRefetching: false,
+ isStale: true,
+ isSuccess: true,
+ status: 'success' as const,
+ dataUpdatedAt: Date.now(),
+ errorUpdateCount: 0,
+ errorUpdatedAt: 0,
+ failureCount: 0,
+ isFetched: true,
+ isFetchedAfterMount: true,
+ isFetching: false,
+ isPlaceholderData: false,
+ isPreviousData: false,
+ refetch: jest.fn(),
+ remove: jest.fn(),
+ ...overrides,
+ } as UseQueryResult<SuccessResponse<any>, unknown>);
+
+ const renderComponent = (
+ endPointMetricsDataQuery: UseQueryResult<SuccessResponse<any>, unknown>,
+ ): ReturnType<typeof render> =>
+ render(
+ <QueryClientProvider client={queryClient}>
+ <EndPointMetrics endPointMetricsDataQuery={endPointMetricsDataQuery} />
+ </QueryClientProvider>,
+ );
+
+ // eslint-disable-next-line sonarjs/cognitive-complexity
+ describe('1. V5 Query Payload with Filters', () => {
+ // eslint-disable-next-line sonarjs/cognitive-complexity
+ it('sends correct V5 payload structure with domain and endpoint filters', async () => {
+ (GetMetricQueryRange as jest.Mock).mockResolvedValue(mockSuccessResponse);
+
+ const domainName = 'api.example.com';
+ const startTime = 1758259531000;
+ const endTime = 1758261331000;
+ const filters = {
+ items: [],
+ op: 'AND' as const,
+ };
+
+ // Get the actual payload that would be generated
+ const payloads = getEndPointDetailsQueryPayload(
+ domainName,
+ startTime,
+ endTime,
+ filters,
+ );
+
+ // First payload is for endpoint metrics
+ const metricsPayload = payloads[0];
+
+ // Verify it's using the correct structure (V3 format for V5 API)
+ expect(metricsPayload.query).toBeDefined();
+ expect(metricsPayload.query.builder).toBeDefined();
+ expect(metricsPayload.query.builder.queryData).toBeDefined();
+
+ const queryData = metricsPayload.query.builder.queryData;
+
+ // Verify Query A - rate with domain and client kind filters
+ const queryA = queryData.find((q: any) => q.queryName === 'A');
+ expect(queryA).toBeDefined();
+ if (queryA) {
+ expect(queryA.dataSource).toBe('traces');
+ expect(queryA.aggregateOperator).toBe('rate');
+ expect(queryA.timeAggregation).toBe('rate');
+ // Verify exact domain filter expression structure
+ if (queryA.filter) {
+ expect(queryA.filter.expression).toContain(
+ "(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
+ );
+ expect(queryA.filter.expression).toContain("kind_string = 'Client'");
+ }
+ }
+
+ // Verify Query B - p99 latency with duration_nano
+ const queryB = queryData.find((q: any) => q.queryName === 'B');
+ expect(queryB).toBeDefined();
+ if (queryB) {
+ expect(queryB.aggregateOperator).toBe('p99');
+ if (queryB.aggregateAttribute) {
+ expect(queryB.aggregateAttribute.key).toBe('duration_nano');
+ }
+ expect(queryB.timeAggregation).toBe('p99');
+ // Verify exact domain filter expression structure
+ if (queryB.filter) {
+ expect(queryB.filter.expression).toContain(
+ "(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
+ );
+ expect(queryB.filter.expression).toContain("kind_string = 'Client'");
+ }
+ }
+
+ // Verify Query C - error count (disabled)
+ const queryC = queryData.find((q: any) => q.queryName === 'C');
+ expect(queryC).toBeDefined();
+ if (queryC) {
+ expect(queryC.disabled).toBe(true);
+ expect(queryC.aggregateOperator).toBe('count');
+ if (queryC.filter) {
+ expect(queryC.filter.expression).toContain(
+ "(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
+ );
+ expect(queryC.filter.expression).toContain("kind_string = 'Client'");
+ expect(queryC.filter.expression).toContain('has_error = true');
+ }
+ }
+
+ // Verify Query D - max timestamp for last used
+ const queryD = queryData.find((q: any) => q.queryName === 'D');
+ expect(queryD).toBeDefined();
+ if (queryD) {
+ expect(queryD.aggregateOperator).toBe('max');
+ if (queryD.aggregateAttribute) {
+ expect(queryD.aggregateAttribute.key).toBe('timestamp');
+ }
+ expect(queryD.timeAggregation).toBe('max');
+ // Verify exact domain filter expression structure
+ if (queryD.filter) {
+ expect(queryD.filter.expression).toContain(
+ "(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
+ );
+ expect(queryD.filter.expression).toContain("kind_string = 'Client'");
+ }
+ }
+
+ // Verify Query E - total count (disabled)
+ const queryE = queryData.find((q: any) => q.queryName === 'E');
+ expect(queryE).toBeDefined();
+ if (queryE) {
+ expect(queryE.disabled).toBe(true);
+ expect(queryE.aggregateOperator).toBe('count');
+ if (queryE.aggregateAttribute) {
+ expect(queryE.aggregateAttribute.key).toBe('span_id');
+ }
+ if (queryE.filter) {
+ expect(queryE.filter.expression).toContain(
+ "(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
+ );
+ expect(queryE.filter.expression).toContain("kind_string = 'Client'");
+ }
+ }
+
+ // Verify Formula F1 - error rate calculation
+ const formulas = metricsPayload.query.builder.queryFormulas;
+ expect(formulas).toBeDefined();
+ expect(formulas.length).toBeGreaterThan(0);
+ const formulaF1 = formulas.find((f: any) => f.queryName === 'F1');
+ expect(formulaF1).toBeDefined();
+ if (formulaF1) {
+ expect(formulaF1.expression).toBe('(C/E)*100');
+ expect(formulaF1.disabled).toBe(false);
+ expect(formulaF1.legend).toBe('error percentage');
+ }
+ });
+
+ it('includes custom domainListFilters in all query expressions', async () => {
+ (GetMetricQueryRange as jest.Mock).mockResolvedValue(mockSuccessResponse);
+
+ const customFilters = {
+ items: [
+ {
+ id: 'test-1',
+ key: {
+ key: 'service.name',
+ dataType: 'string' as any,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'payment-service',
+ },
+ {
+ id: 'test-2',
+ key: {
+ key: 'deployment.environment',
+ dataType: 'string' as any,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'staging',
+ },
+ ],
+ op: 'AND' as const,
+ };
+
+ const payloads = getEndPointDetailsQueryPayload(
+ 'api.internal.com',
+ 1758259531000,
+ 1758261331000,
+ customFilters,
+ );
+
+ const queryData = payloads[0].query.builder.queryData;
+
+ // Verify ALL queries (A, B, C, D, E) include the custom filters
+ const allQueryNames = ['A', 'B', 'C', 'D', 'E'];
+ allQueryNames.forEach((queryName) => {
+ const query = queryData.find((q: any) => q.queryName === queryName);
+ expect(query).toBeDefined();
+ if (query && query.filter && query.filter.expression) {
+ // Check for exact filter inclusion
+ expect(query.filter.expression).toContain('service.name');
+ expect(query.filter.expression).toContain('payment-service');
+ expect(query.filter.expression).toContain('deployment.environment');
+ expect(query.filter.expression).toContain('staging');
+ // Also verify domain filter is still present
+ expect(query.filter.expression).toContain(
+ "(net.peer.name = 'api.internal.com' OR server.address = 'api.internal.com')",
+ );
+ // Verify client kind filter is present
+ expect(query.filter.expression).toContain("kind_string = 'Client'");
+ }
+ });
+ });
+ });
+
+ describe('2. Data Display State', () => {
+ it('displays metrics when data is successfully loaded', async () => {
+ const mockQuery = createMockQueryResult(mockSuccessResponse);
+
+ renderComponent(mockQuery);
+
+ // Wait for skeletons to disappear
+ await waitFor(() => {
+ const skeletons = document.querySelectorAll('.ant-skeleton-button');
+ expect(skeletons.length).toBe(0);
+ });
+
+ // Verify all metric labels are displayed
+ expect(screen.getByText('Rate')).toBeInTheDocument();
+ expect(screen.getByText('AVERAGE LATENCY')).toBeInTheDocument();
+ expect(screen.getByText('ERROR %')).toBeInTheDocument();
+ expect(screen.getByText('LAST USED')).toBeInTheDocument();
+
+ // Verify metric values are displayed
+ expect(screen.getByText('85.5 ops/sec')).toBeInTheDocument();
+ expect(screen.getByText('245ms')).toBeInTheDocument();
+ });
+ });
+
+ describe('3. Empty/Missing Data State', () => {
+ it("displays '-' for missing data values", async () => {
+ const emptyResponse = {
+ statusCode: 200,
+ error: null,
+ payload: {
+ data: {
+ result: [
+ {
+ table: {
+ rows: [],
+ },
+ },
+ ],
+ },
+ },
+ };
+
+ const mockQuery = createMockQueryResult(emptyResponse);
+
+ renderComponent(mockQuery);
+
+ await waitFor(() => {
+ const skeletons = document.querySelectorAll('.ant-skeleton-button');
+ expect(skeletons.length).toBe(0);
+ });
+
+ // When no data, all values should show "-"
+ const dashValues = screen.getAllByText('-');
+ // Should have at least 2 dashes (rate and last used - latency shows "-", error % shows progress bar)
+ expect(dashValues.length).toBeGreaterThanOrEqual(2);
+ });
+ });
+
+ describe('4. Error State', () => {
+ it('displays error state when API call fails', async () => {
+ const mockQuery = createMockQueryResult(null, {
+ isError: true,
+ isSuccess: false,
+ status: 'error',
+ error: new Error('API Error'),
+ });
+
+ renderComponent(mockQuery);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('error-state')).toBeInTheDocument();
+ });
+
+ expect(screen.getByTestId('retry-button')).toBeInTheDocument();
+ });
+
+ it('retries API call when retry button is clicked', async () => {
+ const refetch = jest.fn().mockResolvedValue(mockSuccessResponse);
+
+ // Start with error state
+ const mockQuery = createMockQueryResult(null, {
+ isError: true,
+ isSuccess: false,
+ status: 'error',
+ error: new Error('API Error'),
+ refetch,
+ });
+
+ const { rerender } = renderComponent(mockQuery);
+
+ // Wait for error state
+ await waitFor(() => {
+ expect(screen.getByTestId('error-state')).toBeInTheDocument();
+ });
+
+ // Click retry
+ const retryButton = screen.getByTestId('retry-button');
+ retryButton.click();
+
+ // Verify refetch was called
+ expect(refetch).toHaveBeenCalledTimes(1);
+
+ // Simulate successful refetch by rerendering with success state
+ const successQuery = createMockQueryResult(mockSuccessResponse);
+ rerender(
+ <QueryClientProvider client={queryClient}>
+ <EndPointMetrics endPointMetricsDataQuery={successQuery} />
+ </QueryClientProvider>,
+ );
+
+ // Wait for successful load
+ await waitFor(() => {
+ expect(screen.getByText('85.5 ops/sec')).toBeInTheDocument();
+ });
+ });
+ });
+});
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/EndPointMetrics.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/EndPointMetrics.tsx
index 07f7d268df..1b176e420a 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/EndPointMetrics.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/EndPointMetrics.tsx
@@ -1,12 +1,16 @@
import { Color } from '@signozhq/design-tokens';
import { Progress, Skeleton, Tooltip, Typography } from 'antd';
-import { getFormattedEndPointMetricsData } from 'container/ApiMonitoring/utils';
+import {
+ getDisplayValue,
+ getFormattedEndPointMetricsData,
+} from 'container/ApiMonitoring/utils';
import { useMemo } from 'react';
import { UseQueryResult } from 'react-query';
import { SuccessResponse } from 'types/api';
import ErrorState from './ErrorState';
+// eslint-disable-next-line sonarjs/cognitive-complexity
function EndPointMetrics({
endPointMetricsDataQuery,
}: {
@@ -70,7 +74,9 @@ function EndPointMetrics({
<Skeleton.Button active size="small" />
) : (
<Tooltip title={metricsData?.rate}>
- <span className="round-metric-tag">{metricsData?.rate} ops/sec</span>
+ <span className="round-metric-tag">
+ {metricsData?.rate !== '-' ? `${metricsData?.rate} ops/sec` : '-'}
+ </span>
</Tooltip>
)}
</Typography.Text>
@@ -79,7 +85,7 @@ function EndPointMetrics({
<Skeleton.Button active size="small" />
) : (
<Tooltip title={metricsData?.latency}>
- <span className="round-metric-tag">{metricsData?.latency}ms</span>
+ {metricsData?.latency !== '-' ? `${metricsData?.latency}ms` : '-'}
</Tooltip>
)}
</Typography.Text>
@@ -88,21 +94,25 @@ function EndPointMetrics({
<Skeleton.Button active size="small" />
) : (
<Tooltip title={metricsData?.errorRate}>
- <Progress
- status="active"
- percent={Number(Number(metricsData?.errorRate ?? 0).toFixed(2))}
- strokeLinecap="butt"
- size="small"
- strokeColor={((): string => {
- const errorRatePercent = Number(
- Number(metricsData?.errorRate ?? 0).toFixed(2),
- );
- if (errorRatePercent >= 90) return Color.BG_SAKURA_500;
- if (errorRatePercent >= 60) return Color.BG_AMBER_500;
- return Color.BG_FOREST_500;
- })()}
- className="progress-bar"
- />
+ {metricsData?.errorRate !== '-' ? (
+ <Progress
+ status="active"
+ percent={Number(Number(metricsData?.errorRate ?? 0).toFixed(2))}
+ strokeLinecap="butt"
+ size="small"
+ strokeColor={((): string => {
+ const errorRatePercent = Number(
+ Number(metricsData?.errorRate ?? 0).toFixed(2),
+ );
+ if (errorRatePercent >= 90) return Color.BG_SAKURA_500;
+ if (errorRatePercent >= 60) return Color.BG_AMBER_500;
+ return Color.BG_FOREST_500;
+ })()}
+ className="progress-bar"
+ />
+ ) : (
+ '-'
+ )}
</Tooltip>
)}
</Typography.Text>
@@ -110,7 +120,9 @@ function EndPointMetrics({
{isLoading || isRefetching ? (
<Skeleton.Button active size="small" />
) : (
- <Tooltip title={metricsData?.lastUsed}>{metricsData?.lastUsed}</Tooltip>
+ <Tooltip title={metricsData?.lastUsed}>
+ {getDisplayValue(metricsData?.lastUsed)}
+ </Tooltip>
)}
</Typography.Text>
</div>
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/MetricOverTimeGraph.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/MetricOverTimeGraph.tsx
index 0de9283fdb..0d50a3488c 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/MetricOverTimeGraph.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/MetricOverTimeGraph.tsx
@@ -1,4 +1,5 @@
import { Card } from 'antd';
+import { ENTITY_VERSION_V5 } from 'constants/app';
import GridCard from 'container/GridCardLayout/GridCard';
import { Widgets } from 'types/api/dashboard/getAll';
@@ -22,6 +23,7 @@ function MetricOverTimeGraph({
customOnDragSelect={(): void => {}}
customTimeRange={timeRange}
customTimeRangeWindowForCoRelation="5m"
+ version={ENTITY_VERSION_V5}
/>
</div>
</Card>
diff --git a/frontend/src/container/ApiMonitoring/__tests__/APIMonitoringUtils.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/APIMonitoringUtils.test.tsx
index afa49033f5..5c5f11b6ea 100644
--- a/frontend/src/container/ApiMonitoring/__tests__/APIMonitoringUtils.test.tsx
+++ b/frontend/src/container/ApiMonitoring/__tests__/APIMonitoringUtils.test.tsx
@@ -8,16 +8,11 @@ import {
endPointStatusCodeColumns,
extractPortAndEndpoint,
formatDataForTable,
- getAllEndpointsWidgetData,
getCustomFiltersForBarChart,
- getFormattedDependentServicesData,
getFormattedEndPointDropDownData,
- getFormattedEndPointMetricsData,
getFormattedEndPointStatusCodeChartData,
getFormattedEndPointStatusCodeData,
getGroupByFiltersFromGroupByValues,
- getLatencyOverTimeWidgetData,
- getRateOverTimeWidgetData,
getStatusCodeBarChartWidgetData,
getTopErrorsColumnsConfig,
getTopErrorsCoRelationQueryFilters,
@@ -48,119 +43,13 @@ jest.mock('../utils', () => {
});
describe('API Monitoring Utils', () => {
- describe('getAllEndpointsWidgetData', () => {
- it('should create a widget with correct configuration', () => {
- // Arrange
- const groupBy = [
- {
- dataType: DataTypes.String,
- // eslint-disable-next-line sonarjs/no-duplicate-string
- key: 'http.method',
- type: '',
- },
- ];
- // eslint-disable-next-line sonarjs/no-duplicate-string
- const domainName = 'test-domain';
- const filters = {
- items: [
- {
- // eslint-disable-next-line sonarjs/no-duplicate-string
- id: 'test-filter',
- key: {
- dataType: DataTypes.String,
- key: 'test-key',
- type: '',
- },
- op: '=',
- // eslint-disable-next-line sonarjs/no-duplicate-string
- value: 'test-value',
- },
- ],
- op: 'AND',
- };
-
- // Act
- const result = getAllEndpointsWidgetData(
- groupBy as BaseAutocompleteData[],
- domainName,
- filters as IBuilderQuery['filters'],
- );
-
- // Assert
- expect(result).toBeDefined();
- expect(result.id).toBeDefined();
- // Title is a React component, not a string
- expect(result.title).toBeDefined();
- expect(result.panelTypes).toBe(PANEL_TYPES.TABLE);
-
- // Check that each query includes the domainName filter
- result.query.builder.queryData.forEach((query) => {
- const serverNameFilter = query.filters?.items?.find(
- (item) => item.key && item.key.key === SPAN_ATTRIBUTES.SERVER_NAME,
- );
- expect(serverNameFilter).toBeDefined();
- expect(serverNameFilter?.value).toBe(domainName);
-
- // Check that the custom filters were included
- const testFilter = query.filters?.items?.find(
- (item) => item.id === 'test-filter',
- );
- expect(testFilter).toBeDefined();
- });
-
- // Verify groupBy was included in queries
- if (result.query.builder.queryData[0].groupBy) {
- const hasCustomGroupBy = result.query.builder.queryData[0].groupBy.some(
- (item) => item && item.key === 'http.method',
- );
- expect(hasCustomGroupBy).toBe(true);
- }
- });
-
- it('should handle empty groupBy correctly', () => {
- // Arrange
- const groupBy: any[] = [];
- const domainName = 'test-domain';
- const filters = { items: [], op: 'AND' };
-
- // Act
- const result = getAllEndpointsWidgetData(groupBy, domainName, filters);
-
- // Assert
- expect(result).toBeDefined();
- // Should only include default groupBy
- if (result.query.builder.queryData[0].groupBy) {
- expect(result.query.builder.queryData[0].groupBy.length).toBeGreaterThan(0);
- // Check that it doesn't have extra group by fields (only defaults)
- const defaultGroupByLength =
- result.query.builder.queryData[0].groupBy.length;
- const resultWithCustomGroupBy = getAllEndpointsWidgetData(
- [
- {
- dataType: DataTypes.String,
- key: 'custom.field',
- type: '',
- },
- ] as BaseAutocompleteData[],
- domainName,
- filters,
- );
- // Custom groupBy should have more fields than default
- if (resultWithCustomGroupBy.query.builder.queryData[0].groupBy) {
- expect(
- resultWithCustomGroupBy.query.builder.queryData[0].groupBy.length,
- ).toBeGreaterThan(defaultGroupByLength);
- }
- }
- });
- });
-
// New tests for formatDataForTable
describe('formatDataForTable', () => {
it('should format rows correctly with valid data', () => {
const columns = APIMonitoringColumnsMock;
const data = [
[
+ // eslint-disable-next-line sonarjs/no-duplicate-string
'test-domain', // domainName
'10', // endpoints
'25', // rps
@@ -218,6 +107,7 @@ describe('API Monitoring Utils', () => {
const groupBy = [
{
id: 'group-by-1',
+ // eslint-disable-next-line sonarjs/no-duplicate-string
key: 'http.method',
dataType: DataTypes.String,
type: '',
@@ -451,172 +341,6 @@ describe('API Monitoring Utils', () => {
});
});
- describe('getRateOverTimeWidgetData', () => {
- it('should generate widget configuration for rate over time', () => {
- // Arrange
- const domainName = 'test-domain';
- const endPointName = '/api/test';
- const filters = { items: [], op: 'AND' };
-
- // Act
- const result = getRateOverTimeWidgetData(
- domainName,
- endPointName,
- filters as IBuilderQuery['filters'],
- );
-
- // Assert
- expect(result).toBeDefined();
- expect(result).toHaveProperty('title', 'Rate Over Time');
- // Check only title since description might vary
-
- // Check query configuration
- expect(result).toHaveProperty('query');
- // eslint-disable-next-line sonarjs/no-duplicate-string
- expect(result).toHaveProperty('query.builder.queryData');
-
- const queryData = result.query.builder.queryData[0];
-
- // Should have domain filter
- const domainFilter = queryData.filters?.items?.find(
- (item) => item.key && item.key.key === SPAN_ATTRIBUTES.SERVER_NAME,
- );
- expect(domainFilter).toBeDefined();
- if (domainFilter) {
- expect(typeof domainFilter.value).toBe('string');
- }
-
- // Should have 'rate' time aggregation
- expect(queryData).toHaveProperty('timeAggregation', 'rate');
-
- // Should have proper legend that includes endpoint info
- expect(queryData).toHaveProperty('legend');
- expect(
- typeof queryData.legend === 'string' ? queryData.legend : '',
- ).toContain('/api/test');
- });
-
- it('should handle case without endpoint name', () => {
- // Arrange
- const domainName = 'test-domain';
- const endPointName = '';
- const filters = { items: [], op: 'AND' };
-
- // Act
- const result = getRateOverTimeWidgetData(
- domainName,
- endPointName,
- filters as IBuilderQuery['filters'],
- );
-
- // Assert
- expect(result).toBeDefined();
-
- const queryData = result.query.builder.queryData[0];
-
- // Legend should be domain name only
- expect(queryData).toHaveProperty('legend', domainName);
- });
- });
-
- describe('getLatencyOverTimeWidgetData', () => {
- it('should generate widget configuration for latency over time', () => {
- // Arrange
- const domainName = 'test-domain';
- const endPointName = '/api/test';
- const filters = { items: [], op: 'AND' };
-
- // Act
- const result = getLatencyOverTimeWidgetData(
- domainName,
- endPointName,
- filters as IBuilderQuery['filters'],
- );
-
- // Assert
- expect(result).toBeDefined();
- expect(result).toHaveProperty('title', 'Latency Over Time');
- // Check only title since description might vary
-
- // Check query configuration
- expect(result).toHaveProperty('query');
- expect(result).toHaveProperty('query.builder.queryData');
-
- const queryData = result.query.builder.queryData[0];
-
- // Should have domain filter
- const domainFilter = queryData.filters?.items?.find(
- (item) => item.key && item.key.key === SPAN_ATTRIBUTES.SERVER_NAME,
- );
- expect(domainFilter).toBeDefined();
- if (domainFilter) {
- expect(typeof domainFilter.value).toBe('string');
- }
-
- // Should use duration_nano as the aggregate attribute
- expect(queryData.aggregateAttribute).toHaveProperty('key', 'duration_nano');
-
- // Should have 'p99' time aggregation
- expect(queryData).toHaveProperty('timeAggregation', 'p99');
- });
-
- it('should handle case without endpoint name', () => {
- // Arrange
- const domainName = 'test-domain';
- const endPointName = '';
- const filters = { items: [], op: 'AND' };
-
- // Act
- const result = getLatencyOverTimeWidgetData(
- domainName,
- endPointName,
- filters as IBuilderQuery['filters'],
- );
-
- // Assert
- expect(result).toBeDefined();
-
- const queryData = result.query.builder.queryData[0];
-
- // Legend should be domain name only
- expect(queryData).toHaveProperty('legend', domainName);
- });
-
- // Changed approach to verify end-to-end behavior for URL with port
- it('should format legends appropriately for complete URLs with ports', () => {
- // Arrange
- const domainName = 'test-domain';
- const endPointName = 'http://example.com:8080/api/test';
- const filters = { items: [], op: 'AND' };
-
- // Extract what we expect the function to extract
- const expectedParts = extractPortAndEndpoint(endPointName);
-
- // Act
- const result = getLatencyOverTimeWidgetData(
- domainName,
- endPointName,
- filters as IBuilderQuery['filters'],
- );
-
- // Assert
- const queryData = result.query.builder.queryData[0];
-
- // Check that legend is present and is a string
- expect(queryData).toHaveProperty('legend');
- expect(typeof queryData.legend).toBe('string');
-
- // If the URL has a port and endpoint, the legend should reflect that appropriately
- // (Testing the integration rather than the exact formatting)
- if (expectedParts.port !== '-') {
- // Verify that both components are incorporated into the legend in some way
- // This tests the behavior without relying on the exact implementation details
- const legendStr = queryData.legend as string;
- expect(legendStr).not.toBe(domainName); // Legend should be different when URL has port/endpoint
- }
- });
- });
-
describe('getFormattedEndPointDropDownData', () => {
it('should format endpoint dropdown data correctly', () => {
// Arrange
@@ -626,6 +350,7 @@ describe('API Monitoring Utils', () => {
data: {
// eslint-disable-next-line sonarjs/no-duplicate-string
[URL_PATH_KEY]: '/api/users',
+ 'url.full': 'http://example.com/api/users',
A: 150, // count or other metric
},
},
@@ -633,6 +358,7 @@ describe('API Monitoring Utils', () => {
data: {
// eslint-disable-next-line sonarjs/no-duplicate-string
[URL_PATH_KEY]: '/api/orders',
+ 'url.full': 'http://example.com/api/orders',
A: 75,
},
},
@@ -716,87 +442,6 @@ describe('API Monitoring Utils', () => {
});
});
- describe('getFormattedEndPointMetricsData', () => {
- it('should format endpoint metrics data correctly', () => {
- // Arrange
- const mockData = [
- {
- data: {
- A: '50', // rate
- B: '15000000', // latency in nanoseconds
- C: '5', // required by type
- D: '1640995200000000', // timestamp in nanoseconds
- F1: '5.5', // error rate
- },
- },
- ];
-
- // Act
- const result = getFormattedEndPointMetricsData(mockData as any);
-
- // Assert
- expect(result).toBeDefined();
- expect(result.key).toBeDefined();
- expect(result.rate).toBe('50');
- expect(result.latency).toBe(15); // Should be converted from ns to ms
- expect(result.errorRate).toBe(5.5);
- expect(typeof result.lastUsed).toBe('string'); // Time formatting is tested elsewhere
- });
-
- // eslint-disable-next-line sonarjs/no-duplicate-string
- it('should handle undefined values in data', () => {
- // Arrange
- const mockData = [
- {
- data: {
- A: undefined,
- B: 'n/a',
- C: '', // required by type
- D: undefined,
- F1: 'n/a',
- },
- },
- ];
-
- // Act
- const result = getFormattedEndPointMetricsData(mockData as any);
-
- // Assert
- expect(result).toBeDefined();
- expect(result.rate).toBe('-');
- expect(result.latency).toBe('-');
- expect(result.errorRate).toBe(0);
- expect(result.lastUsed).toBe('-');
- });
-
- it('should handle empty input array', () => {
- // Act
- const result = getFormattedEndPointMetricsData([]);
-
- // Assert
- expect(result).toBeDefined();
- expect(result.rate).toBe('-');
- expect(result.latency).toBe('-');
- expect(result.errorRate).toBe(0);
- expect(result.lastUsed).toBe('-');
- });
-
- it('should handle undefined input', () => {
- // Arrange
- const undefinedInput = undefined as any;
-
- // Act
- const result = getFormattedEndPointMetricsData(undefinedInput);
-
- // Assert
- expect(result).toBeDefined();
- expect(result.rate).toBe('-');
- expect(result.latency).toBe('-');
- expect(result.errorRate).toBe(0);
- expect(result.lastUsed).toBe('-');
- });
- });
-
describe('getFormattedEndPointStatusCodeData', () => {
it('should format status code data correctly', () => {
// Arrange
@@ -933,139 +578,6 @@ describe('API Monitoring Utils', () => {
});
});
- describe('getFormattedDependentServicesData', () => {
- it('should format dependent services data correctly', () => {
- // Arrange
- const mockData = [
- {
- data: {
- // eslint-disable-next-line sonarjs/no-duplicate-string
- 'service.name': 'auth-service',
- A: '500', // count
- B: '120000000', // latency in nanoseconds
- C: '15', // rate
- F1: '2.5', // error percentage
- },
- },
- {
- data: {
- 'service.name': 'db-service',
- A: '300',
- B: '80000000',
- C: '10',
- F1: '1.2',
- },
- },
- ];
-
- // Act
- const result = getFormattedDependentServicesData(mockData as any);
-
- // Assert
- expect(result).toBeDefined();
- expect(result.length).toBe(2);
-
- // Check first service
- expect(result[0].key).toBeDefined();
- expect(result[0].serviceData.serviceName).toBe('auth-service');
- expect(result[0].serviceData.count).toBe(500);
- expect(typeof result[0].serviceData.percentage).toBe('number');
- expect(result[0].latency).toBe(120); // Should be converted from ns to ms
- expect(result[0].rate).toBe('15');
- expect(result[0].errorPercentage).toBe('2.5');
-
- // Check second service
- expect(result[1].serviceData.serviceName).toBe('db-service');
- expect(result[1].serviceData.count).toBe(300);
- expect(result[1].latency).toBe(80);
- expect(result[1].rate).toBe('10');
- expect(result[1].errorPercentage).toBe('1.2');
-
- // Verify percentage calculation
- const totalCount = 500 + 300;
- expect(result[0].serviceData.percentage).toBeCloseTo(
- (500 / totalCount) * 100,
- 2,
- );
- expect(result[1].serviceData.percentage).toBeCloseTo(
- (300 / totalCount) * 100,
- 2,
- );
- });
-
- it('should handle undefined values in data', () => {
- // Arrange
- const mockData = [
- {
- data: {
- 'service.name': 'auth-service',
- A: 'n/a',
- B: undefined,
- C: 'n/a',
- F1: undefined,
- },
- },
- ];
-
- // Act
- const result = getFormattedDependentServicesData(mockData as any);
-
- // Assert
- expect(result).toBeDefined();
- expect(result.length).toBe(1);
- expect(result[0].serviceData.serviceName).toBe('auth-service');
- expect(result[0].serviceData.count).toBe('-');
- expect(result[0].serviceData.percentage).toBe(0);
- expect(result[0].latency).toBe('-');
- expect(result[0].rate).toBe('-');
- expect(result[0].errorPercentage).toBe(0);
- });
-
- it('should handle empty input array', () => {
- // Act
- const result = getFormattedDependentServicesData([]);
-
- // Assert
- expect(result).toBeDefined();
- expect(result).toEqual([]);
- });
-
- it('should handle undefined input', () => {
- // Arrange
- const undefinedInput = undefined as any;
-
- // Act
- const result = getFormattedDependentServicesData(undefinedInput);
-
- // Assert
- expect(result).toBeDefined();
- expect(result).toEqual([]);
- });
-
- it('should handle missing service name', () => {
- // Arrange
- const mockData = [
- {
- data: {
- // Missing service.name
- A: '200',
- B: '50000000',
- C: '8',
- F1: '0.5',
- },
- },
- ];
-
- // Act
- const result = getFormattedDependentServicesData(mockData as any);
-
- // Assert
- expect(result).toBeDefined();
- expect(result.length).toBe(1);
- expect(result[0].serviceData.serviceName).toBe('-');
- });
- });
-
describe('getFormattedEndPointStatusCodeChartData', () => {
afterEach(() => {
jest.resetAllMocks();
diff --git a/frontend/src/container/ApiMonitoring/__tests__/AllEndpointsWidgetV5Migration.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/AllEndpointsWidgetV5Migration.test.tsx
new file mode 100644
index 0000000000..0e2d37ad29
--- /dev/null
+++ b/frontend/src/container/ApiMonitoring/__tests__/AllEndpointsWidgetV5Migration.test.tsx
@@ -0,0 +1,221 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/* eslint-disable sonarjs/no-duplicate-string */
+/**
+ * V5 Migration Tests for All Endpoints Widget (Endpoint Overview)
+ *
+ * These tests validate the migration from V4 to V5 format for getAllEndpointsWidgetData:
+ * - Filter format change: filters.items[] → filter.expression
+ * - Aggregation format: aggregateAttribute → aggregations[] array
+ * - Domain filter: (net.peer.name OR server.address)
+ * - Kind filter: kind_string = 'Client'
+ * - Four queries: A (count), B (p99 latency), C (max timestamp), D (error count - disabled)
+ * - GroupBy: Both http.url AND url.full with type 'attribute'
+ */
+import { getAllEndpointsWidgetData } from 'container/ApiMonitoring/utils';
+import {
+ BaseAutocompleteData,
+ DataTypes,
+} from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+describe('AllEndpointsWidget - V5 Migration Validation', () => {
+ const mockDomainName = 'api.example.com';
+ const emptyFilters: IBuilderQuery['filters'] = {
+ items: [],
+ op: 'AND',
+ };
+ const emptyGroupBy: BaseAutocompleteData[] = [];
+
+ describe('1. V5 Format Migration - All Four Queries', () => {
+ it('all queries use filter.expression format (not filters.items)', () => {
+ const widget = getAllEndpointsWidgetData(
+ emptyGroupBy,
+ mockDomainName,
+ emptyFilters,
+ );
+
+ const { queryData } = widget.query.builder;
+
+ // All 4 queries must use V5 filter.expression format
+ queryData.forEach((query) => {
+ expect(query.filter).toBeDefined();
+ expect(query.filter?.expression).toBeDefined();
+ expect(typeof query.filter?.expression).toBe('string');
+ // OLD V4 format should NOT exist
+ expect(query).not.toHaveProperty('filters');
+ });
+
+ // Verify we have exactly 4 queries
+ expect(queryData).toHaveLength(4);
+ });
+
+ it('all queries use aggregations array format (not aggregateAttribute)', () => {
+ const widget = getAllEndpointsWidgetData(
+ emptyGroupBy,
+ mockDomainName,
+ emptyFilters,
+ );
+
+ const [queryA, queryB, queryC, queryD] = widget.query.builder.queryData;
+
+ // Query A: count()
+ expect(queryA.aggregations).toBeDefined();
+ expect(Array.isArray(queryA.aggregations)).toBe(true);
+ expect(queryA.aggregations).toEqual([{ expression: 'count()' }]);
+ expect(queryA).not.toHaveProperty('aggregateAttribute');
+
+ // Query B: p99(duration_nano)
+ expect(queryB.aggregations).toBeDefined();
+ expect(Array.isArray(queryB.aggregations)).toBe(true);
+ expect(queryB.aggregations).toEqual([{ expression: 'p99(duration_nano)' }]);
+ expect(queryB).not.toHaveProperty('aggregateAttribute');
+
+ // Query C: max(timestamp)
+ expect(queryC.aggregations).toBeDefined();
+ expect(Array.isArray(queryC.aggregations)).toBe(true);
+ expect(queryC.aggregations).toEqual([{ expression: 'max(timestamp)' }]);
+ expect(queryC).not.toHaveProperty('aggregateAttribute');
+
+ // Query D: count() (disabled, for errors)
+ expect(queryD.aggregations).toBeDefined();
+ expect(Array.isArray(queryD.aggregations)).toBe(true);
+ expect(queryD.aggregations).toEqual([{ expression: 'count()' }]);
+ expect(queryD).not.toHaveProperty('aggregateAttribute');
+ });
+
+ it('all queries have correct base filter expressions', () => {
+ const widget = getAllEndpointsWidgetData(
+ emptyGroupBy,
+ mockDomainName,
+ emptyFilters,
+ );
+
+ const [queryA, queryB, queryC, queryD] = widget.query.builder.queryData;
+
+ const baseExpression = `(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}') AND kind_string = 'Client'`;
+
+ // Queries A, B, C have identical base filter
+ expect(queryA.filter?.expression).toBe(
+ `${baseExpression} AND (http.url EXISTS OR url.full EXISTS)`,
+ );
+ expect(queryB.filter?.expression).toBe(
+ `${baseExpression} AND (http.url EXISTS OR url.full EXISTS)`,
+ );
+ expect(queryC.filter?.expression).toBe(
+ `${baseExpression} AND (http.url EXISTS OR url.full EXISTS)`,
+ );
+
+ // Query D has additional has_error filter
+ expect(queryD.filter?.expression).toBe(
+ `${baseExpression} AND has_error = true AND (http.url EXISTS OR url.full EXISTS)`,
+ );
+ });
+ });
+
+ describe('2. GroupBy Structure', () => {
+ it('default groupBy includes both http.url and url.full with type attribute', () => {
+ const widget = getAllEndpointsWidgetData(
+ emptyGroupBy,
+ mockDomainName,
+ emptyFilters,
+ );
+
+ const { queryData } = widget.query.builder;
+
+ // All queries should have the same default groupBy
+ queryData.forEach((query) => {
+ expect(query.groupBy).toHaveLength(2);
+
+ // http.url
+ expect(query.groupBy).toContainEqual({
+ dataType: DataTypes.String,
+ isColumn: false,
+ isJSON: false,
+ key: 'http.url',
+ type: 'attribute',
+ });
+
+ // url.full
+ expect(query.groupBy).toContainEqual({
+ dataType: DataTypes.String,
+ isColumn: false,
+ isJSON: false,
+ key: 'url.full',
+ type: 'attribute',
+ });
+ });
+ });
+
+ it('custom groupBy is appended after defaults', () => {
+ const customGroupBy: BaseAutocompleteData[] = [
+ {
+ dataType: DataTypes.String,
+ key: 'service.name',
+ type: 'resource',
+ },
+ {
+ dataType: DataTypes.String,
+ key: 'deployment.environment',
+ type: 'resource',
+ },
+ ];
+
+ const widget = getAllEndpointsWidgetData(
+ customGroupBy,
+ mockDomainName,
+ emptyFilters,
+ );
+
+ const { queryData } = widget.query.builder;
+
+ // All queries should have defaults + custom groupBy
+ queryData.forEach((query) => {
+ expect(query.groupBy).toHaveLength(4); // 2 defaults + 2 custom
+
+ // First two should be defaults (http.url, url.full)
+ expect(query.groupBy[0].key).toBe('http.url');
+ expect(query.groupBy[1].key).toBe('url.full');
+
+ // Last two should be custom (matching subset of properties)
+ expect(query.groupBy[2]).toMatchObject({
+ dataType: DataTypes.String,
+ key: 'service.name',
+ type: 'resource',
+ });
+ expect(query.groupBy[3]).toMatchObject({
+ dataType: DataTypes.String,
+ key: 'deployment.environment',
+ type: 'resource',
+ });
+ });
+ });
+ });
+
+ describe('3. Query-Specific Validations', () => {
+ it('query D has has_error filter and is disabled', () => {
+ const widget = getAllEndpointsWidgetData(
+ emptyGroupBy,
+ mockDomainName,
+ emptyFilters,
+ );
+
+ const [queryA, queryB, queryC, queryD] = widget.query.builder.queryData;
+
+ // Query D should be disabled
+ expect(queryD.disabled).toBe(true);
+
+ // Queries A, B, C should NOT be disabled
+ expect(queryA.disabled).toBe(false);
+ expect(queryB.disabled).toBe(false);
+ expect(queryC.disabled).toBe(false);
+
+ // Query D should have has_error in filter
+ expect(queryD.filter?.expression).toContain('has_error = true');
+
+ // Queries A, B, C should NOT have has_error
+ expect(queryA.filter?.expression).not.toContain('has_error');
+ expect(queryB.filter?.expression).not.toContain('has_error');
+ expect(queryC.filter?.expression).not.toContain('has_error');
+ });
+ });
+});
diff --git a/frontend/src/container/ApiMonitoring/__tests__/EndPointMetrics.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/EndPointMetrics.test.tsx
deleted file mode 100644
index c0accaa6a8..0000000000
--- a/frontend/src/container/ApiMonitoring/__tests__/EndPointMetrics.test.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { getFormattedEndPointMetricsData } from 'container/ApiMonitoring/utils';
-import { SuccessResponse } from 'types/api';
-
-import EndPointMetrics from '../Explorer/Domains/DomainDetails/components/EndPointMetrics';
-import ErrorState from '../Explorer/Domains/DomainDetails/components/ErrorState';
-
-// Create a partial mock of the UseQueryResult interface for testing
-interface MockQueryResult {
- isLoading: boolean;
- isRefetching: boolean;
- isError: boolean;
- data?: any;
- refetch: () => void;
-}
-
-// Mock the utils function
-jest.mock('container/ApiMonitoring/utils', () => ({
- getFormattedEndPointMetricsData: jest.fn(),
-}));
-
-// Mock the ErrorState component
-jest.mock('../Explorer/Domains/DomainDetails/components/ErrorState', () => ({
- __esModule: true,
- default: jest.fn().mockImplementation(({ refetch }) => (
- <div data-testid="error-state-mock">
- <button type="button" data-testid="refetch-button" onClick={refetch}>
- Retry
- </button>
- </div>
- )),
-}));
-
-// Mock antd components
-jest.mock('antd', () => {
- const originalModule = jest.requireActual('antd');
- return {
- ...originalModule,
- Progress: jest
- .fn()
- .mockImplementation(() => <div data-testid="progress-bar-mock" />),
- Skeleton: {
- Button: jest
- .fn()
- .mockImplementation(() => <div data-testid="skeleton-button-mock" />),
- },
- Tooltip: jest
- .fn()
- .mockImplementation(({ children }) => (
- <div data-testid="tooltip-mock">{children}</div>
- )),
- Typography: {
- Text: jest.fn().mockImplementation(({ children, className }) => (
- <div data-testid={`typography-${className}`} className={className}>
- {children}
- </div>
- )),
- },
- };
-});
-
-describe('EndPointMetrics', () => {
- // Common metric data to use in tests
- const mockMetricsData = {
- key: 'test-key',
- rate: '42',
- latency: 99,
- errorRate: 5.5,
- lastUsed: '5 minutes ago',
- };
-
- // Basic props for tests
- const refetchFn = jest.fn();
-
- beforeEach(() => {
- jest.clearAllMocks();
- (getFormattedEndPointMetricsData as jest.Mock).mockReturnValue(
- mockMetricsData,
- );
- });
-
- it('renders loading state correctly', () => {
- const mockQuery: MockQueryResult = {
- isLoading: true,
- isRefetching: false,
- isError: false,
- data: undefined,
- refetch: refetchFn,
- };
-
- render(<EndPointMetrics endPointMetricsDataQuery={mockQuery as any} />);
-
- // Verify skeleton loaders are visible
- const skeletonElements = screen.getAllByTestId('skeleton-button-mock');
- expect(skeletonElements.length).toBe(4);
-
- // Verify labels are visible even during loading
- expect(screen.getByText('Rate')).toBeInTheDocument();
- expect(screen.getByText('AVERAGE LATENCY')).toBeInTheDocument();
- expect(screen.getByText('ERROR %')).toBeInTheDocument();
- expect(screen.getByText('LAST USED')).toBeInTheDocument();
- });
-
- it('renders error state correctly', () => {
- const mockQuery: MockQueryResult = {
- isLoading: false,
- isRefetching: false,
- isError: true,
- data: undefined,
- refetch: refetchFn,
- };
-
- render(<EndPointMetrics endPointMetricsDataQuery={mockQuery as any} />);
-
- // Verify error state is shown
- expect(screen.getByTestId('error-state-mock')).toBeInTheDocument();
- expect(ErrorState).toHaveBeenCalledWith(
- { refetch: expect.any(Function) },
- expect.anything(),
- );
- });
-
- it('renders data correctly when loaded', () => {
- const mockData = {
- payload: {
- data: {
- result: [
- {
- table: {
- rows: [
- { data: { A: '42', B: '99000000', D: '1609459200000000', F1: '5.5' } },
- ],
- },
- },
- ],
- },
- },
- } as SuccessResponse<any>;
-
- const mockQuery: MockQueryResult = {
- isLoading: false,
- isRefetching: false,
- isError: false,
- data: mockData,
- refetch: refetchFn,
- };
-
- render(<EndPointMetrics endPointMetricsDataQuery={mockQuery as any} />);
-
- // Verify the utils function was called with the data
- expect(getFormattedEndPointMetricsData).toHaveBeenCalledWith(
- mockData.payload.data.result[0].table.rows,
- );
-
- // Verify data is displayed
- expect(
- screen.getByText(`${mockMetricsData.rate} ops/sec`),
- ).toBeInTheDocument();
- expect(screen.getByText(`${mockMetricsData.latency}ms`)).toBeInTheDocument();
- expect(screen.getByText(mockMetricsData.lastUsed)).toBeInTheDocument();
- expect(screen.getByTestId('progress-bar-mock')).toBeInTheDocument(); // For error rate
- });
-
- it('handles refetching state correctly', () => {
- const mockQuery: MockQueryResult = {
- isLoading: false,
- isRefetching: true,
- isError: false,
- data: undefined,
- refetch: refetchFn,
- };
-
- render(<EndPointMetrics endPointMetricsDataQuery={mockQuery as any} />);
-
- // Verify skeleton loaders are visible during refetching
- const skeletonElements = screen.getAllByTestId('skeleton-button-mock');
- expect(skeletonElements.length).toBe(4);
- });
-
- it('handles null metrics data gracefully', () => {
- // Mock the utils function to return null to simulate missing data
- (getFormattedEndPointMetricsData as jest.Mock).mockReturnValue(null);
-
- const mockData = {
- payload: {
- data: {
- result: [
- {
- table: {
- rows: [],
- },
- },
- ],
- },
- },
- } as SuccessResponse<any>;
-
- const mockQuery: MockQueryResult = {
- isLoading: false,
- isRefetching: false,
- isError: false,
- data: mockData,
- refetch: refetchFn,
- };
-
- render(<EndPointMetrics endPointMetricsDataQuery={mockQuery as any} />);
-
- // Even with null data, the component should render without crashing
- expect(screen.getByText('Rate')).toBeInTheDocument();
- });
-});
diff --git a/frontend/src/container/ApiMonitoring/__tests__/EndpointDropdownV5Migration.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/EndpointDropdownV5Migration.test.tsx
new file mode 100644
index 0000000000..94df26a466
--- /dev/null
+++ b/frontend/src/container/ApiMonitoring/__tests__/EndpointDropdownV5Migration.test.tsx
@@ -0,0 +1,173 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/* eslint-disable sonarjs/no-duplicate-string */
+/**
+ * V5 Migration Tests for Endpoint Dropdown Query
+ *
+ * These tests validate the migration from V4 to V5 format for the third payload
+ * in getEndPointDetailsQueryPayload (endpoint dropdown data):
+ * - Filter format change: filters.items[] → filter.expression
+ * - Domain handling: (net.peer.name OR server.address)
+ * - Kind filter: kind_string = 'Client'
+ * - Existence check: (http.url EXISTS OR url.full EXISTS)
+ * - Aggregation: count() expression
+ * - GroupBy: Both http.url AND url.full with type 'attribute'
+ */
+import { getEndPointDetailsQueryPayload } from 'container/ApiMonitoring/utils';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+describe('EndpointDropdown - V5 Migration Validation', () => {
+ const mockDomainName = 'api.example.com';
+ const mockStartTime = 1000;
+ const mockEndTime = 2000;
+ const emptyFilters: IBuilderQuery['filters'] = {
+ items: [],
+ op: 'AND',
+ };
+
+ describe('1. V5 Format Migration - Structure and Base Filters', () => {
+ it('migrates to V5 format with correct filter expression structure, aggregations, and groupBy', () => {
+ const payload = getEndPointDetailsQueryPayload(
+ mockDomainName,
+ mockStartTime,
+ mockEndTime,
+ emptyFilters,
+ );
+
+ // Third payload is the endpoint dropdown query (index 2)
+ const dropdownQuery = payload[2];
+ const queryA = dropdownQuery.query.builder.queryData[0];
+
+ // CRITICAL V5 MIGRATION: filter.expression (not filters.items)
+ expect(queryA.filter).toBeDefined();
+ expect(queryA.filter?.expression).toBeDefined();
+ expect(typeof queryA.filter?.expression).toBe('string');
+ expect(queryA).not.toHaveProperty('filters');
+
+ // Base filter 1: Domain (net.peer.name OR server.address)
+ expect(queryA.filter?.expression).toContain(
+ `(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
+ );
+
+ // Base filter 2: Kind
+ expect(queryA.filter?.expression).toContain("kind_string = 'Client'");
+
+ // Base filter 3: Existence check
+ expect(queryA.filter?.expression).toContain(
+ '(http.url EXISTS OR url.full EXISTS)',
+ );
+
+ // V5 Aggregation format: aggregations array (not aggregateAttribute)
+ expect(queryA.aggregations).toBeDefined();
+ expect(Array.isArray(queryA.aggregations)).toBe(true);
+ expect(queryA.aggregations?.[0]).toEqual({
+ expression: 'count()',
+ });
+ expect(queryA).not.toHaveProperty('aggregateAttribute');
+
+ // GroupBy: Both http.url and url.full
+ expect(queryA.groupBy).toHaveLength(2);
+ expect(queryA.groupBy).toContainEqual({
+ key: 'http.url',
+ dataType: 'string',
+ type: 'attribute',
+ });
+ expect(queryA.groupBy).toContainEqual({
+ key: 'url.full',
+ dataType: 'string',
+ type: 'attribute',
+ });
+ });
+ });
+
+ describe('2. Custom Filters Integration', () => {
+ it('merges custom filters into filter expression with AND logic', () => {
+ const customFilters: IBuilderQuery['filters'] = {
+ items: [
+ {
+ id: 'test-1',
+ key: {
+ key: 'service.name',
+ dataType: 'string' as any,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'user-service',
+ },
+ {
+ id: 'test-2',
+ key: {
+ key: 'deployment.environment',
+ dataType: 'string' as any,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'production',
+ },
+ ],
+ op: 'AND',
+ };
+
+ const payload = getEndPointDetailsQueryPayload(
+ mockDomainName,
+ mockStartTime,
+ mockEndTime,
+ customFilters,
+ );
+
+ const dropdownQuery = payload[2];
+ const expression =
+ dropdownQuery.query.builder.queryData[0].filter?.expression;
+
+ // Exact filter expression with custom filters merged
+ expect(expression).toBe(
+ "(net.peer.name = 'api.example.com' OR server.address = 'api.example.com') AND kind_string = 'Client' AND (http.url EXISTS OR url.full EXISTS) service.name = 'user-service' AND deployment.environment = 'production'",
+ );
+ });
+ });
+
+ describe('3. HTTP URL Filter Special Handling', () => {
+ it('converts http.url filter to (http.url OR url.full) expression', () => {
+ const filtersWithHttpUrl: IBuilderQuery['filters'] = {
+ items: [
+ {
+ id: 'http-url-filter',
+ key: {
+ key: 'http.url',
+ dataType: 'string' as any,
+ type: 'tag',
+ },
+ op: '=',
+ value: '/api/users',
+ },
+ {
+ id: 'service-filter',
+ key: {
+ key: 'service.name',
+ dataType: 'string' as any,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'user-service',
+ },
+ ],
+ op: 'AND',
+ };
+
+ const payload = getEndPointDetailsQueryPayload(
+ mockDomainName,
+ mockStartTime,
+ mockEndTime,
+ filtersWithHttpUrl,
+ );
+
+ const dropdownQuery = payload[2];
+ const expression =
+ dropdownQuery.query.builder.queryData[0].filter?.expression;
+
+ // CRITICAL: Exact filter expression with http.url converted to OR logic
+ expect(expression).toBe(
+ "(net.peer.name = 'api.example.com' OR server.address = 'api.example.com') AND kind_string = 'Client' AND (http.url EXISTS OR url.full EXISTS) service.name = 'user-service' AND (http.url = '/api/users' OR url.full = '/api/users')",
+ );
+ });
+ });
+});
diff --git a/frontend/src/container/ApiMonitoring/__tests__/MetricOverTimeV5Migration.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/MetricOverTimeV5Migration.test.tsx
new file mode 100644
index 0000000000..9802382537
--- /dev/null
+++ b/frontend/src/container/ApiMonitoring/__tests__/MetricOverTimeV5Migration.test.tsx
@@ -0,0 +1,173 @@
+import {
+ getLatencyOverTimeWidgetData,
+ getRateOverTimeWidgetData,
+} from 'container/ApiMonitoring/utils';
+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+describe('MetricOverTime - V5 Migration Validation', () => {
+ const mockDomainName = 'api.example.com';
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ const mockEndpointName = '/api/users';
+ const emptyFilters: IBuilderQuery['filters'] = {
+ items: [],
+ op: 'AND',
+ };
+
+ describe('1. Rate Over Time - V5 Payload Structure', () => {
+ it('generates V5 filter expression format (not V3 filters.items)', () => {
+ const widget = getRateOverTimeWidgetData(
+ mockDomainName,
+ mockEndpointName,
+ emptyFilters,
+ );
+
+ const queryData = widget.query.builder.queryData[0];
+
+ // CRITICAL: Must use V5 format (filter.expression), not V3 format (filters.items)
+ expect(queryData.filter).toBeDefined();
+ expect(queryData?.filter?.expression).toBeDefined();
+ expect(typeof queryData?.filter?.expression).toBe('string');
+
+ // OLD V3 format should NOT exist
+ expect(queryData).not.toHaveProperty('filters.items');
+ });
+
+ it('uses new domain filter format: (net.peer.name OR server.address)', () => {
+ const widget = getRateOverTimeWidgetData(
+ mockDomainName,
+ mockEndpointName,
+ emptyFilters,
+ );
+
+ const queryData = widget.query.builder.queryData[0];
+
+ // Verify EXACT new filter format with OR operator
+ expect(queryData?.filter?.expression).toContain(
+ `(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
+ );
+
+ // Endpoint name is used in legend, not filter
+ expect(queryData.legend).toContain('/api/users');
+ });
+
+ it('merges custom filters into filter expression', () => {
+ const customFilters: IBuilderQuery['filters'] = {
+ items: [
+ {
+ id: 'test-1',
+ key: {
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ key: 'service.name',
+ dataType: DataTypes.String,
+ type: 'resource',
+ },
+ op: '=',
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ value: 'user-service',
+ },
+ {
+ id: 'test-2',
+ key: {
+ key: 'deployment.environment',
+ dataType: DataTypes.String,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'production',
+ },
+ ],
+ op: 'AND',
+ };
+
+ const widget = getRateOverTimeWidgetData(
+ mockDomainName,
+ mockEndpointName,
+ customFilters,
+ );
+
+ const queryData = widget.query.builder.queryData[0];
+
+ // Verify domain filter is present
+ expect(queryData?.filter?.expression).toContain(
+ `(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
+ );
+
+ // Verify custom filters are merged into the expression
+ expect(queryData?.filter?.expression).toContain('service.name');
+ expect(queryData?.filter?.expression).toContain('user-service');
+ expect(queryData?.filter?.expression).toContain('deployment.environment');
+ expect(queryData?.filter?.expression).toContain('production');
+ });
+ });
+
+ describe('2. Latency Over Time - V5 Payload Structure', () => {
+ it('generates V5 filter expression format (not V3 filters.items)', () => {
+ const widget = getLatencyOverTimeWidgetData(
+ mockDomainName,
+ mockEndpointName,
+ emptyFilters,
+ );
+
+ const queryData = widget.query.builder.queryData[0];
+
+ // CRITICAL: Must use V5 format (filter.expression), not V3 format (filters.items)
+ expect(queryData.filter).toBeDefined();
+ expect(queryData?.filter?.expression).toBeDefined();
+ expect(typeof queryData?.filter?.expression).toBe('string');
+
+ // OLD V3 format should NOT exist
+ expect(queryData).not.toHaveProperty('filters.items');
+ });
+
+ it('uses new domain filter format: (net.peer.name OR server.address)', () => {
+ const widget = getLatencyOverTimeWidgetData(
+ mockDomainName,
+ mockEndpointName,
+ emptyFilters,
+ );
+
+ const queryData = widget.query.builder.queryData[0];
+
+ // Verify EXACT new filter format with OR operator
+ expect(queryData.filter).toBeDefined();
+ expect(queryData?.filter?.expression).toContain(
+ `(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
+ );
+
+ // Endpoint name is used in legend, not filter
+ expect(queryData.legend).toContain('/api/users');
+ });
+
+ it('merges custom filters into filter expression', () => {
+ const customFilters: IBuilderQuery['filters'] = {
+ items: [
+ {
+ id: 'test-1',
+ key: {
+ key: 'service.name',
+ dataType: DataTypes.String,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'user-service',
+ },
+ ],
+ op: 'AND',
+ };
+
+ const widget = getLatencyOverTimeWidgetData(
+ mockDomainName,
+ mockEndpointName,
+ customFilters,
+ );
+
+ const queryData = widget.query.builder.queryData[0];
+
+ // Verify domain filter is present
+ expect(queryData?.filter?.expression).toContain(
+ `(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}') service.name = 'user-service'`,
+ );
+ });
+ });
+});
diff --git a/frontend/src/container/ApiMonitoring/__tests__/StatusCodeBarChartsV5Migration.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/StatusCodeBarChartsV5Migration.test.tsx
new file mode 100644
index 0000000000..b6528c1c6a
--- /dev/null
+++ b/frontend/src/container/ApiMonitoring/__tests__/StatusCodeBarChartsV5Migration.test.tsx
@@ -0,0 +1,237 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/* eslint-disable sonarjs/no-duplicate-string */
+/**
+ * V5 Migration Tests for Status Code Bar Chart Queries
+ *
+ * These tests validate the migration to V5 format for the bar chart payloads
+ * in getEndPointDetailsQueryPayload (5th and 6th payloads):
+ * - Number of Calls Chart (count aggregation)
+ * - Latency Chart (p99 aggregation)
+ *
+ * V5 Changes:
+ * - Filter format change: filters.items[] → filter.expression
+ * - Domain filter: (net.peer.name OR server.address)
+ * - Kind filter: kind_string = 'Client'
+ * - stepInterval: 60 → null
+ * - Grouped by response_status_code
+ */
+import { TraceAggregation } from 'api/v5/v5';
+import { getEndPointDetailsQueryPayload } from 'container/ApiMonitoring/utils';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+describe('StatusCodeBarCharts - V5 Migration Validation', () => {
+ const mockDomainName = '0.0.0.0';
+ const mockStartTime = 1762573673000;
+ const mockEndTime = 1762832873000;
+ const emptyFilters: IBuilderQuery['filters'] = {
+ items: [],
+ op: 'AND',
+ };
+
+ describe('1. Number of Calls Chart - V5 Payload Structure', () => {
+ it('generates correct V5 payload for count aggregation grouped by status code', () => {
+ const payload = getEndPointDetailsQueryPayload(
+ mockDomainName,
+ mockStartTime,
+ mockEndTime,
+ emptyFilters,
+ );
+
+ // 5th payload (index 4) is the number of calls bar chart
+ const callsChartQuery = payload[4];
+ const queryA = callsChartQuery.query.builder.queryData[0];
+
+ // V5 format: filter.expression (not filters.items)
+ expect(queryA.filter).toBeDefined();
+ expect(queryA.filter?.expression).toBeDefined();
+ expect(typeof queryA.filter?.expression).toBe('string');
+ expect(queryA).not.toHaveProperty('filters.items');
+
+ // Base filter 1: Domain (net.peer.name OR server.address)
+ expect(queryA.filter?.expression).toContain(
+ `(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
+ );
+
+ // Base filter 2: Kind
+ expect(queryA.filter?.expression).toContain("kind_string = 'Client'");
+
+ // Aggregation: count
+ expect(queryA.queryName).toBe('A');
+ expect(queryA.aggregateOperator).toBe('count');
+ expect(queryA.disabled).toBe(false);
+
+ // Grouped by response_status_code
+ expect(queryA.groupBy).toContainEqual(
+ expect.objectContaining({
+ key: 'response_status_code',
+ dataType: 'string',
+ type: 'span',
+ }),
+ );
+
+ // V5 critical: stepInterval should be null
+ expect(queryA.stepInterval).toBeNull();
+
+ // Time aggregation
+ expect(queryA.timeAggregation).toBe('rate');
+ });
+ });
+
+ describe('2. Latency Chart - V5 Payload Structure', () => {
+ it('generates correct V5 payload for p99 aggregation grouped by status code', () => {
+ const payload = getEndPointDetailsQueryPayload(
+ mockDomainName,
+ mockStartTime,
+ mockEndTime,
+ emptyFilters,
+ );
+
+ // 6th payload (index 5) is the latency bar chart
+ const latencyChartQuery = payload[5];
+ const queryA = latencyChartQuery.query.builder.queryData[0];
+
+ // V5 format: filter.expression (not filters.items)
+ expect(queryA.filter).toBeDefined();
+ expect(queryA.filter?.expression).toBeDefined();
+ expect(typeof queryA.filter?.expression).toBe('string');
+ expect(queryA).not.toHaveProperty('filters.items');
+
+ // Base filter 1: Domain (net.peer.name OR server.address)
+ expect(queryA.filter?.expression).toContain(
+ `(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
+ );
+
+ // Base filter 2: Kind
+ expect(queryA.filter?.expression).toContain("kind_string = 'Client'");
+
+ // Aggregation: p99 on duration_nano
+ expect(queryA.queryName).toBe('A');
+ expect(queryA.aggregateOperator).toBe('p99');
+ expect(queryA.aggregations?.[0]).toBeDefined();
+ expect((queryA.aggregations?.[0] as TraceAggregation)?.expression).toBe(
+ 'p99(duration_nano)',
+ );
+ expect(queryA.disabled).toBe(false);
+
+ // Grouped by response_status_code
+ expect(queryA.groupBy).toContainEqual(
+ expect.objectContaining({
+ key: 'response_status_code',
+ dataType: 'string',
+ type: 'span',
+ }),
+ );
+
+ // V5 critical: stepInterval should be null
+ expect(queryA.stepInterval).toBeNull();
+
+ // Time aggregation
+ expect(queryA.timeAggregation).toBe('p99');
+ });
+ });
+
+ describe('3. Custom Filters Integration', () => {
+ it('merges custom filters into filter expression for both charts', () => {
+ const customFilters: IBuilderQuery['filters'] = {
+ items: [
+ {
+ id: 'test-1',
+ key: {
+ key: 'service.name',
+ dataType: 'string' as any,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'user-service',
+ },
+ {
+ id: 'test-2',
+ key: {
+ key: 'deployment.environment',
+ dataType: 'string' as any,
+ type: 'resource',
+ },
+ op: '=',
+ value: 'production',
+ },
+ ],
+ op: 'AND',
+ };
+
+ const payload = getEndPointDetailsQueryPayload(
+ mockDomainName,
+ mockStartTime,
+ mockEndTime,
+ customFilters,
+ );
+
+ const callsChartQuery = payload[4];
+ const latencyChartQuery = payload[5];
+
+ const callsExpression =
+ callsChartQuery.query.builder.queryData[0].filter?.expression;
+ const latencyExpression =
+ latencyChartQuery.query.builder.queryData[0].filter?.expression;
+
+ // Both charts should have the same filter expression
+ expect(callsExpression).toBe(latencyExpression);
+
+ // Verify base filters
+ expect(callsExpression).toContain('net.peer.name');
+ expect(callsExpression).toContain("kind_string = 'Client'");
+
+ // Verify custom filters are merged
+ expect(callsExpression).toContain('service.name');
+ expect(callsExpression).toContain('user-service');
+ expect(callsExpression).toContain('deployment.environment');
+ expect(callsExpression).toContain('production');
+ });
+ });
+
+ describe('4. HTTP URL Filter Handling', () => {
+ it('converts http.url filter to (http.url OR url.full) expression in both charts', () => {
+ const filtersWithHttpUrl: IBuilderQuery['filters'] = {
+ items: [
+ {
+ id: 'http-url-filter',
+ key: {
+ key: 'http.url',
+ dataType: 'string' as any,
+ type: 'tag',
+ },
+ op: '=',
+ value: '/api/metrics',
+ },
+ ],
+ op: 'AND',
+ };
+
+ const payload = getEndPointDetailsQueryPayload(
+ mockDomainName,
+ mockStartTime,
+ mockEndTime,
+ filtersWithHttpUrl,
+ );
+
+ const callsChartQuery = payload[4];
+ const latencyChartQuery = payload[5];
+
+ const callsExpression =
+ callsChartQuery.query.builder.queryData[0].filter?.expression;
+ const latencyExpression =
+ latencyChartQuery.query.builder.queryData[0].filter?.expression;
+
+ // CRITICAL: http.url converted to OR logic
+ expect(callsExpression).toContain(
+ "(http.url = '/api/metrics' OR url.full = '/api/metrics')",
+ );
+ expect(latencyExpression).toContain(
+ "(http.url = '/api/metrics' OR url.full = '/api/metrics')",
+ );
+
+ // Base filters still present
+ expect(callsExpression).toContain('net.peer.name');
+ expect(callsExpression).toContain("kind_string = 'Client'");
+ });
+ });
+});
diff --git a/frontend/src/container/ApiMonitoring/__tests__/TopErrors.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/TopErrors.test.tsx
index def3b589be..d81b5bf295 100644
--- a/frontend/src/container/ApiMonitoring/__tests__/TopErrors.test.tsx
+++ b/frontend/src/container/ApiMonitoring/__tests__/TopErrors.test.tsx
@@ -1,9 +1,11 @@
+import { BuilderQuery } from 'api/v5/v5';
import { useNavigateToExplorer } from 'components/CeleryTask/useNavigateToExplorer';
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';
+import { getTopErrorsQueryPayload } from '../utils';
// Mock the EndPointsDropDown component to avoid issues
jest.mock(
@@ -36,6 +38,7 @@ describe('TopErrors', () => {
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,
@@ -305,45 +308,14 @@ describe('TopErrors', () => {
});
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]],
- },
- ],
- },
- },
- }),
- );
- }),
+ // let capturedRequest: any;
+
+ const topErrorsPayload = getTopErrorsQueryPayload(
+ 'test-domain',
+ mockProps.timeRange.startTime,
+ mockProps.timeRange.endTime,
+ { items: [], op: 'AND' },
+ false,
);
// eslint-disable-next-line react/jsx-props-no-spreading
@@ -351,20 +323,18 @@ describe('TopErrors', () => {
// Wait for the API call to be made
await waitFor(() => {
- expect(capturedRequest).toBeDefined();
+ expect(topErrorsPayload).toBeDefined();
});
// Extract the filter expression from the captured request
- const filterExpression =
- capturedRequest.compositeQuery.queries[0].spec.filter.expression;
+ // getTopErrorsQueryPayload returns a builder_query with TraceBuilderQuery spec
+ const builderQuery = topErrorsPayload.compositeQuery.queries[0]
+ .spec as BuilderQuery;
+ const filterExpression = builderQuery.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')`,
+ `kind_string = 'Client' AND (http.url EXISTS OR url.full EXISTS) AND (net.peer.name = 'test-domain' OR server.address = 'test-domain') AND has_error = true`,
);
- 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 4ccc783863..9858963a1f 100644
--- a/frontend/src/container/ApiMonitoring/utils.tsx
+++ b/frontend/src/container/ApiMonitoring/utils.tsx
@@ -11,8 +11,10 @@ import { PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { GraphClickMetaData } from 'container/GridCardLayout/useNavigateToExplorerPages';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
+import { convertNanoToMilliseconds } from 'container/MetricsExplorer/Summary/utils';
import dayjs from 'dayjs';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
+import { RowData } from 'lib/query/createTableColumnsFromQuery';
import { cloneDeep } from 'lodash-es';
import { ArrowUpDown, ChevronDown, ChevronRight, Info } from 'lucide-react';
import { getWidgetQuery } from 'pages/MessagingQueues/MQDetails/MetricPage/MetricPageUtil';
@@ -58,6 +60,56 @@ export const getDomainNameFilterExpression = (domainName: string): string =>
`(net.peer.name = '${domainName}' OR server.address = '${domainName}')`;
export const clientKindExpression = `kind_string = 'Client'`;
+
+/**
+ * Converts filters to expression, handling http.url specially by creating (http.url OR url.full) condition
+ * @param filters Filters to convert
+ * @param baseExpression Base expression to combine with filters
+ * @returns Filter expression string
+ */
+export const convertFiltersWithUrlHandling = (
+ filters: IBuilderQuery['filters'],
+ baseExpression: string,
+): string => {
+ if (!filters) {
+ return baseExpression;
+ }
+
+ // Check if filters contain http.url (SPAN_ATTRIBUTES.URL_PATH)
+ const httpUrlFilter = filters.items?.find(
+ (item) => item.key?.key === SPAN_ATTRIBUTES.URL_PATH,
+ );
+
+ // If http.url filter exists, create modified filters with (http.url OR url.full)
+ if (httpUrlFilter && httpUrlFilter.value) {
+ // Remove ALL http.url filters from items (guards against duplicates)
+ const otherFilters = filters.items?.filter(
+ (item) => item.key?.key !== SPAN_ATTRIBUTES.URL_PATH,
+ );
+
+ // Convert to expression first with other filters
+ const {
+ filter: intermediateFilter,
+ } = convertFiltersToExpressionWithExistingQuery(
+ { ...filters, items: otherFilters || [] },
+ baseExpression,
+ );
+
+ // Add the OR condition for http.url and url.full
+ const urlValue = httpUrlFilter.value;
+ const urlCondition = `(http.url = '${urlValue}' OR url.full = '${urlValue}')`;
+ return intermediateFilter.expression.trim()
+ ? `${intermediateFilter.expression} AND ${urlCondition}`
+ : urlCondition;
+ }
+
+ const { filter } = convertFiltersToExpressionWithExistingQuery(
+ filters,
+ baseExpression,
+ );
+ return filter.expression;
+};
+
export const ApiMonitoringQuickFiltersConfig: IQuickFiltersConfig[] = [
{
type: FiltersType.CHECKBOX,
@@ -309,6 +361,8 @@ export const formatDataForTable = (
});
};
+const urlExpression = `(url.full EXISTS OR http.url EXISTS)`;
+
export const getDomainMetricsQueryPayload = (
domainName: string,
start: number,
@@ -325,29 +379,19 @@ export const getDomainMetricsQueryPayload = (
dataSource: DataSource.TRACES,
queryName: 'A',
aggregateOperator: 'count',
- aggregateAttribute: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.URL_PATH,
- type: 'tag',
- },
+ aggregations: [
+ {
+ expression: 'count()',
+ },
+ ],
timeAggregation: 'rate',
spaceAggregation: 'sum',
functions: [],
- filters: {
- items: [
- {
- id: '4c57937c',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(domainName)} AND ${urlExpression}`,
+ ),
},
expression: 'A',
disabled: false,
@@ -363,29 +407,19 @@ export const getDomainMetricsQueryPayload = (
dataSource: DataSource.TRACES,
queryName: 'B',
aggregateOperator: 'p99',
- aggregateAttribute: {
- dataType: DataTypes.Float64,
- key: 'duration_nano',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'p99(duration_nano)',
+ },
+ ],
timeAggregation: 'p99',
spaceAggregation: 'sum',
functions: [],
- filters: {
- items: [
- {
- id: '2cf675cd',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(domainName)}`,
+ ),
},
expression: 'B',
disabled: false,
@@ -401,40 +435,19 @@ export const getDomainMetricsQueryPayload = (
dataSource: DataSource.TRACES,
queryName: 'C',
aggregateOperator: 'count',
- aggregateAttribute: {
- dataType: DataTypes.String,
- id: '------false',
- key: '',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'count()',
+ },
+ ],
timeAggregation: 'count',
spaceAggregation: 'sum',
functions: [],
- filters: {
- items: [
- {
- id: '3db0f605',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '6096f745',
- key: {
- dataType: DataTypes.bool,
- key: 'has_error',
- type: '',
- },
- op: '=',
- value: 'true',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(domainName)} AND has_error = true`,
+ ),
},
expression: 'C',
disabled: true,
@@ -450,30 +463,19 @@ export const getDomainMetricsQueryPayload = (
dataSource: DataSource.TRACES,
queryName: 'D',
aggregateOperator: 'max',
- aggregateAttribute: {
- dataType: DataTypes.String,
- id: 'timestamp------false',
- key: 'timestamp',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'max(timestamp)',
+ },
+ ],
timeAggregation: 'max',
spaceAggregation: 'sum',
functions: [],
- filters: {
- items: [
- {
- id: '8ff8dea1',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(domainName)}`,
+ ),
},
expression: 'D',
disabled: false,
@@ -546,21 +548,27 @@ export const formatDomainMetricsDataForTable = (
return {
endpointCount: '-',
latency: '-',
- errorRate: 0,
+ errorRate: '-',
lastUsed: '-',
};
}
+
+ const dataMap = row.data;
+ // Convert nanoseconds to milliseconds for latency (only if valid)
+ const latencyInMs = !isEmptyFilterValue(dataMap.B)
+ ? convertNanoToMilliseconds(Number(dataMap.B))
+ : undefined;
+
+ // Convert nanoseconds to milliseconds for timestamp, then format (only if valid)
+ const lastUsedFormatted = !isEmptyFilterValue(dataMap.D)
+ ? getLastUsedRelativeTime(new Date(dataMap.D as string).getTime())
+ : undefined;
+
return {
- endpointCount: row.data.A === 'n/a' || !row.data.A ? '-' : Number(row.data.A),
- latency:
- row.data.B === 'n/a' || row.data.B === undefined
- ? '-'
- : Math.round(Number(row.data.B) / 1000000),
- errorRate: row.data.F1 === 'n/a' || !row.data.F1 ? 0 : Number(row.data.F1),
- lastUsed:
- row.data.D === 'n/a' || !row.data.D
- ? '-'
- : getLastUsedRelativeTime(Math.floor(Number(row.data.D) / 1000000)),
+ endpointCount: getDisplayValue(dataMap.A),
+ latency: getDisplayValue(latencyInMs),
+ errorRate: getDisplayValue(dataMap.F1),
+ lastUsed: getDisplayValue(lastUsedFormatted),
};
};
@@ -571,7 +579,14 @@ const defaultGroupBy = [
isColumn: false,
isJSON: false,
key: SPAN_ATTRIBUTES.URL_PATH,
- type: 'tag',
+ type: 'attribute',
+ },
+ {
+ dataType: DataTypes.String,
+ isColumn: false,
+ isJSON: false,
+ key: 'url.full',
+ type: 'attribute',
},
// {
// key: SPAN_ATTRIBUTES.SERVER_PORT,
@@ -834,55 +849,6 @@ export const getEndPointsQueryPayload = (
];
};
-/**
- * Converts filters to expression, handling http.url specially by creating (http.url OR url.full) condition
- * @param filters Filters to convert
- * @param baseExpression Base expression to combine with filters
- * @returns Filter expression string
- */
-export const convertFiltersWithUrlHandling = (
- filters: IBuilderQuery['filters'],
- baseExpression: string,
-): string => {
- if (!filters) {
- return baseExpression;
- }
-
- // Check if filters contain http.url (SPAN_ATTRIBUTES.URL_PATH)
- const httpUrlFilter = filters.items?.find(
- (item) => item.key?.key === SPAN_ATTRIBUTES.URL_PATH,
- );
-
- // If http.url filter exists, create modified filters with (http.url OR url.full)
- if (httpUrlFilter && httpUrlFilter.value) {
- // Remove ALL http.url filters from items (guards against duplicates)
- const otherFilters = filters.items?.filter(
- (item) => item.key?.key !== SPAN_ATTRIBUTES.URL_PATH,
- );
-
- // Convert to expression first with other filters
- const {
- filter: intermediateFilter,
- } = convertFiltersToExpressionWithExistingQuery(
- { ...filters, items: otherFilters || [] },
- baseExpression,
- );
-
- // Add the OR condition for http.url and url.full
- const urlValue = httpUrlFilter.value;
- const urlCondition = `(http.url = '${urlValue}' OR url.full = '${urlValue}')`;
- return intermediateFilter.expression.trim()
- ? `${intermediateFilter.expression} AND ${urlCondition}`
- : urlCondition;
- }
-
- const { filter } = convertFiltersToExpressionWithExistingQuery(
- filters,
- baseExpression,
- );
- return filter.expression;
-};
-
// eslint-disable-next-line sonarjs/cognitive-complexity
function buildFilterExpression(
domainName: string,
@@ -899,14 +865,8 @@ function buildFilterExpression(
baseFilterParts.push('status_message EXISTS');
}
const filterExpression = baseFilterParts.join(' AND ');
- if (!filters) {
- return filterExpression;
- }
- const { filter } = convertFiltersToExpressionWithExistingQuery(
- filters,
- filterExpression,
- );
- return filter.expression;
+
+ return convertFiltersWithUrlHandling(filters, filterExpression);
}
export const getTopErrorsQueryPayload = (
@@ -1447,41 +1407,22 @@ export const getEndPointDetailsQueryPayload = (
builder: {
queryData: [
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- id: '------false',
- key: '',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'rate()',
+ },
+ ],
aggregateOperator: 'rate',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
- filters: {
- items: [
- {
- id: '874562e1',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression}`,
+ ),
},
functions: [],
groupBy: [],
@@ -1496,40 +1437,22 @@ export const getEndPointDetailsQueryPayload = (
timeAggregation: 'rate',
},
{
- aggregateAttribute: {
- dataType: DataTypes.Float64,
- key: 'duration_nano',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'p99(duration_nano)',
+ },
+ ],
aggregateOperator: 'p99',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'B',
- filters: {
- items: [
- {
- id: '0c5564e0',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression}`,
+ ),
},
functions: [],
groupBy: [],
@@ -1544,50 +1467,22 @@ export const getEndPointDetailsQueryPayload = (
timeAggregation: 'p99',
},
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- key: 'span_id',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'count(span_id)',
+ },
+ ],
aggregateOperator: 'count',
dataSource: DataSource.TRACES,
disabled: true,
expression: 'C',
- filters: {
- items: [
- {
- id: '0d656701',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '83ef9a1b',
- key: {
- dataType: DataTypes.bool,
- key: 'has_error',
- type: '',
- },
- op: '=',
- value: 'true',
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression} AND has_error = true`,
+ ),
},
functions: [],
groupBy: [],
@@ -1602,41 +1497,22 @@ export const getEndPointDetailsQueryPayload = (
timeAggregation: 'count',
},
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- id: 'timestamp------false',
- key: 'timestamp',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'max(timestamp)',
+ },
+ ],
aggregateOperator: 'max',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'D',
- filters: {
- items: [
- {
- id: '918f5b99',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression}`,
+ ),
},
functions: [],
groupBy: [],
@@ -1651,40 +1527,22 @@ export const getEndPointDetailsQueryPayload = (
timeAggregation: 'max',
},
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- key: 'span_id',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'count(span_id)',
+ },
+ ],
aggregateOperator: 'count',
dataSource: DataSource.TRACES,
disabled: true,
expression: 'E',
- filters: {
- items: [
- {
- id: 'b355d1aa',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression}`,
+ ),
},
functions: [],
groupBy: [],
@@ -1888,43 +1746,25 @@ export const getEndPointDetailsQueryPayload = (
dataSource: DataSource.TRACES,
queryName: 'A',
aggregateOperator: 'count',
- aggregateAttribute: {
- dataType: DataTypes.String,
- key: '',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'count()',
+ },
+ ],
timeAggregation: 'count',
spaceAggregation: 'sum',
functions: [],
- filters: {
- items: [
- {
- id: '3db61dd6',
- key: {
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- dataType: DataTypes.String,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression} AND (http.url EXISTS OR url.full EXISTS)`,
+ ),
},
expression: 'A',
disabled: false,
- stepInterval: 60,
+ stepInterval: null,
having: [],
legend: '',
limit: null,
@@ -1933,7 +1773,12 @@ export const getEndPointDetailsQueryPayload = (
{
key: SPAN_ATTRIBUTES.URL_PATH,
dataType: DataTypes.String,
- type: 'tag',
+ type: 'attribute',
+ },
+ {
+ key: 'url.full',
+ dataType: DataTypes.String,
+ type: 'attribute',
},
],
reduceTo: 'avg',
@@ -1974,40 +1819,22 @@ export const getEndPointDetailsQueryPayload = (
builder: {
queryData: [
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- key: 'span_id',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'count(span_id)',
+ },
+ ],
aggregateOperator: 'count',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
- filters: {
- items: [
- {
- id: 'b78ff216',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression}`,
+ ),
},
functions: [],
groupBy: [
@@ -2029,40 +1856,22 @@ export const getEndPointDetailsQueryPayload = (
timeAggregation: 'count',
},
{
- aggregateAttribute: {
- dataType: DataTypes.Float64,
- key: 'duration_nano',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'p99(duration_nano)',
+ },
+ ],
aggregateOperator: 'p99',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'B',
- filters: {
- items: [
- {
- id: 'a9024472',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression}`,
+ ),
},
functions: [],
groupBy: [
@@ -2084,41 +1893,22 @@ export const getEndPointDetailsQueryPayload = (
timeAggregation: 'p99',
},
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- id: '------false',
- key: '',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'rate()',
+ },
+ ],
aggregateOperator: 'rate',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'C',
- filters: {
- items: [
- {
- id: '1b6c062d',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression}`,
+ ),
},
functions: [],
groupBy: [
@@ -2140,49 +1930,22 @@ export const getEndPointDetailsQueryPayload = (
timeAggregation: 'rate',
},
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- key: 'span_id',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'count(span_id)',
+ },
+ ],
aggregateOperator: 'count',
dataSource: DataSource.TRACES,
disabled: true,
expression: 'D',
- filters: {
- items: [
- {
- id: 'd14792a8',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '3212bf1a',
- key: {
- key: 'has_error',
- type: '',
- },
- op: '=',
- value: 'true',
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression} AND has_error = true`,
+ ),
},
functions: [],
groupBy: [
@@ -2246,48 +2009,29 @@ export const getEndPointDetailsQueryPayload = (
builder: {
queryData: [
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- id: '------false',
- key: '',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'count()',
+ },
+ ],
aggregateOperator: 'count',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
- filters: {
- items: [
- {
- id: 'c6724407',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression}`,
+ ),
},
functions: [],
groupBy: [
{
dataType: DataTypes.String,
key: 'response_status_code',
- type: '',
+ type: 'span',
},
],
having: [],
@@ -2297,7 +2041,7 @@ export const getEndPointDetailsQueryPayload = (
queryName: 'A',
reduceTo: 'avg',
spaceAggregation: 'sum',
- stepInterval: 60,
+ stepInterval: null,
timeAggregation: 'rate',
},
],
@@ -2336,47 +2080,29 @@ export const getEndPointDetailsQueryPayload = (
builder: {
queryData: [
{
- aggregateAttribute: {
- dataType: DataTypes.Float64,
- key: 'duration_nano',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'p99(duration_nano)',
+ },
+ ],
aggregateOperator: 'p99',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
- filters: {
- items: [
- {
- id: 'aae93366',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression}`,
+ ),
},
functions: [],
groupBy: [
{
dataType: DataTypes.String,
key: 'response_status_code',
- type: '',
+ type: 'span',
},
],
having: [],
@@ -2386,7 +2112,7 @@ export const getEndPointDetailsQueryPayload = (
queryName: 'A',
reduceTo: 'avg',
spaceAggregation: 'sum',
- stepInterval: 60,
+ stepInterval: null,
timeAggregation: 'p99',
},
],
@@ -2563,19 +2289,24 @@ export const getFormattedEndPointMetricsData = (
};
}
+ const dataMap = data[0].data;
+
+ // Convert nanoseconds to milliseconds for latency (only if valid)
+ const latencyInMs = !isEmptyFilterValue(dataMap.B)
+ ? convertNanoToMilliseconds(Number(dataMap.B))
+ : undefined;
+
+ // Convert timestamp to relative time (only if valid)
+ const lastUsedFormatted = !isEmptyFilterValue(data[0].data.D)
+ ? getLastUsedRelativeTime(new Date(data[0].data.D as string).getTime())
+ : undefined;
+
return {
key: v4(),
- rate: data[0].data.A === 'n/a' || !data[0].data.A ? '-' : data[0].data.A,
- latency:
- data[0].data.B === 'n/a' || data[0].data.B === undefined
- ? '-'
- : Math.round(Number(data[0].data.B) / 1000000),
- errorRate:
- data[0].data.F1 === 'n/a' || !data[0].data.F1 ? 0 : Number(data[0].data.F1),
- lastUsed:
- data[0].data.D === 'n/a' || !data[0].data.D
- ? '-'
- : getLastUsedRelativeTime(Math.floor(Number(data[0].data.D) / 1000000)),
+ rate: getDisplayValue(dataMap.A),
+ latency: getDisplayValue(latencyInMs),
+ errorRate: getDisplayValue(dataMap.F1),
+ lastUsed: getDisplayValue(lastUsedFormatted),
};
};
@@ -2665,6 +2396,7 @@ export const statusCodeWidgetInfo = [
interface EndPointDropDownResponseRow {
data: {
[SPAN_ATTRIBUTES.URL_PATH]: string;
+ 'url.full': string;
A: number;
};
}
@@ -2681,8 +2413,8 @@ export const getFormattedEndPointDropDownData = (
if (!data) return [];
return data.map((row) => ({
key: v4(),
- label: row.data[SPAN_ATTRIBUTES.URL_PATH] || '-',
- value: row.data[SPAN_ATTRIBUTES.URL_PATH] || '-',
+ label: row.data[SPAN_ATTRIBUTES.URL_PATH] || row.data['url.full'] || '-',
+ value: row.data[SPAN_ATTRIBUTES.URL_PATH] || row.data['url.full'] || '-',
}));
};
@@ -2720,21 +2452,18 @@ export const getFormattedDependentServicesData = (
return data?.map((row) => ({
key: v4(),
serviceData: {
- serviceName: row.data['service.name'] || '-',
- count:
- row.data.A !== undefined && row.data.A !== 'n/a' ? Number(row.data.A) : '-',
+ serviceName: getDisplayValue(row.data['service.name']),
+ count: !isEmptyFilterValue(row.data.A) ? Number(row.data.A) : '-',
percentage:
- totalCount > 0 && row.data.A !== undefined && row.data.A !== 'n/a'
+ totalCount > 0 && !isEmptyFilterValue(row.data.A)
? Number(((Number(row.data.A) / totalCount) * 100).toFixed(2))
- : 0,
+ : '-',
},
- latency:
- row.data.B !== undefined && row.data.B !== 'n/a'
- ? Math.round(Number(row.data.B) / 1000000)
- : '-',
- rate: row.data.C !== undefined && row.data.C !== 'n/a' ? row.data.C : '-',
- errorPercentage:
- row.data.F1 !== undefined && row.data.F1 !== 'n/a' ? row.data.F1 : 0,
+ latency: !isEmptyFilterValue(row.data.B)
+ ? Math.round(Number(row.data.B) / 1000000)
+ : '-',
+ rate: getDisplayValue(row.data.C),
+ errorPercentage: !isEmptyFilterValue(row.data.F1) ? row.data.F1 : '-',
}));
};
@@ -2747,7 +2476,9 @@ export const dependentServicesColumns: ColumnType<DependentServicesData>[] = [
<div className="top-services-item">
<div className="top-services-item-progress">
<div className="top-services-item-key">{serviceData.serviceName}</div>
- <div className="top-services-item-count">{serviceData.count} Calls</div>
+ <div className="top-services-item-count">
+ {serviceData.count !== '-' ? `${serviceData.count} Calls` : '-'}
+ </div>
<div
className="top-services-item-progress-bar"
style={{ width: `${serviceData.percentage}%` }}
@@ -2755,9 +2486,8 @@ export const dependentServicesColumns: ColumnType<DependentServicesData>[] = [
</div>
<div className="top-services-item-percentage">
{typeof serviceData.percentage === 'number'
- ? serviceData.percentage.toFixed(2)
- : serviceData.percentage}
- %
+ ? `${serviceData.percentage.toFixed(2)}%`
+ : '-'}
</div>
</div>
),
@@ -2781,8 +2511,10 @@ export const dependentServicesColumns: ColumnType<DependentServicesData>[] = [
),
dataIndex: 'latency',
key: 'latency',
- render: (latency: number): ReactNode => (
- <div className="top-services-item-latency">{latency || '-'}ms</div>
+ render: (latency: number | string): ReactNode => (
+ <div className="top-services-item-latency">
+ {latency !== '-' ? `${latency || '-'}ms` : '-'}
+ </div>
),
sorter: (a: DependentServicesData, b: DependentServicesData): number => {
const latencyA =
@@ -2804,19 +2536,17 @@ export const dependentServicesColumns: ColumnType<DependentServicesData>[] = [
render: (
errorPercentage: number | string,
// eslint-disable-next-line sonarjs/no-identical-functions
- ): React.ReactNode => {
- const errorPercentageValue =
- errorPercentage === 'n/a' || errorPercentage === '-' ? 0 : errorPercentage;
- return (
+ ): React.ReactNode =>
+ errorPercentage !== '-' ? (
<Progress
status="active"
- percent={Number((errorPercentageValue as number).toFixed(2))}
+ percent={Number((errorPercentage as number).toFixed(2))}
strokeLinecap="butt"
size="small"
strokeColor={((): // eslint-disable-next-line sonarjs/no-identical-functions
string => {
const errorPercentagePercent = Number(
- (errorPercentageValue as number).toFixed(2),
+ (errorPercentage as number).toFixed(2),
);
if (errorPercentagePercent >= 90) return Color.BG_SAKURA_500;
if (errorPercentagePercent >= 60) return Color.BG_AMBER_500;
@@ -2824,8 +2554,9 @@ export const dependentServicesColumns: ColumnType<DependentServicesData>[] = [
})()}
className="progress-bar error-rate"
/>
- );
- },
+ ) : (
+ '-'
+ ),
sorter: (a: DependentServicesData, b: DependentServicesData): number => {
const errorPercentageA =
a.errorPercentage === '-' || a.errorPercentage === 'n/a'
@@ -2845,8 +2576,10 @@ export const dependentServicesColumns: ColumnType<DependentServicesData>[] = [
dataIndex: 'rate',
key: 'rate',
align: 'right',
- render: (rate: number): ReactNode => (
- <div className="top-services-item-rate">{rate || '-'} ops/sec</div>
+ render: (rate: number | string): ReactNode => (
+ <div className="top-services-item-rate">
+ {rate !== '-' ? `${rate || '-'} ops/sec` : '-'}
+ </div>
),
// eslint-disable-next-line sonarjs/no-identical-functions
sorter: (a: DependentServicesData, b: DependentServicesData): number => {
@@ -3127,12 +2860,12 @@ export const getFormattedEndPointStatusCodeChartData = (
export const END_POINT_DETAILS_QUERY_KEYS_ARRAY = [
REACT_QUERY_KEY.GET_ENDPOINT_METRICS_DATA,
REACT_QUERY_KEY.GET_ENDPOINT_STATUS_CODE_DATA,
- REACT_QUERY_KEY.GET_ENDPOINT_RATE_OVER_TIME_DATA,
- REACT_QUERY_KEY.GET_ENDPOINT_LATENCY_OVER_TIME_DATA,
REACT_QUERY_KEY.GET_ENDPOINT_DROPDOWN_DATA,
REACT_QUERY_KEY.GET_ENDPOINT_DEPENDENT_SERVICES_DATA,
REACT_QUERY_KEY.GET_ENDPOINT_STATUS_CODE_BAR_CHARTS_DATA,
REACT_QUERY_KEY.GET_ENDPOINT_STATUS_CODE_LATENCY_BAR_CHARTS_DATA,
+ REACT_QUERY_KEY.GET_ENDPOINT_RATE_OVER_TIME_DATA,
+ REACT_QUERY_KEY.GET_ENDPOINT_LATENCY_OVER_TIME_DATA,
];
export const getAllEndpointsWidgetData = (
@@ -3150,40 +2883,22 @@ export const getAllEndpointsWidgetData = (
panelTypes: PANEL_TYPES.TABLE,
queryData: [
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- key: 'span_id',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'count()',
+ },
+ ],
aggregateOperator: 'count',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
- filters: {
- items: [
- {
- id: 'ec316e57',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters,
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression} AND (http.url EXISTS OR url.full EXISTS)`,
+ ),
},
functions: [],
groupBy: isGroupedByAttribute
@@ -3200,40 +2915,22 @@ export const getAllEndpointsWidgetData = (
timeAggregation: 'count',
},
{
- aggregateAttribute: {
- dataType: DataTypes.Float64,
- key: 'duration_nano',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'p99(duration_nano)',
+ },
+ ],
aggregateOperator: 'p99',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'B',
- filters: {
- items: [
- {
- id: '46d57857',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters,
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression} AND (http.url EXISTS OR url.full EXISTS)`,
+ ),
},
functions: [],
groupBy: isGroupedByAttribute
@@ -3250,41 +2947,22 @@ export const getAllEndpointsWidgetData = (
timeAggregation: 'p99',
},
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- id: 'timestamp------false',
- key: 'timestamp',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'max(timestamp)',
+ },
+ ],
aggregateOperator: 'max',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'C',
- filters: {
- items: [
- {
- id: '4a237616',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters,
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression} AND (http.url EXISTS OR url.full EXISTS)`,
+ ),
},
functions: [],
groupBy: isGroupedByAttribute
@@ -3301,50 +2979,22 @@ export const getAllEndpointsWidgetData = (
timeAggregation: 'max',
},
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- key: 'span_id',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'count()',
+ },
+ ],
aggregateOperator: 'count',
dataSource: DataSource.TRACES,
disabled: true,
expression: 'D',
- filters: {
- items: [
- {
- id: 'f162de1e',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- {
- id: '3df0ac1d',
- key: {
- dataType: DataTypes.bool,
- key: 'has_error',
- type: '',
- },
- op: '=',
- value: true,
- },
- {
- id: '212678b9',
- key: {
- key: 'kind_string',
- dataType: DataTypes.String,
- type: '',
- },
- op: '=',
- value: 'Client',
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters,
+ `${getDomainNameFilterExpression(
+ domainName,
+ )} AND ${clientKindExpression} AND has_error = true AND (http.url EXISTS OR url.full EXISTS)`,
+ ),
},
functions: [],
groupBy: isGroupedByAttribute
@@ -3374,11 +3024,25 @@ export const getAllEndpointsWidgetData = (
);
widget.renderColumnCell = {
- [SPAN_ATTRIBUTES.URL_PATH]: (url: any): ReactNode => {
- const { endpoint } = extractPortAndEndpoint(url);
- return (
- <span>{endpoint === 'n/a' || url === undefined ? '-' : endpoint}</span>
- );
+ [SPAN_ATTRIBUTES.URL_PATH]: (
+ url: string | number,
+ record?: RowData,
+ ): ReactNode => {
+ // First try to use the url from the column value
+ let urlValue = url;
+
+ // If url is empty/null and we have the record, fallback to url.full
+ if (isEmptyFilterValue(url) && record) {
+ const { 'url.full': urlFull } = record;
+ urlValue = urlFull;
+ }
+
+ if (!urlValue || urlValue === 'n/a') {
+ return <span>-</span>;
+ }
+
+ const { endpoint } = extractPortAndEndpoint(String(urlValue));
+ return <span>{getDisplayValue(endpoint)}</span>;
},
A: (numOfCalls: any): ReactNode => (
<span>
@@ -3397,9 +3061,7 @@ export const getAllEndpointsWidgetData = (
{lastUsed === 'n/a' || lastUsed === undefined
? '-'
: getLastUsedRelativeTime(
- new Date(
- new Date(Math.floor(Number(lastUsed) / 1000000)).toISOString(),
- ).getTime(),
+ new Date(new Date(lastUsed).toISOString()).getTime(),
)}
</span>
),
@@ -3456,10 +3118,12 @@ export const getAllEndpointsWidgetData = (
</div>
);
+ widget.hiddenColumns = ['url.full'];
+
return widget;
};
-const keysToRemove = ['http.url', 'A', 'B', 'C', 'F1'];
+const keysToRemove = ['http.url', 'url.full', 'B', 'C', 'F1'];
export const getGroupByFiltersFromGroupByValues = (
rowData: any,
@@ -3505,31 +3169,20 @@ export const getRateOverTimeWidgetData = (
description: 'Rate over time.',
queryData: [
{
- aggregateAttribute: {
- dataType: DataTypes.String,
- id: '------false',
- key: '',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'rate()',
+ },
+ ],
aggregateOperator: 'rate',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
- filters: {
- items: [
- {
- id: '3c76fe0b',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `(net.peer.name = '${domainName}' OR server.address = '${domainName}')`,
+ ),
},
functions: [],
groupBy: [],
@@ -3540,7 +3193,7 @@ export const getRateOverTimeWidgetData = (
queryName: 'A',
reduceTo: 'avg',
spaceAggregation: 'sum',
- stepInterval: 60,
+ stepInterval: null,
timeAggregation: 'rate',
},
],
@@ -3567,30 +3220,20 @@ export const getLatencyOverTimeWidgetData = (
description: 'Latency over time.',
queryData: [
{
- aggregateAttribute: {
- dataType: DataTypes.Float64,
- key: 'duration_nano',
- type: '',
- },
+ aggregations: [
+ {
+ expression: 'p99(duration_nano)',
+ },
+ ],
aggregateOperator: 'p99',
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
- filters: {
- items: [
- {
- id: '63adb3ff',
- key: {
- dataType: DataTypes.String,
- key: SPAN_ATTRIBUTES.SERVER_NAME,
- type: 'tag',
- },
- op: '=',
- value: domainName,
- },
- ...(filters?.items || []),
- ],
- op: 'AND',
+ filter: {
+ expression: convertFiltersWithUrlHandling(
+ filters || { items: [], op: 'AND' },
+ `(net.peer.name = '${domainName}' OR server.address = '${domainName}')`,
+ ),
},
functions: [],
groupBy: [],
@@ -3601,7 +3244,7 @@ export const getLatencyOverTimeWidgetData = (
queryName: 'A',
reduceTo: 'avg',
spaceAggregation: 'sum',
- stepInterval: 60,
+ stepInterval: null,
timeAggregation: 'p99',
},
],
diff --git a/frontend/src/container/GridTableComponent/index.tsx b/frontend/src/container/GridTableComponent/index.tsx
index f9ba1f21f2..968935be4a 100644
--- a/frontend/src/container/GridTableComponent/index.tsx
+++ b/frontend/src/container/GridTableComponent/index.tsx
@@ -49,17 +49,29 @@ function GridTableComponent({
panelType,
queryRangeRequest,
decimalPrecision,
+ hiddenColumns = [],
...props
}: GridTableComponentProps): JSX.Element {
const { t } = useTranslation(['valueGraph']);
// create columns and dataSource in the ui friendly structure
// use the query from the widget here to extract the legend information
- const { columns, dataSource: originalDataSource } = useMemo(
+ const { columns: allColumns, dataSource: originalDataSource } = useMemo(
() => createColumnsAndDataSource((data as unknown) as TableData, query),
[query, data],
);
+ // Filter out hidden columns from being displayed
+ const columns = useMemo(
+ () =>
+ allColumns.filter(
+ (column) =>
+ !('dataIndex' in column) ||
+ !hiddenColumns.includes(column.dataIndex as string),
+ ),
+ [allColumns, hiddenColumns],
+ );
+
const createDataInCorrectFormat = useCallback(
(dataSource: RowData[]): RowData[] =>
dataSource.map((d) => {
diff --git a/frontend/src/container/GridTableComponent/types.ts b/frontend/src/container/GridTableComponent/types.ts
index d3e55c9338..842550ebc2 100644
--- a/frontend/src/container/GridTableComponent/types.ts
+++ b/frontend/src/container/GridTableComponent/types.ts
@@ -30,6 +30,7 @@ export type GridTableComponentProps = {
contextLinks?: ContextLinksData;
panelType?: PANEL_TYPES;
queryRangeRequest?: QueryRangeRequestV5;
+ hiddenColumns?: string[];
} & Pick<LogsExplorerTableProps, 'data'> &
Omit<TableProps<RowData>, 'columns' | 'dataSource'>;
diff --git a/frontend/src/container/PanelWrapper/TablePanelWrapper.tsx b/frontend/src/container/PanelWrapper/TablePanelWrapper.tsx
index 4c50e4bbf7..7df15e46a1 100644
--- a/frontend/src/container/PanelWrapper/TablePanelWrapper.tsx
+++ b/frontend/src/container/PanelWrapper/TablePanelWrapper.tsx
@@ -41,6 +41,7 @@ function TablePanelWrapper({
panelType={widget.panelTypes}
queryRangeRequest={queryRangeRequest}
decimalPrecision={widget.decimalPrecision}
+ hiddenColumns={widget.hiddenColumns}
// eslint-disable-next-line react/jsx-props-no-spreading
{...GRID_TABLE_CONFIG}
/>
diff --git a/frontend/src/container/QueryTable/QueryTable.intefaces.ts b/frontend/src/container/QueryTable/QueryTable.intefaces.ts
index 35f4007f04..07a04bf598 100644
--- a/frontend/src/container/QueryTable/QueryTable.intefaces.ts
+++ b/frontend/src/container/QueryTable/QueryTable.intefaces.ts
@@ -17,7 +17,7 @@ export type QueryTableProps = Omit<
query: Query;
renderActionCell?: (record: RowData) => ReactNode;
modifyColumns?: (columns: ColumnsType<RowData>) => ColumnsType<RowData>;
- renderColumnCell?: Record<string, (record: RowData) => ReactNode>;
+ renderColumnCell?: Record<string, (...args: any[]) => ReactNode>;
downloadOption?: DownloadOptions;
columns?: ColumnsType<RowData>;
dataSource?: RowData[];
diff --git a/frontend/src/types/api/dashboard/getAll.ts b/frontend/src/types/api/dashboard/getAll.ts
index c41d6ae57b..14125f03b4 100644
--- a/frontend/src/types/api/dashboard/getAll.ts
+++ b/frontend/src/types/api/dashboard/getAll.ts
@@ -136,6 +136,7 @@ export interface Widgets extends IBaseWidget {
query: Query;
renderColumnCell?: QueryTableProps['renderColumnCell'];
customColTitles?: Record<string, string>;
+ hiddenColumns?: string[];
}
export interface PromQLWidgets extends IBaseWidget {