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.

6.8 KB
Raw Blame
import { MakeLogicType, connect, kea, key, listeners, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'

import { teamLogic } from 'scenes/teamLogic'

import { UniversalFiltersGroup } from '~/types'

import { tracingSpansImpactCreate } from 'products/tracing/frontend/generated/api'
import type {
    _TracingCountBodyApi,
    _TracingCountBodyApiFilterGroup,
    _TracingImpactResponseApi,
} from 'products/tracing/frontend/generated/api.schemas'

import { tracingDataLogic } from './tracingDataLogic'
import { TRACING_SCENE_VIEWER_ID, dataScopeKey, type TracingFilters, tracingFiltersLogic } from './tracingFiltersLogic'

export interface TracingImpactLogicProps {
    id: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingImpactLogicValues {
    currentTeamId: number | null // teamLogic
    filters: TracingFilters // tracingFiltersLogic
    queryFilterGroup: UniversalFiltersGroup // tracingFiltersLogic
    utcDateRange: {
        date_from: string | null | undefined
        date_to: string
    } // tracingFiltersLogic
    impact: _TracingImpactResponseApi | null
    impactLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingImpactLogicActions {
    refreshQuery: () => {
        value: true
    } // tracingDataLogic
    runQuery: () => {
        value: true
    } // tracingDataLogic
    loadImpact: (_: any) => any
    loadImpactFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadImpactSuccess: (
        impact: _TracingImpactResponseApi | null,
        payload?: any
    ) => {
        impact: _TracingImpactResponseApi | null
        payload?: any
    }
}

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

export type tracingImpactLogicType = MakeLogicType<
    tracingImpactLogicValues,
    tracingImpactLogicActions,
    TracingImpactLogicProps,
    tracingImpactLogicMeta
>

export const tracingImpactLogic = kea<tracingImpactLogicType>([
    props({ id: TRACING_SCENE_VIEWER_ID } as TracingImpactLogicProps),
    key(({ id }) => id),
    path((key) => ['products', 'tracing', 'frontend', 'tracingImpactLogic', key]),
    connect(({ id }: TracingImpactLogicProps) => ({
        values: [
            tracingFiltersLogic({ id }),
            ['utcDateRange', 'queryFilterGroup', 'filters'],
            teamLogic,
            ['currentTeamId'],
        ],
        actions: [tracingDataLogic({ id }), ['runQuery', 'refreshQuery']],
    })),
    loaders(({ cache, values }) => ({
        impact: [
            null as _TracingImpactResponseApi | null,
            {
                loadImpact: async (_, breakpoint) => {
                    // Team loading can outlast this logic's mount, and a request built without an
                    // ID asks for /api/projects/null/. The currentTeamId subscription below runs
                    // the load once the ID lands.
                    const currentTeamId = values.currentTeamId
                    if (currentTeamId === null) {
                        return null
                    }
                    // Read up front so the recorded scope is the one the response covers, and
                    // claimed so a runQuery arriving mid-flight starts no second scan.
                    const scopeKey = dataScopeKey(values)
                    cache.inFlightScope = scopeKey
                    await breakpoint(300)
                    const query: _TracingCountBodyApi = {
                        dateRange: values.utcDateRange,
                        serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
                        // The editor's group holds any universal filter, while the endpoint reads
                        // only the span ones, so the narrowing is asserted rather than checked.
                        filterGroup: values.queryFilterGroup as _TracingCountBodyApiFilterGroup,
                    }
                    // Re-adding the key aborts the superseded request. A hidden tab must not.
                    const controller = new AbortController()
                    cache.disposables.add(() => () => controller.abort(), 'impactRequest', {
                        pauseOnPageHidden: false,
                    })
                    let response: _TracingImpactResponseApi | null = null
                    try {
                        response = await tracingSpansImpactCreate(
                            String(currentTeamId),
                            { query },
                            { signal: controller.signal }
                        )
                    } catch {
                        // Passive decoration, so a failure shows nothing rather than a toast.
                    }
                    breakpoint()
                    cache.inFlightScope = undefined
                    // Only on success, so a failure retries instead of being cached as done.
                    if (response) {
                        cache.impactScope = scopeKey
                    }
                    return response
                },
            },
        ],
    })),
    reducers({
        impact: {
            // So the previous query's counts never render beside the new query's results.
            loadImpact: () => null,
        },
    }),
    listeners(({ actions, values, cache }) => ({
        // A latency-heatmap brush reaches the strip here: it lands as filters, then re-queries.
        runQuery: () => {
            const scopeKey = dataScopeKey(values)
            if (scopeKey === cache.impactScope || scopeKey === cache.inFlightScope) {
                return
            }
            actions.loadImpact(null)
        },
        // Loads here rather than relying on tracingDataLogic's runQuery, whose listener could
        // reach the guard first.
        refreshQuery: () => {
            cache.impactScope = undefined
            cache.inFlightScope = undefined
            actions.loadImpact(null)
        },
    })),
    // Stands in for an afterMount load: the data logic usually fires its initial runQuery before
    // this logic exists, so the strip starts its own. Keyed on the team ID so a team that arrives
    // late still gets a load, rather than leaving the strip empty until the next filter change.
    subscriptions(({ actions, values, cache }) => ({
        currentTeamId: (currentTeamId: number | null) => {
            if (currentTeamId === null) {
                return
            }
            const scopeKey = dataScopeKey(values)
            if (scopeKey === cache.impactScope || scopeKey === cache.inFlightScope) {
                return
            }
            actions.loadImpact(null)
        },
    })),
])