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.

4.6 KB
Raw Blame
import { MakeLogicType, afterMount, kea, key, path, props, propsChanged, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { v4 as uuid } from 'uuid'

import api from 'lib/api'
import { objectsEqual } from 'lib/utils/objects'

import { performQuery } from '~/queries/query'
import { ActorsQuery } from '~/queries/schema/schema-general'

export interface DashboardInsightResultMenuProps {
    key: string
    query: ActorsQuery | null
}

interface ActorResult {
    query: ActorsQuery
    sql: string | undefined
    sessionIds: string[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardInsightResultMenuLogicValues {
    result: ActorResult | null
    resultLoading: boolean
    selectedResult: ActorResult | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardInsightResultMenuLogicActions {
    loadResult: (_: void) => void
    loadResultFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadResultSuccess: (
        result: ActorResult | null,
        payload?: void
    ) => {
        result: ActorResult | null
        payload?: void
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardInsightResultMenuLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        selectedResult: (result: ActorResult | null, arg: any) => ActorResult | null
    }
}

export type dashboardInsightResultMenuLogicType = MakeLogicType<
    dashboardInsightResultMenuLogicValues,
    dashboardInsightResultMenuLogicActions,
    DashboardInsightResultMenuProps,
    dashboardInsightResultMenuLogicMeta
>

export const dashboardInsightResultMenuLogic = kea<dashboardInsightResultMenuLogicType>([
    props({} as DashboardInsightResultMenuProps),
    key((props): string => props.key),
    path((key) => ['products', 'dashboards', 'components', 'dashboardInsightResultMenuLogic', key]),
    loaders(({ props, cache }) => ({
        result: [
            null as ActorResult | null,
            {
                loadResult: async (_: void, breakpoint): Promise<ActorResult | null> => {
                    cache.disposables.dispose('actorQuery')
                    const query = props.query
                    if (!query) {
                        return null
                    }
                    const controller = new AbortController()
                    const queryId = uuid()
                    let settled = false
                    cache.disposables.add(
                        () => () => {
                            if (!settled) {
                                controller.abort()
                                void api.cancelQuery(queryId).catch((error) => {
                                    console.warn('Failed cancelling dashboard actor query', error)
                                })
                            }
                        },
                        'actorQuery',
                        { pauseOnPageHidden: false }
                    )
                    const response = await performQuery(query, { signal: controller.signal }, undefined, queryId)
                        .catch((error) => {
                            breakpoint()
                            throw error
                        })
                        .finally(() => {
                            settled = true
                        })
                    breakpoint()
                    const recordingsIndex = query.select?.indexOf('matched_recordings') ?? -1
                    const recordings: { session_id?: string }[] =
                        recordingsIndex < 0 ? [] : response.results.flatMap((row) => row[recordingsIndex] ?? [])
                    return {
                        query,
                        sql: response.hogql,
                        sessionIds: [
                            ...new Set(recordings.flatMap(({ session_id }) => (session_id ? [session_id] : []))),
                        ],
                    }
                },
            },
        ],
    })),
    selectors({
        selectedResult: [
            (s) => [s.result, (_, props) => props.query],
            (result: ActorResult | null, query: ActorsQuery | null): ActorResult | null =>
                result && objectsEqual(result.query, query) ? result : null,
        ],
    }),
    afterMount(({ actions }) => actions.loadResult()),
    propsChanged(({ actions, props }, previousProps) => {
        if (!objectsEqual(props.query, previousProps.query)) {
            actions.loadResult()
        }
    }),
])