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.

18.5 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, urlToAction } from 'kea-router'

import { teamLogic } from 'scenes/teamLogic'

import { apmEndpointsList, apmServiceMapList, apmServicesList } from './generated/api'
import type {
    EndpointHealthApi,
    EndpointsHealthResponseApi,
    ServiceHealthApi,
    ServiceMapResponseApi,
    ServicesHealthResponseApi,
} from './generated/api.schemas'
import { ServiceGraph, buildServiceGraph, layoutServiceGraph } from './serviceMap'

export const APPLICATION_OBSERVABILITY_PATH = '/application-observability'

export type TimeRange = '-1h' | '-6h' | '-24h' | '-7d'

export type ApplicationObservabilityTab = 'services' | 'endpoints' | 'map'

export type ServiceMapWarning = 'map' | 'layout' | 'health' | null

export const TABS: ApplicationObservabilityTab[] = ['services', 'endpoints', 'map']

export const TIME_RANGE_LABELS: Record<TimeRange, string> = {
    '-1h': 'Last hour',
    '-6h': 'Last 6 hours',
    '-24h': 'Last 24 hours',
    '-7d': 'Last 7 days',
}

const TIME_RANGE_MS: Record<TimeRange, number> = {
    '-1h': 60 * 60 * 1000,
    '-6h': 6 * 60 * 60 * 1000,
    '-24h': 24 * 60 * 60 * 1000,
    '-7d': 7 * 24 * 60 * 60 * 1000,
}

// One 5-minute bucket, the grain the backend computes health at.
const POLL_INTERVAL_MS = 5 * 60 * 1000

// Matches the Traces and Logs URL readers: `serviceNames` goes through parseTagsFilter, which splits a
// plain string on commas, so it is a JSON array; `dateRange` is a JSON `{date_from, date_to}` object.
export function drillDownParams(serviceName: string, timeRange: TimeRange): string {
    const serviceNames = JSON.stringify([serviceName])
    const dateRange = JSON.stringify({ date_from: timeRange, date_to: null })
    return `serviceNames=${encodeURIComponent(serviceNames)}&dateRange=${encodeURIComponent(dateRange)}`
}

function isTab(value: unknown): value is ApplicationObservabilityTab {
    return typeof value === 'string' && (TABS as string[]).includes(value)
}

