:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-catalog): add metric detail scene with definition editing (#73977)
Thiago Salvatorecaf61c24256e
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 95cbef65b0d5..f459fa3f6bc2 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -52,6 +52,7 @@ export const productScenes: Record<string, () => Promise<any>> = {CustomerJourneyTemplates: () =>import('../../products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/CustomerJourneyTemplatesScene'),DataCatalog: () => import('../../products/data_catalog/frontend/DataCatalogScene'),+ DataCatalogMetric: () => import('../../products/data_catalog/frontend/DataCatalogMetricScene'),DataOps: () => import('../../products/data_warehouse/DataWarehouseScene'),Models: () => import('../../frontend/src/scenes/models/ModelsScene'),NodeDetail: () => import('../../frontend/src/scenes/models/NodeDetailScene'),diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex bde2904598f8..03ee6ba2179a 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -108,6 +108,7 @@ export const productRoutes: Record<string, [string, string]> = {'/customer_analytics/journeys': ['CustomerAnalytics', 'customerAnalyticsJourneys'],'/customer_analytics/configuration': ['CustomerAnalyticsConfiguration', 'customerAnalyticsConfiguration'],'/data-catalog': ['DataCatalog', 'dataCatalog'],+ '/data-catalog/metrics/:name': ['DataCatalogMetric', 'dataCatalogMetric'],'/data-ops': ['DataOps', 'dataOps'],'/models': ['Models', 'models'],'/models/dags': ['Models', 'models'],@@ -540,6 +541,7 @@ export const productConfiguration: Record<string, any> = {iconType: 'data_warehouse',description: 'Review and manage governed metrics, certifications, and relationships for your data.',},+ DataCatalogMetric: { projectBased: true, name: 'Metric' },DataOps: {name: 'Data ops',projectBased: true,@@ -992,6 +994,7 @@ export const productUrls = {`/dashboard/${id}/subscriptions/${subscriptionId}`,sharedDashboard: (shareToken: string): string => `/shared_dashboard/${shareToken}`,dataCatalog: (tab?: string): string => `/data-catalog${tab ? `?tab=${tab}` : ''}`,+ dataCatalogMetric: (name: string): string => `/data-catalog/metrics/${name}`,dataOps: (tab?: string, dagId?: string): string => {const params = new URLSearchParams()if (tab) {@@ -1797,7 +1800,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [href: urls.dataCatalog(),flag: FEATURE_FLAGS.PRODUCT_DATA_CATALOG,sceneKey: 'DataCatalog',- sceneKeys: ['DataCatalog'],+ sceneKeys: ['DataCatalog', 'DataCatalogMetric'],},{path: 'Data warehouse',diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex 81af481f3edc..bffb2f0adafa 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -376,12 +376,16 @@ function SQLEditorSceneTitle(): JSX.Element | null {saveAsInsight,saveAsView,saveAsEndpoint,+ saveAsMetric,+ updateEditingMetric,+ setEditingMetricName,setSourceQuery,setSuggestedQueryInput,reportAIQueryPromptOpen,setEditingInsightName,setEditingInsightDescription,} = useActions(sqlEditorLogic)+ const { editingMetricName, metricUpdating } = useValues(sqlEditorLogic)const { response, responseError, responseLoading } = useValues(dataNodeLogic)const { updatingDataWarehouseSavedQuery } = useValues(dataWarehouseViewsLogic)@@ -418,6 +422,11 @@ function SQLEditorSceneTitle(): JSX.Element | null {return}+ if (item.action === 'metric') {+ saveAsMetric()+ return+ }+saveAsView()},accessDisabledReason:@@ -430,6 +439,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {[saveAsEndpoint,saveAsInsight,+ saveAsMetric,saveAsMenuItems.secondary,saveAsView,saveAsViewAccessDisabledReason,@@ -443,6 +453,11 @@ function SQLEditorSceneTitle(): JSX.Element | null {return}+ if (saveAsMenuItems.primary.action === 'metric') {+ saveAsMetric()+ return+ }+if (saveAsMenuItems.primary.action === 'view') {saveAsView()return@@ -707,6 +722,42 @@ function SQLEditorSceneTitle(): JSX.Element | null {tooltip={closeObjectTooltip}/></>+ ) : editingMetricName ? (+ <>+ <LemonButton+ type="primary"+ size="small"+ onClick={() => updateEditingMetric()}+ loading={metricUpdating}+ disabledReason={saveAsDisabledReason}+ data-attr="sql-editor-update-metric"+ sideAction={{+ icon: <IconChevronDown />,+ dropdown: {+ placement: 'bottom-end',+ overlay: (+ <LemonMenuOverlay+ items={secondarySaveMenuItems.map((item) => ({+ ...item,+ disabledReason:+ saveAsDisabledReason ?? item.accessDisabledReason,+ }))}+ />+ ),+ },+ }}+ >+ Update metric+ </LemonButton>+ <LemonButton+ onClick={() => setEditingMetricName(null)}+ icon={<IconX />}+ type="tertiary"+ size="small"+ aria-label="Stop editing metric"+ tooltip="Stop editing this metric and start a new query"+ />+ </>) : (<LemonButtontype="primary"diff --git a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsxindex 91ab07133500..483ff67c136f 100644--- a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx@@ -18,7 +18,7 @@ import { normalizeFiltersForUrl, sqlEditorLogic, toDataVisualizationNode } fromimport type { QueryTab, SqlEditorSource } from './sqlEditorLogic'export interface SaveAsMenuItem {- action: 'insight' | 'endpoint' | 'view'+ action: 'insight' | 'endpoint' | 'view' | 'metric'label: stringdataAttr?: string}@@ -405,6 +405,7 @@ export const editorSceneLogic = kea<editorSceneLogicType>([featureFlags: import('../../../lib/logic/featureFlagLogic').FeatureFlagsSet): { primary: SaveAsMenuItem; secondary: SaveAsMenuItem[] } => {const endpointsEnabled = !!featureFlags[FEATURE_FLAGS.ENDPOINTS]+ const metricsEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_DATA_CATALOG]const saveAsInsightItem: SaveAsMenuItem = {action: 'insight',label: dashboardId ? 'Save & add to dashboard' : 'Save as insight',@@ -418,24 +419,43 @@ export const editorSceneLogic = kea<editorSceneLogicType>([label: 'Save as view',dataAttr: 'sql-editor-save-view-button',}+ const saveAsMetricItem: SaveAsMenuItem = {+ action: 'metric',+ label: 'Save as metric',+ }+ const extraItems = [+ ...(endpointsEnabled ? [saveAsEndpointItem] : []),+ ...(metricsEnabled ? [saveAsMetricItem] : []),+ ]++ if (editorSource === 'metric' && metricsEnabled) {+ return {+ primary: saveAsMetricItem,+ secondary: [+ saveAsInsightItem,+ saveAsViewItem,+ ...(endpointsEnabled ? [saveAsEndpointItem] : []),+ ],+ }+ }if (editorSource === 'endpoint' && endpointsEnabled) {return {primary: saveAsEndpointItem,- secondary: [saveAsInsightItem, saveAsViewItem],+ secondary: [saveAsInsightItem, saveAsViewItem, ...(metricsEnabled ? [saveAsMetricItem] : [])],}}if (editorSource === 'view') {return {primary: saveAsViewItem,- secondary: endpointsEnabled ? [saveAsInsightItem, saveAsEndpointItem] : [saveAsInsightItem],+ secondary: [saveAsInsightItem, ...extraItems],}}return {primary: saveAsInsightItem,- secondary: endpointsEnabled ? [saveAsEndpointItem, saveAsViewItem] : [saveAsViewItem],+ secondary: [saveAsViewItem, ...extraItems],}},],diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex c22ac300f82d..e4da3e0c8ca1 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -913,6 +913,90 @@ describe('sqlEditorLogic', () => {})})+ describe('edit_metric URL parameter', () => {+ it('binds the update target to the server-loaded metric query, ignoring URL-supplied open_query', async () => {+ // Guards against re-binding the "Update metric" button to attacker-controlled+ // open_query SQL: a crafted link must not overwrite a teammate's metric.+ useMocks({+ get: {+ '/api/projects/:team_id/data_catalog/metrics/my_metric/': [+ 200,+ {+ name: 'my_metric',+ definition: { kind: NodeKind.HogQLQuery, query: 'SELECT count() FROM events' },+ },+ ],+ },+ })++ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ router.actions.push(urls.sqlEditor(), {+ source: 'metric',+ edit_metric: 'my_metric',+ open_query: 'SELECT * FROM sensitive_table',+ })++ await expectLogic(logic)+ .toDispatchActions(['createTab', 'setQueryInput'])+ .toNotHaveDispatchedActions(['runQuery'])+ .toMatchValues({+ queryInput: 'SELECT count() FROM events',+ editingMetricName: 'my_metric',+ })+ })++ it('opens an unbound tab when the metric cannot be loaded', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/data_catalog/metrics/missing_metric/': [404],+ },+ })++ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ router.actions.push(urls.sqlEditor(), { source: 'metric', edit_metric: 'missing_metric' })++ await expectLogic(logic).toDispatchActions(['createTab']).toMatchValues({ editingMetricName: null })+ })++ it('does not request or bind a traversal-shaped edit_metric name', async () => {+ // edit_metric is interpolated into the request path unencoded, so a "../"-shaped+ // name must be rejected before it can reach another project's metric.+ const retrieveMock = jest.fn(() => [200, { name: 'x', definition: { query: 'SELECT 1' } }])+ useMocks({+ get: {+ '/api/projects/:team_id/data_catalog/metrics/:name/': retrieveMock,+ },+ })++ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ router.actions.push(urls.sqlEditor(), {+ source: 'metric',+ edit_metric: '../../../1/data_catalog/metrics/other',+ })++ await expectLogic(logic).toDispatchActions(['createTab']).toMatchValues({ editingMetricName: null })+ expect(retrieveMock).not.toHaveBeenCalled()+ })+ })+describe('Update view', () => {it('advances the saved baseline after updating so reverting to the original query re-enables Update view', async () => {logic = sqlEditorLogic({diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex fbc87c4e9eaa..c72a078f7c71 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -32,7 +32,7 @@ import {Tooltip,} from '@posthog/lemon-ui'-import api, { ApiError } from 'lib/api'+import api, { ApiConfig, ApiError } from 'lib/api'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { FEATURE_FLAGS } from 'lib/constants'@@ -80,6 +80,12 @@ import {QueryBasedInsightModel,} from '~/types'+import { validateMetricName } from 'products/data_catalog/frontend/common'+import {+ dataCatalogMetricsCreate,+ dataCatalogMetricsPartialUpdate,+ dataCatalogMetricsRetrieve,+} from 'products/data_catalog/frontend/generated/api'import { DagSelector, openCreateDagDialog } from 'products/data_modeling/frontend/DagSelector'import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'import { validateEndpointName } from 'products/endpoints/frontend/common'@@ -236,9 +242,10 @@ export interface QueryTab {insight?: QueryBasedInsightModelresponse?: Record<string, any>draft?: DataWarehouseSavedQueryDraft+ metricName?: string}-export type SqlEditorSource = 'insight' | 'endpoint' | 'view'+export type SqlEditorSource = 'insight' | 'endpoint' | 'view' | 'metric'export interface DataWarehouseAccessControlModalProps {resource: AccessControlResourceType.WarehouseTable | AccessControlResourceType.WarehouseView@@ -494,6 +501,7 @@ export interface sqlEditorLogicValues {diffShowRunButton: boolean | undefinededitingAccessControlObject: DataWarehouseAccessControlModalProps | nulleditingInsight: QueryBasedInsightModel | null+ editingMetricName: string | nulleditingView: DataWarehouseSavedQuery | undefinededitorKey: stringeditorSource: SqlEditorSource@@ -517,6 +525,7 @@ export interface sqlEditorLogicValues {materializationModalView: DataWarehouseSavedQuery | nullmetadata: HogQLMetadataResponse | nullmetadataLoading: boolean+ metricUpdating: booleanoriginalQueryInput: string | null | undefinedqueryInput: string | nullrejectText: string@@ -736,10 +745,12 @@ export interface sqlEditorLogicActions {query?: string,view?: DataWarehouseSavedQuery,insight?: QueryBasedInsightModel,- draft?: DataWarehouseSavedQueryDraft+ draft?: DataWarehouseSavedQueryDraft,+ metricName?: string) => {draft: DataWarehouseSavedQueryDraft | undefinedinsight: QueryBasedInsightModel<Node<Record<string, any>>> | undefined+ metricName: string | undefinedquery: string | undefinedview: DataWarehouseSavedQuery | undefined}@@ -857,6 +868,18 @@ export interface sqlEditorLogicActions {name: stringqueryOverride: string | undefined}+ saveAsMetric: () => {+ value: true+ }+ saveAsMetricSubmit: (+ name: string,+ description: string,+ queryOverride?: string+ ) => {+ description: string+ name: string+ queryOverride: string | undefined+ }saveAsView: (materializeAfterSave?: any,fromDraft?: string@@ -909,6 +932,9 @@ export interface sqlEditorLogicActions {setEditingInsightName: (name: string) => {name: string}+ setEditingMetricName: (metricName: string | null) => {+ metricName: string | null+ }setEditorSource: (source: SqlEditorSource) => {source: SqlEditorSource}@@ -959,6 +985,9 @@ export interface sqlEditorLogicActions {setMetadataLoading: (loading: boolean) => {loading: boolean}+ setMetricUpdating: (updating: boolean) => {+ updating: boolean+ }setQueryInput: (queryInput: string | null) => {queryInput: string | null}@@ -990,6 +1019,9 @@ export interface sqlEditorLogicActions {syncUrlWithQuery: () => {value: true}+ updateEditingMetric: () => {+ value: true+ }updateInsight: () => {value: true}@@ -1028,6 +1060,7 @@ export interface sqlEditorLogicMeta {queryInput: string | null) => string | null | undefinededitingView: (activeTab: QueryTab | null) => DataWarehouseSavedQuery | undefined+ editingMetricName: (activeTab: QueryTab | null) => string | nullchangesToSave: (editingView: DataWarehouseSavedQuery | undefined, queryInput: string | null) => booleanexportContext: (sourceQuery: DataVisualizationNode) => ExportContextselectedConnectionId: (sourceQuery: DataVisualizationNode) => string | undefined@@ -1135,12 +1168,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([query?: string,view?: DataWarehouseSavedQuery,insight?: QueryBasedInsightModel,- draft?: DataWarehouseSavedQueryDraft+ draft?: DataWarehouseSavedQueryDraft,+ metricName?: string) => ({query,view,insight,draft,+ metricName,}),updateTab: (tab: QueryTab) => ({ tab }),@@ -1182,6 +1217,15 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([queryOverride,dagId,}),+ saveAsMetric: true,+ saveAsMetricSubmit: (name: string, description: string, queryOverride?: string) => ({+ name,+ description,+ queryOverride,+ }),+ setEditingMetricName: (metricName: string | null) => ({ metricName }),+ updateEditingMetric: true,+ setMetricUpdating: (updating: boolean) => ({ updating }),updateInsight: true,setEditingInsightName: (name: string) => ({ name }),setEditingInsightDescription: (description: string) => ({ description }),@@ -1464,6 +1508,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([setInsightLoading: (_, { loading }) => loading,},],+ metricUpdating: [+ false,+ {+ setMetricUpdating: (_, { updating }) => updating,+ },+ ],activeTab: [null as QueryTab | null,{@@ -1688,7 +1738,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([editInsight: ({ query, insight }) => {actions.createTab(query, undefined, insight)},- createTab: async ({ query = '', view, insight, draft }) => {+ createTab: async ({ query = '', view, insight, draft, metricName }) => {// Use tabId to ensure each browser tab has its own unique Monaco modelconst tabName = insight ? (insight.name ?? NEW_QUERY) : draft?.name || view?.name || NEW_QUERYconst tabDescription = insight?.description ?? ''@@ -1723,6 +1773,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([description: tabDescription,sourceQuery: insightVisualizationQuery,draft: draft,+ metricName,})}if (insightVisualizationQuery) {@@ -2431,6 +2482,81 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([lemonToast.error(error.detail || 'Failed to create endpoint')}},+ saveAsMetric: async () => {+ const candidates = resolveSaveCandidates()+ const selectedRef = { current: candidates.queries[candidates.initialIndex] }+ LemonDialog.openForm({+ title: 'Save as metric',+ initialValues: { name: '', description: '' },+ content: (+ <>+ <LemonField name="name" label="Name">+ <LemonInput placeholder="monthly_active_users" autoFocus />+ </LemonField>+ <LemonField name="description" label="Description" className="mt-2">+ <LemonInput placeholder="What this metric measures and how to read it" />+ </LemonField>+ <SaveTargetCycler+ candidates={candidates}+ onChange={(q) => {+ selectedRef.current = q+ }}+ />+ </>+ ),+ errors: {+ name: (name) => validateMetricName(name?.trim() || ''),+ description: (description) => (!description?.trim() ? 'Add a description' : undefined),+ },+ onSubmit: async ({ name, description }) =>+ actions.saveAsMetricSubmit(name.trim(), description.trim(), selectedRef.current),+ })+ },+ saveAsMetricSubmit: async ({ name, description, queryOverride }) => {+ try {+ const metric = await dataCatalogMetricsCreate(String(ApiConfig.getCurrentTeamId()), {+ name,+ description,+ definition: normalizeRawQuerySource({+ ...(values.sourceQuery.source as HogQLQuery),+ query: queryOverride ?? values.queryInput ?? '',+ }) as unknown as Record<string, unknown>,+ })+ lemonToast.success('Metric created')+ router.actions.push(urls.dataCatalogMetric(metric.name))+ } catch (error: any) {+ lemonToast.error(error.detail || 'Failed to create metric')+ }+ },+ updateEditingMetric: async () => {+ if (!values.editingMetricName || values.metricUpdating) {+ return+ }+ actions.setMetricUpdating(true)+ try {+ await dataCatalogMetricsPartialUpdate(+ String(ApiConfig.getCurrentTeamId()),+ values.editingMetricName,+ {+ definition: normalizeRawQuerySource({+ ...(values.sourceQuery.source as HogQLQuery),+ query: values.queryInput ?? '',+ }) as unknown as Record<string, unknown>,+ }+ )+ lemonToast.success('Metric updated')+ router.actions.push(urls.dataCatalogMetric(values.editingMetricName))+ } catch (error: any) {+ lemonToast.error(error.detail || 'Failed to update metric')+ } finally {+ actions.setMetricUpdating(false)+ }+ },+ setEditingMetricName: ({ metricName }) => {+ if (values.activeTab) {+ actions.updateTab({ ...values.activeTab, metricName: metricName ?? undefined })+ }+ },setEditingInsightName: ({ name }) => {if (values.activeTab) {actions.updateTab({ ...values.activeTab, name })@@ -2831,6 +2957,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([return activeTab?.view},],+ editingMetricName: [+ (s) => [s.activeTab],+ (activeTab: QueryTab | null) => {+ return activeTab?.metricName ?? null+ },+ ],changesToSave: [(s) => [s.editingView, s.queryInput],(editingView: DataWarehouseSavedQuery | undefined, queryInput: string | null) => {@@ -2968,7 +3100,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([if (searchParams.source === 'endpoint' ||searchParams.source === 'insight' ||- searchParams.source === 'view'+ searchParams.source === 'view' ||+ searchParams.source === 'metric') {actions.setEditorSource(searchParams.source)}@@ -3213,6 +3346,33 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([tabAdded = truerouter.actions.replace(urls.sqlEditor(), undefined, getTabHash(values))+ } else if (searchParams.edit_metric) {+ // edit_metric binds the "Update metric" button to overwrite a named metric.+ // Both edit_metric and open_query are URL-controlled, so we never bind the+ // update target to URL-supplied SQL — a crafted link could otherwise overwrite+ // a teammate's metric with arbitrary HogQL. Load the metric server-side and open+ // its stored query, so the update target and its definition come from the same+ // authenticated response.+ try {+ // Validate before it reaches the request path: the value is interpolated+ // into the URL unencoded, so a name containing "../" could otherwise+ // traverse to a metric in another project. The name regex forbids slashes.+ if (validateMetricName(searchParams.edit_metric)) {+ throw new Error('Invalid metric name')+ }+ const metric = await dataCatalogMetricsRetrieve(+ String(ApiConfig.getCurrentTeamId()),+ searchParams.edit_metric+ )+ const definition = metric.definition as Record<string, unknown> | null | undefined+ const metricQuery = typeof definition?.query === 'string' ? definition.query : ''+ actions.createTab(metricQuery, undefined, undefined, undefined, metric.name)+ } catch {+ // Invalid name, metric not found, or no access — open an unbound empty tab+ // rather than binding an update target we couldn't verify.+ actions.createTab('')+ }+ tabAdded = true} else if (searchParams.open_query) {// kea-router decodes JSON-shaped URL values to objects — a node here carries// visualization settings (display, chartSettings) alongside the SQLdiff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex cfa3f9fd1303..cd09a60439a3 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -78,6 +78,7 @@ export const urls = {connectionId,dashboard,filters,+ metricName,}: {/** Raw SQL, or a node whose visualization settings (display, chartSettings) should survive the trip */query?: string | DataVisualizationNode | DataTableNode@@ -91,6 +92,8 @@ export const urls = {dashboard?: number/** Applied on top of the opened query/insight — carries unsaved view-mode filter edits into the editor */filters?: HogQLFilters+ /** Opens the editor bound to this data catalog metric so its query can be updated in place */+ metricName?: string} = {}): string => {const params = new URLSearchParams()@@ -116,6 +119,10 @@ export const urls = {params.set('source', source)}+ if (metricName) {+ params.set('edit_metric', metricName)+ }+if (dashboard) {params.set('dashboard', String(dashboard))}diff --git a/products/data_catalog/frontend/DataCatalogMetricScene.tsx b/products/data_catalog/frontend/DataCatalogMetricScene.tsxnew file mode 100644index 000000000000..118ec714846e--- /dev/null+++ b/products/data_catalog/frontend/DataCatalogMetricScene.tsx@@ -0,0 +1,624 @@+import { BindLogic, useActions, useValues } from 'kea'+import { router } from 'kea-router'+import { ReactNode, useState } from 'react'++import { IconCheck, IconGraph, IconPencil, IconPlay, IconRefresh, IconServer, IconTrash } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonDialog, LemonDivider, LemonTag } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'+import { NotFound } from 'lib/components/NotFound'+import { TZLabel } from 'lib/components/TZLabel'+import { FEATURE_FLAGS } from 'lib/constants'+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { LemonTable } from 'lib/lemon-ui/LemonTable'+import { LemonTextAreaMarkdown } from 'lib/lemon-ui/LemonTextArea/LemonTextAreaMarkdown'+import { Spinner } from 'lib/lemon-ui/Spinner'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'+import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import {+ SceneMenuBar,+ SceneMenuBarItem,+ SceneMenuBarMenu,+ SceneMenuBarSeparator,+} from '~/layout/scenes/components/SceneMenuBar'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { ScenePanel, ScenePanelActionsSection, ScenePanelInfoSection } from '~/layout/scenes/SceneLayout'+import { InsightShortId } from '~/types'++import { humanizeDefinitionKind } from './common'+import {+ dataCatalogMetricSceneLogic,+ DataCatalogMetricSceneLogicProps,+ definitionField,+} from './dataCatalogMetricSceneLogic'+import type { DataCatalogMetricApi } from './generated/api.schemas'++export const scene: SceneExport<DataCatalogMetricSceneLogicProps> = {+ component: DataCatalogMetricScene,+ logic: dataCatalogMetricSceneLogic,+ paramsToProps: ({ params: { name } }) => ({ name: name ?? '' }),+}++interface MetricAction {+ key: string+ label: string+ icon: JSX.Element+ onClick: () => void+ disabledReason?: string+ destructive?: boolean+ opensFloatingUi?: boolean+}++const DRIFT_APPROVE_DISABLED = 'This metric has drifted from its source insight. Refresh it first.'++export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicProps): JSX.Element {+ const { metric, metricLoading, mutating, runResult, runResultLoading, editingDefinition, draftMarkdown } =+ useValues(dataCatalogMetricSceneLogic)+ const {+ approveMetric,+ refreshMetricFromInsight,+ deleteMetric,+ updateMetric,+ loadRunResult,+ setEditingDefinition,+ setDraftMarkdown,+ } = useActions(dataCatalogMetricSceneLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const sceneMenuBarEnabled = !!featureFlags[FEATURE_FLAGS.SCENE_MENU_BAR]++ if (metricLoading && !metric) {+ return <Spinner className="text-2xl" />+ }+ if (!metric) {+ return <NotFound object="metric" />+ }++ const sourceShortId = metric.source_insight_short_id+ const definitionSql = definitionField(metric, 'query')+ const isApproved = metric.status === 'approved'++ const confirmAndUpdate = (patch: Partial<DataCatalogMetricApi>): void => {+ if (!isApproved) {+ updateMetric(patch)+ return+ }+ LemonDialog.open({+ title: 'Edit this approved metric?',+ content: (+ <div className="text-sm text-secondary">+ Saving this change sets the metric back to proposed, so it will need to be approved again.+ </div>+ ),+ primaryButton: { children: 'Save and reset to proposed', onClick: () => updateMetric(patch) },+ secondaryButton: { children: 'Cancel' },+ })+ }++ const confirmDelete = (): void => {+ LemonDialog.open({+ title: 'Delete metric?',+ content: <div className="text-sm text-secondary">Deleting {metric.name} cannot be undone.</div>,+ primaryButton: { children: 'Delete', status: 'danger', onClick: deleteMetric },+ secondaryButton: { children: 'Cancel' },+ })+ }++ const actions: MetricAction[] = [+ ...(isApproved+ ? []+ : [+ {+ key: 'approve',+ label: 'Approve',+ icon: <IconCheck />,+ onClick: approveMetric,+ disabledReason: metric.is_drifted ? DRIFT_APPROVE_DISABLED : mutating ? 'Working' : undefined,+ },+ ]),+ ...(sourceShortId+ ? [+ {+ key: 'refresh',+ label: 'Refresh from insight',+ icon: <IconRefresh />,+ onClick: refreshMetricFromInsight,+ disabledReason: mutating ? 'Working' : undefined,+ },+ {+ key: 'source-insight',+ label: 'View source insight',+ icon: <IconGraph />,+ onClick: () => router.actions.push(urls.insightView(sourceShortId as InsightShortId)),+ },+ ]+ : []),+ {+ key: 'run',+ label: 'Run metric',+ icon: <IconPlay />,+ onClick: loadRunResult,+ disabledReason: metric.definition_kind ? undefined : 'This metric has no runnable definition yet',+ },+ ...(definitionSql+ ? [+ {+ key: 'open-sql',+ label: 'Open in SQL editor',+ icon: <IconServer />,+ onClick: () => router.actions.push(urls.sqlEditor({ source: 'metric', metricName: metric.name })),+ },+ ]+ : []),+ {+ key: 'delete',+ label: 'Delete',+ icon: <IconTrash />,+ onClick: confirmDelete,+ destructive: true,+ opensFloatingUi: true,+ },+ ]++ const nonDestructive = actions.filter((action) => !action.destructive)+ const destructive = actions.filter((action) => action.destructive)++ return (+ <BindLogic logic={dataCatalogMetricSceneLogic} props={{ name }}>+ <SceneContent>+ {sceneMenuBarEnabled && (+ <SceneMenuBar>+ <SceneMenuBarMenu label="Metric" dataAttr="data-catalog-metric-menubar">+ {nonDestructive.map((action) => (+ <SceneMenuBarItem+ key={action.key}+ onClick={action.onClick}+ disabled={!!action.disabledReason}+ data-attr={`data-catalog-metric-menubar-${action.key}`}+ >+ {action.icon}+ {action.label}+ </SceneMenuBarItem>+ ))}+ <SceneMenuBarSeparator />+ {destructive.map((action) => (+ <SceneMenuBarItem+ key={action.key}+ variant="destructive"+ onClick={action.onClick}+ data-attr={`data-catalog-metric-menubar-${action.key}`}+ >+ {action.icon}+ {action.label}+ </SceneMenuBarItem>+ ))}+ </SceneMenuBarMenu>+ </SceneMenuBar>+ )}++ <SceneTitleSection+ name={metric.display_name || metric.name}+ description={metric.description}+ resourceType={{ type: 'data_warehouse' }}+ canEdit+ onNameChange={(value) => confirmAndUpdate({ display_name: value })}+ onDescriptionChange={(value) => confirmAndUpdate({ description: value })}+ renameDebounceMs={0}+ />++ {metric.is_drifted && (+ <LemonBanner type="warning">+ This metric has drifted from its source insight, so it cannot be approved. Refresh it from the+ insight to pick up the current query.+ <div className="flex gap-2 mt-2">+ {sourceShortId && (+ <LemonButton type="secondary" size="small" onClick={refreshMetricFromInsight}>+ Refresh from insight+ </LemonButton>+ )}+ {sourceShortId && (+ <LemonButton+ type="secondary"+ size="small"+ to={urls.insightView(sourceShortId as InsightShortId)}+ >+ View source insight+ </LemonButton>+ )}+ </div>+ </LemonBanner>+ )}++ {!isApproved && !metric.is_drifted && (+ <LemonBanner type="info">+ This metric is proposed. Approve it once the definition looks right.+ <div className="flex gap-2 mt-2">+ <LemonButton+ type="primary"+ size="small"+ onClick={approveMetric}+ disabledReason={mutating ? 'Working' : undefined}+ >+ Approve metric+ </LemonButton>+ </div>+ </LemonBanner>+ )}++ <MetricMetadata metric={metric} onSaveUnit={(unit) => confirmAndUpdate({ unit })} />++ <MetricDefinition+ metric={metric}+ editingDefinition={editingDefinition}+ draftMarkdown={draftMarkdown}+ saving={mutating}+ runResult={runResult}+ runResultLoading={runResultLoading}+ onDraftMarkdown={setDraftMarkdown}+ onEdit={setEditingDefinition}+ onSaveMarkdown={(markdown) =>+ confirmAndUpdate({ definition: { kind: 'MarkdownDefinition', markdown } })+ }+ onRun={loadRunResult}+ />+ </SceneContent>++ <ScenePanel>+ <ScenePanelInfoSection>+ <div className="flex flex-col gap-1 text-sm">+ <StatusRow metric={metric} />+ </div>+ </ScenePanelInfoSection>+ <ScenePanelActionsSection>+ {nonDestructive.map((action) => (+ <ButtonPrimitive+ key={action.key}+ menuItem+ onClick={action.onClick}+ disabled={!!action.disabledReason}+ tooltip={action.disabledReason}+ >+ {action.icon}+ {action.label}+ </ButtonPrimitive>+ ))}+ <LemonDivider />+ {destructive.map((action) => (+ <ButtonPrimitive key={action.key} menuItem onClick={action.onClick} className="text-danger">+ {action.icon}+ {action.label}+ </ButtonPrimitive>+ ))}+ </ScenePanelActionsSection>+ </ScenePanel>+ </BindLogic>+ )+}++function StatusRow({ metric }: { metric: DataCatalogMetricApi }): JSX.Element {+ return (+ <div className="flex items-center gap-1">+ <LemonTag type={metric.status === 'approved' ? 'success' : 'warning'}>{metric.status}</LemonTag>+ {metric.is_drifted && <LemonTag type="danger">Drifted</LemonTag>}+ <LemonTag type="option">{humanizeDefinitionKind(metric.definition_kind)}</LemonTag>+ </div>+ )+}++function MetricMetadata({+ metric,+ onSaveUnit,+}: {+ metric: DataCatalogMetricApi+ onSaveUnit: (unit: string) => void+}): JSX.Element {+ const referencedTables = Array.isArray(metric.referenced_table_names)+ ? (metric.referenced_table_names as string[])+ : []+ const showProvenance = metric.created_source === 'ai_generated'++ return (+ <div className="flex flex-col gap-3">+ <StatusRow metric={metric} />+ <div className="grid grid-cols-2 gap-x-8 gap-y-2 text-sm max-w-2xl">+ <MetadataItem label="Owner" value={metric.owner || 'Unassigned'} />+ <MetadataItem label="Approved by" value={metric.approved_by?.email || 'Not approved'} />+ <MetadataItem+ label="Approved at"+ value={metric.approved_at ? <TZLabel time={metric.approved_at} /> : 'Not approved'}+ />+ <MetadataItem+ label="Last run"+ value={metric.last_run_at ? <TZLabel time={metric.last_run_at} /> : 'Never'}+ />+ {referencedTables.length > 0 && (+ <div className="flex flex-col gap-1">+ <span className="text-secondary">Referenced tables</span>+ <div className="flex flex-wrap gap-1">+ {referencedTables.map((table) => (+ <LemonTag key={table} type="option">+ {table}+ </LemonTag>+ ))}+ </div>+ </div>+ )}+ </div>+ {showProvenance && (+ <LemonCollapse+ panels={[+ {+ key: 'provenance',+ header: 'AI provenance',+ content: (+ <div className="flex flex-col gap-1 text-sm">+ {metric.ai_model && <span>Model: {metric.ai_model}</span>}+ {metric.confidence != null && (+ <span>Confidence: {Math.round(metric.confidence * 100)}%</span>+ )}+ {metric.reasoning && <span>{metric.reasoning}</span>}+ </div>+ ),+ },+ ]}+ />+ )}+ <UnitEditor key={metric.unit || ''} unit={metric.unit || ''} onSave={onSaveUnit} />+ </div>+ )+}++function MetadataItem({ label, value }: { label: string; value: ReactNode }): JSX.Element {+ return (+ <div className="flex flex-col">+ <span className="text-secondary">{label}</span>+ <span>{value}</span>+ </div>+ )+}++function UnitEditor({ unit, onSave }: { unit: string; onSave: (unit: string) => void }): JSX.Element {+ const [value, setValue] = useState(unit)+ return (+ <LemonField.Pure label="Unit" info="How the result is measured, like users, dollars, or percent.">+ <div className="flex items-center gap-2 max-w-md">+ <LemonInput value={value} onChange={setValue} placeholder="users" />+ <LemonButton+ type="secondary"+ size="small"+ disabledReason={value === unit ? 'No changes to save' : undefined}+ onClick={() => onSave(value)}+ >+ Save+ </LemonButton>+ </div>+ </LemonField.Pure>+ )+}++function MetricDefinition({+ metric,+ editingDefinition,+ draftMarkdown,+ saving,+ runResult,+ runResultLoading,+ onDraftMarkdown,+ onEdit,+ onSaveMarkdown,+ onRun,+}: {+ metric: DataCatalogMetricApi+ editingDefinition: boolean+ draftMarkdown: string+ saving: boolean+ runResult: DataCatalogMetricRunResult | null+ runResultLoading: boolean+ onDraftMarkdown: (value: string) => void+ onEdit: (editing: boolean) => void+ onSaveMarkdown: (markdown: string) => void+ onRun: () => void+}): JSX.Element {+ const kind = metric.definition_kind+ const sql = definitionField(metric, 'query')++ const runButton = (+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlay />}+ loading={runResultLoading}+ disabledReason={kind ? undefined : 'This metric has no runnable definition yet'}+ onClick={onRun}+ >+ Run metric+ </LemonButton>+ )+ const results = runResult ? <RunResult runResult={runResult} /> : null++ if (kind === 'HogQLQuery') {+ return (+ <Section title="Definition">+ <CodeSnippet language={Language.SQL}>{sql}</CodeSnippet>+ <div className="flex gap-2">+ {runButton}+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconServer />}+ to={urls.sqlEditor({ source: 'metric', metricName: metric.name })}+ >+ Open in SQL editor+ </LemonButton>+ </div>+ {results}+ </Section>+ )+ }++ if (kind === 'MarkdownDefinition') {+ return (+ <Section title="Definition">+ {editingDefinition ? (+ <>+ <LemonTextAreaMarkdown value={draftMarkdown} onChange={onDraftMarkdown} />+ <div className="flex gap-2">+ <LemonButton+ type="primary"+ size="small"+ loading={saving}+ onClick={() => onSaveMarkdown(draftMarkdown)}+ >+ Save+ </LemonButton>+ <LemonButton type="secondary" size="small" onClick={() => onEdit(false)}>+ Cancel+ </LemonButton>+ </div>+ </>+ ) : (+ <>+ <LemonMarkdown disableImages>+ {definitionField(metric, 'markdown') || '_No instructions yet._'}+ </LemonMarkdown>+ <div className="flex gap-2">+ {runButton}+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconPencil />}+ onClick={() => onEdit(true)}+ >+ Edit+ </LemonButton>+ </div>+ {results}+ </>+ )}+ </Section>+ )+ }++ if (!kind) {+ return (+ <Section title="Definition">+ <LemonBanner type="info">+ This metric is a stub with no definition. Add one to make it runnable.+ <div className="flex gap-2 mt-2">+ <LemonButton+ type="secondary"+ size="small"+ to={urls.sqlEditor({ source: 'metric', metricName: metric.name })}+ >+ Write SQL+ </LemonButton>+ <LemonButton+ type="secondary"+ size="small"+ loading={saving}+ onClick={() => onSaveMarkdown('1. Describe how to calculate this metric')}+ >+ Write markdown+ </LemonButton>+ </div>+ </LemonBanner>+ </Section>+ )+ }++ return (+ <Section title="Definition">+ <p className="text-secondary">+ This metric is derived from an insight. Edit the query in the insight, then refresh the metric.+ </p>+ <div className="flex gap-2">+ {runButton}+ {metric.source_insight_short_id && (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconGraph />}+ to={urls.insightView(metric.source_insight_short_id as InsightShortId)}+ >+ View source insight+ </LemonButton>+ )}+ </div>+ {results}+ </Section>+ )+}++interface DataCatalogMetricRunResult {+ results?: unknown+ instructions?: string | null+ compiled_query?: string | null+}++function RunResult({ runResult }: { runResult: DataCatalogMetricRunResult }): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ {runResult.instructions ? (+ <LemonMarkdown disableImages>{runResult.instructions}</LemonMarkdown>+ ) : (+ <ResultsTable results={runResult.results} />+ )}+ {runResult.compiled_query && (+ <LemonCollapse+ panels={[+ {+ key: 'compiled',+ header: 'Compiled query',+ content: <CodeSnippet language={Language.SQL}>{runResult.compiled_query}</CodeSnippet>,+ },+ ]}+ />+ )}+ </div>+ )+}++function ResultsTable({ results }: { results: unknown }): JSX.Element {+ const rows = Array.isArray(results) ? results : []+ if (rows.length === 0) {+ return <p className="text-secondary">No results.</p>+ }+ const first = rows[0]+ if (first && typeof first === 'object' && !Array.isArray(first)) {+ const keys = Object.keys(first as Record<string, unknown>)+ return (+ <LemonTable+ dataSource={rows as Record<string, unknown>[]}+ columns={keys.map((columnKey) => ({+ title: columnKey,+ key: columnKey,+ render: (_: unknown, row: Record<string, unknown>) => formatCell(row[columnKey]),+ }))}+ size="small"+ />+ )+ }+ return <CodeSnippet language={Language.JSON}>{JSON.stringify(results, null, 2)}</CodeSnippet>+}++function formatCell(value: unknown): string {+ if (value == null) {+ return ''+ }+ return typeof value === 'object' ? JSON.stringify(value) : String(value)+}++function Section({ title, children }: { title: string; children: ReactNode }): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">{title}</h3>+ {children}+ </div>+ )+}diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.tsnew file mode 100644index 000000000000..39f11fcd99e3--- /dev/null+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts@@ -0,0 +1,133 @@+import { ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import { dataCatalogMetricSceneLogic } from './dataCatalogMetricSceneLogic'+import {+ dataCatalogMetricsApproveCreate,+ dataCatalogMetricsPartialUpdate,+ dataCatalogMetricsRetrieve,+ dataCatalogMetricsRunCreate,+} from './generated/api'+import type { DataCatalogMetricApi, DataCatalogMetricRunApi } from './generated/api.schemas'++jest.mock('lib/api', () => {+ class ApiError extends Error {+ status?: number+ detail: string | null+ constructor(message?: string, status?: number, _headers?: unknown, data?: { detail?: string }) {+ super(message)+ this.status = status+ this.detail = data?.detail ?? null+ }+ }+ return {+ __esModule: true,+ default: {},+ ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },+ ApiError,+ }+})++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn(), warning: jest.fn() },+}))++jest.mock('./generated/api', () => ({+ dataCatalogMetricsRetrieve: jest.fn(),+ dataCatalogMetricsApproveCreate: jest.fn(),+ dataCatalogMetricsRefreshFromInsightCreate: jest.fn(),+ dataCatalogMetricsPartialUpdate: jest.fn(),+ dataCatalogMetricsDestroy: jest.fn(),+ dataCatalogMetricsRunCreate: jest.fn(),+}))++function buildMetric(overrides: Partial<DataCatalogMetricApi> = {}): DataCatalogMetricApi {+ return {+ id: 'metric-1',+ name: 'weekly_active_users',+ description: 'Weekly active users',+ definition_kind: 'HogQLQuery',+ definition: { kind: 'HogQLQuery', query: 'SELECT 1' },+ status: 'approved',+ is_drifted: false,+ owner: null,+ ...overrides,+ } as DataCatalogMetricApi+}++describe('dataCatalogMetricSceneLogic', () => {+ let logic: ReturnType<typeof dataCatalogMetricSceneLogic.build>++ beforeEach(async () => {+ jest.clearAllMocks()+ ;(dataCatalogMetricsRetrieve as jest.Mock).mockResolvedValue(buildMetric())+ initKeaTests()+ logic = dataCatalogMetricSceneLogic({ name: 'weekly_active_users' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadMetricSuccess'])+ })++ it('saving an approved metric edit reflects the proposed status from the response', async () => {+ ;(dataCatalogMetricsPartialUpdate as jest.Mock).mockResolvedValue(+ buildMetric({ status: 'proposed', definition: { kind: 'HogQLQuery', query: 'SELECT 2' } })+ )++ logic.actions.updateMetric({ definition: { kind: 'HogQLQuery', query: 'SELECT 2' } })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.metric?.status).toEqual('proposed')+ })++ it('surfaces refresh when approve returns 409 and leaves the metric untouched', async () => {+ ;(dataCatalogMetricsApproveCreate as jest.Mock).mockRejectedValue(new ApiError('drifted', 409))++ logic.actions.approveMetric()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.metric?.status).toEqual('approved')+ const errorCall = (lemonToast.error as jest.Mock).mock.calls.at(-1)+ expect(errorCall?.[1]?.button?.label).toEqual('Refresh from insight')+ })++ it('stores the run result envelope', async () => {+ const envelope: Partial<DataCatalogMetricRunApi> = {+ status: 'approved',+ results: [{ value: 5 }],+ instructions: null,+ compiled_query: 'SELECT count()',+ posthog_url: 'https://us.posthog.com/project/1/sql',+ }+ ;(dataCatalogMetricsRunCreate as jest.Mock).mockResolvedValue(envelope)++ logic.actions.loadRunResult()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.runResult?.compiled_query).toEqual('SELECT count()')+ })++ it('issues no requests for a traversal-shaped metric name', async () => {+ // props.name is interpolated unencoded into the request path, so a "../"-shaped route+ // value must never reach retrieve/run/approve/refresh/update/delete.+ jest.clearAllMocks()+ const traversalLogic = dataCatalogMetricSceneLogic({ name: '../../../1/data_catalog/metrics/other' })+ traversalLogic.mount()+ await expectLogic(traversalLogic).toDispatchActions(['loadMetricFailure'])++ traversalLogic.actions.approveMetric()+ traversalLogic.actions.refreshMetricFromInsight()+ traversalLogic.actions.updateMetric({ definition: { kind: 'HogQLQuery', query: 'SELECT 2' } })+ traversalLogic.actions.deleteMetric()+ traversalLogic.actions.loadRunResult()+ await expectLogic(traversalLogic).toFinishAllListeners()++ expect(dataCatalogMetricsRetrieve).not.toHaveBeenCalled()+ expect(dataCatalogMetricsRunCreate).not.toHaveBeenCalled()+ expect(dataCatalogMetricsApproveCreate).not.toHaveBeenCalled()+ expect(dataCatalogMetricsPartialUpdate).not.toHaveBeenCalled()++ traversalLogic.unmount()+ })+})diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsxnew file mode 100644index 000000000000..5f5ad68867c5--- /dev/null+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx@@ -0,0 +1,316 @@+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router, urlToAction } from 'kea-router'++import { ApiConfig, ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { urls } from 'scenes/urls'++import { Breadcrumb } from '~/types'++import { validateMetricName } from './common'+import {+ dataCatalogMetricsApproveCreate,+ dataCatalogMetricsDestroy,+ dataCatalogMetricsPartialUpdate,+ dataCatalogMetricsRefreshFromInsightCreate,+ dataCatalogMetricsRetrieve,+ dataCatalogMetricsRunCreate,+} from './generated/api'+import type {+ DataCatalogMetricApi,+ DataCatalogMetricRunApi,+ PatchedDataCatalogMetricApi,+} from './generated/api.schemas'++export interface DataCatalogMetricSceneLogicProps {+ name: string+}++function projectId(): string {+ return String(ApiConfig.getCurrentTeamId())+}++// props.name comes from the route and is interpolated unencoded into the generated API+// paths. Reject anything the metric-name regex won't accept (it forbids slashes and dots)+// before issuing a request, so a traversal-shaped name can't resolve to another project.+function isInvalidMetricName(name: string): boolean {+ return validateMetricName(name) !== undefined+}++function apiErrorDetail(error: unknown): string | null {+ return error instanceof ApiError ? error.detail : null+}++export function definitionField(metric: DataCatalogMetricApi | null, field: string): string {+ const definition = metric?.definition as Record<string, unknown> | null | undefined+ const value = definition?.[field]+ return typeof value === 'string' ? value : ''+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataCatalogMetricSceneLogicValues {+ breadcrumbs: Breadcrumb[]+ draftMarkdown: string+ draftSql: string+ editingDefinition: boolean+ metric: DataCatalogMetricApi | null+ metricLoading: boolean+ mutating: boolean+ runResult: DataCatalogMetricRunApi | null+ runResultLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataCatalogMetricSceneLogicActions {+ approveMetric: () => {+ value: true+ }+ deleteMetric: () => {+ value: true+ }+ loadMetric: () => any+ loadMetricFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadMetricSuccess: (+ metric: DataCatalogMetricApi,+ payload?: any+ ) => {+ metric: DataCatalogMetricApi+ payload?: any+ }+ loadRunResult: () => any+ loadRunResultFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRunResultSuccess: (+ runResult: DataCatalogMetricRunApi,+ payload?: any+ ) => {+ runResult: DataCatalogMetricRunApi+ payload?: any+ }+ refreshMetricFromInsight: () => {+ value: true+ }+ setDraftMarkdown: (draftMarkdown: string) => {+ draftMarkdown: string+ }+ setDraftSql: (draftSql: string) => {+ draftSql: string+ }+ setEditingDefinition: (editingDefinition: boolean) => {+ editingDefinition: boolean+ }+ setMetric: (metric: DataCatalogMetricApi) => {+ metric: DataCatalogMetricApi+ }+ setMetricFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ setMetricSuccess: (+ metric: DataCatalogMetricApi,+ payload?: {+ metric: DataCatalogMetricApi+ }+ ) => {+ metric: DataCatalogMetricApi+ payload?: {+ metric: DataCatalogMetricApi+ }+ }+ setMutating: (mutating: boolean) => {+ mutating: boolean+ }+ updateMetric: (patch: PatchedDataCatalogMetricApi) => {+ patch: PatchedDataCatalogMetricApi+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataCatalogMetricSceneLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ breadcrumbs: (metric: DataCatalogMetricApi | null, arg: any) => Breadcrumb[]+ }+}++export type dataCatalogMetricSceneLogicType = MakeLogicType<+ dataCatalogMetricSceneLogicValues,+ dataCatalogMetricSceneLogicActions,+ DataCatalogMetricSceneLogicProps,+ dataCatalogMetricSceneLogicMeta+>++export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>([+ props({ name: '' } as DataCatalogMetricSceneLogicProps),+ key((props) => props.name),+ path((key) => ['products', 'data_catalog', 'frontend', 'dataCatalogMetricSceneLogic', key]),+ actions({+ setMetric: (metric: DataCatalogMetricApi) => ({ metric }),+ approveMetric: true,+ refreshMetricFromInsight: true,+ deleteMetric: true,+ updateMetric: (patch: PatchedDataCatalogMetricApi) => ({ patch }),+ setMutating: (mutating: boolean) => ({ mutating }),+ setEditingDefinition: (editingDefinition: boolean) => ({ editingDefinition }),+ setDraftSql: (draftSql: string) => ({ draftSql }),+ setDraftMarkdown: (draftMarkdown: string) => ({ draftMarkdown }),+ }),+ loaders(({ props }) => ({+ metric: [+ null as DataCatalogMetricApi | null,+ {+ loadMetric: async () => {+ if (isInvalidMetricName(props.name)) {+ throw new Error('Invalid metric name')+ }+ return await dataCatalogMetricsRetrieve(projectId(), props.name)+ },+ setMetric: ({ metric }) => metric,+ },+ ],+ runResult: [+ null as DataCatalogMetricRunApi | null,+ {+ loadRunResult: async () => {+ if (isInvalidMetricName(props.name)) {+ throw new Error('Invalid metric name')+ }+ return await dataCatalogMetricsRunCreate(projectId(), props.name, {})+ },+ },+ ],+ })),+ reducers({+ mutating: [+ false,+ {+ setMutating: (_, { mutating }) => mutating,+ },+ ],+ editingDefinition: [+ false,+ {+ setEditingDefinition: (_, { editingDefinition }) => editingDefinition,+ setMetric: () => false,+ },+ ],+ draftSql: [+ '',+ {+ setDraftSql: (_, { draftSql }) => draftSql,+ },+ ],+ draftMarkdown: [+ '',+ {+ setDraftMarkdown: (_, { draftMarkdown }) => draftMarkdown,+ },+ ],+ }),+ selectors({+ breadcrumbs: [+ (s) => [s.metric, (_, props) => props.name],+ (metric: DataCatalogMetricApi | null, name: string): Breadcrumb[] => [+ { key: 'DataCatalog', name: 'Data catalog', path: urls.dataCatalog() },+ { key: name, name: metric?.display_name || name },+ ],+ ],+ }),+ listeners(({ props, values, actions }) => ({+ loadMetricSuccess: ({ metric }) => {+ actions.setDraftSql(definitionField(metric, 'query'))+ actions.setDraftMarkdown(definitionField(metric, 'markdown'))+ },+ setMetric: ({ metric }) => {+ actions.setDraftSql(definitionField(metric, 'query'))+ actions.setDraftMarkdown(definitionField(metric, 'markdown'))+ },+ approveMetric: async () => {+ if (values.mutating || isInvalidMetricName(props.name)) {+ return+ }+ actions.setMutating(true)+ try {+ actions.setMetric(await dataCatalogMetricsApproveCreate(projectId(), props.name))+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ lemonToast.error(+ 'This metric has drifted from its source insight and cannot be approved. Refresh it first.',+ { button: { label: 'Refresh from insight', action: () => actions.refreshMetricFromInsight() } }+ )+ } else {+ lemonToast.error(apiErrorDetail(error) || 'Could not approve the metric. Try again.')+ }+ } finally {+ actions.setMutating(false)+ }+ },+ refreshMetricFromInsight: async () => {+ if (values.mutating || isInvalidMetricName(props.name)) {+ return+ }+ actions.setMutating(true)+ try {+ actions.setMetric(await dataCatalogMetricsRefreshFromInsightCreate(projectId(), props.name))+ lemonToast.success('Metric refreshed from its source insight')+ } catch (error) {+ lemonToast.error(+ apiErrorDetail(error) || 'Could not refresh the metric from its source insight. Try again.'+ )+ } finally {+ actions.setMutating(false)+ }+ },+ updateMetric: async ({ patch }) => {+ if (values.mutating || isInvalidMetricName(props.name)) {+ return+ }+ actions.setMutating(true)+ try {+ actions.setMetric(await dataCatalogMetricsPartialUpdate(projectId(), props.name, patch))+ lemonToast.success('Metric saved')+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) || 'Could not save the metric. Try again.')+ } finally {+ actions.setMutating(false)+ }+ },+ deleteMetric: async () => {+ if (values.mutating || isInvalidMetricName(props.name)) {+ return+ }+ actions.setMutating(true)+ try {+ await dataCatalogMetricsDestroy(projectId(), props.name)+ lemonToast.success('Metric deleted')+ router.actions.push(urls.dataCatalog())+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) || 'Could not delete the metric. Try again.')+ actions.setMutating(false)+ }+ },+ })),+ urlToAction(({ actions }) => ({+ [urls.dataCatalogMetric(':name')]: () => {+ actions.loadMetric()+ },+ })),+ afterMount(({ actions }) => {+ actions.loadMetric()+ }),+])diff --git a/products/data_catalog/frontend/tabs/MetricsTab.tsx b/products/data_catalog/frontend/tabs/MetricsTab.tsxindex d122542da778..6f55554f5130 100644--- a/products/data_catalog/frontend/tabs/MetricsTab.tsx+++ b/products/data_catalog/frontend/tabs/MetricsTab.tsx@@ -13,6 +13,7 @@ import { createdAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'import { LemonTag } from 'lib/lemon-ui/LemonTag'import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { urls } from 'scenes/urls'import { ProductKey } from '~/queries/schema/schema-general'@@ -94,6 +95,7 @@ export function MetricsTab(): JSX.Element {dataIndex: 'name',render: (_, metric) => (<LemonTableLink+ to={urls.dataCatalogMetric(metric.name)}title={metric.display_name || metric.name}// Render descriptions with images disabled so a stored image URL can't beacon other viewers.description={diff --git a/products/data_catalog/manifest.tsx b/products/data_catalog/manifest.tsxindex 2eb54f32efb5..5d419347045f 100644--- a/products/data_catalog/manifest.tsx+++ b/products/data_catalog/manifest.tsx@@ -15,13 +15,20 @@ export const manifest: ProductManifest = {iconType: 'data_warehouse',description: 'Review and manage governed metrics, certifications, and relationships for your data.',},+ DataCatalogMetric: {+ import: () => import('./frontend/DataCatalogMetricScene'),+ projectBased: true,+ name: 'Metric',+ },},routes: {'/data-catalog': ['DataCatalog', 'dataCatalog'],+ '/data-catalog/metrics/:name': ['DataCatalogMetric', 'dataCatalogMetric'],},redirects: {},urls: {dataCatalog: (tab?: string): string => `/data-catalog${tab ? `?tab=${tab}` : ''}`,+ dataCatalogMetric: (name: string): string => `/data-catalog/metrics/${name}`,},fileSystemTypes: {},treeItemsNew: [],