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.

10.7 KB
Raw Blame
import { deepEqual as equal } from 'fast-equals'
import { MakeLogicType, actions, connect, kea, key, listeners, path, reducers, selectors } from 'kea'
import { urlToAction } from 'kea-router'
import { UrlToActionPayload } from 'kea-router/lib/types'

import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
import { objectsEqual } from 'lib/utils/objects'
import {
    applyTestAccountFilter,
    getDefaultEventsSceneQuery,
    isUnnamedEventLookup,
} from 'scenes/activity/explore/defaults'
import {
    FEATURE_FLAG_CALLED_EVENT,
    reachesPastFlagEvaluationsRetention,
    readsFlagEvaluationsTable,
    storesFlagCallsOutsideEvents,
} from 'scenes/feature-flags/flagEvaluationsTable'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { getDefaultEventsQueryForTeam } from '~/queries/nodes/DataTable/defaultEventsQuery'
import { performQuery } from '~/queries/query'
import { isDataTableNode } from '~/queries/schema/node-guards'
import { DataTableNode, EventsQuery, Node, ProductKey } from '~/queries/schema/schema-general'
import { isEventsQuery } from '~/queries/utils'
import { ActivityTab, Breadcrumb } from '~/types'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { TeamPublicType, TeamType } from '../../../types'

export type FlagCallsNote = 'stored-separately' | 'retention'

