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 {
    LogicWrapper,
    MakeLogicType,
    actions,
    afterMount,
    kea,
    key,
    listeners,
    path,
    props,
    propsChanged,
    reducers,
} from 'kea'
import { loaders } from 'kea-loaders'

import { ApiError } from 'lib/api'

import { DataQualitySubjectRef, apiErrorDetail, checksApi } from './checksApi'
import type { DataQualityCheckScheduleApi, PatchedDataQualityCheckScheduleUpdateApi } from './generated/api.schemas'

const SCHEDULE_REFRESH_INTERVAL_MS = 30_000

export interface DataQualityScheduleLogicProps extends DataQualitySubjectRef {
    initialSchedule?: DataQualityCheckScheduleApi | null
    poll?: boolean
}

function surfaceStillLoading(initialSchedule: DataQualityCheckScheduleApi | null | undefined): boolean {
    return initialSchedule === null
}

export interface DataQualityScheduleError {
    message: string
    uncertain: boolean
}

const REJECTED_SCHEDULE_MESSAGE = 'Could not save the schedule. Try again.'

function isDefinitiveRejection(error: unknown): boolean {
    return error instanceof ApiError && error.status !== undefined && error.status < 500
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataQualityScheduleLogicValues {
    schedule: DataQualityCheckScheduleApi | null
    scheduleError: DataQualityScheduleError | null
    scheduleLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataQualityScheduleLogicActions {
    loadSchedule: () => any
    loadScheduleFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadScheduleSuccess: (
        schedule: DataQualityCheckScheduleApi,
        payload?: any
    ) => {
        schedule: DataQualityCheckScheduleApi
        payload?: any
    }
    refreshSchedule: () => {
        value: true
    }
    refreshScheduleSuccess: (schedule: DataQualityCheckScheduleApi) => {
        schedule: DataQualityCheckScheduleApi
    }
    updateSchedule: (patch: PatchedDataQualityCheckScheduleUpdateApi) => PatchedDataQualityCheckScheduleUpdateApi
    updateScheduleFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateScheduleSuccess: (
        schedule: DataQualityCheckScheduleApi,
        payload?: PatchedDataQualityCheckScheduleUpdateApi
    ) => {
        schedule: DataQualityCheckScheduleApi
        payload?: PatchedDataQualityCheckScheduleUpdateApi
    }
}

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

export type dataQualityScheduleLogicType = MakeLogicType<
    dataQualityScheduleLogicValues,
    dataQualityScheduleLogicActions,
    DataQualityScheduleLogicProps,
    dataQualityScheduleLogicMeta
>

export const dataQualityScheduleLogic: LogicWrapper<dataQualityScheduleLogicType> = kea<dataQualityScheduleLogicType>([
    props({} as DataQualityScheduleLogicProps),
    key((props) => `${props.subjectType}:${props.subjectId}`),
    path((key) => ['products', 'data_quality', 'frontend', 'dataQualityScheduleLogic', key]),
    actions({
        refreshSchedule: true,
        refreshScheduleSuccess: (schedule: DataQualityCheckScheduleApi) => ({ schedule }),
    }),
    loaders(({ props, actions }) => ({
        schedule: [
            null as DataQualityCheckScheduleApi | null,
            {
                loadSchedule: async () => checksApi.schedule(props),
                updateSchedule: async (patch: PatchedDataQualityCheckScheduleUpdateApi) => {
                    try {
                        return await checksApi.updateSchedule(props, patch)
                    } catch (error) {
                        if (isDefinitiveRejection(error)) {
                            throw error
                        }
                        try {
                            actions.loadScheduleSuccess(await checksApi.schedule(props))
                        } catch {
                            // The edit can have committed even when neither response reaches us.
                        }
                        throw error
                    }
                },
            },
        ],
    })),
    reducers({
        schedule: {
            refreshScheduleSuccess: (_, { schedule }) => schedule,
        },
        scheduleError: [
            null as DataQualityScheduleError | null,
            {
                loadSchedule: () => null,
                updateSchedule: () => null,
                loadScheduleFailure: (_, { error }) => ({ message: error, uncertain: true }),
                updateScheduleFailure: (_, { error, errorObject }) => ({
                    message: apiErrorDetail(errorObject) ?? error ?? REJECTED_SCHEDULE_MESSAGE,
                    uncertain: !isDefinitiveRejection(errorObject),
                }),
            },
        ],
    }),
    listeners(({ actions, props, values }) => ({
        refreshSchedule: async () => {
            if (values.scheduleLoading) {
                return
            }
            const previousSchedule = values.schedule
            try {
                const schedule = await checksApi.schedule(props)
                if (!values.scheduleLoading && values.schedule === previousSchedule) {
                    actions.refreshScheduleSuccess(schedule)
                }
            } catch {
                return
            }
        },
    })),
    propsChanged(({ actions, props, values }, oldProps) => {
        if (props.initialSchedule && props.initialSchedule !== oldProps.initialSchedule && !values.scheduleLoading) {
            actions.refreshScheduleSuccess(props.initialSchedule)
            return
        }
        if (surfaceStillLoading(oldProps.initialSchedule) && props.initialSchedule === undefined && !values.schedule) {
            actions.loadSchedule()
        }
    }),
    afterMount(({ actions, props, cache }) => {
        if (props.initialSchedule) {
            actions.refreshScheduleSuccess(props.initialSchedule)
        } else if (!surfaceStillLoading(props.initialSchedule)) {
            actions.loadSchedule()
        }
        if (props.poll === false) {
            return
        }
        cache.disposables.add(() => {
            const refreshTimer = window.setInterval(actions.refreshSchedule, SCHEDULE_REFRESH_INTERVAL_MS)
            return () => window.clearInterval(refreshTimer)
        })
    }),
])