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.

16.0 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    propsChanged,
    reducers,
} from 'kea'

import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'

import type { MetricsDashboardVariable, MetricsDashboardVariableSelection } from '~/queries/schema/schema-general'

import { metricsVariableOptionsCreate } from 'products/metrics/frontend/generated/api'

import {
    dependentsOf,
    orderVariables,
    reconcileSelection,
    selectionsForRequest,
    variableParents,
    variablesToReload,
} from './metricVariables'

export interface DashboardMetricVariablesLogicProps {
    dashboardId: number | string
    variables: MetricsDashboardVariable[]
    dateFrom?: string | null
    dateTo?: string | null
    /** Called when loaded options make a selection out of date. */
    onSelectionsChange: (variables: MetricsDashboardVariable[]) => void
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardMetricVariablesLogicValues {
    currentTeamId: number | null // teamLogic
    errors: Record<string, string>
    loadingNames: string[]
    options: Record<string, string[]>
    pendingVariables: MetricsDashboardVariable[] | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardMetricVariablesLogicActions {
    loadOptions: (
        names: string[] | null,
        reconcile: boolean
    ) => {
        names: string[] | null
        reconcile: boolean
    }
    retry: (name: string) => {
        name: string
    }
    select: (
        name: string,
        current: MetricsDashboardVariableSelection | null
    ) => {
        current: MetricsDashboardVariableSelection | null
        name: string
    }
    setError: (
        name: string,
        error: string | null
    ) => {
        error: string | null
        name: string
    }
    setLoading: (
        name: string,
        loading: boolean
    ) => {
        loading: boolean
        name: string
    }
    setOptions: (
        name: string,
        options: string[]
    ) => {
        name: string
        options: string[]
    }
    setPendingVariables: (variables: MetricsDashboardVariable[] | null) => {
        variables: MetricsDashboardVariable[] | null
    }
    stage: (
        variables: MetricsDashboardVariable[],
        names: string[]
    ) => {
        names: string[]
        variables: MetricsDashboardVariable[]
    }
}

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

export type dashboardMetricVariablesLogicType = MakeLogicType<
    dashboardMetricVariablesLogicValues,
    dashboardMetricVariablesLogicActions,
    DashboardMetricVariablesLogicProps,
    dashboardMetricVariablesLogicMeta
>

function errorMessage(error: unknown): string {
    if (error && typeof error === 'object' && 'detail' in error && typeof error.detail === 'string') {
        return error.detail
    }
    return error instanceof Error ? error.message : 'The options could not be loaded.'
}

const MAX_OPTION_REQUESTS = 4

async function acquireRequestSlot(cache: Record<string, any>): Promise<void> {
    while ((cache.runningRequests ?? 0) >= MAX_OPTION_REQUESTS) {
        await new Promise<void>((resolve) => (cache.queuedRequests ??= []).push(resolve))
    }
    cache.runningRequests = (cache.runningRequests ?? 0) + 1
}

function releaseRequestSlot(cache: Record<string, any>): void {
    cache.runningRequests -= 1
    cache.queuedRequests?.shift()?.()
}

export const dashboardMetricVariablesLogic = kea<dashboardMetricVariablesLogicType>([
    path((key) => ['products', 'metrics', 'frontend', 'components', 'dashboardMetricVariablesLogic', key]),
    props({} as DashboardMetricVariablesLogicProps),
    key((props) => props.dashboardId),
    connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
    actions({
        loadOptions: (names: string[] | null, reconcile: boolean) => ({ names, reconcile }),
        setOptions: (name: string, options: string[]) => ({ name, options }),
        setError: (name: string, error: string | null) => ({ name, error }),
        setLoading: (name: string, loading: boolean) => ({ name, loading }),
        setPendingVariables: (variables: MetricsDashboardVariable[] | null) => ({ variables }),
        select: (name: string, current: MetricsDashboardVariableSelection | null) => ({ name, current }),
        stage: (variables: MetricsDashboardVariable[], names: string[]) => ({ variables, names }),
        retry: (name: string) => ({ name }),
    }),
    reducers({
        options: [
            {} as Record<string, string[]>,
            { setOptions: (state, { name, options }) => ({ ...state, [name]: options }) },
        ],
        errors: [
            {} as Record<string, string>,
            {
                setError: (state, { name, error }) => {
                    const { [name]: _, ...rest } = state
                    return error ? { ...rest, [name]: error } : rest
                },
            },
        ],
        loadingNames: [
            [] as string[],
            {
                setLoading: (state, { name, loading }) =>
                    loading ? [...state.filter((other) => other !== name), name] : state.filter((n) => n !== name),
            },
        ],
        // Selections the dashboard does not have yet: their dependents still load, or the dashboard has not
        // rendered the published ones. The dashboard gets a change once its dependents reconcile, so tiles refresh once.
        pendingVariables: [
            null as MetricsDashboardVariable[] | null,
            { setPendingVariables: (_, { variables }) => variables },
        ],
    }),
    listeners(({ actions, values, props, cache }) => ({
        loadOptions: async ({ names, reconcile }, breakpoint) => {
            // Definitions come from the staged variables, so a change from the editor loads before tiles refresh.
            const start = values.pendingVariables ?? props.variables
            // A newer load cancels this one at its next breakpoint, so its unfinished names move to the newer load.
            const pending = new Set<string>([
                ...((cache.pending as Set<string> | undefined) ?? []),
                ...(names ?? start.map((variable) => variable.name)),
            ])
            const reconciling: Set<string> = (cache.reconciling ??= new Set())
            if (reconcile) {
                ;(names ?? start.map((variable) => variable.name)).forEach((name) => reconciling.add(name))
            }
            const shouldReconcile = reconcile || !!cache.pendingReconcile
            cache.pending = pending
            cache.pendingReconcile = shouldReconcile
            // A newer load also takes over the selections that this one reconciled but did not publish yet.
            const reconciled: Map<string, MetricsDashboardVariableSelection | null> = (cache.reconciled ??= new Map())
            let variables = start.map((variable) =>
                reconciled.has(variable.name) ? { ...variable, current: reconciled.get(variable.name) } : variable
            )

            // Each variable loads when its parents finish, and shows its options at once, so a slow
            // query delays only the variables that depend on it.
            const loads = new Map<string, Promise<void>>()
            const load = async (definition: MetricsDashboardVariable): Promise<void> => {
                const { name } = definition
                await Promise.all(variableParents(definition, start).map((parent) => loads.get(parent)))
                breakpoint()
                if (!pending.has(name) || definition.source === 'textbox') {
                    reconciling.delete(name)
                    return
                }
                // The parents may have changed their selections, which the request must use.
                const variable = variables.find((other) => other.name === name)!
                let options: string[]
                if (variable.source === 'custom') {
                    options = [...new Set((variable.customValues ?? []).filter(Boolean))]
                    actions.setLoading(name, false)
                } else {
                    actions.setLoading(name, true)
                    const body = {
                        source: variable.source,
                        query: variable.query ?? null,
                        regex: variable.regex ?? null,
                        variables: selectionsForRequest(variable, variables, values.options),
                        // The server resolves the dashboard date filter as the tiles do.
                        dateFrom: props.dateFrom ?? null,
                        dateTo: props.dateTo ?? null,
                    }
                    // A cancelled load leaves its request running, so a newer load with the same inputs waits for it.
                    const inflight: Map<string, ReturnType<typeof metricsVariableOptionsCreate>> = (cache.inflight ??=
                        new Map())
                    const key = JSON.stringify(body)
                    let request = inflight.get(key)
                    if (!request) {
                        const teamId = String(values.currentTeamId)
                        request = (async () => {
                            // Option queries share the organization's query slots with the tiles, so few run at once.
                            await acquireRequestSlot(cache)
                            try {
                                // A request that waited past the dashboard would take a query slot from the next page.
                                if (cache.disposables.isDisposed) {
                                    throw new Error('The dashboard closed.')
                                }
                                return await metricsVariableOptionsCreate(teamId, body)
                            } finally {
                                releaseRequestSlot(cache)
                            }
                        })()
                        inflight.set(key, request)
                        void request.catch(() => undefined).finally(() => inflight.delete(key))
                    }
                    try {
                        const response = await request
                        breakpoint()
                        options = response.results
                    } catch (error) {
                        breakpoint()
                        actions.setLoading(name, false)
                        pending.delete(name)
                        reconciling.delete(name)
                        // Keep the options and the selection: they are unknown now, not empty.
                        actions.setError(name, errorMessage(error))
                        return
                    }
                    actions.setLoading(name, false)
                }
                pending.delete(name)
                reconciling.delete(name)
                actions.setError(name, null)
                actions.setOptions(name, options)
                const current = reconcileSelection(variable, options)
                // Without reconcile, the dependents load for the saved selection, which the tiles use.
                if (shouldReconcile && !objectsEqual(current, variable.current ?? null)) {
                    reconciled.set(name, current)
                    variables = variables.map((other) => (other.name === name ? { ...other, current } : other))
                }
            }
            for (const name of orderVariables(start).order) {
                const loading = load(start.find((variable) => variable.name === name)!)
                // A newer load can cancel this listener before it waits for every load.
                void loading.catch(() => undefined)
                loads.set(name, loading)
            }
            let published = props.variables
            const publish = (): void => {
                // The first load only shows options. A saved selection changes only after the user changes something.
                if (!shouldReconcile) {
                    return
                }
                // A selection the user changed during the load wins over what the load reconciled.
                const latest = values.pendingVariables ?? props.variables
                const next = latest.map((variable) => {
                    const before = start.find((other) => other.name === variable.name)
                    return reconciled.has(variable.name) &&
                        objectsEqual(variable.current ?? null, before?.current ?? null)
                        ? { ...variable, current: reconciled.get(variable.name) }
                        : variable
                })
                if (!objectsEqual(next, published)) {
                    published = next
                    ;(cache.published ??= []).push(next)
                    actions.setPendingVariables(next)
                    props.onSelectionsChange(next)
                }
            }
            // A slow query that this load took over from an older one must not hold back the changed selections,
            // unless the older load was reconciling them too.
            const barrier = [...(names ?? [...loads.keys()]), ...[...pending].filter((name) => reconciling.has(name))]
            await Promise.allSettled(barrier.map((name) => loads.get(name)))
            breakpoint()
            publish()
            await Promise.allSettled(loads.values())
            breakpoint()
            cache.pending = undefined
            cache.pendingReconcile = false
            publish()
            cache.reconciled = undefined
        },
        select: ({ name, current }) => {
            const base = values.pendingVariables ?? props.variables
            const next = base.map((variable) => (variable.name === name ? { ...variable, current } : variable))
            // Staged definitions can differ from the dashboard's, and they decide what depends on the change.
            actions.stage(next, dependentsOf(base, [name]))
        },
        stage: ({ variables, names }) => {
            if (!names.length && !values.pendingVariables) {
                ;(cache.published ??= []).push(variables)
                props.onSelectionsChange(variables)
                return
            }
            actions.setPendingVariables(variables)
            actions.loadOptions(names, true)
        },
        retry: ({ name }) => {
            // The variables that depend on a failed variable kept options that its new values can change.
            actions.loadOptions([name, ...dependentsOf(values.pendingVariables ?? props.variables, [name])], true)
        },
    })),
    propsChanged(({ actions, values, props, cache }, oldProps) => {
        if (props.dateFrom !== oldProps.dateFrom || props.dateTo !== oldProps.dateTo) {
            actions.loadOptions(null, true)
            return
        }
        if (objectsEqual(props.variables, oldProps.variables)) {
            return
        }
        const published: MetricsDashboardVariable[][] = cache.published ?? []
        const ownUpdate = published.findIndex((variables) => objectsEqual(props.variables, variables))
        if (ownUpdate >= 0) {
            cache.published = published.slice(ownUpdate + 1)
            if (objectsEqual(props.variables, values.pendingVariables)) {
                actions.setPendingVariables(null)
            }
            return
        }
        // Settings from outside, such as Discard, replace the selections that are not published yet. The options that
        // are still loading stay in `cache.pending`, so the next load takes them over.
        cache.pendingReconcile = false
        cache.reconciling = undefined
        cache.reconciled = undefined
        actions.setPendingVariables(null)
        const names = variablesToReload(oldProps.variables, props.variables)
        // An empty load still cancels the older loads.
        actions.loadOptions(names, names.length > 0)
    }),
    afterMount(({ actions }) => {
        actions.loadOptions(null, false)
    }),
])