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.

17.3 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'

import api from 'lib/api'
import {
    type TraceDialogCloseReason,
    type TraceDialogEntryPoint,
    type TraceDialogSource,
    traceDialogOpenLogic,
} from 'lib/components/ViewTraceButton/traceDialogOpenLogic'
import type { TraceLinkParams } from 'lib/components/ViewTraceButton/traceUrl'
import { dayjs } from 'lib/dayjs'

import { parseTimestampUs } from 'products/tracing/frontend/spanTree'
import {
    EMPTY_TRACE_IDENTITY,
    resolveTraceIdentity,
    resolveTraceSessionId,
    type TraceIdentity,
} from 'products/tracing/frontend/traceIdentity'
import { resolveTraceLookupRange } from 'products/tracing/frontend/traceLinks'
import { tracingConfigLogic } from 'products/tracing/frontend/tracingConfigLogic'
import { tracingCorrelationConfigLogic } from 'products/tracing/frontend/tracingCorrelationConfigLogic'
import type { Span, SpanInspectorTab, TraceViewMode } from 'products/tracing/frontend/types'

import { traceViewLogic } from '../TraceView/traceViewLogic'

// The trace endpoint pages at 2,000 spans, so this caps the dialog at 10,000. Bigger traces open in
// Tracing, which pages in on scroll.
const TRACE_DIALOG_MAX_PAGES = 5

// Pinned: autocapture and the span keys both match on the dialog's data-attr.
export const TRACE_DIALOG_DATA_ATTR = 'trace-dialog'
const TRACE_DIALOG_SELECTOR = `[data-attr="${TRACE_DIALOG_DATA_ATTR}"]`

export const TRACE_DIALOG_VIEW_ID = 'trace-dialog'

export interface TraceDialogSpans {
    spans: Span[]
    truncated: boolean
}

interface TraceDialogSession {
    entryPoint: TraceDialogEntryPoint
    openedAtMs: number
    loadStartedAtMs: number
    spansSelected: number
    keyboardSteps: number
    collapseToggles: number
    tabsViewed: Set<SpanInspectorTab>
}