function isTimeRange(value: unknown): value is TimeRange {
    // `in` also matches inherited keys like `toString`, so a `?range=toString` URL would pass.
    return typeof value === 'string' && Object.hasOwn(TIME_RANGE_LABELS, value)
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface applicationObservabilityLogicValues {
    currentTeamId: number | null // teamLogic
    attentionCount: number
    endpoints: EndpointHealthApi[]
    endpointsHealth: EndpointsHealthResponseApi | null
    endpointsHealthLoading: boolean
    endpointsLoadError: boolean
    endpointsService: string | null
    environment: string | null
    environments: string[]
    hasLoadError: boolean
    resolvedEnvironment: string
    selectedMapService: ServiceHealthApi | null
    selectedMapServiceName: string | null
    serviceMap: ServiceMapResponseApi | null
    serviceMapLayout: ServiceGraph | null
    serviceMapLayoutError: boolean
    serviceMapLayoutLoading: boolean
    serviceMapLoadError: boolean
    serviceMapLoading: boolean
    serviceMapWarning: ServiceMapWarning
    services: ServiceHealthApi[]
    servicesHealth: ServicesHealthResponseApi | null
    servicesHealthLoading: boolean
    tab: ApplicationObservabilityTab
    timeRange: TimeRange
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface applicationObservabilityLogicActions {
    layoutServiceMap: (_: void) => void
    layoutServiceMapFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    layoutServiceMapSuccess: (
        serviceMapLayout: ServiceGraph,
        payload?: void
    ) => {
        serviceMapLayout: ServiceGraph
        payload?: void
    }
    loadEndpointsHealth: (_: void) => void
    loadEndpointsHealthFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadEndpointsHealthSuccess: (
        endpointsHealth: EndpointsHealthResponseApi,
        payload?: void
    ) => {
        endpointsHealth: EndpointsHealthResponseApi
        payload?: void
    }
    loadServiceMap: (_: void) => void
    loadServiceMapFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadServiceMapSuccess: (
        serviceMap: ServiceMapResponseApi,
        payload?: void
    ) => {
        serviceMap: ServiceMapResponseApi
        payload?: void
    }
    loadServicesHealth: (_: void) => void
    loadServicesHealthFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadServicesHealthSuccess: (
        servicesHealth: ServicesHealthResponseApi,
        payload?: void
    ) => {
        servicesHealth: ServicesHealthResponseApi
        payload?: void
    }
    requestReload: (includeServices?: boolean) => {
        includeServices: boolean
    }
    setEndpointsService: (service: string | null) => {
        service: string | null
    }
    setEnvironment: (environment: string | null) => {
        environment: string | null
    }
    setSelectedMapService: (service: string | null) => {
        service: string | null
    }
    setTab: (tab: ApplicationObservabilityTab) => {
        tab: ApplicationObservabilityTab
    }
    setTimeRange: (timeRange: TimeRange) => {
        timeRange: TimeRange
    }
    showServiceEndpoints: (service: string) => {
        service: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface applicationObservabilityLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        services: (servicesHealth: ServicesHealthResponseApi | null) => ServiceHealthApi[]
        environments: (servicesHealth: ServicesHealthResponseApi | null) => string[]
        resolvedEnvironment: (environment: string | null, servicesHealth: ServicesHealthResponseApi | null) => string
        endpoints: (endpointsHealth: EndpointsHealthResponseApi | null) => EndpointHealthApi[]
        selectedMapService: (
            serviceMapLayout: ServiceGraph | null,
            selectedMapServiceName: string | null
        ) => ServiceHealthApi | null
        serviceMapWarning: (
            serviceMapLoadError: boolean,
            serviceMapLayoutError: boolean,
            hasLoadError: boolean
        ) => ServiceMapWarning
        attentionCount: (services: ServiceHealthApi[]) => number
    }
}

export type applicationObservabilityLogicType = MakeLogicType<
    applicationObservabilityLogicValues,
    applicationObservabilityLogicActions,
    Record<string, any>,
    applicationObservabilityLogicMeta
>

export const applicationObservabilityLogic = kea<applicationObservabilityLogicType>([
    path(['products', 'apm', 'frontend', 'applicationObservabilityLogic']),
    connect(() => ({ values: [teamLogic, ['currentTeamId']] })),

    actions({
        setEnvironment: (environment: string | null) => ({ environment }),
        setTimeRange: (timeRange: TimeRange) => ({ timeRange }),
        setTab: (tab: ApplicationObservabilityTab) => ({ tab }),
        setEndpointsService: (service: string | null) => ({ service }),
        showServiceEndpoints: (service: string) => ({ service }),
        setSelectedMapService: (service: string | null) => ({ service }),
        // Internal: coalesces the picker actions and the initial URL sync into a single reload.
        // `includeServices` is false for changes that only affect the active tab's own data.
        requestReload: (includeServices: boolean = true) => ({ includeServices }),
    }),

    reducers({
        environment: [null as string | null, { setEnvironment: (_, { environment }) => environment }],
        timeRange: ['-1h' as TimeRange, { setTimeRange: (_, { timeRange }) => timeRange }],
        tab: [
            'services' as ApplicationObservabilityTab,
            { setTab: (_, { tab }) => tab, showServiceEndpoints: () => 'endpoints' },
        ],
        endpointsService: [
            null as string | null,
            { setEndpointsService: (_, { service }) => service, showServiceEndpoints: (_, { service }) => service },
        ],
        // Tracks the *last* load's outcome so a refresh failure can be told apart from a
        // genuinely empty result, and from a healthy result that's gone stale.
        hasLoadError: [
            false,
            {
                loadServicesHealthSuccess: () => false,
                loadServicesHealthFailure: () => true,
            },
        ],
        selectedMapServiceName: [
            null as string | null,
            { setSelectedMapService: (_, { service }) => service, setEnvironment: () => null },
        ],
        serviceMapLoadError: [
            false,
            {
                loadServiceMapSuccess: () => false,
                loadServiceMapFailure: () => true,
            },
        ],
        serviceMapLayoutError: [
            false,
            {
                layoutServiceMapSuccess: () => false,
                layoutServiceMapFailure: () => true,
            },
        ],
        endpointsLoadError: [
            false,
            {
                loadEndpointsHealthSuccess: () => false,
                loadEndpointsHealthFailure: () => true,
            },
        ],
    }),

    loaders(({ values }) => ({
        endpointsHealth: [
            null as EndpointsHealthResponseApi | null,
            {
                loadEndpointsHealth: async (_: void, breakpoint): Promise<EndpointsHealthResponseApi> => {
                    const dateTo = new Date()
                    const dateFrom = new Date(dateTo.getTime() - TIME_RANGE_MS[values.timeRange])
                    const response = await apmEndpointsList(String(values.currentTeamId), {
                        date_from: dateFrom.toISOString(),
                        date_to: dateTo.toISOString(),
                        ...(values.environment ? { environment: values.environment } : {}),
                        ...(values.endpointsService ? { service: values.endpointsService } : {}),
                    })
                    breakpoint()
                    return response
                },
            },
        ],
        serviceMap: [
            null as ServiceMapResponseApi | null,
            {
                loadServiceMap: async (_: void, breakpoint): Promise<ServiceMapResponseApi> => {
                    const dateTo = new Date()
                    const dateFrom = new Date(dateTo.getTime() - TIME_RANGE_MS[values.timeRange])
                    const response = await apmServiceMapList(String(values.currentTeamId), {
                        date_from: dateFrom.toISOString(),
                        date_to: dateTo.toISOString(),
                        ...(values.environment ? { environment: values.environment } : {}),
                    })
                    breakpoint()
                    return response
                },
            },
        ],
        // ELK runs async, so the layout is a loader of its own over the services and the edges.
        serviceMapLayout: [
            null as ServiceGraph | null,
            {
                layoutServiceMap: async (_: void, breakpoint): Promise<ServiceGraph> => {
                    // Health joins the map by service name only, so attach it only when it is current
                    // and for the same environment. A failed or pending refresh would otherwise paint
                    // the previous environment's status onto the new map.
                    const healthMatchesMap =
                        !values.servicesHealthLoading &&
                        !values.hasLoadError &&
                        values.servicesHealth?.environment === values.serviceMap?.environment
                    const graph = await layoutServiceGraph(
                        buildServiceGraph(healthMatchesMap ? values.services : [], values.serviceMap?.edges ?? [])
                    )
                    breakpoint()
                    return graph
                },
            },
        ],
        servicesHealth: [
            null as ServicesHealthResponseApi | null,
            {
                loadServicesHealth: async (_: void, breakpoint): Promise<ServicesHealthResponseApi> => {
                    const dateTo = new Date()
                    const dateFrom = new Date(dateTo.getTime() - TIME_RANGE_MS[values.timeRange])
                    const response = await apmServicesList(String(values.currentTeamId), {
                        date_from: dateFrom.toISOString(),
                        date_to: dateTo.toISOString(),
                        ...(values.environment ? { environment: values.environment } : {}),
                    })
                    // A superseded call (environment/range changed again mid-flight) throws here
                    // instead of overwriting state with a stale response.
                    breakpoint()
                    return response
                },
            },
        ],
    })),

    selectors({
        services: [
            (s) => [s.servicesHealth],
            (servicesHealth: ServicesHealthResponseApi | null): ServiceHealthApi[] => servicesHealth?.results ?? [],
        ],
        environments: [
            (s) => [s.servicesHealth],
            (servicesHealth: ServicesHealthResponseApi | null): string[] => servicesHealth?.environments ?? [],
        ],
        resolvedEnvironment: [
            (s) => [s.environment, s.servicesHealth],
            (environment: string | null, servicesHealth: ServicesHealthResponseApi | null): string =>
                environment ?? servicesHealth?.environment ?? 'default',
        ],
        endpoints: [
            (s) => [s.endpointsHealth],
            (endpointsHealth: EndpointsHealthResponseApi | null): EndpointHealthApi[] => endpointsHealth?.results ?? [],
        ],
        selectedMapService: [
            (s) => [s.serviceMapLayout, s.selectedMapServiceName],
            (serviceMapLayout: ServiceGraph | null, selectedMapServiceName: string | null): ServiceHealthApi | null =>
                serviceMapLayout?.nodes.find((node) => node.id === selectedMapServiceName)?.data.service ?? null,
        ],
        serviceMapWarning: [
            (s) => [s.serviceMapLoadError, s.serviceMapLayoutError, s.hasLoadError],
            (serviceMapLoadError: boolean, serviceMapLayoutError: boolean, hasLoadError: boolean): ServiceMapWarning =>
                serviceMapLoadError ? 'map' : serviceMapLayoutError ? 'layout' : hasLoadError ? 'health' : null,
        ],
        attentionCount: [
            (s) => [s.services],
            (services: ServiceHealthApi[]): number =>
                services.filter((row: ServiceHealthApi) => row.status === 'serious' || row.status === 'critical')
                    .length,
        ],
    }),

    actionToUrl(({ values }) => {
        const toUrl = (): [string, Record<string, string>] => [
            APPLICATION_OBSERVABILITY_PATH,
            {
                ...(values.environment ? { environment: values.environment } : {}),
                ...(values.timeRange !== '-1h' ? { range: values.timeRange } : {}),
                ...(values.tab !== 'services' ? { tab: values.tab } : {}),
                ...(values.endpointsService ? { service: values.endpointsService } : {}),
            },
        ]
        return {
            setEnvironment: toUrl,
            setTimeRange: toUrl,
            setTab: toUrl,
            setEndpointsService: toUrl,
            showServiceEndpoints: toUrl,
        }
    }),

    urlToAction(({ actions, values }) => ({
        // Only forwards URL state into the picker reducers. The reload itself comes from
        // `requestReload`'s listeners below, so a picker-driven change and a URL-driven change
        // reload exactly once either way (see the `listeners` block).
        [APPLICATION_OBSERVABILITY_PATH]: (_, searchParams) => {
            const environment = typeof searchParams.environment === 'string' ? searchParams.environment : null
            const range = isTimeRange(searchParams.range) ? searchParams.range : '-1h'
            const tab = isTab(searchParams.tab) ? searchParams.tab : 'services'
            const service = typeof searchParams.service === 'string' ? searchParams.service : null
            if (service !== values.endpointsService) {
                actions.setEndpointsService(service)
            }
            if (tab !== values.tab) {
                actions.setTab(tab)
            }
            if (environment !== values.environment) {
                actions.setEnvironment(environment)
            }
            if (range !== values.timeRange) {
                actions.setTimeRange(range)
            }
        },
    })),

    listeners(({ actions, values, cache }) => ({
        setEnvironment: () => actions.requestReload(),
        setTimeRange: () => actions.requestReload(),
        setTab: () => actions.requestReload(false),
        setEndpointsService: () => actions.requestReload(false),
        showServiceEndpoints: () => actions.requestReload(false),
        loadServiceMapSuccess: () => actions.layoutServiceMap(),
        loadServicesHealthSuccess: () => {
            if (values.tab === 'map' && values.serviceMap) {
                actions.layoutServiceMap()
            }
        },
        // Debounced with a replaceable timer: several `requestReload` calls in the same tick
        // (e.g. the initial URL sync setting both the environment and the range at once, or that
        // sync landing in the same tick as the mount-time load) collapse into a single request.
        requestReload: ({ includeServices }) => {
            cache.reloadServices = cache.reloadServices || includeServices
            cache.disposables.add(() => {
                const timerId = setTimeout(() => {
                    if (cache.reloadServices) {
                        cache.reloadServices = false
                        actions.loadServicesHealth()
                    }
                    if (values.tab === 'endpoints') {
                        actions.loadEndpointsHealth()
                    }
                    if (values.tab === 'map') {
                        actions.loadServiceMap()
                    }
                }, 0)
                return () => clearTimeout(timerId)
            }, 'reloadTimer')
        },
    })),

    afterMount(({ actions, cache }) => {
        actions.requestReload()
        cache.disposables.add(() => {
            const handle = setInterval(() => actions.requestReload(), POLL_INTERVAL_MS)
            return () => clearInterval(handle)
        }, 'poll')
    }),
])