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.

fix(service-map): stop the resource attribute filter bar from clearing (#12521)

Abhi kumar6ecfa839f3e5
diff --git a/frontend/src/container/ResourceAttributesFilter/ResourceAttributesFilter.tsx b/frontend/src/container/ResourceAttributesFilter/ResourceAttributesFilter.tsx
index 7c17c2ef3b..b37564f14a 100644
--- a/frontend/src/container/ResourceAttributesFilter/ResourceAttributesFilter.tsx
+++ b/frontend/src/container/ResourceAttributesFilter/ResourceAttributesFilter.tsx
@@ -80,7 +80,6 @@ function ResourceAttributesFilter({
<div className="environment-selector">
<Select
getPopupContainer={popupContainer}
- key={selectedEnvironments.join('')}
showSearch
mode="multiple"
value={selectedEnvironments}
diff --git a/frontend/src/container/ResourceAttributesFilter/__tests__/ResourceAttributesFilter.test.tsx b/frontend/src/container/ResourceAttributesFilter/__tests__/ResourceAttributesFilter.test.tsx
new file mode 100644
index 0000000000..130e2f3656
--- /dev/null
+++ b/frontend/src/container/ResourceAttributesFilter/__tests__/ResourceAttributesFilter.test.tsx
@@ -0,0 +1,175 @@
+import { ReactNode } from 'react';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { Router } from 'react-router-dom';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import ROUTES from 'constants/routes';
+import { createMemoryHistory, MemoryHistory } from 'history';
+import { ResourceProvider } from 'hooks/useResourceAttribute';
+import { IResourceAttribute } from 'hooks/useResourceAttribute/types';
+import { encode } from 'js-base64';
+
+import ResourceAttributesFilter from '../ResourceAttributesFilter';
+
+jest.mock('lib/history', () => ({
+ __esModule: true,
+ default: {
+ push: jest.fn(),
+ location: { search: '', pathname: '/' },
+ },
+}));
+
+jest.mock('api/metrics/getResourceAttributes', () => ({
+ getResourceAttributesTagKeys: jest.fn(),
+ getResourceAttributesTagValues: jest.fn(),
+}));
+
+// eslint-disable-next-line import/first, import/order
+import {
+ getResourceAttributesTagKeys,
+ getResourceAttributesTagValues,
+ // eslint-disable-next-line import/newline-after-import
+} from 'api/metrics/getResourceAttributes';
+// eslint-disable-next-line import/first, import/order
+import history from 'lib/history';
+
+const mockTagKeys = getResourceAttributesTagKeys as jest.MockedFunction<
+ typeof getResourceAttributesTagKeys
+>;
+const mockTagValues = getResourceAttributesTagValues as jest.MockedFunction<
+ typeof getResourceAttributesTagValues
+>;
+
+function tagKeysPayload(keys: string[]): never {
+ return {
+ statusCode: 200,
+ error: null,
+ message: 'ok',
+ payload: {
+ data: {
+ attributeKeys: keys.map((key) => ({
+ key,
+ dataType: 'string',
+ type: 'resource',
+ isColumn: false,
+ })),
+ },
+ },
+ } as unknown as never;
+}
+
+function tagValuesPayload(values: string[]): never {
+ return {
+ statusCode: 200,
+ error: null,
+ message: 'ok',
+ payload: { data: { stringAttributeValues: values } },
+ } as unknown as never;
+}
+
+function seedUrl(queries: IResourceAttribute[], pathname: string): void {
+ const location = history.location as { search: string; pathname: string };
+ location.search = queries.length
+ ? `?resourceAttribute=${encode(JSON.stringify(queries))}`
+ : '';
+ location.pathname = pathname;
+}
+
+function renderFilter(pathname: string): MemoryHistory {
+ const routerHistory = createMemoryHistory({
+ initialEntries: [`${pathname}${history.location.search}`],
+ });
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ function Wrapper({ children }: { children: ReactNode }): JSX.Element {
+ return (
+ <QueryClientProvider client={queryClient}>
+ <Router history={routerHistory}>
+ <ResourceProvider>{children}</ResourceProvider>
+ </Router>
+ </QueryClientProvider>
+ );
+ }
+
+ render(
+ <Wrapper>
+ <ResourceAttributesFilter />
+ </Wrapper>,
+ );
+
+ return routerHistory;
+}
+
+describe('ResourceAttributesFilter', () => {
+ beforeEach(() => {
+ mockTagKeys.mockReset();
+ mockTagValues.mockReset();
+ mockTagKeys.mockResolvedValue(
+ tagKeysPayload(['resource_deployment.environment']),
+ );
+ mockTagValues.mockResolvedValue(tagValuesPayload(['production', 'staging']));
+ seedUrl([], '/');
+ });
+
+ it('shows every applied filter on the service map, including ones it cannot apply', async () => {
+ seedUrl(
+ [
+ {
+ id: 'svc',
+ tagKey: 'resource_service_name',
+ operator: 'IN',
+ tagValue: ['frontend'],
+ },
+ {
+ id: 'env',
+ tagKey: 'resource_deployment.environment',
+ operator: 'IN',
+ tagValue: ['production'],
+ },
+ ],
+ ROUTES.SERVICE_MAP,
+ );
+
+ renderFilter(ROUTES.SERVICE_MAP);
+
+ await waitFor(() =>
+ expect(screen.getByText(/service\.name/)).toBeInTheDocument(),
+ );
+ await waitFor(() =>
+ expect(
+ screen
+ .getByTestId('resource-environment-filter')
+ .querySelector('.ant-select-selection-item'),
+ ).toHaveTextContent('production'),
+ );
+ });
+
+ it('keeps the environment dropdown open so more than one environment can be picked', async () => {
+ const user = userEvent.setup();
+ renderFilter('/services');
+
+ const environmentFilter = screen.getByTestId('resource-environment-filter');
+ await user.click(
+ environmentFilter.querySelector('input') as HTMLInputElement,
+ );
+
+ await user.click(await screen.findByTitle('production'));
+
+ await waitFor(() =>
+ expect(
+ screen.getByTitle('staging').closest('.ant-select-dropdown'),
+ ).not.toHaveClass('ant-select-dropdown-hidden'),
+ );
+
+ await user.click(screen.getByTitle('staging'));
+
+ await waitFor(() => {
+ const selected = Array.from(
+ environmentFilter.querySelectorAll('.ant-select-selection-item-content'),
+ ).map((node) => node.textContent);
+ expect(selected).toStrictEqual(['production', 'staging']);
+ });
+ });
+});
diff --git a/frontend/src/hooks/useResourceAttribute/ResourceProvider.tsx b/frontend/src/hooks/useResourceAttribute/ResourceProvider.tsx
index 4911b670a9..8a7c73b778 100644
--- a/frontend/src/hooks/useResourceAttribute/ResourceProvider.tsx
+++ b/frontend/src/hooks/useResourceAttribute/ResourceProvider.tsx
@@ -1,12 +1,10 @@
import { ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { QueryParams } from 'constants/query';
-import ROUTES from 'constants/routes';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import { encode } from 'js-base64';
-import { whilelistedKeys } from './config';
import { ResourceContext } from './context';
import {
IResourceAttribute,
@@ -195,16 +193,9 @@ function ResourceProvider({ children }: Props): JSX.Element {
setOptionsData({ mode: undefined, options: [] });
}, [dispatchQueries]);
- const getVisibleQueries = useMemo(() => {
- if (pathname === ROUTES.SERVICE_MAP) {
- return queries.filter((query) => whilelistedKeys.includes(query.tagKey));
- }
- return queries;
- }, [queries, pathname]);
-
const value: IResourceAttributeProps = useMemo(
() => ({
- queries: getVisibleQueries,
+ queries,
staging,
handleClearAll,
handleClose,
@@ -227,7 +218,7 @@ function ResourceProvider({ children }: Props): JSX.Element {
staging,
selectedQuery,
optionsData,
- getVisibleQueries,
+ queries,
],
);
diff --git a/frontend/src/hooks/useResourceAttribute/__tests__/ResourceProvider.test.tsx b/frontend/src/hooks/useResourceAttribute/__tests__/ResourceProvider.test.tsx
index 4d47267686..e439ec0152 100644
--- a/frontend/src/hooks/useResourceAttribute/__tests__/ResourceProvider.test.tsx
+++ b/frontend/src/hooks/useResourceAttribute/__tests__/ResourceProvider.test.tsx
@@ -504,22 +504,23 @@ describe('ResourceProvider', () => {
});
});
- describe('getVisibleQueries (SERVICE_MAP filtering)', () => {
- it('filters queries down to whitelisted keys on SERVICE_MAP', () => {
- const seeded = [
- {
- id: 'a',
- tagKey: 'resource_service_name',
- operator: 'IN',
- tagValue: ['frontend'],
- },
- {
- id: 'b',
- tagKey: 'resource_k8s_cluster_name',
- operator: 'IN',
- tagValue: ['prod'],
- },
- ];
+ describe('SERVICE_MAP', () => {
+ const seeded = [
+ {
+ id: 'a',
+ tagKey: 'resource_service_name',
+ operator: 'IN',
+ tagValue: ['frontend'],
+ },
+ {
+ id: 'b',
+ tagKey: 'resource_k8s_cluster_name',
+ operator: 'IN',
+ tagValue: ['prod'],
+ },
+ ];
+
+ it('exposes every query from the URL, including ones the map cannot apply', () => {
mockLibHistory(
`?resourceAttribute=${encode(JSON.stringify(seeded))}`,
ROUTES.SERVICE_MAP,
@@ -532,24 +533,10 @@ describe('ResourceProvider', () => {
wrapper: createWrapper({ routerHistory }),
});
- expect(result.current.queries).toStrictEqual([seeded[1]]);
+ expect(result.current.queries).toStrictEqual(seeded);
});
it('returns all queries on non-SERVICE_MAP routes', () => {
- const seeded = [
- {
- id: 'a',
- tagKey: 'resource_service_name',
- operator: 'IN',
- tagValue: ['frontend'],
- },
- {
- id: 'b',
- tagKey: 'resource_k8s_cluster_name',
- operator: 'IN',
- tagValue: ['prod'],
- },
- ];
mockLibHistory(
`?resourceAttribute=${encode(JSON.stringify(seeded))}`,
'/services',
diff --git a/frontend/src/hooks/useResourceAttribute/__tests__/whitelistedKeys.test.ts b/frontend/src/hooks/useResourceAttribute/__tests__/whitelistedKeys.test.ts
index f51e32bd09..04f90b6e70 100644
--- a/frontend/src/hooks/useResourceAttribute/__tests__/whitelistedKeys.test.ts
+++ b/frontend/src/hooks/useResourceAttribute/__tests__/whitelistedKeys.test.ts
@@ -1,7 +1,10 @@
import ROUTES from 'constants/routes';
import { whilelistedKeys } from '../config';
-import { mappingWithRoutesAndKeys } from '../utils';
+import {
+ filterServiceMapSupportedQueries,
+ mappingWithRoutesAndKeys,
+} from '../utils';
describe('useResourceAttribute config', () => {
describe('whilelistedKeys', () => {
@@ -74,4 +77,29 @@ describe('useResourceAttribute config', () => {
expect(result).toStrictEqual(allFilters);
});
});
+
+ describe('filterServiceMapSupportedQueries', () => {
+ const environmentQuery = {
+ id: 'env',
+ tagKey: 'resource_deployment_environment',
+ operator: 'IN',
+ tagValue: ['production'],
+ };
+ const serviceQuery = {
+ id: 'svc',
+ tagKey: 'resource_service_name',
+ operator: 'IN',
+ tagValue: ['frontend'],
+ };
+
+ it('should keep only the queries the service map can filter on', () => {
+ expect(
+ filterServiceMapSupportedQueries([environmentQuery, serviceQuery]),
+ ).toStrictEqual([environmentQuery]);
+ });
+
+ it('should return an empty list when no query is supported', () => {
+ expect(filterServiceMapSupportedQueries([serviceQuery])).toStrictEqual([]);
+ });
+ });
});
diff --git a/frontend/src/hooks/useResourceAttribute/utils.ts b/frontend/src/hooks/useResourceAttribute/utils.ts
index 97ed5d13b2..3ee0ac0c13 100644
--- a/frontend/src/hooks/useResourceAttribute/utils.ts
+++ b/frontend/src/hooks/useResourceAttribute/utils.ts
@@ -281,3 +281,8 @@ export const mappingWithRoutesAndKeys = (
}
return filters;
};
+
+export const filterServiceMapSupportedQueries = (
+ queries: IResourceAttribute[],
+): IResourceAttribute[] =>
+ queries.filter((query) => whilelistedKeys.includes(query.tagKey));
diff --git a/frontend/src/modules/Servicemap/ServiceMap.tsx b/frontend/src/modules/Servicemap/ServiceMap.tsx
index d2c1cec877..32494aadc6 100644
--- a/frontend/src/modules/Servicemap/ServiceMap.tsx
+++ b/frontend/src/modules/Servicemap/ServiceMap.tsx
@@ -1,6 +1,6 @@
//@ts-nocheck
-import { useEffect, useRef } from 'react';
+import { useEffect, useMemo, useRef } from 'react';
// eslint-disable-next-line no-restricted-imports
import { connect } from 'react-redux';
import { RouteComponentProps, withRouter } from 'react-router-dom';
@@ -11,6 +11,7 @@ import ResourceAttributesFilter from 'container/ResourceAttributesFilter';
import useResourceAttribute from 'hooks/useResourceAttribute';
import { whilelistedKeys } from 'hooks/useResourceAttribute/config';
import { IResourceAttribute } from 'hooks/useResourceAttribute/types';
+import { filterServiceMapSupportedQueries } from 'hooks/useResourceAttribute/utils';
import { getDetailedServiceMapItems, ServiceMapStore } from 'store/actions';
import { AppState } from 'store/reducers';
import styled from 'styled-components';
@@ -70,32 +71,37 @@ function ServiceMap(props: ServiceMapProps): JSX.Element {
const { queries } = useResourceAttribute();
+ const supportedQueries = useMemo(
+ () => filterServiceMapSupportedQueries(queries),
+ [queries],
+ );
+
useEffect(() => {
/*
Call the apis only when the route is loaded.
Check this issue: https://github.com/SigNoz/signoz/issues/110
*/
- getDetailedServiceMapItems(globalTime, queries);
- }, [globalTime, getDetailedServiceMapItems, queries]);
+ getDetailedServiceMapItems(globalTime, supportedQueries);
+ }, [globalTime, getDetailedServiceMapItems, supportedQueries]);
useEffect(() => {
fgRef.current && fgRef.current.d3Force('charge').strength(-400);
});
- if (serviceMap.loading) {
- return <Spinner size="large" tip="Loading..." />;
- }
+ const renderBody = (): JSX.Element => {
+ if (serviceMap.loading) {
+ return <Spinner size="large" tip="Loading..." />;
+ }
+
+ if (serviceMap.items.length === 0) {
+ return <Card>No Service Found</Card>;
+ }
+
+ return <Map fgRef={fgRef} serviceMap={serviceMap} />;
+ };
- if (!serviceMap.loading && serviceMap.items.length === 0) {
- return (
- <Container>
- <ResourceAttributesFilter />
- <Card>No Service Found</Card>
- </Container>
- );
- }
return (
- <div className="service-map-container">
+ <Container className="service-map-container">
<ResourceAttributesFilter
suffixIcon={
<TextToolTip
@@ -108,8 +114,8 @@ function ServiceMap(props: ServiceMapProps): JSX.Element {
}
/>
- <Map fgRef={fgRef} serviceMap={serviceMap} />
- </div>
+ {renderBody()}
+ </Container>
);
}