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.

3.8 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, key, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import { teamLogic } from 'scenes/teamLogic'

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

const TRACE_SAMPLES_LIMIT = 100

export interface TraceMetricSamplesLogicProps {
    /** Hex trace id, as the tracing product uses. */
    traceId: string
    /** Narrow to emissions recorded on this span (hex span id), filtered server-side. */
    spanId?: string | null
    /** ISO lower bound for the sample window — the caller derives it from the trace's timestamp. */
    dateFrom: string
    /** ISO upper bound for the sample window. */
    dateTo: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceMetricSamplesLogicValues {
    currentTeamId: number | null // teamLogic
    samples: _MetricEventSampleApi[]
    samplesError: boolean
    samplesLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceMetricSamplesLogicActions {
    loadSamples: () => any
    loadSamplesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSamplesSuccess: (
        samples: _MetricEventSampleApi[],
        payload?: any
    ) => {
        samples: _MetricEventSampleApi[]
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceMetricSamplesLogicMeta {
    key: string
}

export type traceMetricSamplesLogicType = MakeLogicType<
    traceMetricSamplesLogicValues,
    traceMetricSamplesLogicActions,
    TraceMetricSamplesLogicProps,
    traceMetricSamplesLogicMeta
>

// Metric emissions whose exemplar carries the given trace id — the trace->metrics pivot
// behind the tracing drawer's Metrics tab. Queried without a metric name, so it spans
// every metric the trace touched.
export const traceMetricSamplesLogic = kea<traceMetricSamplesLogicType>([
    path(['products', 'metrics', 'frontend', 'components', 'traceMetricSamplesLogic']),
    props({} as TraceMetricSamplesLogicProps),
    // Keyed by every query input: kea updates a mounted logic's props in place without
    // re-firing afterMount, so a scope or window change must mint a fresh instance to
    // refetch rather than silently serving the previous query's samples.
    key((props) => `${props.traceId}|${props.spanId ?? ''}|${props.dateFrom}|${props.dateTo}`),
    connect({ values: [teamLogic, ['currentTeamId']] }),
    loaders(({ values, props }) => ({
        samples: [
            [] as _MetricEventSampleApi[],
            {
                loadSamples: async (): Promise<_MetricEventSampleApi[]> => {
                    if (!canViewMetrics()) {
                        return []
                    }
                    const response = await metricsSamplesCreate(String(values.currentTeamId), {
                        query: {
                            traceId: props.traceId,
                            ...(props.spanId ? { spanId: props.spanId } : {}),
                            dateFrom: props.dateFrom,
                            dateTo: props.dateTo,
                            limit: TRACE_SAMPLES_LIMIT,
                        },
                    })
                    return response.results
                },
            },
        ],
    })),
    reducers({
        samplesError: [
            false,
            {
                loadSamples: () => false,
                loadSamplesFailure: () => true,
            },
        ],
    }),
    afterMount(({ actions }) => {
        actions.loadSamples()
    }),
])