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

import api from 'lib/api'
import { dayjs, dayjsUtcToTimezone } from 'lib/dayjs'
import { range } from 'lib/utils/arrays'
import { projectLogic } from 'scenes/projectLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { Breadcrumb } from '~/types'

import { teamLogic } from '../../teamLogic'
import { DataManagementTab } from '../DataManagementScene'

export interface IngestionWarningSummary {
    type: string
    lastSeen: string
    count: number
    warnings: IngestionWarning[]
    // count and day date pairs
    sparkline: [number, string][]
}

export interface IngestionWarning {
    type: string
    timestamp: string
    details: Record<string, any>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface ingestionWarningsLogicValues {
    currentProjectId: number | null // projectLogic
    timezone: string // teamLogic
    breadcrumbs: Breadcrumb[]
    data: IngestionWarningSummary[]
    dataLoading: boolean
    dates: string[]
    searchQuery: string
    showProductIntro: boolean
    summaryDatasets: Record<string, number[]>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface ingestionWarningsLogicActions {
    loadData: () => any
    loadDataFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDataSuccess: (
        data: IngestionWarningSummary[],
        payload?: any
    ) => {
        data: IngestionWarningSummary[]
        payload?: any
    }
    setSearchQuery: (search: string) => {
        search: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface ingestionWarningsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        summaryDatasets: (data: IngestionWarningSummary[], timezone: string) => Record<string, number[]>
        showProductIntro: (data: IngestionWarningSummary[], dataLoading: boolean, searchQuery: string) => boolean
    }
}

export type ingestionWarningsLogicType = MakeLogicType<
    ingestionWarningsLogicValues,
    ingestionWarningsLogicActions,
    Record<string, any>,
    ingestionWarningsLogicMeta
>

export const ingestionWarningsLogic = kea<ingestionWarningsLogicType>([
    path(['scenes', 'data-management', 'ingestion-warnings', 'ingestionWarningsLogic']),

    connect(() => ({
        values: [teamLogic, ['timezone'], projectLogic, ['currentProjectId']],
    })),

    actions({
        setSearchQuery: (search: string) => ({ search }),
    }),

    reducers({
        searchQuery: [
            '',
            {
                setSearchQuery: (_, { search }) => search,
            },
        ],
    }),

    loaders(({ values }) => ({
        data: [
            [] as IngestionWarningSummary[],
            {
                loadData: async () => {
                    const q = values.searchQuery ? `?q=${values.searchQuery}` : ''
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    const { results } = await api.get(`api/projects/${values.currentProjectId}/ingestion_warnings${q}`)
                    return results
                },
            },
        ],
    })),

    selectors({
        breadcrumbs: [
            () => [],
            (): Breadcrumb[] => {
                return [
                    {
                        key: Scene.DataManagement,
                        name: `Data management`,
                        path: urls.eventDefinitions(),
                        iconType: 'event_definition',
                    },
                    {
                        key: DataManagementTab.IngestionWarnings,
                        name: 'Event ingestion warnings',
                        path: urls.ingestionWarnings(),
                        iconType: 'ingestion_warning',
                    },
                ]
            },
        ],
        dates: [
            () => [],
            () => {
                return range(0, 30)
                    .map((i) => dayjs().subtract(i, 'days').format('D MMM YYYY'))
                    .reverse()
            },
        ],
        summaryDatasets: [
            (s) => [s.data, s.timezone],
            (data: IngestionWarningSummary[], timezone: string): Record<string, number[]> => {
                const summaryDatasets: Record<string, number[]> = {}
                data.forEach((summary) => {
                    const result = new Array(30).fill(0)
                    for (const spark of summary.sparkline) {
                        const date = dayjsUtcToTimezone(spark[1], timezone)
                        const dayIndex = dayjs().diff(date, 'days')
                        result[dayIndex] = spark[0]
                    }
                    summaryDatasets[summary.type] = result.reverse()
                })
                return summaryDatasets
            },
        ],
        showProductIntro: [
            (s) => [s.data, s.dataLoading, s.searchQuery],
            (data: IngestionWarningSummary[], dataLoading: boolean, searchQuery: string) =>
                data.length === 0 && !dataLoading && !searchQuery.trim().length,
        ],
    }),

    listeners(({ actions }) => ({
        setSearchQuery: async (_, breakpoint) => {
            await breakpoint(100)
            actions.loadData()
        },
    })),

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