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.3 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'

import { RetainedValues } from 'lib/utils/retainedValues'
import { BlastRadiusError, toBlastRadiusError } from 'scenes/feature-flags/featureFlagReleaseConditionsLogic'
import { isIncompleteRulesV2Condition } from 'scenes/feature-flags/featureFlagRulesV2Draft'
import { projectLogic } from 'scenes/projectLogic'

import { AnyPropertyFilter } from '~/types'

import { featureFlagsUserBlastRadiusCreate } from './generated/api'

export interface RulesV2MatchCount {
    affected: number
    total: number
}

export interface RulesV2MatchCountLogicProps {
    /** The rule's targeting properties, serialized, so equal targeting shares one request. */
    propertiesKey: string
    groupTypeIndex: number | null
}

// The estimate is a slow query, and the view and the editor ask for the same targeting, so a pending or recent
// request is shared.
const recentMatchCounts = new RetainedValues<Promise<RulesV2MatchCount>>({
    maxEntries: 200,
    ttlMs: 5 * 60 * 1000,
    scopeToProject: false, // the key already names the project
})

function sharedMatchCount(
    projectId: number | null,
    { propertiesKey, groupTypeIndex }: RulesV2MatchCountLogicProps,
    properties: AnyPropertyFilter[]
): Promise<RulesV2MatchCount> {
    const cacheKey = `${projectId}:${groupTypeIndex}:${propertiesKey}`
    const cached = recentMatchCounts.get(cacheKey)
    if (cached) {
        return cached
    }
    const promise = featureFlagsUserBlastRadiusCreate(String(projectId), {
        condition: { properties },
        group_type_index: groupTypeIndex,
    }).then(({ affected, total }) => ({ affected, total }))
    recentMatchCounts.set(cacheKey, promise)
    promise.catch(() => {
        if (recentMatchCounts.get(cacheKey) === promise) {
            recentMatchCounts.delete(cacheKey)
        }
    })
    return promise
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface rulesV2MatchCountLogicValues {
    currentProjectId: number | null // projectLogic
    countable: boolean
    matchCount: RulesV2MatchCount | null
    matchCountError: BlastRadiusError | null
    properties: AnyPropertyFilter[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface rulesV2MatchCountLogicActions {
    loadMatchCount: () => {
        value: true
    }
    loadMatchCountFailure: (error: BlastRadiusError) => {
        error: BlastRadiusError
    }
    loadMatchCountSuccess: (matchCount: RulesV2MatchCount) => {
        matchCount: RulesV2MatchCount
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface rulesV2MatchCountLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        properties: (arg: any) => AnyPropertyFilter[]
        countable: (properties: AnyPropertyFilter[]) => boolean
    }
}

export type rulesV2MatchCountLogicType = MakeLogicType<
    rulesV2MatchCountLogicValues,
    rulesV2MatchCountLogicActions,
    RulesV2MatchCountLogicProps,
    rulesV2MatchCountLogicMeta
>

/**
 * How many persons or groups a rule's targeting matches, from the estimate the v1 release conditions show. An estimate is a
 * hint, so a failure shows inline with a retry instead of a toast.
 */
export const rulesV2MatchCountLogic = kea<rulesV2MatchCountLogicType>([
    props({} as RulesV2MatchCountLogicProps),
    key(({ propertiesKey, groupTypeIndex }) => `${groupTypeIndex ?? 'persons'}:${propertiesKey}`),
    path((key) => ['products', 'feature_flags', 'frontend', 'rulesV2MatchCountLogic', key]),
    connect(() => ({ values: [projectLogic, ['currentProjectId']] })),
    actions({
        loadMatchCount: true,
        loadMatchCountSuccess: (matchCount: RulesV2MatchCount) => ({ matchCount }),
        loadMatchCountFailure: (error: BlastRadiusError) => ({ error }),
    }),
    reducers({
        matchCount: [
            null as RulesV2MatchCount | null,
            {
                loadMatchCount: () => null,
                loadMatchCountSuccess: (_, { matchCount }) => matchCount,
            },
        ],
        matchCountError: [
            null as BlastRadiusError | null,
            {
                loadMatchCount: () => null,
                loadMatchCountFailure: (_, { error }) => error,
            },
        ],
    }),
    selectors({
        properties: [
            () => [(_, props) => props.propertiesKey],
            (propertiesKey: string): AnyPropertyFilter[] => JSON.parse(propertiesKey),
        ],
        countable: [
            (s) => [s.properties],
            (properties: AnyPropertyFilter[]): boolean => !properties.some(isIncompleteRulesV2Condition),
        ],
    }),
    listeners(({ actions, props, values }) => ({
        loadMatchCount: async (_, breakpoint) => {
            let matchCount: RulesV2MatchCount
            try {
                matchCount = await sharedMatchCount(values.currentProjectId, props, values.properties)
            } catch (error) {
                breakpoint()
                actions.loadMatchCountFailure(toBlastRadiusError(error))
                return
            }
            breakpoint()
            actions.loadMatchCountSuccess(matchCount)
        },
    })),
    afterMount(({ actions, values }) => {
        if (values.countable) {
            actions.loadMatchCount()
        }
    }),
])