function captureClosed(session: TraceDialogSession, reason: TraceDialogCloseReason): void {
    posthog.capture('tracing trace dialog closed', {
        entry_point: session.entryPoint,
        reason,
        seconds_open: Math.round((Date.now() - session.openedAtMs) / 1000),
        spans_selected: session.spansSelected,
        keyboard_steps: session.keyboardSteps,
        collapse_toggles: session.collapseToggles,
        tabs_viewed: [...session.tabsViewed],
    })
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceDialogLogicValues {
    entryPoint: TraceDialogEntryPoint | null // traceDialogOpenLogic
    isOpen: boolean // traceDialogOpenLogic
    openedFrom: TraceDialogSource | null // traceDialogOpenLogic
    trace: TraceLinkParams | null // traceDialogOpenLogic
    traceViewMode: TraceViewMode // tracingConfigLogic
    configuredDistinctIdKeys: string[] | undefined // tracingCorrelationConfigLogic
    configuredSessionIdKeys: string[] | undefined // tracingCorrelationConfigLogic
    correlationLinksEnabled: boolean // tracingCorrelationConfigLogic
    sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
    inspectorOpen: boolean
    isFullscreen: boolean
    openedAtUs: number | null
    traceIdentity: TraceIdentity
    traceSessionId: string | null
    traceSpans: TraceDialogSpans | null
    traceSpansFailed: boolean
    traceSpansLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceDialogLogicActions {
    closeTraceDialog: (reason?: TraceDialogCloseReason | undefined) => {
        reason: TraceDialogCloseReason
    } // traceDialogOpenLogic
    openTraceDialog: (
        trace: TraceLinkParams,
        options: import('lib/components/ViewTraceButton/traceDialogOpenLogic').OpenTraceDialogOptions
    ) => {
        entryPoint: TraceDialogEntryPoint
        openedFrom: TraceDialogSource | null
        trace: {
            spanId: string | null
            traceId: string
            ts?: string | null | undefined
        }
    } // traceDialogOpenLogic
    collapseSelectedSpan: (surface: import('../TraceView/traceViewLogic').TraceViewSurface) => {
        surface: import('../TraceView/traceViewLogic').TraceViewSurface
    } // traceViewLogic
    disableSpanKeys: () => {
        value: true
    } // traceViewLogic
    enableSpanKeys: (
        containerSelector: string,
        surface: import('../TraceView/traceViewLogic').TraceViewSurface
    ) => {
        containerSelector: string
        surface: import('../TraceView/traceViewLogic').TraceViewSurface
    } // traceViewLogic
    expandSelectedSpan: (surface: import('../TraceView/traceViewLogic').TraceViewSurface) => {
        surface: import('../TraceView/traceViewLogic').TraceViewSurface
    } // traceViewLogic
    selectNextSpan: () => {
        value: true
    } // traceViewLogic
    selectPreviousSpan: () => {
        value: true
    } // traceViewLogic
    selectSpan: (spanId: string | null) => {
        spanId: string | null
    } // traceViewLogic
    setInspectorTab: (
        tab: SpanInspectorTab,
        surface?: import('../TraceView/traceViewLogic').TraceViewSurface | undefined
    ) => {
        surface: null | import('../TraceView/traceViewLogic').TraceViewSurface
        tab: SpanInspectorTab
    } // traceViewLogic
    setSpans: (spans: Span[]) => {
        spans: Span[]
    } // traceViewLogic
    showTrace: (
        pinnedSpanId: string | null,
        tab: SpanInspectorTab | null
    ) => {
        pinnedSpanId: string | null
        tab: SpanInspectorTab | null
    } // traceViewLogic
    spanStepped: () => {
        value: true
    } // traceViewLogic
    toggleChain: (spanId: string) => {
        spanId: string
    } // traceViewLogic
    toggleRun: (
        spanId: string,
        method?: import('../TraceView/traceViewLogic').TraceRunToggleMethod | undefined,
        surface?: import('../TraceView/traceViewLogic').TraceViewSurface | undefined
    ) => {
        method: null | import('../TraceView/traceViewLogic').TraceRunToggleMethod
        spanId: string
        surface: null | import('../TraceView/traceViewLogic').TraceViewSurface
    } // traceViewLogic
    toggleSpanCollapsed: (spanId: string) => {
        spanId: string
    } // traceViewLogic
    loadTraceSpans: (trace: TraceLinkParams) => TraceLinkParams
    loadTraceSpansFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTraceSpansSuccess: (
        traceSpans: TraceDialogSpans | null,
        payload?: TraceLinkParams
    ) => {
        traceSpans: TraceDialogSpans | null
        payload?: TraceLinkParams
    }
    openInTracing: () => {
        value: true
    }
    startSession: () => {
        value: true
    }
    toggleFullscreen: () => {
        value: true
    }
    toggleInspector: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceDialogLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        traceIdentity: (
            traceSpans: TraceDialogSpans | null,
            configuredDistinctIdKeys: string[] | undefined,
            configuredSessionIdKeys: string[] | undefined,
            correlationLinksEnabled: boolean
        ) => TraceIdentity
        traceSessionId: (
            traceSpans: TraceDialogSpans | null,
            configuredSessionIdKeys: string[] | undefined,
            sessionErrorBadgesEnabled: boolean
        ) => string | null
        openedAtUs: (trace: TraceLinkParams | null, openedFrom: TraceDialogSource | null) => number | null
    }
}

export type traceDialogLogicType = MakeLogicType<
    traceDialogLogicValues,
    traceDialogLogicActions,
    Record<string, any>,
    traceDialogLogicMeta
>

export const traceDialogLogic = kea<traceDialogLogicType>([
    path(['products', 'tracing', 'frontend', 'components', 'TraceDialog', 'traceDialogLogic']),
    connect(() => ({
        actions: [
            traceDialogOpenLogic,
            ['openTraceDialog', 'closeTraceDialog'],
            traceViewLogic({ id: TRACE_DIALOG_VIEW_ID }),
            [
                'showTrace',
                'setSpans',
                'selectSpan',
                'setInspectorTab',
                'toggleSpanCollapsed',
                'toggleChain',
                'toggleRun',
                'spanStepped',
                'selectNextSpan',
                'selectPreviousSpan',
                'collapseSelectedSpan',
                'expandSelectedSpan',
                'enableSpanKeys',
                'disableSpanKeys',
            ],
        ],
        values: [
            traceDialogOpenLogic,
            ['isOpen', 'trace', 'openedFrom', 'entryPoint'],
            tracingCorrelationConfigLogic,
            [
                'configuredDistinctIdKeys',
                'configuredSessionIdKeys',
                'correlationLinksEnabled',
                'sessionErrorBadgesEnabled',
            ],
            tracingConfigLogic,
            ['traceViewMode'],
        ],
    })),
    actions({
        startSession: true,
        openInTracing: true,
        toggleInspector: true,
        toggleFullscreen: true,
    }),
    loaders(({ values }) => ({
        traceSpans: [
            null as TraceDialogSpans | null,
            {
                loadTraceSpans: async (trace: TraceLinkParams, breakpoint): Promise<TraceDialogSpans | null> => {
                    const dateRange = resolveTraceLookupRange(trace.ts)
                    const seen = new Set<string>()
                    const spans: Span[] = []
                    let offset: number | undefined = undefined
                    try {
                        for (let page = 0; page < TRACE_DIALOG_MAX_PAGES; page++) {
                            const response = await api.tracing.getTrace(trace.traceId, { dateRange, offset })
                            breakpoint()
                            // A page that adds no new span means the pages overlap, so paging further only repeats them.
                            const fresh = (response.results as Span[]).filter((span) => !seen.has(span.span_id))
                            fresh.forEach((span) => seen.add(span.span_id))
                            spans.push(...fresh)
                            if (!response.hasMore || response.nextOffset == null || fresh.length === 0) {
                                return { spans, truncated: false }
                            }
                            if (!values.isOpen) {
                                return { spans, truncated: true }
                            }
                            offset = response.nextOffset
                        }
                    } catch (error) {
                        // A failure from a load that a newer one replaced must not mark the newer trace as failed.
                        breakpoint()
                        throw error
                    }
                    return { spans, truncated: true }
                },
            },
        ],
    })),
    reducers({
        traceSpans: {
            openTraceDialog: () => null,
        },
        traceSpansFailed: [
            false,
            {
                loadTraceSpans: () => false,
                loadTraceSpansFailure: () => true,
            },
        ],
        inspectorOpen: [
            true,
            { persist: true },
            {
                toggleInspector: (open) => !open,
            },
        ],
        isFullscreen: [
            false,
            { persist: true },
            {
                toggleFullscreen: (fullscreen) => !fullscreen,
            },
        ],
    }),
    selectors({
        // A truncated trace may hold a second, conflicting person on a page the dialog never
        // loaded, so it names no one rather than risk naming the wrong one.
        traceIdentity: [
            (s) => [s.traceSpans, s.configuredDistinctIdKeys, s.configuredSessionIdKeys, s.correlationLinksEnabled],
            (
                traceSpans: TraceDialogSpans | null,
                distinctIdKeys: string[] | undefined,
                sessionIdKeys: string[] | undefined,
                linksEnabled: boolean
            ): TraceIdentity =>
                linksEnabled && traceSpans && !traceSpans.truncated
                    ? resolveTraceIdentity(traceSpans.spans, distinctIdKeys, sessionIdKeys)
                    : EMPTY_TRACE_IDENTITY,
        ],
        // The Errors tab's session scope follows the badge flag rather than the links flag, the
        // same split the drawer makes.
        traceSessionId: [
            (s) => [s.traceSpans, s.configuredSessionIdKeys, s.sessionErrorBadgesEnabled],
            (
                traceSpans: TraceDialogSpans | null,
                sessionIdKeys: string[] | undefined,
                badgesEnabled: boolean
            ): string | null =>
                badgesEnabled && traceSpans && !traceSpans.truncated
                    ? resolveTraceSessionId(traceSpans.spans, sessionIdKeys)
                    : null,
        ],
        // When the record that opened the dialog was written: a log's timestamp, so its span can show
        // when the log fired. Parsed to microseconds, like the timeline, so sub-millisecond spans place it right.
        openedAtUs: [
            (s) => [s.trace, s.openedFrom],
            (trace: TraceLinkParams | null, openedFrom: TraceDialogSource | null): number | null =>
                // Other links pass a time near the trace, not the moment anything happened in it.
                openedFrom && trace?.ts && dayjs(trace.ts).isValid() ? parseTimestampUs(trace.ts) : null,
        ],
    }),
    // pinned: analytics event names and properties. Renaming one breaks the dashboards built on it.
    listeners(({ values, actions, cache }) => ({
        openTraceDialog: () => {
            actions.startSession()
        },
        startSession: () => {
            const { trace, openedFrom, entryPoint } = values
            if (!trace || !entryPoint) {
                return
            }
            // Opening another trace over an open dialog ends the first session.
            if (cache.session) {
                captureClosed(cache.session, 'replaced')
            }
            const session: TraceDialogSession = {
                entryPoint,
                openedAtMs: Date.now(),
                loadStartedAtMs: Date.now(),
                spansSelected: 0,
                keyboardSteps: 0,
                collapseToggles: 0,
                tabsViewed: new Set(),
            }
            cache.session = session
            posthog.capture('tracing trace dialog opened', {
                entry_point: entryPoint,
                has_span: !!trace.spanId,
                has_log: !!openedFrom,
                // The view persists across traces, so the view change event alone cannot count the traces read
                // as a call tree.
                view: values.traceViewMode,
            })
            actions.showTrace(trace.spanId ?? null, null)
            actions.loadTraceSpans(trace)
            actions.enableSpanKeys(TRACE_DIALOG_SELECTOR, 'trace_dialog')
        },
        closeTraceDialog: ({ reason }) => {
            actions.disableSpanKeys()
            const session: TraceDialogSession | undefined = cache.session
            if (!session) {
                return
            }
            cache.session = undefined
            captureClosed(session, reason)
        },
        openInTracing: () => {
            // Close here rather than on navigation: from /tracing itself the link only changes the query.
            actions.closeTraceDialog('open_in_tracing')
        },
        loadTraceSpans: () => {
            if (cache.session) {
                cache.session.loadStartedAtMs = Date.now()
            }
        },
        loadTraceSpansSuccess: ({ traceSpans }) => {
            actions.setSpans(traceSpans?.spans ?? [])
            if (!cache.session || !traceSpans) {
                return
            }
            posthog.capture('tracing trace dialog loaded', {
                entry_point: cache.session.entryPoint,
                span_count: traceSpans.spans.length,
                truncated: traceSpans.truncated,
                load_ms: Date.now() - cache.session.loadStartedAtMs,
            })
        },
        loadTraceSpansFailure: () => {
            if (cache.session) {
                posthog.capture('tracing trace dialog load failed', { entry_point: cache.session.entryPoint })
            }
        },
        selectSpan: () => {
            if (cache.session) {
                cache.session.spansSelected += 1
            }
        },
        setInspectorTab: ({ tab }) => {
            cache.session?.tabsViewed.add(tab)
        },
        spanStepped: () => {
            if (cache.session) {
                cache.session.keyboardSteps += 1
            }
        },
        toggleSpanCollapsed: () => {
            if (cache.session) {
                cache.session.collapseToggles += 1
            }
        },
        toggleChain: () => {
            if (cache.session) {
                cache.session.collapseToggles += 1
            }
        },
        toggleRun: () => {
            if (cache.session) {
                cache.session.collapseToggles += 1
            }
        },
    })),
    afterMount(({ values, actions }) => {
        // The dialog mounts this logic after traceDialogOpenLogic opens it, so the open action has
        // already gone by and the session starts here.
        if (values.isOpen) {
            actions.startSession()
        }
    }),
])