: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { LogicWrapper, MakeLogicType, actions, connect, kea, key, path, props, reducers, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { Noun, groupsModel } from '~/models/groupsModel'
import { DateRange } from '~/queries/schema/schema-general'
import { DateMappingOption, FeatureFlagType, TeamPublicType, TeamType } from '~/types'
import { featureFlagLogic } from './featureFlagLogic'
import {
DEFAULT_USAGE_DATE_RANGE,
FlagUsageChart,
FlagUsageQueryOptions,
buildEnrichedUsageCharts,
buildFlagCalledTotalVolumeChart,
buildFlagCalledUniqueCallersChart,
buildFlagEvaluationsTotalVolumeChart,
buildFlagEvaluationsUniqueCallersChart,
clampToFlagEvaluationsRetention,
flagEvaluationsDateOptions,
} from './featureFlagUsageQueries'
import { readsFlagEvaluationsTable } from './flagEvaluationsTable'
// The Usage tab only renders for persisted flags, so unlike featureFlagLogic this
// logic never mounts for 'new'/'link' ids.
export interface FeatureFlagUsageLogicProps {
id: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagUsageLogicValues {
featureFlag: FeatureFlagType // featureFlagLogic
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
currentTeam: TeamPublicType | TeamType | null // teamLogic
aggregationGroupTypeIndex: number | null | undefined
dateOptions: DateMappingOption[] | undefined
dateRange: DateRange
flagKey: string
hasEnrichedAnalytics: boolean | undefined
readsFlagEvaluationsTable: boolean
selectedDateRange: DateRange
usageCharts: FlagUsageChart[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagUsageLogicActions {
setDates: (
dateFrom: string | null,
dateTo: string | null
) => {
dateFrom: string | null
dateTo: string | null
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagUsageLogicMeta {
key: number
__keaTypeGenInternalSelectorTypes: {
flagKey: (featureFlag: FeatureFlagType) => string
aggregationGroupTypeIndex: (featureFlag: FeatureFlagType) => number | null | undefined
hasEnrichedAnalytics: (featureFlag: FeatureFlagType) => boolean | undefined
readsFlagEvaluationsTable: (currentTeam: TeamPublicType | TeamType | null) => boolean
dateRange: (selectedDateRange: DateRange, readsFlagEvaluationsTable: boolean) => DateRange
dateOptions: (readsFlagEvaluationsTable: boolean) => DateMappingOption[] | undefined
usageCharts: (
flagKey: string,
aggregationGroupTypeIndex: number | null | undefined,
hasEnrichedAnalytics: boolean | undefined,
dateRange: DateRange,
readsFlagEvaluationsTable: boolean,
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
) => FlagUsageChart[]
}
}
export type featureFlagUsageLogicType = MakeLogicType<
featureFlagUsageLogicValues,
featureFlagUsageLogicActions,
FeatureFlagUsageLogicProps,
featureFlagUsageLogicMeta
>
export const featureFlagUsageLogic: LogicWrapper<featureFlagUsageLogicType> = kea<featureFlagUsageLogicType>([
props({} as FeatureFlagUsageLogicProps),
key(({ id }) => id),
path((key) => ['scenes', 'feature-flags', 'featureFlagUsageLogic', key]),
connect((props: FeatureFlagUsageLogicProps) => ({
values: [
featureFlagLogic(props),
['featureFlag'],
groupsModel,
['aggregationLabel'],
teamLogic,
['currentTeam'],
],
})),
actions({
setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
}),
reducers({
selectedDateRange: [
DEFAULT_USAGE_DATE_RANGE,
{
setDates: (_, { dateFrom, dateTo }) => ({ date_from: dateFrom, date_to: dateTo }),
},
],
}),
selectors({
// Split out of `featureFlag` so a reload that only touches an unrelated field (name,
// description, ...) doesn't change these inputs and cascade into rebuilding every chart.
flagKey: [(s) => [s.featureFlag], (featureFlag: FeatureFlagType): string => featureFlag.key],
aggregationGroupTypeIndex: [
(s) => [s.featureFlag],
(featureFlag: FeatureFlagType): number | null | undefined =>
featureFlag.filters?.aggregation_group_type_index,
],
hasEnrichedAnalytics: [
(s) => [s.featureFlag],
(featureFlag: FeatureFlagType): boolean | undefined => featureFlag.has_enriched_analytics,
],
// The backend adds flag_evaluations to the HogQL catalog whenever the organization's stored mode is
// above Events. This field is above Events only when the stored mode is, so a query here never hits
// a missing table.
readsFlagEvaluationsTable: [
(s) => [s.currentTeam],
(currentTeam: TeamPublicType | TeamType | null): boolean => readsFlagEvaluationsTable(currentTeam),
],
// flag_evaluations holds 90 days, so a longer range would show fewer rows than the events
// table. The clamp covers the date picker, a shared link, and a range typed into the URL.
dateRange: [
(s) => [s.selectedDateRange, s.readsFlagEvaluationsTable],
(selectedDateRange: DateRange, readsFlagEvaluationsTable: boolean): DateRange =>
readsFlagEvaluationsTable ? clampToFlagEvaluationsRetention(selectedDateRange) : selectedDateRange,
],
dateOptions: [
(s) => [s.readsFlagEvaluationsTable],
(readsFlagEvaluationsTable: boolean): DateMappingOption[] | undefined =>
readsFlagEvaluationsTable ? flagEvaluationsDateOptions() : undefined,
],
usageCharts: [
(s) => [
s.flagKey,
s.aggregationGroupTypeIndex,
s.hasEnrichedAnalytics,
s.dateRange,
s.readsFlagEvaluationsTable,
s.aggregationLabel,
],
(
flagKey: string,
aggregationGroupTypeIndex: number | null | undefined,
hasEnrichedAnalytics: boolean | undefined,
dateRange: DateRange,
readsFlagEvaluationsTable: boolean,
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun
): FlagUsageChart[] => {
const options: FlagUsageQueryOptions = {
flagKey,
aggregationGroupTypeIndex,
callerNoun: aggregationLabel(aggregationGroupTypeIndex, true),
dateRange,
}
// The enriched-analytics charts stay on the events table either way: $feature_view
// and $feature_interaction are not flag evaluations, so that table does not hold them.
const charts: FlagUsageChart[] = readsFlagEvaluationsTable
? [buildFlagEvaluationsTotalVolumeChart(options), buildFlagEvaluationsUniqueCallersChart(options)]
: [buildFlagCalledTotalVolumeChart(options), buildFlagCalledUniqueCallersChart(options)]
if (hasEnrichedAnalytics) {
charts.push(...buildEnrichedUsageCharts(options))
}
return charts
},
],
}),
actionToUrl(({ values }) => ({
setDates: () => {
const searchParams = { ...router.values.searchParams }
for (const [param, value] of [
['date_from', values.dateRange.date_from],
['date_to', values.dateRange.date_to],
] as const) {
if (value) {
searchParams[param] = value
} else {
delete searchParams[param]
}
}
// Replace rather than push: featureFlagLogic reloads the flag on a PUSH to this pathname.
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
},
})),
urlToAction(({ actions, props, values }) => ({
[urls.featureFlag(props.id)]: (_, searchParams) => {
// Absent params mean "use the default range", not "clear the range". A range is only
// read off the URL when at least one of the two params is present; otherwise both
// fall back to the default, matching the DateRange convention of a null date_to.
const useDefaultRange = !searchParams.date_from && !searchParams.date_to
const dateFrom = useDefaultRange
? (DEFAULT_USAGE_DATE_RANGE.date_from ?? null)
: (searchParams.date_from ?? null)
const dateTo = useDefaultRange ? (DEFAULT_USAGE_DATE_RANGE.date_to ?? null) : (searchParams.date_to ?? null)
if (dateFrom !== values.dateRange.date_from || dateTo !== values.dateRange.date_to) {
actions.setDates(dateFrom, dateTo)
}
},
})),
])