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.

11.2 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { useMemo } from 'react'

import { IconChevronLeft, IconChevronRight } from '@posthog/icons'
import { LemonButton, LemonSegmentedButton, LemonTag, Link, SpinnerOverlay } from '@posthog/lemon-ui'

import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { TZLabel } from 'lib/components/TZLabel'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneDivider } from '~/layout/scenes/components/SceneDivider'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'

import { TRACING_DATE_FORMAT, TRACING_DISPLAY_TIMEZONE, TRACING_TIME_FORMAT } from './dateFormats'
import { formatBucketLabel } from './durationBuckets'
import { OperationHistogram } from './OperationHistogram'
import { errorRate, formatErrorRate } from './OperationsTable'
import { formatDuration, TraceWaterfallView } from './TraceWaterfallView'
import { TRACING_AGENT_HEADLINES, buildTracingOperationAgentContext } from './tracingAgentContext'
import { TracingLatencyHeatmap } from './TracingLatencyHeatmap'
import {
    type OperationChartType,
    tracingOperationSceneLogic,
    type TracingOperationSceneLogicProps,
} from './tracingOperationSceneLogic'

export const scene: SceneExport<TracingOperationSceneLogicProps> = {
    component: TracingOperationScene,
    logic: tracingOperationSceneLogic,
    paramsToProps: ({ searchParams: { service, name } }) => ({
        serviceName: String(service ?? ''),
        spanName: String(name ?? ''),
    }),
    productKey: ProductKey.TRACING,
}

function OperationChartToggle({
    chartType,
    onChange,
}: {
    chartType: OperationChartType
    onChange: (chartType: OperationChartType) => void
}): JSX.Element {
    return (
        <LemonSegmentedButton
            size="xsmall"
            value={chartType}
            onChange={(value) => onChange(value as OperationChartType)}
            options={[
                { value: 'histogram', label: 'Histogram' },
                { value: 'heatmap', label: 'Heatmap' },
            ]}
        />
    )
}

function StatBlock({ label, value }: { label: string; value: string }): JSX.Element {
    return (
        <div className="flex flex-col">
            <span className="text-xs text-muted">{label}</span>
            <span className="font-mono text-sm">{value}</span>
        </div>
    )
}

