Skip to content

: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.

18.8 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path } from 'kea'
import posthog from 'posthog-js'

import { isUserInitiatedError } from 'lib/utils/kea-logic-builders'
import { teamLogic } from 'scenes/teamLogic'

import {
    type MetricsDisplayType,
    type MetricsQuery,
    type MetricsReducer,
    ProductIntentContext,
    ProductKey,
} from '~/queries/schema/schema-general'

import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'

import type { ProductIntentProperties } from '../../../../frontend/src/lib/utils/product-intents'
import type { Node } from '../../../../frontend/src/queries/schema/schema-general'
import type { DashboardType, InsightModel, UniversalFiltersGroup } from '../../../../frontend/src/types'
import { metricsDashboardImportLogic } from '../dashboardImport/metricsDashboardImportLogic'
import type { DashboardImportStep } from '../dashboardImport/metricsDashboardImportLogic'
import type { DashboardImportSourceEnumApi, _MetricFilterApi, _MetricSeriesApi } from '../generated/api.schemas'
import { metricsSceneLogic } from '../metricsSceneLogic'
import type { MetricsSceneActiveTab } from '../metricsSceneLogic'
import { metricsSamplesLogic } from './metricsSamplesLogic'
import type { MetricsPanelTab } from './metricsSamplesLogic'
import { metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'
import { metricsViewerLogic, viewerAggregationFromNode } from './metricsViewerLogic'
import type {
    MetricAggregation,
    MetricRangeFunction,
    MetricsQueryRequestBody,
    MetricsViewerClause,
} from './metricsViewerLogic'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsUsageTrackingLogicValues {
    dashboardImportSource: DashboardImportSourceEnumApi // metricsDashboardImportLogic
    dashboardImportStep: DashboardImportStep // metricsDashboardImportLogic
    isRestoringFromUrl: boolean // metricsSceneLogic
    aggregation: MetricAggregation | null // metricsViewerLogic
    dateFrom: string | null // metricsViewerLogic
    displayType: MetricsDisplayType // metricsViewerLogic
    formula: string // metricsViewerLogic
    groupByKeys: string[] // metricsViewerLogic
    hasMetricName: boolean // metricsViewerLogic
    queryFilters: _MetricFilterApi[] // metricsViewerLogic
    queryPayload: MetricsQueryRequestBody | null // metricsViewerLogic
    rangeFunction: MetricRangeFunction | null // metricsViewerLogic
    viewerClauses: MetricsViewerClause[] // metricsViewerLogic
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsUsageTrackingLogicActions {
    dashboardImportOpened: (source: DashboardImportSourceEnumApi) => {
        source: DashboardImportSourceEnumApi
    } // metricsDashboardImportLogic
    dashboardImportStartFailed: (
        error: string,
        status: number | null
    ) => {
        error: string
        status: number | null
    } // metricsDashboardImportLogic
    dashboardImportViewed: (
        dashboardImport: import('products/metrics/frontend/generated/api.schemas').DashboardImportApi
    ) => {
        dashboardImport: import('products/metrics/frontend/generated/api.schemas').DashboardImportApi
    } // metricsDashboardImportLogic
    importedDashboardOpened: (dashboardId: number) => {
        dashboardId: number
    } // metricsDashboardImportLogic
    loadSamplesSuccess: (
        samples: import('./metricsSamplesMerge').MetricsSampleRow[],
        payload?: any
    ) => {
        payload?: any
        samples: import('./metricsSamplesMerge').MetricsSampleRow[]
    } // metricsSamplesLogic
    samplesPanelTabChanged: (activeTab: MetricsPanelTab) => {
        activeTab: MetricsPanelTab
    } // metricsSamplesLogic
    sceneTabChanged: (activeTab: MetricsSceneActiveTab) => {
        activeTab: MetricsSceneActiveTab
    } // metricsSceneLogic
    starterDashboardCreated: (
        createdDashboard: DashboardType,
        warning?: string | undefined
    ) => {
        createdDashboard: DashboardType
        warning: string | undefined
    } // metricsStarterDashboardLogic
    starterDashboardOpened: () => {
        value: true
    } // metricsStarterDashboardLogic
    addClause: () => {
        value: true
    } // metricsViewerLogic
    addToDashboard: () => {
        value: true
    } // metricsViewerLogic
    fetchQueryResults: (_: any) => any // metricsViewerLogic
    fetchQueryResultsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // metricsViewerLogic
    fetchQueryResultsSuccess: (
        queryResults: _MetricSeriesApi[],
        payload?: any
    ) => {
        payload?: any
        queryResults: _MetricSeriesApi[]
    } // metricsViewerLogic
    saveAsInsightSuccess: (
        savedInsight: InsightModel<Node<Record<string, any>>> | null,
        payload?: any
    ) => {
        payload?: any
        savedInsight: InsightModel<Node<Record<string, any>>> | null
    } // metricsViewerLogic
    setAggregation: (aggregation: MetricAggregation | null) => {
        aggregation: MetricAggregation | null
    } // metricsViewerLogic
    setDateFrom: (dateFrom: string | null) => {
        dateFrom: string | null
    } // metricsViewerLogic
    setDisplayType: (displayType: MetricsDisplayType) => {
        displayType: MetricsDisplayType
    } // metricsViewerLogic
    setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
        filterGroup: UniversalFiltersGroup
    } // metricsViewerLogic
    setFormula: (formula: string) => {
        formula: string
    } // metricsViewerLogic
    setGroupByKeys: (groupByKeys: string[]) => {
        groupByKeys: string[]
    } // metricsViewerLogic
    setLiveRefresh: (liveRefresh: boolean) => {
        liveRefresh: boolean
    } // metricsViewerLogic
    setMetricName: (metricName: string) => {
        metricName: string
    } // metricsViewerLogic
    setRangeFunction: (rangeFunction: MetricRangeFunction | null) => {
        rangeFunction: MetricRangeFunction | null
    } // metricsViewerLogic
    setReduce: (reduce: MetricsReducer) => {
        reduce: MetricsReducer
    } // metricsViewerLogic
    addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
    exemplarDotClicked: (hasSpanId: boolean) => {
        hasSpanId: boolean
    }
    sampleRowExpanded: (sample: _MetricEventSampleApi) => {
        sample: _MetricEventSampleApi
    }
    seriesRowExpanded: () => {
        value: true
    }
    tracePivotClicked: (sample: _MetricEventSampleApi) => {
        sample: _MetricEventSampleApi
    }
}

export type metricsUsageTrackingLogicType = MakeLogicType<
    metricsUsageTrackingLogicValues,
    metricsUsageTrackingLogicActions
>

// Central usage tracking for the metrics scene, following the metricsSqlEditorTrackingLogic
// precedent: captures fire from listeners on the source logics' actions, not from onClick
// handlers scattered through components.
//
// Privacy rule: never capture customer metric names, series labels, attribute keys, or
// attribute values — only counts, booleans, durations, and our own enum values.
export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
    path(['products', 'metrics', 'frontend', 'components', 'metricsUsageTrackingLogic']),
    connect(() => ({
        actions: [
            metricsSceneLogic,
            ['setActiveTab as sceneTabChanged'],
            metricsViewerLogic,
            [
                'setMetricName',
                'setAggregation',
                'setRangeFunction',
                'setDateFrom',
                'setLiveRefresh',
                'setGroupByKeys',
                'setFilterGroup',
                'addClause',
                'setFormula',
                'setDisplayType',
                'setReduce',
                'addToDashboard',
                'saveAsInsightSuccess',
                'fetchQueryResults',
                'fetchQueryResultsSuccess',
                'fetchQueryResultsFailure',
            ],
            metricsSamplesLogic,
            ['setActiveTab as samplesPanelTabChanged', 'loadSamplesSuccess'],
            metricsDashboardImportLogic,
            [
                'openImportModal as dashboardImportOpened',
                'startImportFailure as dashboardImportStartFailed',
                'openImportedDashboard as importedDashboardOpened',
                'openImport as dashboardImportViewed',
            ],
            metricsStarterDashboardLogic,
            ['openModal as starterDashboardOpened', 'createDashboardSuccess as starterDashboardCreated'],
            teamLogic,
            ['addProductIntent'],
        ],
        values: [
            metricsDashboardImportLogic,
            ['source as dashboardImportSource', 'step as dashboardImportStep'],
            metricsViewerLogic,
            [
                'hasMetricName',
                'aggregation',
                'dateFrom',
                'rangeFunction',
                'groupByKeys',
                'queryFilters',
                'viewerClauses',
                'formula',
                'queryPayload',
                'displayType',
            ],
            metricsSceneLogic,
            ['isRestoringFromUrl'],
        ],
    })),
    actions({
        // Component-only interactions with no source-logic action to listen to.
        seriesRowExpanded: true,
        sampleRowExpanded: (sample: _MetricEventSampleApi) => ({ sample }),
        tracePivotClicked: (sample: _MetricEventSampleApi) => ({ sample }),
        exemplarDotClicked: (hasSpanId: boolean) => ({ hasSpanId }),
    }),
    listeners(({ actions, values, cache }) => ({
        sceneTabChanged: ({ activeTab }) => {
            posthog.capture('metrics tab changed', { tab: activeTab })
        },
        // The viewer setters also fire while the scene restores state from URL params —
        // a restore is not a user interaction, so those dispatches are not captured.
        setMetricName: ({ metricName }) => {
            if (metricName.trim() && !values.isRestoringFromUrl) {
                posthog.capture('metrics viewer metric selected')
            }
        },
        setAggregation: ({ aggregation }) => {
            if (!values.isRestoringFromUrl) {
                posthog.capture('metrics viewer aggregation changed', { aggregation })
            }
        },
        setRangeFunction: ({ rangeFunction }) => {
            if (!values.isRestoringFromUrl) {
                posthog.capture('metrics viewer range function changed', { range_function: rangeFunction })
            }
        },
        // The DateFilter dispatches setDateFrom and setDateTo together on every change,
        // so listening to setDateFrom alone captures each range change exactly once.
        setDateFrom: ({ dateFrom }) => {
            if (!values.isRestoringFromUrl) {
                posthog.capture('metrics viewer date range changed', { date_from: dateFrom })
            }
        },
        setLiveRefresh: ({ liveRefresh }) => {
            posthog.capture('metrics viewer live toggled', { enabled: liveRefresh })
        },
        setGroupByKeys: ({ groupByKeys }) => {
            if (!values.isRestoringFromUrl) {
                posthog.capture('metrics viewer group by changed', { group_by_count: groupByKeys.length })
            }
        },
        setFilterGroup: () => {
            if (values.isRestoringFromUrl) {
                return
            }
            // queryFilters counts only complete, backend-valid chips (reducers ran before us).
            posthog.capture('metrics viewer attribute filter changed', { filter_count: values.queryFilters.length })
        },
        addClause: () => {
            posthog.capture('metrics viewer series added', { clause_count: values.viewerClauses.length })
        },
        // Only shape signals — the formula references clause letters, but stay consistent
        // with the "no customer content" rule and capture booleans/counts only.
        setFormula: ({ formula }) => {
            if (!values.isRestoringFromUrl) {
                posthog.capture('metrics viewer formula changed', {
                    has_formula: formula.trim().length > 0,
                    formula_length: formula.trim().length,
                })
            }
        },
        setDisplayType: ({ displayType }) => {
            if (!values.isRestoringFromUrl) {
                posthog.capture('metrics viewer display type changed', { display_type: displayType })
            }
        },
        setReduce: ({ reduce }) => {
            posthog.capture('metrics viewer value reducer changed', {
                reduce,
                display_type: values.displayType,
            })
        },
        addToDashboard: () => {
            posthog.capture('metrics add to dashboard clicked', {
                aggregation: values.aggregation,
                range_function: values.rangeFunction,
                clause_count: values.viewerClauses.length,
                has_formula: !!values.formula,
            })
        },
        saveAsInsightSuccess: ({ savedInsight }) => {
            if (!savedInsight) {
                return
            }
            // Read the aggregation off the insight itself — the viewer's current
            // value can already differ if it changed while the save was in flight.
            const savedQuery = savedInsight.query as MetricsQuery | undefined
            posthog.capture('metrics insight saved', {
                aggregation: viewerAggregationFromNode(
                    savedQuery?.clauses?.[0]?.aggregation,
                    savedQuery?.clauses?.[0]?.quantile
                ),
                range_function: savedQuery?.clauses?.[0]?.rangeFunction ?? null,
                clause_count: savedQuery?.clauses?.length ?? null,
                has_formula: !!savedQuery?.formula,
            })
        },
        fetchQueryResults: () => {
            cache.queryStartedAt = performance.now()
        },
        fetchQueryResultsSuccess: ({ queryResults }) => {
            // The loader resolves [] without querying when no metric is picked yet — not a query.
            if (!values.hasMetricName) {
                return
            }
            // load_ms includes the loader's 300ms debounce breakpoint — consistent overhead,
            // fine for trend comparisons.
            const loadMs =
                cache.queryStartedAt !== undefined ? Math.round(performance.now() - cache.queryStartedAt) : null
            posthog.capture('metrics query completed', {
                series_count: queryResults.length,
                point_count: queryResults.reduce((sum: number, series) => sum + series.points.length, 0),
                load_ms: loadMs,
                aggregation: values.aggregation,
                range_function: values.rangeFunction,
                has_group_by: values.groupByKeys.length > 0,
                has_filters: values.queryFilters.length > 0,
                // The range and the clause shape let this event compare with `query completed` for MetricsQuery.
                date_from: values.dateFrom,
                // From the request body, which leaves out a series row with no metric.
                clause_count: values.queryPayload?.clauses?.length ?? 0,
                has_formula: !!values.queryPayload?.formula,
            })
            // Once per mount, not per query — live refresh re-runs the query every 15s,
            // and each intent call is an API request (the backend counts repeats itself).
            if (!cache.viewerQueryIntentFired) {
                cache.viewerQueryIntentFired = true
                posthog.setPersonProperties(undefined, { first_used_metrics_at: new Date().toISOString() })
                actions.addProductIntent({
                    product_type: ProductKey.METRICS,
                    intent_context: ProductIntentContext.METRICS_VIEWER_QUERY_RUN,
                })
            }
        },
        fetchQueryResultsFailure: ({ error, errorObject }) => {
            // A superseded/unmounted query aborts — user-initiated, not a failure.
            if (isUserInitiatedError(error) || isUserInitiatedError(errorObject)) {
                return
            }
            // Only a coarse class — the message can embed the customer's metric name.
            const status = (errorObject as { status?: number } | undefined)?.status
            posthog.capture('metrics query failed', { error_type: status ? `http_${status}` : 'unknown' })
        },
        samplesPanelTabChanged: ({ activeTab }) => {
            posthog.capture('metrics samples panel tab changed', { tab: activeTab })
        },
        loadSamplesSuccess: ({ samples }) => {
            if (!values.hasMetricName) {
                return
            }
            const withTrace = samples.filter((sample) => !!sample.trace_id).length
            posthog.capture('metrics samples loaded', {
                sample_count: samples.length,
                trace_coverage: samples.length ? Math.round((100 * withTrace) / samples.length) : 0,
            })
        },
        seriesRowExpanded: () => {
            posthog.capture('metrics series row expanded')
        },
        sampleRowExpanded: ({ sample }) => {
            posthog.capture('metrics sample row expanded', {
                attribute_count: Object.keys(sample.attributes).length + Object.keys(sample.resource_attributes).length,
                has_trace: !!sample.trace_id,
            })
        },
        tracePivotClicked: ({ sample }) => {
            posthog.capture('metrics trace pivot clicked', { has_span_id: !!sample.span_id })
        },
        exemplarDotClicked: ({ hasSpanId }) => {
            posthog.capture('metrics exemplar dot clicked', { has_span_id: hasSpanId })
        },
        // The step tells a new import from a reopened one that runs or ended.
        dashboardImportOpened: ({ source }) => {
            posthog.capture('metrics dashboard import opened', { source, step: values.dashboardImportStep })
        },
        // The server captures the imports that start and end. Only a refused start shows here.
        dashboardImportStartFailed: ({ status }) => {
            posthog.capture('metrics dashboard import start failed', {
                source: values.dashboardImportSource,
                status_code: status,
            })
        },
        importedDashboardOpened: () => {
            posthog.capture('metrics dashboard import dashboard opened')
        },
        // A running or ended import opened from the Import menu or from a message.
        dashboardImportViewed: ({ dashboardImport }) => {
            posthog.capture('metrics dashboard import viewed', { status: dashboardImport.status })
        },
        starterDashboardOpened: () => {
            posthog.capture('metrics starter dashboard opened')
        },
        starterDashboardCreated: ({ warning }) => {
            posthog.capture('metrics starter dashboard created', { partial: !!warning })
        },
    })),
])