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.

5.1 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { RetainedValues } from 'lib/utils/retainedValues'
import { projectLogic } from 'scenes/projectLogic'

import { FeatureFlagConfig, MultivariateFlagVariant } from '~/types'

import { isV1FeatureFlagConfig } from './featureFlagConfigFormat'
import { featureFlagsList } from './generated/api'
import { FeatureFlagsListArchived, type FeatureFlagApi } from './generated/api.schemas'

const FLAG_LOOKUP_TTL_MS = 60 * 1000

const retainedFlagLookups = new RetainedValues<{ flag: FeatureFlagApi | null }>({
    maxEntries: 200,
    ttlMs: FLAG_LOOKUP_TTL_MS,
})

export function forgetFlagLookup(flagKey: string): void {
    retainedFlagLookups.delete(flagKey)
}

export interface FeatureFlagSummaryLogicProps {
    flagKey: string
}

export interface FeatureFlagSummary {
    active: boolean
    archived: boolean
    variants: MultivariateFlagVariant[] | null
    conditionCount: number | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagSummaryLogicValues {
    currentProjectId: number | null // projectLogic
    flag: FeatureFlagApi | null
    flagLoadFailed: boolean
    flagLoading: boolean
    summary: FeatureFlagSummary | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagSummaryLogicActions {
    loadFlag: (_: void) => void
    loadFlagFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadFlagSuccess: (
        flag: FeatureFlagApi | null,
        payload?: void
    ) => {
        flag: FeatureFlagApi | null
        payload?: void
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagSummaryLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        summary: (flag: FeatureFlagApi | null) => FeatureFlagSummary | null
    }
}

export type featureFlagSummaryLogicType = MakeLogicType<
    featureFlagSummaryLogicValues,
    featureFlagSummaryLogicActions,
    FeatureFlagSummaryLogicProps,
    featureFlagSummaryLogicMeta
>

/** A short overview of the flag behind a `$feature/<key>` property, for its definition popover. */
export const featureFlagSummaryLogic = kea<featureFlagSummaryLogicType>([
    props({} as FeatureFlagSummaryLogicProps),
    key((props) => props.flagKey),
    path((key) => ['products', 'feature_flags', 'frontend', 'featureFlagSummaryLogic', key]),
    connect(() => ({ values: [projectLogic, ['currentProjectId']] })),
    loaders(({ props, values }) => ({
        flag: [
            null as FeatureFlagApi | null,
            {
                loadFlag: async (_: void, breakpoint) => {
                    // A pointer that sweeps across `$feature/` rows mounts this logic for each row it crosses.
                    await breakpoint(300)
                    if (!values.currentProjectId) {
                        return null
                    }
                    const projectId = String(values.currentProjectId)
                    // The API matches the key case-insensitively, but flag keys that differ only by case can both exist.
                    const findFlag = async (archived?: FeatureFlagsListArchived): Promise<FeatureFlagApi | null> =>
                        (await featureFlagsList(projectId, { key: props.flagKey, archived })).results.find(
                            (flag) => flag.key === props.flagKey
                        ) ?? null
                    // The list leaves out archived flags unless asked, and old events can still carry their key.
                    const flag = (await findFlag()) ?? (await findFlag(FeatureFlagsListArchived.True))
                    retainedFlagLookups.set(props.flagKey, { flag })
                    return flag
                },
            },
        ],
    })),
    reducers({
        flagLoadFailed: [
            false,
            {
                loadFlag: () => false,
                loadFlagSuccess: () => false,
                loadFlagFailure: () => true,
            },
        ],
    }),
    selectors({
        summary: [
            (s) => [s.flag],
            (flag: FeatureFlagApi | null): FeatureFlagSummary | null => {
                if (!flag) {
                    return null
                }
                const filters = flag.filters as FeatureFlagConfig | undefined
                const isV1 = !!filters && isV1FeatureFlagConfig(filters)
                return {
                    active: !!flag.active,
                    archived: !!flag.archived,
                    variants: isV1 ? (filters.multivariate?.variants ?? []) : null,
                    conditionCount: isV1 ? (filters.groups?.length ?? 0) : null,
                }
            },
        ],
    }),
    afterMount(({ actions, props }) => {
        const retained = retainedFlagLookups.get(props.flagKey)
        if (retained) {
            actions.loadFlagSuccess(retained.flag)
        } else {
            actions.loadFlag()
        }
    }),
])