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.

17.6 KB
Raw Blame
import { MakeLogicType, actions, events, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import api from 'lib/api'
import { getAppContext } from 'lib/utils/getAppContext'
import { identifyInstanceInPostHog } from 'lib/utils/posthogIdentity'
import { urls } from 'scenes/urls'

import { PreflightStatus, Realm } from '~/types'

export type PreflightMode = 'experimentation' | 'live'

export type PreflightCheckStatus = 'validated' | 'error' | 'warning' | 'optional'

export interface PreflightItem {
    name: string
    status: PreflightCheckStatus
    caption?: string
    id: string
}

export interface PreflightCheckSummary {
    summaryString: string
    summaryStatus: PreflightCheckStatus
}

export interface EnvironmentConfigOption {
    key: string
    metric: string
    value: string | undefined
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface preflightLogicValues {
    areChecksExpanded: boolean
    areChecksManuallyExpanded: boolean | null
    checks: PreflightItem[]
    checksSummary: PreflightCheckSummary
    configOptions: EnvironmentConfigOption[]
    disableNavigationHooks: boolean | undefined
    isCloud: boolean | undefined
    isCloudOrDev: boolean | undefined
    isDev: boolean | undefined
    isHobby: boolean
    isTest: boolean
    objectStorageAvailable: boolean
    preflight: PreflightStatus | null
    preflightLoading: boolean
    preflightMode: PreflightMode | null
    realm: Realm | null
    siteUrlMisconfigured: boolean
    socialAuthAvailable: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface preflightLogicActions {
    handlePreflightFinished: () => {
        value: true
    }
    loadPreflight: () => any
    loadPreflightFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPreflightSuccess: (
        preflight: PreflightStatus,
        payload?: any
    ) => {
        preflight: PreflightStatus
        payload?: any
    }
    registerInstrumentationProps: () => {
        value: true
    }
    revalidatePreflight: () => {
        value: true
    }
    setChecksManuallyExpanded: (expanded: boolean | null) => {
        expanded: boolean | null
    }
    setPreflightMode: (
        mode: PreflightMode | null,
        noReload?: boolean
    ) => {
        mode: PreflightMode | null
        noReload: boolean | undefined
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface preflightLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        checks: (preflight: PreflightStatus | null, preflightMode: PreflightMode | null) => PreflightItem[]
        checksSummary: (checks: PreflightItem[]) => PreflightCheckSummary
        areChecksExpanded: (checksSummary: PreflightCheckSummary, areChecksManuallyExpanded: boolean | null) => boolean
        socialAuthAvailable: (preflight: PreflightStatus | null) => boolean
        objectStorageAvailable: (preflight: PreflightStatus | null) => boolean
        realm: (preflight: PreflightStatus | null) => Realm | null
        siteUrlMisconfigured: (preflight: PreflightStatus | null) => boolean
        configOptions: (preflight: PreflightStatus | null) => EnvironmentConfigOption[]
        isCloudOrDev: (preflight: PreflightStatus | null) => boolean | undefined
        isTest: (preflight: PreflightStatus | null) => boolean
        isHobby: (isCloudOrDev: boolean | undefined, isTest: boolean) => boolean
        isCloud: (preflight: PreflightStatus | null) => boolean | undefined
        isDev: (preflight: PreflightStatus | null) => boolean | undefined
        disableNavigationHooks: (preflight: PreflightStatus | null) => boolean | undefined
    }
}

export type preflightLogicType = MakeLogicType<
    preflightLogicValues,
    preflightLogicActions,
    Record<string, any>,
    preflightLogicMeta
>

export const preflightLogic = kea<preflightLogicType>([
    path(['scenes', 'PreflightCheck', 'preflightLogic']),
    loaders({
        preflight: [
            null as PreflightStatus | null,
            {
                loadPreflight: async () => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call to a route outside /api/, with an unchecked response type. No generated function can cover it until the route is in the OpenAPI schema.
                    const response = await api.get<PreflightStatus>('_preflight/')
                    return response
                },
            },
        ],
    }),
    actions({
        registerInstrumentationProps: true,
        setPreflightMode: (mode: PreflightMode | null, noReload?: boolean) => ({ mode, noReload }),
        handlePreflightFinished: true,
        setChecksManuallyExpanded: (expanded: boolean | null) => ({ expanded }),
        revalidatePreflight: true,
    }),
    reducers({
        preflightMode: [
            null as PreflightMode | null,
            {
                setPreflightMode: (_, { mode }) => mode,
            },
        ],
        areChecksManuallyExpanded: [
            null as boolean | null,
            {
                setChecksManuallyExpanded: (_, { expanded }) => expanded,
            },
        ],
    }),
    selectors({
        checks: [
            (s) => [s.preflight, s.preflightMode],
            (preflight: PreflightStatus | null, preflightMode: PreflightMode | null) => {
                const preflightItems = [
                    {
                        id: 'database',
                        name: 'Application database · Postgres',
                        status: preflight?.db ? 'validated' : 'error',
                    },
                    {
                        id: 'clickhouse',
                        name: 'Analytics database · ClickHouse',
                        status: preflight?.clickhouse ? 'validated' : 'error',
                    },
                    {
                        id: 'kafka',
                        name: 'Queue · Kafka',
                        status: preflight?.kafka ? 'validated' : 'error',
                    },
                    {
                        id: 'backend',
                        name: 'Backend server · Django',
                        status: preflight?.django ? 'validated' : 'error',
                    },
                    {
                        id: 'redis',
                        name: 'Cache · Redis',
                        status: preflight?.redis
                            ? 'validated'
                            : preflightMode === 'experimentation'
                              ? 'warning'
                              : 'error',
                        caption:
                            !preflight?.redis && preflightMode === 'experimentation'
                                ? 'Required in production environments'
                                : undefined,
                    },
                    {
                        id: 'celery',
                        name: 'Background jobs · Celery',
                        status: preflight?.celery
                            ? 'validated'
                            : preflightMode === 'experimentation'
                              ? 'warning'
                              : 'error',
                        caption:
                            !preflight?.celery && preflightMode === 'experimentation'
                                ? 'Required in production environments'
                                : undefined,
                    },
                    {
                        id: 'plugins',
                        name: 'Plugin server · Node',
                        status: preflight?.plugins
                            ? 'validated'
                            : preflightMode === 'experimentation'
                              ? 'warning'
                              : 'error',
                        caption:
                            !preflight?.plugins && preflightMode === 'experimentation'
                                ? 'Required in production environments'
                                : undefined,
                    },
                    {
                        id: 'frontend',
                        name: 'Frontend build · Vite',
                        status: 'validated', // Always validated if we're showing the preflight check
                    },
                    {
                        id: 'tls',
                        name: 'SSL/TLS certificate',
                        status:
                            window.location.protocol === 'https:'
                                ? 'validated'
                                : preflightMode === 'experimentation'
                                  ? 'optional'
                                  : 'warning',
                        caption:
                            !(window.location.protocol === 'https:') && preflightMode === 'experimentation'
                                ? 'Not required for experimentation mode'
                                : 'Set up before ingesting real user data',
                    },
                ]

                if (preflight?.object_storage || preflight?.is_debug) {
                    /** __for now__, only prompt debug users if object storage is unhealthy **/
                    preflightItems.push({
                        id: 'object_storage',
                        name: 'Object Storage',
                        status: preflight?.object_storage ? 'validated' : 'warning',
                        caption: preflight?.object_storage
                            ? undefined
                            : 'Some features will not work without object storage',
                    })
                }

                return preflightItems as PreflightItem[]
            },
        ],
        checksSummary: [
            (s) => [s.checks],
            (checks: PreflightItem[]): PreflightCheckSummary => {
                const statusCounts = {} as Record<PreflightCheckStatus, number>
                if (checks.length > 0) {
                    for (const check of checks) {
                        statusCounts[check.status] = (statusCounts[check.status] || 0) + 1
                    }
                }

                let summaryString = ''
                let summaryStatus: PreflightCheckStatus = 'validated'

                if (statusCounts.validated) {
                    summaryString += `${statusCounts.validated} successful, `
                }
                if (statusCounts.warning) {
                    summaryString += `${statusCounts.warning} warning${statusCounts.warning > 1 ? 's' : ''}, `
                    summaryStatus = 'warning'
                }
                if (statusCounts.error) {
                    summaryString += `${statusCounts.error} error${statusCounts.error > 1 ? 's' : ''}, `
                    summaryStatus = 'error'
                }
                if (statusCounts.optional) {
                    summaryString += `${statusCounts.optional} optional, `
                }

                return { summaryString: summaryString.slice(0, -2), summaryStatus: summaryStatus }
            },
        ],
        areChecksExpanded: [
            (s) => [s.checksSummary, s.areChecksManuallyExpanded],
            (checksSummary: PreflightCheckSummary, areChecksManuallyExpanded: boolean | null) => {
                return areChecksManuallyExpanded ?? checksSummary?.summaryStatus !== 'validated'
            },
        ],
        socialAuthAvailable: [
            (s) => [s.preflight],
            (preflight: PreflightStatus | null): boolean =>
                Boolean(preflight && Object.values(preflight.available_social_auth_providers).filter((i) => i).length),
        ],
        objectStorageAvailable: [
            (s) => [s.preflight],
            (preflight: PreflightStatus | null): boolean => Boolean(preflight && preflight.object_storage),
        ],
        realm: [
            (s) => [s.preflight],
            (preflight: PreflightStatus | null): Realm | null => {
                if (!preflight) {
                    return null
                }
                return preflight.realm
            },
        ],
        siteUrlMisconfigured: [
            (s) => [s.preflight],
            (preflight: PreflightStatus | null): boolean => {
                if (process?.env.STORYBOOK) {
                    // Disable the "site URL misconfigured" warning in Storybook. This is for consistent snapshots
                    // - when opening Storybook in the browser or when updating the snapshots in CI, the origin is
                    // http://localhost:6006, but in the local dockerized setup http://host.docker.internal:6006
                    return false
                }
                const isMismatchPresent =
                    !!preflight && (!preflight.site_url || preflight.site_url != window.location.origin)
                if (
                    isMismatchPresent &&
                    preflight.site_url === 'http://localhost:8010' &&
                    window.location.origin === 'http://localhost:8000'
                ) {
                    // Local development setup using the old port - we have a warning in DebugNotice for this
                    return false
                }
                return isMismatchPresent
            },
        ],
        configOptions: [
            (s) => [s.preflight],
            (preflight: PreflightStatus | null): EnvironmentConfigOption[] => {
                // Returns the preflight config options to display in the /instance/status page

                const RELEVANT_CONFIGS = [
                    {
                        key: 'site_url',
                        label: 'Site URL',
                    },
                ] as const

                if (!preflight) {
                    return []
                }
                return RELEVANT_CONFIGS.map((config) => ({
                    key: config.key,
                    metric: config.label,
                    value: preflight[config.key],
                }))
            },
        ],
        isCloudOrDev: [
            (s) => [s.preflight],
            (preflight: PreflightStatus | null): boolean | undefined => {
                return preflight?.cloud || preflight?.is_debug
            },
        ],
        isTest: [(s) => [s.preflight], (preflight: PreflightStatus | null) => !!preflight?.is_test],
        isHobby: [
            (s) => [s.isCloudOrDev, s.isTest],
            (isCloudOrDev: boolean | undefined, isTest: boolean) => !isCloudOrDev && !isTest,
        ],
        isCloud: [
            (s) => [s.preflight],
            (preflight: PreflightStatus | null): boolean | undefined => {
                return preflight?.cloud
            },
        ],
        isDev: [
            (s) => [s.preflight],
            (preflight: PreflightStatus | null): boolean | undefined => {
                return preflight?.is_debug
            },
        ],
        disableNavigationHooks: [
            (s) => [s.preflight],
            (preflight: PreflightStatus | null): boolean | undefined => {
                return preflight?.dev_disable_navigation_hooks
            },
        ],
    }),
    listeners(({ values, actions }) => ({
        handlePreflightFinished: () => {
            router.actions.push(urls.signup())
        },
        loadPreflightSuccess: () => {
            actions.registerInstrumentationProps()
            actions.setChecksManuallyExpanded(values.areChecksManuallyExpanded || null)
        },
        registerInstrumentationProps: async (_, breakpoint) => {
            await breakpoint(100)
            if (posthog && values.preflight) {
                const appContext = getAppContext()

                posthog.register({
                    realm: values.realm,
                    email_service_available: values.preflight.email_service_available,
                    slack_service_available: values.preflight.slack_service?.available,
                    commit_sha: appContext?.commit_sha,
                })

                if (values.preflight.site_url && identifyInstanceInPostHog(posthog, values.preflight.site_url)) {
                    posthog.reloadFeatureFlags()
                }
            }
        },
        setPreflightMode: async ({ mode, noReload }) => {
            if (mode && !noReload) {
                actions.loadPreflight()
            }
        },
        revalidatePreflight: () => {
            // The TLS check MUST be in the array returned by the `checks` selector
            const tlsCheckResult = values.checks.find((check) => check.id === 'tls') as PreflightItem
            if (tlsCheckResult.status === 'warning') {
                // Full page reload is needed to revalidate whether the page is served over HTTPS
                window.location.reload()
            } else {
                // Otherwise, just fetch from the preflight endpoint within the logic
                actions.loadPreflight()
            }
        },
    })),
    events(({ actions, values }) => ({
        afterMount: () => {
            const appContext = getAppContext()
            const preflight = appContext?.preflight
            if (preflight) {
                actions.loadPreflightSuccess(preflight)
            } else if (!values.preflight) {
                actions.loadPreflight()
            }
        },
    })),
    actionToUrl(({ values }) => ({
        setPreflightMode: () => ['/preflight', { mode: values.preflightMode }],
    })),
    urlToAction(({ actions, values }) => ({
        '/preflight': (_, { mode }) => {
            if (values.preflightMode !== mode) {
                actions.setPreflightMode(mode ?? (null as PreflightMode | null), true)
            }
        },
    })),
])