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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(alerts): adopt server-side clone API in frontend (#13181)
ashu8912089de88bf020
diff --git a/frontend/src/constants/reactQueryKeys.ts b/frontend/src/constants/reactQueryKeys.tsindex 1503cb8461..d208fee55e 100644--- a/frontend/src/constants/reactQueryKeys.ts+++ b/frontend/src/constants/reactQueryKeys.ts@@ -24,7 +24,7 @@ export const REACT_QUERY_KEY = {GET_ALL_ALERTS: 'GET_ALL_ALERTS',ALERT_RULES_CHART_PREVIEW: 'ALERT_RULES_CHART_PREVIEW',REMOVE_ALERT_RULE: 'REMOVE_ALERT_RULE',- DUPLICATE_ALERT_RULE: 'DUPLICATE_ALERT_RULE',+ CLONE_ALERT_RULE: 'CLONE_ALERT_RULE',GET_HOST_LIST: 'GET_HOST_LIST',UPDATE_ALERT_RULE: 'UPDATE_ALERT_RULE',GET_TRACE_V2_WATERFALL: 'GET_TRACE_V2_WATERFALL',diff --git a/frontend/src/container/ListAlertRules/__tests__/ListAlertRules.actions.test.tsx b/frontend/src/container/ListAlertRules/__tests__/ListAlertRules.actions.test.tsxindex bad398f9e3..bbf64cbc69 100644--- a/frontend/src/container/ListAlertRules/__tests__/ListAlertRules.actions.test.tsx+++ b/frontend/src/container/ListAlertRules/__tests__/ListAlertRules.actions.test.tsx@@ -2,6 +2,7 @@ import userEvent from '@testing-library/user-event';import { logEventMock } from '__tests__/logEventMock';import { safeNavigateMock } from '__tests__/safeNavigateMock';import { server } from 'mocks-server/server';+import { alertRulesFixture } from 'mocks-server/__mockdata__/alert_rules';import { rest } from 'msw';import { screen, waitFor } from 'tests/test-utils';@@ -121,22 +122,26 @@ describe('ListAlertRules — actions menu', () => {expect(options).toStrictEqual(expect.objectContaining({ newTab: true }));});- it('clone action: sends POST with " - Copy" suffix and opens the cloned rule returned by the API', async () => {- let capturedPostBody: unknown = null;+ it('clone action: sends POST to clone endpoint and opens the cloned rule returned by the API', async () => {+ let capturedRuleId: string | null = null;server.use(- rest.post('http://localhost/api/v2/rules', async (req, res, ctx) => {- capturedPostBody = await req.json();- return res(- ctx.status(201),- ctx.json({- data: {- ...(capturedPostBody as Record<string, unknown>),- id: 'cloned-from-server',- },- status: 'success',- }),- );- }),+ rest.post(+ 'http://localhost/api/v2/rules/:id/clone',+ async (req, res, ctx) => {+ capturedRuleId = req.params.id as string;+ return res(+ ctx.status(201),+ ctx.json({+ data: {+ ...alertRulesFixture[0],+ id: 'cloned-from-server',+ alert: 'High CPU Alert - Copy',+ },+ status: 'success',+ }),+ );+ },+ ),);renderListAlertRules();@@ -145,9 +150,7 @@ describe('ListAlertRules — actions menu', () => {await clickMenuItem('Clone');await waitFor(() => {- expect(capturedPostBody).toStrictEqual(- expect.objectContaining({ alert: 'High CPU Alert - Copy' }),- );+ expect(capturedRuleId).toBe('rule-1');});// The id from the server response round-trips into the navigate URL — thisdiff --git a/frontend/src/container/ListAlertRules/components/ActionsMenu.tsx b/frontend/src/container/ListAlertRules/components/ActionsMenu.tsxindex 5ad789d799..09e88966b1 100644--- a/frontend/src/container/ListAlertRules/components/ActionsMenu.tsx+++ b/frontend/src/container/ListAlertRules/components/ActionsMenu.tsx@@ -6,10 +6,10 @@ import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';import { toast } from '@signozhq/ui/sonner';import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';import {- createRule,deleteRuleByID,invalidateListRules,patchRuleByID,+ cloneRuleByID,} from 'api/generated/services/rules';import type {RenderErrorResponseDTO,@@ -62,10 +62,9 @@ function ActionsMenu({ rule, onEdit }: ActionsMenuProps): JSX.Element {const handleClone = useCallback((): void => {alertActionLogEvent(ALERT_ACTIONS.CLONE, rule);toast.promise(- createRule({- ...rule,- alert: `${rule.alert} - Copy`,- } as RuletypesPostableRuleDTO).then(async (response) => {+ cloneRuleByID({+ id: rule.id,+ }).then(async (response) => {await invalidateListRules(queryClient);const newRule = response.data;if (newRule) {diff --git a/frontend/src/pages/AlertDetails/AlertHeader/ActionButtons/ActionButtons.tsx b/frontend/src/pages/AlertDetails/AlertHeader/ActionButtons/ActionButtons.tsxindex 49eaadefc7..5ad5d97465 100644--- a/frontend/src/pages/AlertDetails/AlertHeader/ActionButtons/ActionButtons.tsx+++ b/frontend/src/pages/AlertDetails/AlertHeader/ActionButtons/ActionButtons.tsx@@ -7,8 +7,8 @@ import { Switch } from '@signozhq/ui/switch';import { useIsDarkMode } from 'hooks/useDarkMode';import { Copy, Ellipsis, PenLine, Trash2 } from '@signozhq/icons';import {+ useAlertRuleClone,useAlertRuleDelete,- useAlertRuleDuplicate,useAlertRuleStatusToggle,useAlertRuleUpdate,} from 'pages/AlertDetails/hooks';@@ -38,9 +38,7 @@ function AlertActionButtons({const isDarkMode = useIsDarkMode();const { handleAlertStateToggle } = useAlertRuleStatusToggle({ ruleId });- const { handleAlertDuplicate } = useAlertRuleDuplicate({- alertDetails: alertDetails as unknown as AlertDef,- });+ const { handleAlertClone } = useAlertRuleClone({ ruleId });const { handleAlertDelete } = useAlertRuleDelete({ ruleId });const { handleAlertUpdate, isLoading } = useAlertRuleUpdate({alertDetails: alertDetails as unknown as AlertDef,@@ -72,10 +70,10 @@ function AlertActionButtons({menuItems.push({type: 'item',- value: 'duplicate-rule',- label: 'Duplicate',+ value: 'clone-rule',+ label: 'Clone',prefix: <Copy size={16} color={Color.BG_VANILLA_400} />,- onClick: handleAlertDuplicate,+ onClick: handleAlertClone,},{type: 'item',diff --git a/frontend/src/pages/AlertDetails/hooks.tsx b/frontend/src/pages/AlertDetails/hooks.tsxindex b2a5e32050..82281f79d7 100644--- a/frontend/src/pages/AlertDetails/hooks.tsx+++ b/frontend/src/pages/AlertDetails/hooks.tsx@@ -6,7 +6,7 @@ import type { FilterValue, SorterResult } from 'antd/es/table/interface';import { patchRulePartial } from 'api/alerts/patchRulePartial';import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';import {- createRule,+ cloneRuleByID,deleteRuleByID,getGetRuleByIDQueryKey,getGetRuleHistoryTimelineQueryOptions,@@ -17,7 +17,6 @@ import {useGetRuleHistoryOverallStatus,useGetRuleHistoryStats,useGetRuleHistoryTopContributors,- useListRules,} from 'api/generated/services/rules';import {Querybuildertypesv5OrderDirectionDTO,@@ -478,39 +477,32 @@ export const useAlertRuleStatusToggle = ({return { handleAlertStateToggle };};-export const useAlertRuleDuplicate = ({- alertDetails,+export const useAlertRuleClone = ({+ ruleId,}: {- alertDetails: AlertDef;+ ruleId: string;}): {- handleAlertDuplicate: () => void;+ handleAlertClone: () => void;} => {const { notifications } = useNotifications();+ const queryClient = useQueryClient();const params = useUrlQuery();- const { refetch } = useListRules({- query: { cacheTime: 0 },- });const { showErrorModal } = useErrorModal();- const { mutate: duplicateAlert } = useMutation(- [REACT_QUERY_KEY.DUPLICATE_ALERT_RULE],- (args: { data: AlertDef }) =>- createRule(toPostableRuleDTOFromAlertDef(args.data)),+ const { mutate: cloneAlert } = useMutation(+ [REACT_QUERY_KEY.CLONE_ALERT_RULE],+ () => cloneRuleByID({ id: ruleId }),{- onSuccess: async () => {+ onSuccess: async (response) => {notifications.success({message: `Success`,});- const { data: allAlertsData } = await refetch();+ await invalidateListRules(queryClient);- const rules = allAlertsData?.data;- if (rules && rules.length > 0) {- const clonedAlert = rules[rules.length - 1];- params.set(QueryParams.ruleId, String(clonedAlert.id));- history.push(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);- }+ params.set(QueryParams.ruleId, response.data.id);+ history.push(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);},onError: (error) =>showErrorModal(@@ -519,15 +511,13 @@ export const useAlertRuleDuplicate = ({},);- const handleAlertDuplicate = (): void => {- const args = {- data: { ...alertDetails, alert: alertDetails.alert?.concat(' - Copy') },- };- duplicateAlert(args);+ const handleAlertClone = (): void => {+ cloneAlert();};- return { handleAlertDuplicate };+ return { handleAlertClone };};+export const useAlertRuleUpdate = ({alertDetails,setAlertRuleName,diff --git a/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.mocks.tsx b/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.mocks.tsxindex f090ad93a0..d13b71f631 100644--- a/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.mocks.tsx+++ b/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.mocks.tsx@@ -107,7 +107,7 @@ export const alertRulesMocks = defineStoryMocks({})),),- rest.post('http://localhost/api/v2/rules', (_req, res, ctx) =>+ rest.post('http://localhost/api/v2/rules/:id/clone', (_req, res, ctx) =>actionResponse(values.cloneState, res, ctx, () => ({status: 'success',data: alertRulesResponse(1, {diff --git a/tests/e2e/tests/alerts/details/actions.spec.ts b/tests/e2e/tests/alerts/details/actions.spec.tsindex 59ed579e05..670e268b3a 100644--- a/tests/e2e/tests/alerts/details/actions.spec.ts+++ b/tests/e2e/tests/alerts/details/actions.spec.ts@@ -43,11 +43,11 @@ test.describe('Alert details — actions', () => {await expect(page.getByText('Alert has been enabled.')).toBeVisible();});- test('TC-02 Duplicate creates a copy and navigates to overview', async ({+ test('TC-02 Clone creates a copy and navigates to overview', async ({authedPage: page,ownedRules,}) => {- const name = `e2e-ad-duplicate-${Date.now()}`;+ const name = `e2e-ad-clone-${Date.now()}`;const ruleId = await ownedRules.logs({ name, schema: 'v2' });await gotoAlertDetails(page, ruleId);@@ -56,10 +56,10 @@ test.describe('Alert details — actions', () => {const [createResponse] = await Promise.all([page.waitForResponse((res) =>- /\/api\/v\d\/rules$/.test(new URL(res.url()).pathname) &&+ /\/api\/v\d\/rules\/[^/]+\/clone$/.test(new URL(res.url()).pathname) &&res.request().method() === 'POST',),- page.getByRole('menuitem', { name: 'Duplicate' }).click(),+ page.getByRole('menuitem', { name: 'Clone' }).click(),]);await ownedRules.register(createResponse);diff --git a/tests/e2e/tests/alerts/details/header.spec.ts b/tests/e2e/tests/alerts/details/header.spec.tsindex 07979421c3..46b742c1eb 100644--- a/tests/e2e/tests/alerts/details/header.spec.ts+++ b/tests/e2e/tests/alerts/details/header.spec.ts@@ -23,7 +23,7 @@ test.describe('Alert details — header', () => {await expect(nameInput).toBeEditable();await page.getByTestId('alert-actions-menu').click();- await expect(page.getByRole('menuitem', { name: 'Duplicate' })).toBeVisible();+ await expect(page.getByRole('menuitem', { name: 'Clone' })).toBeVisible();await expect(page.getByRole('menuitem', { name: 'Delete' })).toBeVisible();await expect(page.getByRole('menuitem', { name: 'Rename' })).toHaveCount(0);});diff --git a/tests/e2e/tests/alerts/list/row-actions.spec.ts b/tests/e2e/tests/alerts/list/row-actions.spec.tsindex 60c694ede6..f62b605fc8 100644--- a/tests/e2e/tests/alerts/list/row-actions.spec.ts+++ b/tests/e2e/tests/alerts/list/row-actions.spec.ts@@ -56,7 +56,7 @@ test.describe('Alert rules list — row actions', () => {const [createResponse] = await Promise.all([page.waitForResponse((res) =>- /\/api\/v\d\/rules$/.test(new URL(res.url()).pathname) &&+ /\/api\/v\d\/rules\/[^/]+\/clone$/.test(new URL(res.url()).pathname) &&res.request().method() === 'POST',),page.getByRole('menuitem', { name: 'Clone' }).click(),