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.

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

import { teamLogic } from 'scenes/teamLogic'

import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import { logsGroupByCreate } from 'products/logs/frontend/generated/api'
import type {
    _LogPropertyFilterApi,
    _LogsGroupByGroupApi,
    _LogsGroupByResponseApi,
    OrderGroupsByEnumApi,
} from 'products/logs/frontend/generated/api.schemas'

import type { DateRange } from '../../../../../frontend/src/queries/schema/schema-general'
import type { UniversalFiltersGroup } from '../../../../../frontend/src/types'
import type { LogsViewerGroupBy } from '../LogsViewer/config/logsViewerConfigLogic'
import type { LogsViewerFilters } from '../LogsViewer/config/types'

export interface LogsGroupByLogicProps {
    id: string
}

const EMPTY_RESPONSE: _LogsGroupByResponseApi = {
    groups: [],
    total_groups: 0,
    total_logs: 0,
    truncated: false,
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsGroupByLogicValues {
    groupBys: LogsViewerGroupBy[] // logsViewerConfigLogic
    filters: LogsViewerFilters // logsViewerFiltersLogic
    personId: string | undefined // logsViewerFiltersLogic
    queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
    sessionId: string | undefined // logsViewerFiltersLogic
    utcDateRange: {
        date_from: string | null | undefined
        date_to: string | null | undefined
        explicitDate: boolean | null | undefined
    } // logsViewerFiltersLogic
    currentTeamId: number | null // teamLogic
    groupByError: string | null
    groupByResponse: _LogsGroupByResponseApi
    groupByResponseLoading: boolean
    groups: _LogsGroupByGroupApi[]
    orderGroupsBy: OrderGroupsByEnumApi
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsGroupByLogicActions {
    addGroupBy: (groupBy: LogsViewerGroupBy) => {
        groupBy: LogsViewerGroupBy
    } // logsViewerConfigLogic
    removeGroupByAt: (index: number) => {
        index: number
    } // logsViewerConfigLogic
    replaceGroupByAt: (
        index: number,
        groupBy: LogsViewerGroupBy
    ) => {
        groupBy: LogsViewerGroupBy
        index: number
    } // logsViewerConfigLogic
    setGroupBys: (groupBys: LogsViewerGroupBy[]) => {
        groupBys: LogsViewerGroupBy[]
    } // logsViewerConfigLogic
    bumpFacetRefresh: () => {
        value: true
    } // logsViewerFiltersLogic
    setDateRange: (dateRange: DateRange) => {
        dateRange: DateRange
    } // logsViewerFiltersLogic
    setFilterGroup: (
        filterGroup: UniversalFiltersGroup,
        openFilterOnInsert?: boolean | undefined
    ) => {
        filterGroup: UniversalFiltersGroup
        openFilterOnInsert: boolean
    } // logsViewerFiltersLogic
    setFilters: (
        filters: Partial<LogsViewerFilters>,
        pushToHistory?: boolean | undefined
    ) => {
        filters: Partial<LogsViewerFilters>
        pushToHistory: boolean
    } // logsViewerFiltersLogic
    setPinnedFilters: (pinnedFilters: UniversalFiltersGroup | undefined) => {
        pinnedFilters: UniversalFiltersGroup | undefined
    } // logsViewerFiltersLogic
    setSearchTerm: (searchTerm: string | undefined) => {
        searchTerm: string | undefined
    } // logsViewerFiltersLogic
    zoomDateRange: (multiplier: number) => {
        multiplier: number
    } // logsViewerFiltersLogic
    loadGroups: (debounceMs?: number) => number
    loadGroupsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadGroupsSuccess: (
        groupByResponse: _LogsGroupByResponseApi,
        payload?: number
    ) => {
        groupByResponse: _LogsGroupByResponseApi
        payload?: number
    }
    setOrderGroupsBy: (orderGroupsBy: OrderGroupsByEnumApi) => {
        orderGroupsBy: OrderGroupsByEnumApi
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsGroupByLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        groups: (groupByResponse: _LogsGroupByResponseApi, groupByError: string | null) => _LogsGroupByGroupApi[]
    }
}

export type logsGroupByLogicType = MakeLogicType<
    logsGroupByLogicValues,
    logsGroupByLogicActions,
    LogsGroupByLogicProps,
    logsGroupByLogicMeta
>

// Keyed by the Viewer's `id`: the logic mounts only while a grouping key is active (the
// Viewer conditionally renders <LogsGroupByResults/>), so loading on mount + reloading on
// the shared filter actions never runs the aggregation while the user is in plain Logs mode.
export const logsGroupByLogic = kea<logsGroupByLogicType>([
    props({ id: 'default' } as LogsGroupByLogicProps),
    key((props) => props.id),
    path((key) => ['products', 'logs', 'frontend', 'components', 'LogsGroupBy', 'logsGroupByLogic', key]),

    connect((props: LogsGroupByLogicProps) => ({
        values: [
            teamLogic,
            ['currentTeamId'],
            logsViewerFiltersLogic({ id: props.id }),
            ['filters', 'utcDateRange', 'queryFilterGroup', 'personId', 'sessionId'],
            logsViewerConfigLogic({ id: props.id }),
            ['groupBys'],
        ],
        actions: [
            logsViewerFiltersLogic({ id: props.id }),
            [
                'setDateRange',
                'zoomDateRange',
                'setSearchTerm',
                'setFilters',
                'setFilterGroup',
                'setPinnedFilters',
                'bumpFacetRefresh',
            ],
            logsViewerConfigLogic({ id: props.id }),
            ['setGroupBys', 'addGroupBy', 'removeGroupByAt', 'replaceGroupByAt'],
        ],
    })),

    actions({
        setOrderGroupsBy: (orderGroupsBy: OrderGroupsByEnumApi) => ({ orderGroupsBy }),
    }),

    loaders(({ values }) => ({
        groupByResponse: [
            EMPTY_RESPONSE,
            {
                loadGroups: async (debounceMs: number = 0, breakpoint) => {
                    await breakpoint(debounceMs)
                    if (values.groupBys.length === 0) {
                        return EMPTY_RESPONSE
                    }
                    return await logsGroupByCreate(String(values.currentTeamId), {
                        query: {
                            dateRange: values.utcDateRange,
                            searchTerm: values.filters.searchTerm || undefined,
                            // Same scoping as Logs/Patterns: `queryFilterGroup` folds in any pinned
                            // filters from an embedded viewer, so a scoped viewer can't aggregate
                            // project-wide logs.
                            filterGroup: values.queryFilterGroup as unknown as _LogPropertyFilterApi[],
                            // Person and session scoping travel as their own fields, not in the
                            // filter group, so they have to be sent explicitly here too.
                            personId: values.personId,
                            sessionId: values.sessionId,
                            groupBys: values.groupBys,
                            orderGroupsBy: values.orderGroupsBy,
                        },
                    })
                },
            },
        ],
    })),

    reducers({
        orderGroupsBy: [
            'log_count' as OrderGroupsByEnumApi,
            {
                setOrderGroupsBy: (_, { orderGroupsBy }) => orderGroupsBy,
            },
        ],
        // A failed aggregation (e.g. the scan exceeding its byte budget) must surface as an
        // error, not render as "no groups found" — that would misrepresent the data.
        groupByError: [
            null as string | null,
            {
                loadGroups: () => null,
                loadGroupsSuccess: () => null,
                loadGroupsFailure: (_, { error }) => error ?? 'Grouping failed',
            },
        ],
    }),

    selectors({
        // Clear groups when the load fails so LemonTable's emptyState (and the error) shows
        // instead of stale rows — kea-loaders leaves groupByResponse untouched on failure.
        groups: [
            (s) => [s.groupByResponse, s.groupByError],
            (response: _LogsGroupByResponseApi, error: string | null): _LogsGroupByGroupApi[] =>
                error ? [] : response.groups,
        ],
    }),

    listeners(({ actions }) => {
        // Debounced so a multi-filter change or search typing collapses into one request —
        // kea's breakpoint cancels superseded loads before the fetch fires.
        const reload = (): void => actions.loadGroups(300)
        return {
            setDateRange: reload,
            zoomDateRange: reload,
            setSearchTerm: reload,
            setFilters: reload,
            setFilterGroup: reload,
            setPinnedFilters: reload,
            // Immediate: changing the grouping dimensions or ranking column is a deliberate click.
            // The refresh button fires `bumpFacetRefresh` through the shared filters logic, so
            // the groups re-aggregate with the logs table instead of showing the earlier result.
            bumpFacetRefresh: () => actions.loadGroups(),
            setGroupBys: () => actions.loadGroups(),
            addGroupBy: () => actions.loadGroups(),
            removeGroupByAt: () => actions.loadGroups(),
            replaceGroupByAt: () => actions.loadGroups(),
            setOrderGroupsBy: () => actions.loadGroups(),
        }
    }),

    afterMount(({ actions }) => {
        actions.loadGroups()
    }),
])