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.

14.7 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { userHasAccess } from 'lib/utils/accessControlUtils'
import { teamLogic } from 'scenes/teamLogic'

import { AccessControlLevel, AccessControlResourceType, UniversalFiltersGroup } from '~/types'

import { metricsErrorSpikesRetrieve, metricsSamplesCreate } from 'products/metrics/frontend/generated/api'
import type { _MetricErrorSpikeApi } from 'products/metrics/frontend/generated/api.schemas'
import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'

import { buildSampleRequests, type MetricsSampleRow, mergeSamples, settleSampleRequests } from './metricsSamplesMerge'
import {
    type SeriesLabel,
    distinctSeriesLabels,
    formatSeriesNames,
    seriesColor,
    seriesNamePrefixes,
} from './metricsSeries'
import {
    type MetricsViewerClause,
    type MetricsViewerSeries,
    metricsViewerLogic,
    resolveDate,
} from './metricsViewerLogic'

// Unresolved dates, so an auto-refresh tick keeps the same key.
const samplesRequestKey = (
    namedClauses: MetricsViewerClause[],
    dateFrom: string | null,
    dateTo: string | null
): string => JSON.stringify([buildSampleRequests(namedClauses), dateFrom, dateTo])

// The side panel next to the chart: per-series totals, or the raw emissions
// behind the chart with their trace linkage (the metric->trace pivot).
// pinned: "aggregates" is the Series tab key and an analytics event value. Renaming it breaks dashboards.
export type MetricsPanelTab = 'aggregates' | 'samples'

export const SAMPLES_LIMIT = 50

// One row of the Series tab: a series with its headline numbers.
export interface MetricsSeriesRow {
    /** Full name with every label, also the row key. */
    name: string
    /** Clause alias ("a · "), set when the chart plots more than one clause. */
    prefix: string
    /** Labels that differ between series. */
    labels: SeriesLabel[]
    /** Shown when no label differs: the clause alias or the metric name. */
    fallbackName: string
    color: string
    latest: number
    total: number
}

