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.

6.4 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 { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { teamLogic } from 'scenes/teamLogic'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'

export type HealthStatus = 'danger' | 'warning' | 'success'

export interface DataHealthIssue {
    id: string
    name: string
    type: 'materialized_view' | 'external_data_sync' | 'source' | 'destination' | 'transformation'
    source_type?: string | null
    status: 'failed' | 'disabled' | 'degraded' | 'billing_limit'
    error: string | null
    failed_at: string | null
    url: string | null
}

export interface DataHealthIssuesResponse {
    results: DataHealthIssue[]
    count: number
}

export const REFRESH_INTERVAL = 60 * 1000 * 5 // 5 minutes

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface pipelineHealthLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentTeamIdStrict: number | string // teamLogic
    hasErrors: boolean
    hasIssues: boolean
    healthIssues: DataHealthIssuesResponse | null
    healthIssuesLoading: boolean
    healthStatus: HealthStatus
    issueCount: number
    issues: DataHealthIssue[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface pipelineHealthLogicActions {
    loadHealthIssues: () => any
    loadHealthIssuesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadHealthIssuesSuccess: (
        healthIssues: DataHealthIssuesResponse | null,
        payload?: any
    ) => {
        healthIssues: DataHealthIssuesResponse | null
        payload?: any
    }
    setPageVisibility: (visible: boolean) => {
        visible: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface pipelineHealthLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        hasIssues: (issueCount: number) => boolean
        healthStatus: (issueCount: number) => HealthStatus
        issues: (healthIssues: DataHealthIssuesResponse | null) => DataHealthIssue[]
        hasErrors: (healthIssues: DataHealthIssuesResponse | null, healthIssuesLoading: boolean) => boolean
    }
}

export type pipelineHealthLogicType = MakeLogicType<
    pipelineHealthLogicValues,
    pipelineHealthLogicActions,
    Record<string, any>,
    pipelineHealthLogicMeta
>

export const pipelineHealthLogic = kea<pipelineHealthLogicType>([
    path(['scenes', 'health', 'pipelineStatus', 'pipelineHealthLogic']),
    connect({
        values: [featureFlagLogic, ['featureFlags'], teamLogic, ['currentTeamIdStrict']],
    }),

    actions({
        setPageVisibility: (visible: boolean) => ({ visible }),
    }),

    reducers(() => ({
        issueCount: [
            0,
            { persist: true },
            {
                loadHealthIssuesSuccess: (_, { healthIssues }) => healthIssues?.count ?? 0,
                loadHealthIssuesFailure: () => 0,
            },
        ],
    })),

    loaders(({ values }) => ({
        healthIssues: [
            null as DataHealthIssuesResponse | null,
            {
                loadHealthIssues: async (): Promise<DataHealthIssuesResponse | null> => {
                    if (!values.featureFlags[FEATURE_FLAGS.PIPELINE_STATUS_PAGE]) {
                        return null
                    }
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. dataWarehouseDataHealthIssuesRetrieve() from 'products/data_warehouse/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                        const response = await api.get<DataHealthIssuesResponse>(
                            `api/projects/${values.currentTeamIdStrict}/data_warehouse/data_health_issues/`
                        )
                        return response
                    } catch (error) {
                        console.error('Error loading health issues', error)
                        return null
                    }
                },
            },
        ],
    })),

    selectors({
        hasIssues: [
            (s) => [s.issueCount],
            (issueCount: number): boolean => {
                return issueCount > 0
            },
        ],

        healthStatus: [
            (s) => [s.issueCount],
            (issueCount: number): HealthStatus => {
                if (issueCount > 0) {
                    return 'danger'
                }
                return 'success'
            },
        ],

        issues: [
            (s) => [s.healthIssues],
            (healthIssues: DataHealthIssuesResponse | null): DataHealthIssue[] => {
                return healthIssues?.results ?? []
            },
        ],

        hasErrors: [
            (s) => [s.healthIssues, s.healthIssuesLoading],
            (healthIssues: DataHealthIssuesResponse | null, healthIssuesLoading: boolean): boolean => {
                return !healthIssuesLoading && healthIssues === null
            },
        ],
    }),

    listeners(({ actions, cache }) => ({
        loadHealthIssuesSuccess: () => {
            cache.disposables.add(() => {
                const timerId = setTimeout(() => actions.loadHealthIssues(), REFRESH_INTERVAL)
                return () => clearTimeout(timerId)
            }, 'refreshTimeout')
        },
        setPageVisibility: ({ visible }) => {
            if (visible) {
                actions.loadHealthIssues()
            } else {
                cache.disposables.dispose('refreshTimeout')
            }
        },
    })),

    afterMount(({ actions, values, cache }) => {
        if (!values.featureFlags[FEATURE_FLAGS.PIPELINE_STATUS_PAGE]) {
            return
        }
        actions.loadHealthIssues()
        cache.disposables.add(() => {
            const onVisibilityChange = (): void => {
                actions.setPageVisibility(document.visibilityState === 'visible')
            }
            document.addEventListener('visibilitychange', onVisibilityChange)
            return () => document.removeEventListener('visibilitychange', onVisibilityChange)
        }, 'visibilityListener')
    }),
])