// Mirrors EventsQueryRunner._list_table, which reads flag_evaluations only for a list of nothing but flag calls.
function listsOnlyFlagCalls({ source, actionId, actionSteps, event, events }: EventsQuery): boolean {
    if (source || actionId || actionSteps?.length) {
        return false
    }
    const eventNames = [event, ...(events ?? [])].filter(Boolean)
    return eventNames.length > 0 && eventNames.every((name) => name === FEATURE_FLAG_CALLED_EVENT)
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface eventsSceneLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    filterTestAccountsDefault: boolean // filterTestAccountsDefaultsLogic
    savedQueryFor: (tabId: string | undefined, sceneKey: string) => Node | null // tabUiStateLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    breadcrumbs: Breadcrumb[]
    defaultQuery: DataTableNode
    flagCallsNote: FlagCallsNote | null
    query: DataTableNode | Node<Record<string, any>>
    savedQuery: Node | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface eventsSceneLogicActions {
    setSavedQueryForTab: (
        tabId: string | undefined,
        sceneKey: string,
        query: Node<Record<string, any>> | null
    ) => {
        query: Node<Record<string, any>> | null
        sceneKey: string
        tabId: string
    } // tabUiStateLogic
    nameFlagCallLookup: (query: Node) => {
        query: Node<Record<string, any>>
    }
    setQuery: (query: Node) => {
        query: Node<Record<string, any>>
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface eventsSceneLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        defaultQuery: (
            currentTeam: TeamPublicType | TeamType | null,
            filterTestAccountsDefault: boolean
        ) => DataTableNode
        query: (
            savedQuery: Node<Record<string, any>> | null,
            defaultQuery: DataTableNode
        ) => DataTableNode | Node<Record<string, any>>
        flagCallsNote: (
            currentTeam: TeamPublicType | TeamType | null,
            query: DataTableNode | Node<Record<string, any>>
        ) => FlagCallsNote | null
    }
}

export type eventsSceneLogicType = MakeLogicType<
    eventsSceneLogicValues,
    eventsSceneLogicActions,
    Record<string, any>,
    eventsSceneLogicMeta
>

export const eventsSceneLogic = kea<eventsSceneLogicType>([
    key(() => 'scene'),
    path((key) => ['scenes', 'events', 'eventsSceneLogic', key]),
    connect(() => ({
        values: [
            teamLogic,
            ['currentTeam'],
            featureFlagLogic,
            ['featureFlags'],
            filterTestAccountsDefaultsLogic,
            ['filterTestAccountsDefault'],
            tabUiStateLogic,
            ['savedQueryFor'],
        ],
        actions: [tabUiStateLogic, ['setSavedQueryForTab']],
    })),

    actions({
        // The URL holds the query as JSON, which drops keys set to undefined. A date edit writes before: undefined.
        // The scene stores the query in its JSON form, so that the scene's own URL update matches the stored query.
        setQuery: (query: Node) => ({ query: JSON.parse(JSON.stringify(query)) as Node }),
        nameFlagCallLookup: (query: Node) => ({ query }),
    }),
    reducers({ savedQuery: [null as Node | null, { setQuery: (_, { query }) => query }] }),
    listeners(({ actions, values }) => ({
        setQuery: ({ query }) => {
            const isDefault = objectsEqual(query, values.defaultQuery)
            actions.setSavedQueryForTab(undefined, 'events', isDefault ? null : query)
        },
        // A lookup that names no event reads the events table. On flag_evaluations_mode 2 that table holds no flag call.
        // This listener runs the lookup again with the flag call event, which reads flag_evaluations.
        // It names the event when that query finds the row.
        // Only a query in the URL dispatches this listener. An edit in the open scene does not dispatch it.
        // A reload after the user clears the event runs the check again, because the URL then holds the cleared lookup.
        nameFlagCallLookup: async ({ query }, breakpoint) => {
            if (
                !storesFlagCallsOutsideEvents(values.currentTeam) ||
                !isDataTableNode(query) ||
                !isEventsQuery(query.source) ||
                !isUnnamedEventLookup(query.source)
            ) {
                return
            }
            const namedSource: EventsQuery = { ...query.source, event: FEATURE_FLAG_CALLED_EVENT }
            const namedQuery: DataTableNode = { ...query, source: namedSource }
            // performQuery reports a failure. On a failure the lookup keeps reading the events table.
            const response = await performQuery({
                ...namedSource,
                select: ['uuid'],
                // An empty order skips the runner's presorted path, which reads flag_evaluations two times.
                orderBy: [],
                limit: 1,
                tags: { productKey: ProductKey.FEATURE_FLAGS },
            }).catch(() => null)
            breakpoint()
            if (response?.results.length && objectsEqual(values.query, query)) {
                actions.setQuery(namedQuery)
            }
        },
    })),
    selectors({
        defaultQuery: [
            (s) => [s.currentTeam, s.filterTestAccountsDefault],
            (
                currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType,
                filterTestAccountsDefault: boolean
            ): DataTableNode => {
                const defaultSourceForTeam = currentTeam && getDefaultEventsQueryForTeam(currentTeam)
                const defaultForScene = getDefaultEventsSceneQuery()
                const base = defaultSourceForTeam
                    ? { ...defaultForScene, source: defaultSourceForTeam }
                    : defaultForScene
                return {
                    ...applyTestAccountFilter(base, currentTeam, filterTestAccountsDefault),
                    showPropertyFilter: true,
                }
            },
        ],
        query: [
            (s) => [s.savedQuery, s.defaultQuery],
            (savedQuery: Node | null, defaultQuery: DataTableNode) => savedQuery || defaultQuery,
        ],
        flagCallsNote: [
            (s) => [s.currentTeam, s.query],
            (currentTeam: TeamPublicType | TeamType | null, query: DataTableNode | Node): FlagCallsNote | null => {
                if (
                    !readsFlagEvaluationsTable(currentTeam) ||
                    !isDataTableNode(query) ||
                    !isEventsQuery(query.source)
                ) {
                    return null
                }
                if (!listsOnlyFlagCalls(query.source)) {
                    return storesFlagCallsOutsideEvents(currentTeam) ? 'stored-separately' : null
                }
                const { after } = query.source
                // The runner reads a missing start as the last 24 hours. The retention window covers that range.
                return after && reachesPastFlagEvaluationsRetention(after) ? 'retention' : null
            },
        ],
        breadcrumbs: [
            () => [],
            (): Breadcrumb[] => [
                {
                    key: Scene.ExploreEvents,
                    name: sceneConfigurations[Scene.ExploreEvents].name,
                    iconType: sceneConfigurations[Scene.ExploreEvents].iconType || 'default_icon_type',
                },
            ],
        ],
    }),
    trackedActionToUrl(({ values }) => ({
        setQuery: () => [
            urls.activity(ActivityTab.ExploreEvents),
            {},
            objectsEqual(values.query, values.defaultQuery) ? {} : { q: values.query },
            { replace: true },
        ],
    })),

    urlToAction(({ actions, values }) => {
        const eventsQueryHandler: UrlToActionPayload[keyof UrlToActionPayload] = (_, __, { q: queryParam }): void => {
            if (!equal(queryParam, values.query)) {
                // nothing in the URL
                if (!queryParam) {
                    // restore from the persisted query if present, else fall back to default
                    const persisted = values.savedQueryFor(undefined, 'events')
                    const target = persisted ?? values.defaultQuery
                    if (!objectsEqual(values.query, target)) {
                        actions.setQuery(target)
                    }
                } else {
                    if (typeof queryParam === 'object') {
                        actions.setQuery(queryParam)
                        actions.nameFlagCallLookup(queryParam)
                    } else {
                        lemonToast.error('Invalid query in URL')
                        console.error({ queryParam })
                    }
                }
            }
        }
        return {
            [urls.activity(ActivityTab.ExploreEvents)]: eventsQueryHandler,
        }
    }),
])