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.

16.3 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    beforeUnmount,
    connect,
    kea,
    listeners,
    path,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'

import api, { CountedPaginatedResponse } from 'lib/api'
import { ConcurrencyController } from 'lib/utils/concurrencyController'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { getCurrentExporterData } from '~/exporter/exporterViewLogic'
import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { CohortType, FilterLogicalOperator } from '~/types'

import * as cohortsApi from 'products/cohorts/frontend/generated/api'

import type { TeamPublicType, TeamType } from '../types'

const POLL_TIMEOUT = 5000

export function getReferencedCohortIds(query: unknown): number[] {
    const ids = new Set<number>()
    const add = (value: unknown): void => {
        for (const candidate of Array.isArray(value) ? value : [value]) {
            if (typeof candidate === 'number' || (typeof candidate === 'string' && /^\d+$/.test(candidate))) {
                const id = Number(candidate)
                if (Number.isSafeInteger(id) && id > 0) {
                    ids.add(id)
                }
            }
        }
    }
    const visit = (value: unknown): void => {
        if (!value || typeof value !== 'object') {
            return
        }
        if (Array.isArray(value)) {
            value.forEach(visit)
            return
        }
        const node = value as Record<string, unknown>
        if (node.type === 'cohort') {
            add(node.value)
        }
        if (node.breakdown_type === 'cohort') {
            add(node.breakdown)
        }
        Object.values(node).forEach(visit)
    }
    visit(query)
    return [...ids]
}

export function isIndividualInsightPath(pathname: string): boolean {
    const match = pathname.match(/^(?:\/project\/[^/]+)?\/insights\/([^/]+)(?:\/[^/]+){0,2}\/?$/)
    return !!match && match[1] !== 'quick-start'
}

export const COHORTS_PER_PAGE = 100

// The cohort list returns at most 1000 rows per request, so a full-list load reads every page.
const COHORTS_FULL_LIST_PAGE_SIZE = 1000

export interface CohortFilters {
    search?: string
    page?: number
}

export const DEFAULT_COHORT_FILTERS: CohortFilters = {
    search: undefined,
    page: 1,
}