export function TracingOperationScene(): JSX.Element {
    const {
        serviceName,
        spanName,
        dateRange,
        histogramData,
        rawHistogramLoading,
        durationSelection,
        samples,
        samplesLoading,
        samplesHaveMore,
        sampleIndex,
        currentSample,
        sampleTraceSpans,
        sampleTraceSpansLoading,
        selectedSpanId,
        operationStats,
        chartType,
        latencyHeatmapData,
        rawLatencyHeatmapLoading,
        heatmapEnabled,
    } = useValues(tracingOperationSceneLogic)
    const { setDateRange, setDurationSelection, setSampleIndex, selectSpan, setChartType, applyHeatmapBrush } =
        useActions(tracingOperationSceneLogic)

    const agentContextItems = useMemo(
        () => buildTracingOperationAgentContext(serviceName, spanName, dateRange),
        [serviceName, spanName, dateRange]
    )
    useSceneAgentPanel({
        sceneKey: 'tracing-operation',
        contextItems: agentContextItems,
        headlines: TRACING_AGENT_HEADLINES,
        active: !!spanName && !!serviceName,
    })

    if (!spanName || !serviceName) {
        return (
            <SceneContent>
                <div className="flex flex-col items-center gap-1 py-16">
                    <span>This link is missing an operation or service name.</span>
                    <Link to={urls.tracing()}>Back to tracing</Link>
                </div>
            </SceneContent>
        )
    }

    return (
        <SceneContent>
            <SceneTitleSection
                name={spanName}
                description={serviceName}
                resourceType={{
                    type: 'tracing',
                }}
                forceBackTo={{
                    key: 'tracing',
                    name: 'Tracing',
                    path: urls.tracing(),
                }}
                actions={
                    <DateFilter
                        dateFrom={dateRange.date_from}
                        dateTo={dateRange.date_to}
                        onChange={(date_from, date_to) => setDateRange({ date_from, date_to })}
                    />
                }
            />
            {operationStats && (
                <div className="flex gap-8">
                    <StatBlock label="Requests" value={humanFriendlyNumber(operationStats.count)} />
                    <StatBlock label="Error rate" value={formatErrorRate(errorRate(operationStats))} />
                    <StatBlock label="p50" value={formatDuration(operationStats.p50_duration_nano)} />
                    <StatBlock label="p95" value={formatDuration(operationStats.p95_duration_nano)} />
                    <StatBlock label="p99" value={formatDuration(operationStats.p99_duration_nano)} />
                </div>
            )}
            {heatmapEnabled && chartType === 'heatmap' ? (
                <div className="flex flex-col gap-1">
                    <div className="flex items-center gap-2 min-h-6">
                        <span className="text-xs text-muted">Latency heatmap</span>
                        {durationSelection ? (
                            <>
                                <span className="text-xs font-mono">
                                    {formatBucketLabel(durationSelection.minNs)} –{' '}
                                    {formatBucketLabel(durationSelection.maxNs)}
                                </span>
                                <LemonButton
                                    size="xsmall"
                                    type="tertiary"
                                    onClick={() => setDurationSelection(null)}
                                    disabledReason={samplesLoading ? 'Loading samples…' : undefined}
                                >
                                    Clear
                                </LemonButton>
                            </>
                        ) : (
                            <span className="text-xs text-muted italic">
                                Drag to select a time window and duration range
                            </span>
                        )}
                        <div className="ml-auto">
                            <OperationChartToggle chartType={chartType} onChange={setChartType} />
                        </div>
                    </div>
                    <div className="relative h-32">
                        <TracingLatencyHeatmap
                            data={latencyHeatmapData}
                            loading={rawLatencyHeatmapLoading}
                            displayTimezone={TRACING_DISPLAY_TIMEZONE}
                            onBrush={applyHeatmapBrush}
                        />
                    </div>
                </div>
            ) : (
                <OperationHistogram
                    data={histogramData}
                    loading={rawHistogramLoading}
                    selection={durationSelection}
                    onSelect={setDurationSelection}
                    onClear={() => setDurationSelection(null)}
                    samplesLoading={samplesLoading}
                    actions={
                        heatmapEnabled ? <OperationChartToggle chartType={chartType} onChange={setChartType} /> : null
                    }
                />
            )}
            <SceneDivider />
            {samples.length === 0 && samplesLoading ? (
                <div className="relative min-h-32">
                    <SpinnerOverlay />
                </div>
            ) : samples.length > 0 ? (
                <>
                    <div className="flex items-center gap-2">
                        <LemonButton
                            size="small"
                            type="secondary"
                            icon={<IconChevronLeft />}
                            onClick={() => setSampleIndex(sampleIndex - 1)}
                            disabledReason={
                                samplesLoading ? 'Loading samples…' : sampleIndex <= 0 ? 'First sample' : undefined
                            }
                        />
                        <span className="text-sm whitespace-nowrap">
                            {sampleIndex + 1} of {samples.length}
                            {samplesHaveMore ? '+' : ''}
                        </span>
                        <LemonButton
                            size="small"
                            type="secondary"
                            icon={<IconChevronRight />}
                            onClick={() => setSampleIndex(sampleIndex + 1)}
                            disabledReason={
                                samplesLoading
                                    ? 'Loading samples…'
                                    : sampleIndex >= samples.length - 1
                                      ? 'Last sample'
                                      : undefined
                            }
                        />
                        {currentSample && (
                            <div className="flex items-center gap-2 ml-2 text-sm text-muted">
                                <TZLabel
                                    time={currentSample.timestamp}
                                    formatDate={TRACING_DATE_FORMAT}
                                    formatTime={TRACING_TIME_FORMAT}
                                    displayTimezone={TRACING_DISPLAY_TIMEZONE}
                                    showSeconds
                                />
                                <span className="font-mono">{formatDuration(currentSample.duration_nano)}</span>
                                {currentSample.status_code === 2 && <LemonTag type="danger">Error</LemonTag>}
                            </div>
                        )}
                    </div>
                    <div className="relative min-h-96 flex-1">
                        <TraceWaterfallView
                            spans={sampleTraceSpans}
                            selectedSpanId={selectedSpanId}
                            onSpanSelect={selectSpan}
                        />
                        {sampleTraceSpansLoading && <SpinnerOverlay />}
                    </div>
                </>
            ) : (
                <div className="flex flex-col items-center gap-1 py-8 text-muted">
                    <span>No sampled traces in this range</span>
                    {durationSelection && (
                        <LemonButton size="small" type="secondary" onClick={() => setDurationSelection(null)}>
                            Clear selection
                        </LemonButton>
                    )}
                </div>
            )}
        </SceneContent>
    )
}

export default TracingOperationScene