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.

10.5 KB
Raw Blame
import { useMemo } from 'react'

import { LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'

import { humanFriendlyNumber } from 'lib/utils/numbers'

import { AggregatedSpanRow, SpanHealthStatus } from '~/queries/schema/schema-general'

import { formatIdentityCoverage } from './identityCoverage'
import { formatDuration } from './TraceWaterfallView'
import { VirtualizedTable, VirtualizedTableColumn } from './VirtualizedTable'

// Span count over the aggregation window, rendered as a request rate. Empty window → no rate.
function formatRate(count: number, windowMs: number): string {
    const seconds = windowMs / 1000
    if (!seconds) {
        return '—'
    }
    const perSec = count / seconds
    if (perSec >= 1) {
        return `${humanFriendlyNumber(perSec, perSec >= 10 ? 0 : 1)}/s`
    }
    const perMin = perSec * 60
    if (perMin >= 1) {
        return `${humanFriendlyNumber(perMin, 1)}/min`
    }
    return `${humanFriendlyNumber(perSec * 3600, 1)}/hr`
}

export function errorRate(row: AggregatedSpanRow): number {
    return row.count > 0 ? row.error_count / row.count : 0
}

// Sub-1% rates get an extra decimal so small-but-nonzero rates don't render as 0.0%.
export function formatErrorRate(rate: number): string {
    return `${(rate * 100).toFixed(rate > 0 && rate < 0.01 ? 2 : 1)}%`
}

const durationCell =
    (pick: (row: AggregatedSpanRow) => number) =>
    (row: AggregatedSpanRow): JSX.Element => <span className="font-mono">{formatDuration(pick(row))}</span>

const impactCell =
    (pick: (row: AggregatedSpanRow) => number | undefined, covered: (row: AggregatedSpanRow) => number | undefined) =>
    (row: AggregatedSpanRow): JSX.Element => {
        const value = pick(row)
        if (value == null) {
            return <span className="text-muted">—</span>
        }
        // An operation whose spans mostly carry no ID has a count covering a fraction of its
        // traffic, so the cell says which fraction. A `title` rather than a Tooltip: this renders
        // per row of a virtualized table, and the text is a plain sentence.
        const coverage = formatIdentityCoverage(covered(row), row.count)
        return (
            <span title={`Estimated from ${coverage} of this operation's spans, the ones carrying the ID.`}>
                {humanFriendlyNumber(value)}
            </span>
        )
    }

// Listed worst first, so the Health column sorts unhealthy rows to the top.
const HEALTH_META: Record<SpanHealthStatus, { label: string; tagType: LemonTagType }> = {
    silent: { label: 'Silent', tagType: 'danger' },
    regressed: { label: 'Regressed', tagType: 'danger' },
    degraded: { label: 'Degraded', tagType: 'warning' },
    new: { label: 'New', tagType: 'highlight' },
    recovered: { label: 'Recovered', tagType: 'success' },
    improved: { label: 'Improved', tagType: 'success' },
    ok: { label: 'OK', tagType: 'muted' },
}
const HEALTH_ORDER = Object.keys(HEALTH_META) as SpanHealthStatus[]

function healthRank(row: AggregatedSpanRow): number {
    return row.health_status ? HEALTH_ORDER.indexOf(row.health_status) : HEALTH_ORDER.length
}

function buildColumns(
    windowMs: number,
    showImpact: boolean,
    groupedByEndpoint: boolean
): VirtualizedTableColumn<AggregatedSpanRow>[] {
    const impactColumns: VirtualizedTableColumn<AggregatedSpanRow>[] = showImpact
        ? [
              {
                  key: 'sessions',
                  title: 'Sessions',
                  width: 90,
                  align: 'right',
                  tooltip: 'Estimated unique sessions behind this operation, over the spans carrying a session ID.',
                  sorter: (a, b) => (a.sessions ?? 0) - (b.sessions ?? 0),
                  render: impactCell(
                      (row) => row.sessions,
                      (row) => row.spans_with_session_id
                  ),
              },
              {
                  key: 'users',
                  title: 'Users',
                  width: 90,
                  align: 'right',
                  tooltip: 'Estimated unique people behind this operation, over the spans carrying a distinct ID.',
                  sorter: (a, b) => (a.users ?? 0) - (b.users ?? 0),
                  render: impactCell(
                      (row) => row.users,
                      (row) => row.spans_with_distinct_id
                  ),
              },
          ]
        : []

    const healthColumns: VirtualizedTableColumn<AggregatedSpanRow>[] = groupedByEndpoint
        ? [
              {
                  key: 'health',
                  title: 'Health',
                  width: 110,
                  tooltip: 'Compared with the previous period of the same length.',
                  sorter: (a, b) => healthRank(b) - healthRank(a),
                  render: (row) => {
                      if (!row.health_status) {
                          return null
                      }
                      const { label, tagType } = HEALTH_META[row.health_status]
                      return (
                          <Tooltip title={row.health_reason || undefined}>
                              <LemonTag type={tagType} size="small">
                                  {label}
                              </LemonTag>
                          </Tooltip>
                      )
                  },
              },
          ]
        : []

    return [
        ...healthColumns,
        {
            key: 'service_name',
            title: 'Service',
            width: 200,
            sorter: (a, b) => a.service_name.localeCompare(b.service_name),
            render: (row) => <span className="font-mono">{row.service_name}</span>,
        },
        {
            key: 'name',
            title: groupedByEndpoint ? 'Endpoint' : 'Operation',
            width: 320,
            grow: true,
            sorter: (a, b) => a.name.localeCompare(b.name),
            render: (row) => <span className="font-mono">{row.name}</span>,
        },
        {
            key: 'requests',
            title: 'Requests',
            width: 120,
            align: 'right',
            sorter: (a, b) => a.count - b.count,
            render: (row) => (
                <div className="flex flex-col items-end">
                    <span>{formatRate(row.count, windowMs)}</span>
                    <span className="text-xs text-muted">{humanFriendlyNumber(row.count)}</span>
                </div>
            ),
        },
        {
            key: 'error_rate',
            title: 'Error rate',
            width: 90,
            align: 'right',
            sorter: (a, b) => errorRate(a) - errorRate(b),
            render: (row) => {
                const rate = errorRate(row)
                return <span className={rate > 0 ? 'text-danger' : 'text-muted'}>{formatErrorRate(rate)}</span>
            },
        },
        {
            key: 'errors',
            title: 'Errors',
            width: 80,
            align: 'right',
            sorter: (a, b) => a.error_count - b.error_count,
            render: (row) => (
                <span className={row.error_count > 0 ? 'text-danger' : 'text-muted'}>
                    {humanFriendlyNumber(row.error_count)}
                </span>
            ),
        },
        ...impactColumns,
        {
            key: 'p50',
            title: 'p50',
            width: 80,
            align: 'right',
            sorter: (a, b) => a.p50_duration_nano - b.p50_duration_nano,
            render: durationCell((row) => row.p50_duration_nano),
        },
        {
            key: 'p95',
            title: 'p95',
            width: 80,
            align: 'right',
            sorter: (a, b) => a.p95_duration_nano - b.p95_duration_nano,
            render: durationCell((row) => row.p95_duration_nano),
        },
        {
            key: 'p99',
            title: 'p99',
            width: 80,
            align: 'right',
            sorter: (a, b) => a.p99_duration_nano - b.p99_duration_nano,
            render: durationCell((row) => row.p99_duration_nano),
        },
        {
            key: 'p999',
            title: 'p99.9',
            width: 80,
            align: 'right',
            sorter: (a, b) => a.p999_duration_nano - b.p999_duration_nano,
            render: durationCell((row) => row.p999_duration_nano),
        },
        {
            key: 'total_time',
            title: 'Total time',
            width: 100,
            align: 'right',
            // Per the JON-89 spike: wall-time, not self-time — nesting is double-counted; labelled as such.
            tooltip: 'Sum of span wall-clock durations; nested spans are counted in both parent and child.',
            sorter: (a, b) => a.total_duration_nano - b.total_duration_nano,
            render: durationCell((row) => row.total_duration_nano),
        },
    ]
}

function operationRowKey(row: AggregatedSpanRow): string {
    return `${row.service_name}::${row.name}`
}

export interface OperationsTableProps {
    rows: AggregatedSpanRow[]
    loading: boolean
    /** Resolved aggregation window (ms) — turns span counts into a request rate. */
    windowMs: number
    /** Show the Sessions and Users columns. Must match the `includeImpact` the rows were fetched with. */
    showImpact?: boolean
    /** Rows are `METHOD route` endpoints. Must match the `groupByEndpoint` the rows were fetched with. */
    groupedByEndpoint?: boolean
    onRowClick?: (row: AggregatedSpanRow) => void
}

export function OperationsTable({
    rows,
    loading,
    windowMs,
    showImpact = false,
    groupedByEndpoint = false,
    onRowClick,
}: OperationsTableProps): JSX.Element {
    const columns = useMemo(
        () => buildColumns(windowMs, showImpact, groupedByEndpoint),
        [windowMs, showImpact, groupedByEndpoint]
    )
    return (
        <VirtualizedTable<AggregatedSpanRow>
            // Remounts on a mode switch, so each mode starts from its own default sort.
            key={groupedByEndpoint ? 'endpoints' : 'operations'}
            // pinned: identifies stored column widths — renaming resets everyone's widths
            tableKey="operations"
            columns={columns}
            dataSource={rows}
            loading={loading}
            rowKey={operationRowKey}
            onRowClick={onRowClick}
            defaultSort={{ columnKey: groupedByEndpoint ? 'health' : 'total_time', order: -1 }}
            emptyLabel={
                groupedByEndpoint
                    ? 'No HTTP server spans found for these filters'
                    : 'No operations found for these filters'
            }
            data-attr="tracing-operations-table"
        />
    )
}