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.

chore: add api to retry migration for a dashboard (#12387)

Naman Verma089f9eb4c608
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index 68550c6b43..e944aea207 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -15477,6 +15477,72 @@ paths:
summary: Lock dashboard (v2)
tags:
- dashboard
+ /api/v2/dashboards/{id}/migrate:
+ post:
+ deprecated: false
+ description: 'This endpoint retries the v1→v2 (Perses) migration on a dashboard
+ still stored in the v1 schema and returns the v2-shape result. It is idempotent:
+ a dashboard already in the v2 schema is returned unchanged.'
+ operationId: MigrateDashboardV2
+ parameters:
+ - in: path
+ name: id
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/DashboardtypesGettableDashboardV2'
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: OK
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Bad Request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - api_key:
+ - EDITOR
+ - tokenizer:
+ - EDITOR
+ summary: Migrate dashboard to v2
+ tags:
+ - dashboard
/api/v2/factor_password/forgot:
post:
deprecated: false
diff --git a/ee/modules/dashboard/impldashboard/module.go b/ee/modules/dashboard/impldashboard/module.go
index 8a438b9b4c..ad89c492c5 100644
--- a/ee/modules/dashboard/impldashboard/module.go
+++ b/ee/modules/dashboard/impldashboard/module.go
@@ -276,6 +276,10 @@ func (module *module) GetV2(ctx context.Context, orgID valuer.UUID, id valuer.UU
return module.pkgDashboardModule.GetV2(ctx, orgID, id)
}
+func (module *module) MigrateV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.DashboardV2, error) {
+ return module.pkgDashboardModule.MigrateV2(ctx, orgID, id)
+}
+
func (module *module) UpdateV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, updatable dashboardtypes.UpdatableDashboardV2) (*dashboardtypes.DashboardV2, error) {
return module.pkgDashboardModule.UpdateV2(ctx, orgID, id, updatedBy, updatable)
}
diff --git a/frontend/src/api/generated/services/dashboard/index.ts b/frontend/src/api/generated/services/dashboard/index.ts
index b0381a5f71..8a3019cb38 100644
--- a/frontend/src/api/generated/services/dashboard/index.ts
+++ b/frontend/src/api/generated/services/dashboard/index.ts
@@ -52,6 +52,8 @@ import type {
ListDashboardsV2200,
ListDashboardsV2Params,
LockDashboardV2PathParameters,
+ MigrateDashboardV2200,
+ MigrateDashboardV2PathParameters,
PatchDashboardV2200,
PatchDashboardV2PathParameters,
PinDashboardV2PathParameters,
@@ -1804,6 +1806,85 @@ export const useLockDashboardV2 = <
> => {
return useMutation(getLockDashboardV2MutationOptions(options));
};
+/**
+ * This endpoint retries the v1→v2 (Perses) migration on a dashboard still stored in the v1 schema and returns the v2-shape result. It is idempotent: a dashboard already in the v2 schema is returned unchanged.
+ * @summary Migrate dashboard to v2
+ */
+export const migrateDashboardV2 = (
+ { id }: MigrateDashboardV2PathParameters,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<MigrateDashboardV2200>({
+ url: `/api/v2/dashboards/${id}/migrate`,
+ method: 'POST',
+ signal,
+ });
+};
+
+export const getMigrateDashboardV2MutationOptions = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof migrateDashboardV2>>,
+ TError,
+ { pathParams: MigrateDashboardV2PathParameters },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof migrateDashboardV2>>,
+ TError,
+ { pathParams: MigrateDashboardV2PathParameters },
+ TContext
+> => {
+ const mutationKey = ['migrateDashboardV2'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof migrateDashboardV2>>,
+ { pathParams: MigrateDashboardV2PathParameters }
+ > = (props) => {
+ const { pathParams } = props ?? {};
+
+ return migrateDashboardV2(pathParams);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type MigrateDashboardV2MutationResult = NonNullable<
+ Awaited<ReturnType<typeof migrateDashboardV2>>
+>;
+
+export type MigrateDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Migrate dashboard to v2
+ */
+export const useMigrateDashboardV2 = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof migrateDashboardV2>>,
+ TError,
+ { pathParams: MigrateDashboardV2PathParameters },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof migrateDashboardV2>>,
+ TError,
+ { pathParams: MigrateDashboardV2PathParameters },
+ TContext
+> => {
+ return useMutation(getMigrateDashboardV2MutationOptions(options));
+};
/**
* This endpoint returns the sanitized v2-shape dashboard data for public access. Each panel query is reduced to a safe field subset, so filters and raw query strings are not exposed.
* @summary Get public dashboard data (v2)
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index 32232a2ef9..d830003f35 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -11164,6 +11164,17 @@ export type UnlockDashboardV2PathParameters = {
export type LockDashboardV2PathParameters = {
id: string;
};
+export type MigrateDashboardV2PathParameters = {
+ id: string;
+};
+export type MigrateDashboardV2200 = {
+ data: DashboardtypesGettableDashboardV2DTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
export type GetFeatures200 = {
/**
* @type array
diff --git a/frontend/src/pages/DashboardsListPageV2/components/DashboardRow/DashboardRow.test.tsx b/frontend/src/pages/DashboardsListPageV2/components/DashboardRow/DashboardRow.test.tsx
index 4349e3f2a6..0d0cc3c10a 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/DashboardRow/DashboardRow.test.tsx
+++ b/frontend/src/pages/DashboardsListPageV2/components/DashboardRow/DashboardRow.test.tsx
@@ -52,12 +52,12 @@ const makeDashboard = (
...overrides,
}) as unknown as DashboardListItem;
-const renderRow = (dashboard: DashboardListItem): void => {
+const renderRow = (dashboard: DashboardListItem, canEdit = true): void => {
render(
<DashboardRow
dashboard={dashboard}
index={0}
- canEdit
+ canEdit={canEdit}
showUpdatedAt={false}
showUpdatedBy={false}
/>,
@@ -105,6 +105,19 @@ describe('DashboardRow', () => {
expect(mockSafeNavigate).not.toHaveBeenCalled();
expect(screen.getByTestId('legacy-dashboard-id')).toBeInTheDocument();
+ expect(
+ screen.getByTestId('legacy-dashboard-retry-migration'),
+ ).toBeInTheDocument();
+ });
+
+ it('withholds the retry action from a row the user cannot edit', async () => {
+ renderRow(makeDashboard({ legacy: true }), false);
+
+ await userEvent.click(screen.getByTestId('dashboard-title-0'));
+
+ expect(
+ screen.queryByTestId('legacy-dashboard-retry-migration'),
+ ).not.toBeInTheDocument();
});
});
});
diff --git a/frontend/src/pages/DashboardsListPageV2/components/DashboardRow/DashboardRow.tsx b/frontend/src/pages/DashboardsListPageV2/components/DashboardRow/DashboardRow.tsx
index a6f5232887..e5421078e5 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/DashboardRow/DashboardRow.tsx
+++ b/frontend/src/pages/DashboardsListPageV2/components/DashboardRow/DashboardRow.tsx
@@ -252,6 +252,7 @@ function DashboardRow({
open={isLegacyDialogOpen}
dashboardId={id}
dashboardName={name}
+ canEdit={canEdit}
onClose={(): void => setIsLegacyDialogOpen(false)}
/>
)}
diff --git a/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.module.scss b/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.module.scss
index 94471da065..e6f3bea673 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.module.scss
+++ b/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.module.scss
@@ -49,6 +49,7 @@
.footer {
display: flex;
+ flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
}
diff --git a/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.test.tsx b/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.test.tsx
index 2a7b036877..e08cb6bbe7 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.test.tsx
+++ b/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.test.tsx
@@ -18,19 +18,30 @@ jest.mock('container/Integrations/utils', () => ({
handleContactSupport: (isCloud: boolean): void => mockContactSupport(isCloud),
}));
+const mockRetryMigration = jest.fn();
+let isMigrating = false;
+jest.mock('../../hooks/useRetryMigration', () => ({
+ useRetryMigration: (): {
+ retryMigration: jest.Mock;
+ isMigrating: boolean;
+ } => ({ retryMigration: mockRetryMigration, isMigrating }),
+}));
+
const DASHBOARD_ID = '0f9a1b2c-3d4e-5f6a-7b8c-9d0e1f2a3b4c';
describe('LegacyDashboardDialog', () => {
beforeEach(() => {
jest.clearAllMocks();
+ isMigrating = false;
});
- const setup = (open = true): void => {
+ const setup = ({ open = true, canEdit = true } = {}): void => {
render(
<LegacyDashboardDialog
open={open}
dashboardId={DASHBOARD_ID}
dashboardName="My Legacy Dashboard"
+ canEdit={canEdit}
onClose={jest.fn()}
/>,
);
@@ -57,8 +68,31 @@ describe('LegacyDashboardDialog', () => {
expect(mockContactSupport).toHaveBeenCalledTimes(1);
});
+ it('retries the migration for the dashboard', async () => {
+ setup();
+ await userEvent.click(screen.getByTestId('legacy-dashboard-retry-migration'));
+ expect(mockRetryMigration).toHaveBeenCalledWith(DASHBOARD_ID);
+ });
+
+ it('blocks retry and close while the migration is in flight', () => {
+ isMigrating = true;
+ setup();
+ expect(screen.getByTestId('legacy-dashboard-retry-migration')).toBeDisabled();
+ expect(screen.getByTestId('legacy-dashboard-close')).toBeDisabled();
+ });
+
+ it('offers only the support path without edit access', () => {
+ setup({ canEdit: false });
+ expect(
+ screen.queryByTestId('legacy-dashboard-retry-migration'),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByTestId('legacy-dashboard-contact-support'),
+ ).toBeInTheDocument();
+ });
+
it('renders nothing when closed', () => {
- setup(false);
+ setup({ open: false });
expect(screen.queryByTestId('legacy-dashboard-id')).not.toBeInTheDocument();
});
});
diff --git a/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.tsx b/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.tsx
index d37dcd4cad..e81d7611f2 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.tsx
+++ b/frontend/src/pages/DashboardsListPageV2/components/LegacyDashboardDialog/LegacyDashboardDialog.tsx
@@ -1,7 +1,7 @@
import { Button } from '@signozhq/ui/button';
import { DialogWrapper } from '@signozhq/ui/dialog';
import { Typography } from '@signozhq/ui/typography';
-import { ArrowUpRight, Copy } from '@signozhq/icons';
+import { ArrowUpRight, Copy, RotateCw } from '@signozhq/icons';
import { useCopyToClipboard } from 'react-use';
import { toast } from '@signozhq/ui/sonner';
import logEvent from 'api/common/logEvent';
@@ -9,28 +9,34 @@ import { handleContactSupport } from 'container/Integrations/utils';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { DashboardListEvents } from 'pages/DashboardsListPageV2/constants/events';
+import { useRetryMigration } from '../../hooks/useRetryMigration';
+
import styles from './LegacyDashboardDialog.module.scss';
interface LegacyDashboardDialogProps {
open: boolean;
dashboardId: string;
dashboardName: string;
+ canEdit: boolean;
onClose: () => void;
}
/**
* Explains why a legacy (pre-v2) dashboard can't be opened in the new experience
- * and hands the user the dashboard ID to share with support. Legacy rows are
- * surfaced by the list API with `legacy: true` but have no v2 spec to render.
+ * and offers to re-run the migration. Legacy rows are surfaced by the list API
+ * with `legacy: true` but have no v2 spec to render. Retrying needs edit access,
+ * so viewers only get the dashboard ID to share with support.
*/
function LegacyDashboardDialog({
open,
dashboardId,
dashboardName,
+ canEdit,
onClose,
}: LegacyDashboardDialogProps): JSX.Element {
const [, copyToClipboard] = useCopyToClipboard();
const { isCloudUser } = useGetTenantLicense();
+ const { retryMigration, isMigrating } = useRetryMigration(onClose);
const onCopyId = (): void => {
copyToClipboard(dashboardId);
@@ -49,6 +55,14 @@ function LegacyDashboardDialog({
});
};
+ const onRetryMigration = (): void => {
+ retryMigration(dashboardId);
+ void logEvent(DashboardListEvents.LegacyDialogAction, {
+ action: 'retryMigration',
+ dashboardId,
+ });
+ };
+
return (
<DialogWrapper
title="This dashboard isn't available in the new experience"
@@ -65,14 +79,15 @@ function LegacyDashboardDialog({
variant="ghost"
color="secondary"
size="md"
+ disabled={isMigrating}
onClick={onClose}
testId="legacy-dashboard-close"
>
Close
</Button>
<Button
- variant="solid"
- color="primary"
+ variant={canEdit ? 'outlined' : 'solid'}
+ color={canEdit ? 'secondary' : 'primary'}
size="md"
suffix={<ArrowUpRight size={14} />}
onClick={onContactSupport}
@@ -80,6 +95,20 @@ function LegacyDashboardDialog({
>
Contact Support
</Button>
+ {canEdit && (
+ <Button
+ variant="solid"
+ color="primary"
+ size="md"
+ prefix={<RotateCw size={14} />}
+ disabled={isMigrating}
+ loading={isMigrating}
+ onClick={onRetryMigration}
+ testId="legacy-dashboard-retry-migration"
+ >
+ Retry migration
+ </Button>
+ )}
</div>
}
>
@@ -87,8 +116,10 @@ function LegacyDashboardDialog({
<Typography.Text className={styles.description}>
<strong>{dashboardName || 'This dashboard'}</strong> hasn&apos;t been
migrated to the new dashboard experience yet, so it can&apos;t be opened
- here. Share the dashboard ID below with support and we&apos;ll help you
- move it over.
+ here.{' '}
+ {canEdit
+ ? "Retrying the migration often works once we've handled the case that blocked it. If it still fails, share the dashboard ID below with support."
+ : "Share the dashboard ID below with support and we'll help you move it over."}
</Typography.Text>
<div className={styles.idField}>
diff --git a/frontend/src/pages/DashboardsListPageV2/hooks/__tests__/useRetryMigration.test.ts b/frontend/src/pages/DashboardsListPageV2/hooks/__tests__/useRetryMigration.test.ts
new file mode 100644
index 0000000000..659fbf771b
--- /dev/null
+++ b/frontend/src/pages/DashboardsListPageV2/hooks/__tests__/useRetryMigration.test.ts
@@ -0,0 +1,109 @@
+import { renderHook } from '@testing-library/react';
+import { useQueryClient } from 'react-query';
+import { toast } from '@signozhq/ui/sonner';
+import {
+ invalidateListDashboardsForUserV2,
+ useMigrateDashboardV2,
+} from 'api/generated/services/dashboard';
+
+import { useRetryMigration } from '../useRetryMigration';
+
+jest.mock('react-query', () => ({
+ useQueryClient: jest.fn(),
+}));
+
+jest.mock('api/generated/services/dashboard', () => ({
+ useMigrateDashboardV2: jest.fn(),
+ invalidateListDashboardsForUserV2: jest.fn().mockResolvedValue(undefined),
+}));
+
+jest.mock('@signozhq/ui/sonner', () => ({
+ toast: { success: jest.fn(), error: jest.fn() },
+}));
+
+const queryClient = { invalidateQueries: jest.fn() };
+const mockMutate = jest.fn();
+const onMigrated = jest.fn();
+
+type MutationHandlers = {
+ onSuccess: () => Promise<void>;
+ onError: (error: unknown) => void;
+};
+
+let captured: MutationHandlers;
+
+// Stands in for the generated mutation hook: records the handlers the hook wires
+// up so each one can be driven directly, and reports the requested in-flight state.
+function setup(isLoading = false): {
+ retryMigration: (id: string) => void;
+ isMigrating: boolean;
+} {
+ (useMigrateDashboardV2 as jest.Mock).mockImplementation(
+ (options: { mutation: MutationHandlers }) => {
+ captured = options.mutation;
+ return { mutate: mockMutate, isLoading };
+ },
+ );
+ return renderHook(() => useRetryMigration(onMigrated)).result.current;
+}
+
+// A 501 from GET/POST on an un-migrated dashboard carries the render error envelope.
+const envelopeError = {
+ response: {
+ status: 501,
+ data: {
+ error: { code: 'dashboard_invalid_data', message: 'not in v6 schema' },
+ },
+ },
+ message: 'Request failed with status code 501',
+};
+
+// A gateway failure responds without an envelope, so there is no backend reason to show.
+const bodylessError = {
+ response: { status: 502, data: '<html>bad gateway</html>' },
+ message: 'Request failed with status code 502',
+};
+
+describe('useRetryMigration', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ (useQueryClient as jest.Mock).mockReturnValue(queryClient);
+ });
+
+ it('sends the dashboard id as a path parameter', () => {
+ setup().retryMigration('dash-1');
+ expect(mockMutate).toHaveBeenCalledWith({ pathParams: { id: 'dash-1' } });
+ });
+
+ it('refreshes the list, confirms with a toast and reports success', async () => {
+ setup();
+ await captured.onSuccess();
+
+ expect(invalidateListDashboardsForUserV2).toHaveBeenCalledWith(queryClient);
+ expect(toast.success).toHaveBeenCalledWith(
+ 'Dashboard migrated to the new experience',
+ );
+ expect(onMigrated).toHaveBeenCalledTimes(1);
+ });
+
+ it('surfaces the backend reason and does not report success on failure', () => {
+ setup();
+ captured.onError(envelopeError);
+
+ expect(toast.error).toHaveBeenCalledWith('not in v6 schema');
+ expect(onMigrated).not.toHaveBeenCalled();
+ });
+
+ it('points the user at support when the failure carries no reason', () => {
+ setup();
+ captured.onError(bodylessError);
+
+ expect(toast.error).toHaveBeenCalledWith(
+ 'Could not migrate this dashboard. Please contact support.',
+ );
+ });
+
+ it('reports the in-flight state from the mutation', () => {
+ expect(setup(true).isMigrating).toBe(true);
+ });
+});
diff --git a/frontend/src/pages/DashboardsListPageV2/hooks/useRetryMigration.ts b/frontend/src/pages/DashboardsListPageV2/hooks/useRetryMigration.ts
new file mode 100644
index 0000000000..e8ec7ffcc1
--- /dev/null
+++ b/frontend/src/pages/DashboardsListPageV2/hooks/useRetryMigration.ts
@@ -0,0 +1,48 @@
+import { useCallback } from 'react';
+import { useQueryClient } from 'react-query';
+import { toast } from '@signozhq/ui/sonner';
+import {
+ invalidateListDashboardsForUserV2,
+ useMigrateDashboardV2,
+} from 'api/generated/services/dashboard';
+import { toAPIError } from 'utils/errorUtils';
+
+const FAILURE_MESSAGE =
+ 'Could not migrate this dashboard. Please contact support.';
+
+export interface UseRetryMigrationResult {
+ // Re-run the v1 to v2 migration for a dashboard.
+ retryMigration: (id: string) => void;
+ isMigrating: boolean;
+}
+
+// Wraps the retry-migration mutation for a legacy (pre-v2) dashboard: refreshes
+// the personalized list so the row loses its legacy flag, and reports the
+// backend's reason as a toast when the dashboard still can't be converted.
+export function useRetryMigration(
+ onMigrated?: () => void,
+): UseRetryMigrationResult {
+ const queryClient = useQueryClient();
+
+ const migrate = useMigrateDashboardV2({
+ mutation: {
+ onSuccess: async (): Promise<void> => {
+ await invalidateListDashboardsForUserV2(queryClient);
+ toast.success('Dashboard migrated to the new experience');
+ onMigrated?.();
+ },
+ onError: (error): void => {
+ toast.error(toAPIError(error, FAILURE_MESSAGE).getErrorMessage());
+ },
+ },
+ });
+
+ const retryMigration = useCallback(
+ (id: string): void => {
+ migrate.mutate({ pathParams: { id } });
+ },
+ [migrate],
+ );
+
+ return { retryMigration, isMigrating: migrate.isLoading };
+}
diff --git a/pkg/apiserver/signozapiserver/dashboard.go b/pkg/apiserver/signozapiserver/dashboard.go
index 28adcdbe63..a1bed05d6e 100644
--- a/pkg/apiserver/signozapiserver/dashboard.go
+++ b/pkg/apiserver/signozapiserver/dashboard.go
@@ -85,6 +85,23 @@ func (provider *provider) addDashboardRoutes(router *mux.Router) error {
return err
}
+ if err := router.Handle("/api/v2/dashboards/{id}/migrate", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.MigrateV2), handler.OpenAPIDef{
+ ID: "MigrateDashboardV2",
+ Tags: []string{"dashboard"},
+ Summary: "Migrate dashboard to v2",
+ Description: "This endpoint retries the v1→v2 (Perses) migration on a dashboard still stored in the v1 schema and returns the v2-shape result. It is idempotent: a dashboard already in the v2 schema is returned unchanged.",
+ Request: nil,
+ RequestContentType: "",
+ Response: new(dashboardtypes.GettableDashboardV2),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: newSecuritySchemes(types.RoleEditor),
+ })).Methods(http.MethodPost).GetError(); err != nil {
+ return err
+ }
+
if err := router.Handle("/api/v2/dashboards/{id}", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.GetV2), handler.OpenAPIDef{
ID: "GetDashboardV2",
Tags: []string{"dashboard"},
diff --git a/pkg/modules/dashboard/dashboard.go b/pkg/modules/dashboard/dashboard.go
index c399100ff4..063c20294b 100644
--- a/pkg/modules/dashboard/dashboard.go
+++ b/pkg/modules/dashboard/dashboard.go
@@ -63,6 +63,9 @@ type Module interface {
GetV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.DashboardV2, error)
+ // MigrateV2 retries the v1→v2 migration on a dashboard still stored in the v1 schema.
+ MigrateV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.DashboardV2, error)
+
ListV2(ctx context.Context, orgID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardV2, error)
ListForUserV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardForUserV2, error)
@@ -132,6 +135,8 @@ type Handler interface {
GetV2(http.ResponseWriter, *http.Request)
+ MigrateV2(http.ResponseWriter, *http.Request)
+
ListV2(http.ResponseWriter, *http.Request)
ListForUserV2(http.ResponseWriter, *http.Request)
diff --git a/pkg/modules/dashboard/impldashboard/v2_handler.go b/pkg/modules/dashboard/impldashboard/v2_handler.go
index 2d18d69881..5d99ac3d84 100644
--- a/pkg/modules/dashboard/impldashboard/v2_handler.go
+++ b/pkg/modules/dashboard/impldashboard/v2_handler.go
@@ -207,6 +207,38 @@ func (handler *handler) GetV2(rw http.ResponseWriter, r *http.Request) {
render.Success(rw, http.StatusOK, dashboard.ToGettableDashboardV2())
}
+func (handler *handler) MigrateV2(rw http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
+ defer cancel()
+
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ orgID := valuer.MustNewUUID(claims.OrgID)
+
+ id := mux.Vars(r)["id"]
+ if id == "" {
+ render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is missing in the path"))
+ return
+ }
+ dashboardID, err := valuer.NewUUID(id)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ dashboard, err := handler.module.MigrateV2(ctx, orgID, dashboardID)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, dashboard.ToGettableDashboardV2())
+}
+
func (handler *handler) LockV2(rw http.ResponseWriter, r *http.Request) {
handler.lockUnlockV2(rw, r, true)
}
diff --git a/pkg/modules/dashboard/impldashboard/v2_module.go b/pkg/modules/dashboard/impldashboard/v2_module.go
index 355550dc22..d4a6856fd5 100644
--- a/pkg/modules/dashboard/impldashboard/v2_module.go
+++ b/pkg/modules/dashboard/impldashboard/v2_module.go
@@ -4,6 +4,7 @@ import (
"context"
"github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/transition"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/types/dashboardtypes"
"github.com/SigNoz/signoz/pkg/types/tagtypes"
@@ -121,6 +122,51 @@ func (module *module) GetV2(ctx context.Context, orgID valuer.UUID, id valuer.UU
return storable.ToDashboardV2(tags)
}
+// MigrateV2 retries the v1→v2 migration on a dashboard still stored as v1 (one the
+// bulk 103 migration skipped or failed). Idempotent: an already-v2 one is unchanged.
+func (module *module) MigrateV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.DashboardV2, error) {
+ storable, err := module.store.Get(ctx, orgID, id)
+ if err != nil {
+ return nil, err
+ }
+
+ // Already migrated: return as-is.
+ if storable.IsV2() {
+ tags, err := module.tagModule.ListForResource(ctx, orgID, coretypes.KindDashboard, id)
+ if err != nil {
+ return nil, err
+ }
+ return storable.ToDashboardV2(tags)
+ }
+
+ // v1→v2 needs v5-shaped queries; run v4→v5 in place first.
+ transition.NewDashboardMigrateV5(module.settings.Logger(), nil, nil).Migrate(ctx, storable.Data)
+
+ v2, err := storable.ConvertV1ToV2()
+ if err != nil {
+ return nil, err
+ }
+
+ err = module.store.RunInTx(ctx, func(ctx context.Context) error {
+ resolvedTags, err := module.tagModule.SyncTags(ctx, orgID, coretypes.KindDashboard, v2.ID, tagtypes.NewPostableTagsFromTags(v2.Tags))
+ if err != nil {
+ return err
+ }
+ v2.Tags = resolvedTags
+
+ storableV2, err := v2.ToStorableDashboard()
+ if err != nil {
+ return err
+ }
+ return module.store.Update(ctx, orgID, storableV2)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return v2, nil
+}
+
func (module *module) UpdateV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, updatable dashboardtypes.UpdatableDashboardV2) (*dashboardtypes.DashboardV2, error) {
if err := updatable.Validate(); err != nil {
return nil, err
diff --git a/pkg/types/dashboardtypes/perses_v1_to_v2_queries.go b/pkg/types/dashboardtypes/perses_v1_to_v2_queries.go
index c3bc398425..0a776f357f 100644
--- a/pkg/types/dashboardtypes/perses_v1_to_v2_queries.go
+++ b/pkg/types/dashboardtypes/perses_v1_to_v2_queries.go
@@ -179,6 +179,7 @@ func (d *v1Decoder) collectV1QueryEnvelopes(widget map[string]any, panelKind Pan
normalizePreV5GroupBy(q)
normalizePreV5PageSize(q, rowLimitPanel)
normalizeQueryLimit(q)
+ normalizeQueryOffset(q)
if needsAggregation {
ensureDefaultAggregation(q)
}
@@ -198,6 +199,7 @@ func (d *v1Decoder) collectV1QueryEnvelopes(widget map[string]any, panelKind Pan
assignMissingFormulaNames(formulas)
for _, f := range formulas {
normalizePreV5QueryData(f, widgetType, panelKind)
+ normalizeQueryLimit(f)
name := d.readString(f, "queryName")
env := qb.WrapInV5Envelope(name, f, string(qb.QueryTypeFormula.StringValue()))
backfillFormulaFields(env, f)
@@ -219,6 +221,8 @@ func (d *v1Decoder) collectV1QueryEnvelopes(widget map[string]any, panelKind Pan
normalizePreV5QueryData(op, widgetType, panelKind)
normalizePreV5GroupBy(op)
normalizeOrderByKeys(op)
+ normalizeQueryLimit(op)
+ normalizeQueryOffset(op)
name := d.readString(op, "queryName")
out = append(out, traceOperatorEnvelope(name, expression, op))
}
diff --git a/pkg/types/dashboardtypes/perses_v1_to_v2_queries_malformed.go b/pkg/types/dashboardtypes/perses_v1_to_v2_queries_malformed.go
index 1d3369f1f6..e7de6bcec5 100644
--- a/pkg/types/dashboardtypes/perses_v1_to_v2_queries_malformed.go
+++ b/pkg/types/dashboardtypes/perses_v1_to_v2_queries_malformed.go
@@ -618,15 +618,32 @@ func normalizePreV5PageSize(query map[string]any, rowLimitPanel bool) {
}
}
-// normalizeQueryLimit drops a limit above the v5 maximum (MaxQueryLimit); v1 allowed
-// larger/unbounded limits, and an over-max value fails validation. Removing it leaves
-// the query unlimited (the field is optional).
+// normalizeQueryLimit coerces limit to the int the v5 decode expects: v1 stored it
+// as a string ("5") or float, both of which fail the typed decode. An unparseable
+// value or one above the v5 maximum (MaxQueryLimit) is dropped, leaving the query
+// unlimited (the field is optional).
func normalizeQueryLimit(query map[string]any) {
- limit, ok := coerceFloat(query["limit"])
- if !ok {
+ if query["limit"] == nil {
return
}
- if limit > qb.MaxQueryLimit {
+ limit, ok := coerceFloat(query["limit"])
+ if !ok || limit > qb.MaxQueryLimit {
delete(query, "limit")
+ return
+ }
+ query["limit"] = int(limit)
+}
+
+// normalizeQueryOffset coerces offset to the int the v5 decode expects; v1 could
+// store it as a string. An unparseable value is dropped (offset defaults to 0).
+func normalizeQueryOffset(query map[string]any) {
+ if query["offset"] == nil {
+ return
+ }
+ offset, ok := coerceFloat(query["offset"])
+ if !ok {
+ delete(query, "offset")
+ return
}
+ query["offset"] = int(offset)
}