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.

7.1 KB
Raw Blame
import { LogicWrapper, MakeLogicType, afterMount, kea, key, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import { teamLogic } from 'scenes/teamLogic'

import { DatabaseSchemaTable } from '~/queries/schema/schema-general'

import * as qualityApi from 'products/data_quality/frontend/generated/api'
import { DataQualitySubjectHealthApi } from 'products/data_quality/frontend/generated/api.schemas'
import * as warehouseApi from 'products/data_warehouse/frontend/generated/api'

export interface BISourceMetadataProps {
    table?: DatabaseSchemaTable
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSourceMetadataLogicValues {
    annotations: Record<string, string>
    annotationsError: boolean
    annotationsLoading: boolean
    health: DataQualitySubjectHealthApi | null
    healthError: boolean
    healthLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSourceMetadataLogicActions {
    loadAnnotations: (_: void) => void
    loadAnnotationsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAnnotationsSuccess: (
        annotations: Record<string, string>,
        payload?: void
    ) => {
        annotations: Record<string, string>
        payload?: void
    }
    loadHealth: (_: void) => void
    loadHealthFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadHealthSuccess: (
        health: DataQualitySubjectHealthApi | null,
        payload?: void
    ) => {
        health: DataQualitySubjectHealthApi | null
        payload?: void
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSourceMetadataLogicMeta {
    key: string
}

export type biSourceMetadataLogicType = MakeLogicType<
    biSourceMetadataLogicValues,
    biSourceMetadataLogicActions,
    BISourceMetadataProps,
    biSourceMetadataLogicMeta
>

export const biSourceMetadataLogic: LogicWrapper<biSourceMetadataLogicType> = kea<biSourceMetadataLogicType>([
    props({} as BISourceMetadataProps),
    key(({ table }) => (table ? `${table.type}:${table.id}:${table.name}` : 'none')),
    path((key) => ['products', 'business_intelligence', 'biSourceMetadataLogic', key]),
    reducers({
        annotationsError: [false, { loadAnnotations: () => false, loadAnnotationsFailure: () => true }],
        healthError: [false, { loadHealth: () => false, loadHealthFailure: () => true }],
    }),
    loaders(({ props }) => ({
        annotations: [
            Object.create(null) as Record<string, string>,
            {
                loadAnnotations: async (_: void, breakpoint): Promise<Record<string, string>> => {
                    const table = props.table
                    if (!table || !['data_warehouse', 'view', 'materialized_view'].includes(table.type) || !table.id) {
                        return Object.create(null) as Record<string, string>
                    }
                    const project = String(teamLogic.values.currentTeamId)
                    const annotations = Object.create(null) as Record<string, string>
                    let offset = 0
                    while (true) {
                        const result =
                            table.type === 'data_warehouse'
                                ? await warehouseApi.warehouseColumnAnnotationsList(project, {
                                      table_id: table.id,
                                      limit: 100,
                                      offset,
                                  })
                                : await warehouseApi.savedQueryColumnAnnotationsList(project, {
                                      saved_query_id: table.id,
                                      limit: 100,
                                      offset,
                                  })
                        breakpoint()
                        for (const annotation of result.results) {
                            annotations[annotation.column_name ?? ''] = annotation.description
                        }
                        if (!result.next || !result.results.length) {
                            return annotations
                        }
                        offset += result.results.length
                    }
                },
            },
        ],
        health: [
            null as DataQualitySubjectHealthApi | null,
            {
                loadHealth: async (_: void, breakpoint): Promise<DataQualitySubjectHealthApi | null> => {
                    const table = props.table
                    if (!table) {
                        return null
                    }
                    const project = String(teamLogic.values.currentTeamId)
                    const subjectType =
                        table.type === 'data_warehouse'
                            ? 'table'
                            : ['view', 'materialized_view'].includes(table.type)
                              ? 'view'
                              : table.type === 'posthog'
                                ? 'posthog_table'
                                : null
                    if (!subjectType || !table.id) {
                        return null
                    }
                    let subjectId = table.id
                    if (subjectType === 'posthog_table') {
                        let offset = 0
                        while (true) {
                            const subjects = await qualityApi.dataQualityChecksSubjectsList(project, {
                                subject_type: 'posthog_table',
                                search: table.name,
                                limit: 100,
                                offset,
                            })
                            breakpoint()
                            const subject = subjects.find((candidate) => candidate.name === table.name)
                            if (subject) {
                                subjectId = subject.id
                                break
                            }
                            if (subjects.length < 100) {
                                return null
                            }
                            offset += subjects.length
                        }
                    }
                    const rollups = await qualityApi.dataQualityChecksHealthList(project, {
                        subject_type: subjectType,
                        subject_uuid: subjectId,
                    })
                    breakpoint()
                    return (
                        rollups[0] ?? {
                            subject_type: subjectType,
                            subject_uuid: subjectId,
                            health: 'unknown',
                            checks_total: 0,
                            checks_failing: 0,
                        }
                    )
                },
            },
        ],
    })),
    afterMount(({ actions }) => {
        actions.loadAnnotations()
    }),
])