// A traced emission rendered as a clickable exemplar dot on the viewer chart —
// the metric->trace pivot straight from the time series.
export interface MetricsTraceExemplar {
    timestamp: string
    value: number
    traceId: string
    spanId: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSamplesLogicValues {
    dateFrom: string | null // metricsViewerLogic
    dateTo: string | null // metricsViewerLogic
    metricName: string // metricsViewerLogic
    namedClauses: MetricsViewerClause[] // metricsViewerLogic
    queryResults: MetricsViewerSeries[] // metricsViewerLogic
    currentTeamId: number | null // teamLogic
    timezone: string // teamLogic
    activeTab: MetricsPanelTab
    errorSpikes: _MetricErrorSpikeApi[]
    errorSpikesLoading: boolean
    failedSampleClauses: string[]
    samples: MetricsSampleRow[]
    samplesLoading: boolean
    seriesRows: MetricsSeriesRow[]
    showErrorSpikes: boolean
    traceExemplars: MetricsTraceExemplar[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSamplesLogicActions {
    fetchQueryResultsSuccess: (
        queryResults: import('products/metrics/frontend/generated/api.schemas')._MetricSeriesApi[],
        payload?: any
    ) => {
        payload?: any
        queryResults: import('products/metrics/frontend/generated/api.schemas')._MetricSeriesApi[]
    } // metricsViewerLogic
    removeClause: (index: number) => {
        index: number
    } // metricsViewerLogic
    setDateFrom: (dateFrom: string | null) => {
        dateFrom: string | null
    } // metricsViewerLogic
    setDateTo: (dateTo: string | null) => {
        dateTo: string | null
    } // metricsViewerLogic
    setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
        filterGroup: UniversalFiltersGroup
    } // metricsViewerLogic
    setMetricName: (metricName: string) => {
        metricName: string
    } // metricsViewerLogic
    setSelectedMetricType: (
        metricType: null | import('products/metrics/frontend/generated/api.schemas').OtelMetricTypeEnumApi
    ) => {
        metricType: null | import('products/metrics/frontend/generated/api.schemas').OtelMetricTypeEnumApi
    } // metricsViewerLogic
    loadErrorSpikes: (_: any) => any
    loadErrorSpikesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadErrorSpikesSuccess: (
        errorSpikes: _MetricErrorSpikeApi[],
        payload?: any
    ) => {
        errorSpikes: _MetricErrorSpikeApi[]
        payload?: any
    }
    loadSamples: (_: any) => any
    loadSamplesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSamplesSuccess: (
        samples: MetricsSampleRow[],
        payload?: any
    ) => {
        samples: MetricsSampleRow[]
        payload?: any
    }
    setActiveTab: (activeTab: MetricsPanelTab) => {
        activeTab: MetricsPanelTab
    }
    setFailedSampleClauses: (failedSampleClauses: string[]) => {
        failedSampleClauses: string[]
    }
    toggleShowErrorSpikes: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSamplesLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        seriesRows: (
            queryResults: import('products/metrics/frontend/generated/api.schemas')._MetricSeriesApi[],
            metricName: string
        ) => MetricsSeriesRow[]
        traceExemplars: (samples: MetricsSampleRow[]) => MetricsTraceExemplar[]
    }
}

export type metricsSamplesLogicType = MakeLogicType<
    metricsSamplesLogicValues,
    metricsSamplesLogicActions,
    Record<string, any>,
    metricsSamplesLogicMeta
>

export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
    path(['products', 'metrics', 'frontend', 'components', 'metricsSamplesLogic']),
    connect(() => ({
        values: [
            teamLogic,
            ['currentTeamId', 'timezone'],
            metricsViewerLogic,
            ['metricName', 'namedClauses', 'dateFrom', 'dateTo', 'queryResults'],
        ],
        actions: [
            metricsViewerLogic,
            [
                'setMetricName',
                'setDateFrom',
                'setDateTo',
                'setFilterGroup',
                'setSelectedMetricType',
                'removeClause',
                'fetchQueryResultsSuccess',
            ],
        ],
    })),
    actions({
        setActiveTab: (activeTab: MetricsPanelTab) => ({ activeTab }),
        toggleShowErrorSpikes: true,
        setFailedSampleClauses: (failedSampleClauses: string[]) => ({ failedSampleClauses }),
    }),
    reducers({
        activeTab: ['aggregates' as MetricsPanelTab, { setActiveTab: (_, { activeTab }) => activeTab }],
        showErrorSpikes: [false, { toggleShowErrorSpikes: (state) => !state }],
        failedSampleClauses: [
            [] as string[],
            { setFailedSampleClauses: (_, { failedSampleClauses }) => failedSampleClauses },
        ],
    }),
    loaders(({ values, actions, cache }) => ({
        samples: [
            [] as MetricsSampleRow[],
            {
                loadSamples: async (_, breakpoint) => {
                    if (!canViewMetrics()) {
                        return []
                    }
                    const dateFrom = resolveDate(values.dateFrom, values.timezone)
                    if (!values.namedClauses.length || !dateFrom) {
                        cache.loadedSamplesKey = undefined
                        actions.setFailedSampleClauses([])
                        return []
                    }
                    const requestKey = samplesRequestKey(values.namedClauses, values.dateFrom, values.dateTo)
                    cache.runningSamplesKey = requestKey
                    try {
                        await breakpoint(300)
                        const dateTo = resolveDate(values.dateTo, values.timezone) ?? undefined
                        const requests = buildSampleRequests(values.namedClauses)
                        const responses = await Promise.allSettled(
                            requests.map(({ query }) =>
                                metricsSamplesCreate(String(values.currentTeamId), {
                                    query: { ...query, dateFrom, ...(dateTo ? { dateTo } : {}), limit: SAMPLES_LIMIT },
                                })
                            )
                        )
                        breakpoint()
                        const { loaded, failedClauses, failure } = settleSampleRequests(requests, responses)
                        actions.setFailedSampleClauses(failedClauses)
                        if (!loaded.length) {
                            throw failure
                        }
                        cache.loadedSamplesKey = requestKey
                        return mergeSamples(loaded, SAMPLES_LIMIT)
                    } finally {
                        if (cache.runningSamplesKey === requestKey) {
                            cache.runningSamplesKey = undefined
                        }
                    }
                },
            },
        ],
        errorSpikes: [
            [] as _MetricErrorSpikeApi[],
            {
                loadErrorSpikes: async (_, breakpoint) => {
                    // The single gate for the overlay's data: listeners dispatch this
                    // unconditionally, and this guard decides — returning [] also clears
                    // stale spikes when the toggle turns off. Error Tracking view access
                    // is required because the response is that product's data.
                    if (
                        !canViewMetrics() ||
                        !values.showErrorSpikes ||
                        !userHasAccess(AccessControlResourceType.ErrorTracking, AccessControlLevel.Viewer)
                    ) {
                        return []
                    }
                    const dateFrom = resolveDate(values.dateFrom, values.timezone)
                    if (!dateFrom) {
                        return []
                    }
                    await breakpoint(300)
                    const dateTo = resolveDate(values.dateTo, values.timezone) ?? undefined
                    const response = await metricsErrorSpikesRetrieve(String(values.currentTeamId), {
                        dateFrom,
                        ...(dateTo ? { dateTo } : {}),
                    })
                    breakpoint()
                    return response.results
                },
            },
        ],
    })),
    selectors({
        // Rows for the Series tab, derived from the chart's series so both
        // views always describe the same query (colors match the chart legend).
        seriesRows: [
            (s) => [s.queryResults, s.metricName],
            (queryResults: MetricsViewerSeries[], metricName: string): MetricsSeriesRow[] => {
                const names = formatSeriesNames(queryResults, metricName)
                const prefixes = seriesNamePrefixes(queryResults)
                const distinctLabels = distinctSeriesLabels(queryResults)
                return queryResults.map((series, index) => {
                    // Null points are gaps (unrepresentable buckets) — skip them
                    // rather than counting them as zero.
                    const values = series.points.map((point) => point.value).filter((value) => value !== null)
                    return {
                        name: names[index],
                        prefix: prefixes[index],
                        labels: distinctLabels[index],
                        fallbackName: (prefixes[index] && series.clause) || series.metric_name || metricName,
                        color: seriesColor(index),
                        latest: values.length ? values[values.length - 1] : 0,
                        total: values.reduce((sum, value) => sum + value, 0),
                    }
                })
            },
        ],
        // Exemplar dots for the chart: only emissions that carry trace context.
        traceExemplars: [
            (s) => [s.samples],
            (samples: MetricsSampleRow[]): MetricsTraceExemplar[] =>
                samples
                    .filter((sample) => sample.trace_id)
                    .map((sample) => ({
                        timestamp: sample.timestamp,
                        value: sample.value,
                        traceId: sample.trace_id,
                        spanId: sample.span_id,
                    })),
        ],
    }),
    listeners(({ actions, values, cache }) => {
        // One gate for every trigger: a request that is already running, or already
        // loaded while nobody looks at the table, is not started again.
        const loadSamplesUnlessCurrent = (): void => {
            const key = samplesRequestKey(values.namedClauses, values.dateFrom, values.dateTo)
            const loadedAndHidden = values.activeTab !== 'samples' && key === cache.loadedSamplesKey
            if (key !== cache.runningSamplesKey && !loadedAndHidden) {
                actions.loadSamples({})
            }
        }
        // The viewer's filters are the samples' filters: any change that redraws
        // the chart refreshes the visible samples too, but only when they're shown.
        const reloadWhenShown = (): void => {
            if (values.activeTab === 'samples') {
                loadSamplesUnlessCurrent()
            }
        }
        return {
            setActiveTab: ({ activeTab }) => {
                if (activeTab === 'samples') {
                    loadSamplesUnlessCurrent()
                }
            },
            // The chart's trace dots render from these samples, so a chart redraw refreshes them.
            // Error spikes ride the same trigger, so both overlays follow the chart's window.
            fetchQueryResultsSuccess: () => {
                loadSamplesUnlessCurrent()
                actions.loadErrorSpikes({})
            },
            toggleShowErrorSpikes: () => {
                actions.loadErrorSpikes({})
            },
            setMetricName: reloadWhenShown,
            setDateFrom: reloadWhenShown,
            setDateTo: reloadWhenShown,
            setFilterGroup: reloadWhenShown,
            // The viewer pins the type in its own setMetricName listener, so without
            // this a metric switch can load samples pinned to the previous type.
            setSelectedMetricType: reloadWhenShown,
            // Removing a clause without a metric leaves the chart query, and so its refetch, unchanged.
            removeClause: loadSamplesUnlessCurrent,
        }
    }),
])