: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 { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import { teamLogic } from 'scenes/teamLogic'
import { UniversalFiltersGroup } from '~/types'
import { tracingFiltersLogic, TracingFiltersLogicProps } from 'products/tracing/frontend/tracingFiltersLogic'
import { tracingSpansAttributeBreakdownCreate } from '../../generated/api'
import {
_SpanPropertyFilterApi,
_SpanPropertyFilterOperatorEnumApi,
_TracingAttributeBreakdownRowApi,
SpanPropertyTypeEnumApi,
} from '../../generated/api.schemas'
import { facetRailLogic } from './facetRailLogic'
import { FacetConfig, facetScopeSignature, facetSourceKey, innerFilters } from './facets'
export interface FacetValuesLogicProps {
id: string
/** Already resolved by resolveFacets, so `source` points at the key the tenant emits. */
facet: FacetConfig
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetValuesLogicValues {
collapsedFacets: string[] // facetRailLogic
currentTeamId: number | null // teamLogic
queryFilterGroup: UniversalFiltersGroup // tracingFiltersLogic
serviceNames: string[] // tracingFiltersLogic
utcDateRange: {
date_from: string | null | undefined
date_to: string
} // tracingFiltersLogic
collapsed: boolean
facetSearch: string
facetValues: _TracingAttributeBreakdownRowApi[]
facetValuesLoading: boolean
fetchFailed: boolean
fetchSignature: string
fetchedSignature: string | null
scopeSignature: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetValuesLogicActions {
clearFetchedSignature: () => {
value: true
}
loadFacetValues: (signature: string) => {
signature: string
}
loadFacetValuesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadFacetValuesSuccess: (
facetValues: _TracingAttributeBreakdownRowApi[],
payload?: {
signature: string
}
) => {
facetValues: _TracingAttributeBreakdownRowApi[]
payload?: {
signature: string
}
}
retryFacetValues: () => {
value: true
}
setFacetSearch: (search: string) => {
search: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetValuesLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
collapsed: (collapsedFacets: string[], arg: any) => boolean
scopeSignature: (
utcDateRange: {
date_from: string | null | undefined
date_to: string
},
serviceNames: string[],
queryFilterGroup: UniversalFiltersGroup,
currentTeamId: number | null,
arg: any
) => string
fetchSignature: (scopeSignature: string, facetSearch: string) => string
}
}
export type facetValuesLogicType = MakeLogicType<
facetValuesLogicValues,
facetValuesLogicActions,
FacetValuesLogicProps,
facetValuesLogicMeta
>
/**
* One facet's values + counts, cross-filtered server-side: the results reflect every active filter
* except this facet's own selection, which excludeBreakdownFilter strips from the query.
*
* One instance per facet, so each fetches on its own schedule and holds its own loading and error
* state. What it fetches on is `fetchSignature` — the breakdown scope with this facet's own filters
* removed, plus its type-ahead — so clicking a value here re-scopes the *other* facets and leaves
* this list alone, and a facet whose section is collapsed doesn't fetch until it's expanded.
*/
export const facetValuesLogic = kea<facetValuesLogicType>([
props({} as FacetValuesLogicProps),
// The resolved source key is part of the key: when alias resolution moves a facet onto another
// attribute spelling, that's a different breakdown, so it gets a fresh instance rather than the
// old key's values.
key((props) => `${props.id}-${props.facet.key}-${facetSourceKey(props.facet)}`),
path((key) => ['products', 'tracing', 'frontend', 'components', 'FacetRail', 'facetValuesLogic', key]),
connect((props: FacetValuesLogicProps) => ({
values: [
tracingFiltersLogic({ id: props.id } as TracingFiltersLogicProps),
['serviceNames', 'utcDateRange', 'queryFilterGroup'],
teamLogic,
['currentTeamId'],
facetRailLogic({ id: props.id }),
['collapsedFacets'],
],
})),
actions({
setFacetSearch: (search: string) => ({ search }),
// Declared here rather than left to the loader: the request is built from current values,
// and the signature payload is only there for the reducer below to record.
loadFacetValues: (signature: string) => ({ signature }),
clearFetchedSignature: true,
retryFacetValues: true,
}),
reducers({
facetSearch: [
'',
{
setFacetSearch: (_, { search }) => search,
},
],
// The signature the values in the store were fetched for. Set when the request goes out, not
// when it lands, so an overlapping trigger (e.g. expanding the facet mid-flight) doesn't
// restart the same request. Cleared on failure, and when collapsing abandons an in-flight
// load, so the next trigger retries rather than trusting values that never arrived.
fetchedSignature: [
null as string | null,
{
loadFacetValues: (_, { signature }) => signature,
loadFacetValuesFailure: () => null,
clearFetchedSignature: () => null,
},
],
// Drives this facet's inline error state, so one broken breakdown shows in place rather than
// blanking the rail.
fetchFailed: [
false,
{
loadFacetValuesSuccess: () => false,
loadFacetValuesFailure: () => true,
},
],
}),
loaders(({ props, values }) => ({
facetValues: [
[] as _TracingAttributeBreakdownRowApi[],
{
loadFacetValues: async (_, breakpoint) => {
await breakpoint(300)
// Collapsed while this was still debouncing: nobody can see the list, so drop the
// request. clearFetchedSignature has already run, so expanding refetches.
if (values.collapsed || !values.currentTeamId) {
return values.facetValues
}
// The endpoint takes the flat inner filter list. The stored filters carry the
// app-side enums (PropertyFilterType/PropertyOperator) which are nominally
// distinct from the generated string-union enums despite identical runtime
// values, so mapping onto the generated shape type-checks the field structure
// (key/value) while casting only the two enum fields.
const filterGroup: _SpanPropertyFilterApi[] = innerFilters(values.queryFilterGroup).map((f) => ({
key: f.key,
type: f.type as unknown as SpanPropertyTypeEnumApi,
operator: f.operator as unknown as _SpanPropertyFilterOperatorEnumApi,
value: f.value,
}))
const { source } = props.facet
const target =
source.type === 'column'
? { breakdownKey: source.column, breakdownType: SpanPropertyTypeEnumApi.Span }
: source.type === 'attribute'
? { breakdownKey: source.key, breakdownType: SpanPropertyTypeEnumApi.SpanAttribute }
: {
breakdownKey: source.key,
breakdownType: SpanPropertyTypeEnumApi.SpanResourceAttribute,
}
const response = await tracingSpansAttributeBreakdownCreate(String(values.currentTeamId), {
query: {
...target,
excludeBreakdownFilter: true,
dateRange: values.utcDateRange,
serviceNames: values.serviceNames ?? [],
facetSearch: values.facetSearch || undefined,
filterGroup,
},
})
// Bail out right after the round-trip: the rail (and this logic) unmounts when
// the user collapses it, and returning into a dead store throws rather than
// being discarded.
breakpoint()
return response.results
},
},
],
})),
selectors({
collapsed: [
(s) => [s.collapsedFacets, (_, p) => p.facet],
(collapsedFacets: string[], facet: FacetConfig): boolean => collapsedFacets.includes(facet.key),
],
// Everything that can change this facet's values, minus its own selection.
scopeSignature: [
(s) => [s.utcDateRange, s.serviceNames, s.queryFilterGroup, s.currentTeamId, (_, p) => p.facet],
(
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
},
serviceNames: string[],
queryFilterGroup: UniversalFiltersGroup,
currentTeamId: number | null,
facet: FacetConfig
): string => facetScopeSignature(facet, { currentTeamId, utcDateRange, serviceNames, queryFilterGroup }),
],
// One trigger for the one in-flight request: a scope change and a keystroke in this facet's
// search box supersede each other rather than racing.
fetchSignature: [
(s) => [s.scopeSignature, s.facetSearch],
(scopeSignature: string, facetSearch: string): string => `${scopeSignature}|${facetSearch}`,
],
}),
listeners(({ actions, values }) => ({
retryFacetValues: () => actions.loadFacetValues(values.fetchSignature),
})),
subscriptions(({ actions, values }) => {
// Subscriptions fire with their initial value, so this is also the mount fetch.
const loadIfStale = (): void => {
if (values.collapsed || values.fetchSignature === values.fetchedSignature) {
return
}
actions.loadFacetValues(values.fetchSignature)
}
return {
fetchSignature: loadIfStale,
collapsed: (collapsed: boolean) => {
if (collapsed) {
// The loader drops a still-debouncing load on collapse, so forget the signature it
// recorded — otherwise expanding would trust values that never arrived. Only when
// one is in flight: settled values stay valid for their signature.
if (values.facetValuesLoading) {
actions.clearFetchedSignature()
}
return
}
// Expanding fetches what it missed while collapsed — and nothing if the scope hasn't
// moved since.
loadIfStale()
},
}
}),
])