async function loadAllCohortPages<T>(
    loadPage: (params: {
        limit: number
        offset: number
    }) => Promise<{ count: number; next?: string | null; results: T[] }>
): Promise<CountedPaginatedResponse<T>> {
    const results: T[] = []
    let count = 0
    let hasNextPage = true
    while (hasNextPage) {
        const page = await loadPage({ limit: COHORTS_FULL_LIST_PAGE_SIZE, offset: results.length })
        results.push(...page.results)
        count = page.count
        hasNextPage = !!page.next && page.results.length > 0
    }
    return { count, results }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface cohortsModelValues {
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    allCohorts: CountedPaginatedResponse<CohortType>
    allCohortsLoading: boolean
    cohortsById: Partial<Record<number | string, CohortType>>
    pollTimeout: number | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface cohortsModelActions {
    locationChanged: ({
        method,
        pathname,
        search,
        searchParams,
        hash,
        hashParams,
        initial,
        url,
        routerState,
    }: LocationChangedPayload) => {
        hash: string
        hashParams: Record<string, any>
        initial: boolean
        method: 'POP' | 'PUSH' | 'REPLACE'
        pathname: string
        routerState: Record<string, any>
        search: string
        searchParams: Record<string, any>
        url: string
    } // router
    cacheCohort: (cohort: CohortType) => {
        cohort: CohortType
    }
    cohortCreated: (cohort: CohortType) => {
        cohort: CohortType
    }
    deleteCohort: (cohort: Partial<CohortType>) => {
        cohort: Partial<CohortType>
    }
    hydrateAllCohortsFromExport: (cohorts: Pick<CohortType, 'id' | 'name'>[]) => {
        cohorts: Pick<CohortType, 'id' | 'name'>[]
    }
    loadAllCohorts: () => any
    loadAllCohortsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAllCohortsSuccess: (
        allCohorts: CountedPaginatedResponse<CohortType>,
        payload?: any
    ) => {
        allCohorts: CountedPaginatedResponse<CohortType>
        payload?: any
    }
    loadCohortsByIds: ({ ids }: { ids: number[] }) => {
        ids: number[]
    }
    loadCohortsByIdsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCohortsByIdsSuccess: (
        allCohorts: CountedPaginatedResponse<CohortType>,
        payload?: {
            ids: number[]
        }
    ) => {
        allCohorts: CountedPaginatedResponse<CohortType>
        payload?: {
            ids: number[]
        }
    }
    setPollTimeout: (pollTimeout: number | null) => {
        pollTimeout: number | null
    }
    updateCohort: (cohort: CohortType) => {
        cohort: CohortType
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface cohortsModelMeta {
    __keaTypeGenInternalSelectorTypes: {
        cohortsById: (allCohorts: CountedPaginatedResponse<CohortType>) => Partial<Record<number | string, CohortType>>
    }
}

export type cohortsModelType = MakeLogicType<
    cohortsModelValues,
    cohortsModelActions,
    Record<string, any>,
    cohortsModelMeta
>

export const cohortsModel = kea<cohortsModelType>([
    path(['models', 'cohortsModel']),
    connect(() => ({
        values: [teamLogic, ['currentTeam']],
        actions: [router, ['locationChanged']],
    })),
    actions(() => ({
        setPollTimeout: (pollTimeout: number | null) => ({ pollTimeout }),
        updateCohort: (cohort: CohortType) => ({ cohort }),
        cacheCohort: (cohort: CohortType) => ({ cohort }),
        deleteCohort: (cohort: Partial<CohortType>) => ({ cohort }),
        cohortCreated: (cohort: CohortType) => ({ cohort }),
        hydrateAllCohortsFromExport: (cohorts: Pick<CohortType, 'id' | 'name'>[]) => ({ cohorts }),
    })),
    loaders(({ actions, values, cache }) => ({
        allCohorts: {
            __default: { count: 0, results: [] } as CountedPaginatedResponse<CohortType>,
            loadCohortsByIds: async ({ ids }: { ids: number[] }) => {
                if (!isAuthenticatedTeam(values.currentTeam)) {
                    return values.allCohorts
                }
                const projectId = String(values.currentTeam.project_id)
                const requests: ConcurrencyController = (cache.cohortRequests ??= new ConcurrencyController(10))
                const referenced: Set<number> = (cache.referencedCohortIds ??= new Set<number>())
                ids.forEach((id) => referenced.add(id))
                const pending: Set<number> = (cache.pendingCohortIds ??= new Set<number>())
                const missing = [...new Set(ids)].filter(
                    (id) => Number.isSafeInteger(id) && id > 0 && !values.cohortsById[id] && !pending.has(id)
                )
                missing.forEach((id) => pending.add(id))
                const results = await Promise.allSettled(
                    missing.map(async (id) => {
                        try {
                            const cohort = await requests.run({ fn: () => cohortsApi.cohortsRetrieve(projectId, id) })
                            // The shared cache still exposes the legacy shape to its consumers.
                            actions.cacheCohort(cohort as unknown as CohortType)
                            const referencedIds = getReferencedCohortIds(cohort.filters)
                            if (referencedIds.length) {
                                actions.loadCohortsByIds({ ids: referencedIds })
                            }
                        } catch (error) {
                            if (![403, 404].includes((error as { status?: number }).status ?? 0)) {
                                throw error
                            }
                        } finally {
                            pending.delete(id)
                        }
                    })
                )
                const failure = results.find((result) => result.status === 'rejected')
                if (failure?.status === 'rejected') {
                    throw failure.reason
                }
                return values.allCohorts
            },
            loadAllCohorts: async () => {
                cache.fullListRequested = true
                // `allCohorts` feeds `cohortsById`, mostly id + name lookups, so request the
                // basic payload that drops the legacy `groups`/`query` JSON. Fetching the full
                // payload for every cohort on this hot path was slow enough to hit the
                // gateway timeout on cohort-heavy teams. `filters` stays in the basic payload:
                // the feature-flag intent warning reads it off `cohortsById` (see
                // featureFlagIntentWarningLogic.hasBehavioralCriteria), and its raw shape is
                // what that check expects, so no `processCohort` normalization is needed here.
                if (!isAuthenticatedTeam(values.currentTeam)) {
                    return values.allCohorts
                }
                const projectId = String(values.currentTeam.project_id)
                const response = await loadAllCohortPages((params) =>
                    cohortsApi.cohortsList(projectId, { ...params, basic: true })
                )
                const listedIds = new Set<CohortType['id']>(response.results.map(({ id }) => id))
                return {
                    count: response.count,
                    // `groups` is dropped from the basic payload but required on CohortType, so
                    // add the empty default back — nothing reading `cohortsById` uses `groups`.
                    results: [
                        ...response.results.map((cohort) => ({ ...(cohort as unknown as CohortType), groups: [] })),
                        ...values.allCohorts.results.filter(
                            ({ id }) => !listedIds.has(id) && cache.referencedCohortIds?.has(id)
                        ),
                    ],
                }
            },
        },
    })),
    reducers({
        pollTimeout: [
            null as number | null,
            {
                setPollTimeout: (_, { pollTimeout }) => pollTimeout,
            },
        ],
        // Update allCohorts state to keep breadcrumbs in sync when cohorts are modified
        // The cohortsById selector depends on allCohorts
        allCohorts: {
            cacheCohort: (state, { cohort }) => ({
                ...state,
                results: [...state.results.filter(({ id }) => id !== cohort.id), cohort],
            }),
            updateCohort: (state, { cohort }) => {
                if (!cohort) {
                    return state
                }
                // Upsert: a cohort opened directly (via cohortEditLogic.fetchCohort) may not be in
                // the list yet, so append it when missing — otherwise its name never reaches
                // cohortsById and the breadcrumb / browser tab title falls back to "Untitled".
                const exists = state.results.some((existingCohort) => existingCohort.id === cohort.id)
                return {
                    ...state,
                    results: exists
                        ? state.results.map((existingCohort) =>
                              existingCohort.id === cohort.id ? cohort : existingCohort
                          )
                        : [...state.results, cohort],
                }
            },
            cohortCreated: (state, { cohort }) => {
                if (!cohort) {
                    return state
                }
                return {
                    ...state,
                    results: [cohort, ...state.results],
                }
            },
            deleteCohort: (state, { cohort }) => {
                if (!cohort.id) {
                    return state
                }
                return {
                    ...state,
                    results: state.results.filter((c) => c.id !== cohort.id),
                }
            },
            hydrateAllCohortsFromExport: (_, { cohorts }: { cohorts: Pick<CohortType, 'id' | 'name'>[] }) => {
                // Sparse CohortType — id+name is all cohortsById consumers need for name lookup.
                const results = cohorts.map(
                    ({ id, name }) =>
                        ({
                            id,
                            name,
                            groups: [],
                            filters: { properties: { type: FilterLogicalOperator.And, values: [] } },
                        }) as unknown as CohortType
                )
                return { count: results.length, results }
            },
        },
    }),
    selectors({
        cohortsById: [
            (s) => [s.allCohorts],
            (allCohorts: CountedPaginatedResponse<CohortType>): Partial<Record<string | number, CohortType>> =>
                Object.fromEntries(allCohorts.results.map((cohort) => [cohort.id, cohort])),
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        loadAllCohortsFailure: () => {
            cache.fullListRequested = false
        },
        locationChanged: ({ pathname }) => {
            if (
                !isIndividualInsightPath(pathname) &&
                isAuthenticatedTeam(values.currentTeam) &&
                !cache.fullListRequested
            ) {
                actions.loadAllCohorts()
            }
        },
        loadAllCohortsSuccess: async ({ allCohorts }: { allCohorts: CountedPaginatedResponse<CohortType> }) => {
            const is_calculating = allCohorts.results.filter((cohort) => cohort.is_calculating).length > 0
            if (!is_calculating || !router.values.location.pathname.includes(urls.cohorts())) {
                return
            }
            actions.setPollTimeout(window.setTimeout(actions.loadAllCohorts, POLL_TIMEOUT))
        },
        deleteCohort: async ({ cohort }) => {
            await deleteWithUndo({
                endpoint: api.cohorts.determineDeleteEndpoint(),
                object: cohort,
                callback: (undo) => {
                    // Refresh `allCohorts` (the source for `cohortsById`) so an undo restores
                    // the row's name to breadcrumbs and pickers.
                    actions.loadAllCohorts()
                    if (cohort.id && cohort.id !== 'new') {
                        if (undo) {
                            refreshTreeItem('cohort', String(cohort.id))
                        } else {
                            deleteFromTree('cohort', String(cohort.id))
                            router.actions.push(urls.cohorts())
                        }
                    }
                },
                // The reducers already removed the cohort, so reload to bring back its name in breadcrumbs and pickers.
                onError: () => actions.loadAllCohorts(),
            })
        },
    })),
    beforeUnmount(({ values }) => {
        clearTimeout(values.pollTimeout || undefined)
    }),
    afterMount(({ actions, values }) => {
        if (isAuthenticatedTeam(values.currentTeam)) {
            // Other scenes still rely on eager loading; insightDataLogic resolves its own references.
            if (!isIndividualInsightPath(router.values.location.pathname)) {
                actions.loadAllCohorts()
            }
        } else {
            // Shared views can't hit /api/cohorts — seed from the inlined export payload.
            const exportedCohorts = getCurrentExporterData()?.cohorts
            if (exportedCohorts?.length) {
                actions.hydrateAllCohortsFromExport(exportedCohorts)
            }
        }
    }),
    permanentlyMount(),
])