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.

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

import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { userLogic } from 'scenes/userLogic'

import { InstanceSetting, SystemStatus, SystemStatusQueriesResult, SystemStatusRow } from '~/types'

export enum ConfigMode {
    View = 'view',
    Edit = 'edit',
    Saving = 'saving',
}

export type InstanceStatusTabName = 'overview' | 'metrics' | 'settings' | 'staff_users'

/**
 * We allow the specific instance settings that can be edited via the /instance/status page.
 * Even if some settings are editable in the frontend according to the API, we may don't want to expose them here.
 * For example: async migrations settings are handled in their own page.
 */
const EDITABLE_INSTANCE_SETTINGS = [
    'RECORDINGS_PERFORMANCE_EVENTS_TTL_WEEKS',
    'EMAIL_ENABLED',
    'EMAIL_HOST',
    'EMAIL_PORT',
    'EMAIL_HOST_USER',
    'EMAIL_HOST_PASSWORD',
    'EMAIL_USE_TLS',
    'EMAIL_USE_SSL',
    'EMAIL_DEFAULT_FROM',
    'EMAIL_REPLY_TO',
    'CONVERSATIONS_EMAIL_INBOUND_DOMAIN',
    'CONVERSATIONS_EMAIL_WEBHOOK_SIGNING_KEY',
    'CONVERSATIONS_EMAIL_MAILGUN_API_KEY',
    'CONVERSATIONS_HMAC_SIGNING_SECRET',
    'AGGREGATE_BY_DISTINCT_IDS_TEAMS',
    'GITHUB_APP_SLUG',
    'PERSON_ON_EVENTS_ENABLED',
    'CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA',
    'CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA_TEAMS',
    'STRICT_CACHING_TEAMS',
    'SLACK_APP_CLIENT_ID',
    'SLACK_APP_CLIENT_SECRET',
    'SLACK_APP_SIGNING_SECRET',
    'SUPPORT_SLACK_APP_CLIENT_ID',
    'SUPPORT_SLACK_APP_CLIENT_SECRET',
    'SUPPORT_SLACK_SIGNING_SECRET',
    'SUPPORT_TEAMS_APP_ID',
    'SUPPORT_TEAMS_APP_SECRET',
    'SUPPORT_TEAMS_APP_TENANT_ID',
    'SUPPORT_TEAMS_CATALOG_APP_ID',
    'PARALLEL_DASHBOARD_ITEM_CACHE',
    'RATE_LIMIT_ENABLED',
    'RATE_LIMITING_ALLOW_LIST_TEAMS',
    'FLAGS_LOG_BODIES_TEAMS',
    'FLAG_EVALUATIONS_READS_FORCE_EVENTS',
    'CLICKHOUSE_KILL_SWITCH',
    'CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS',
    'CLICKHOUSE_KILL_SWITCH_FULL_TEAMS',
    'HOGQL_SHARED_INSIGHT_DATABASE_ENABLED',
    'WEB_ANALYTICS_WARMING_SHARD_THREADS',
    'WEB_ANALYTICS_WARMING_SHARDS',
]

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface systemStatusLogicValues {
    editableInstanceSettings: InstanceSetting[]
    error: string | null
    instanceConfigEditingState: Record<string, boolean | number | string>
    instanceConfigMode: ConfigMode
    instanceSettings: InstanceSetting[]
    instanceSettingsLoading: boolean
    openSections: string[]
    overview: SystemStatusRow[]
    queries: SystemStatusQueriesResult | null
    queriesLoading: boolean
    systemStatus: SystemStatus | null
    systemStatusLoading: boolean
    tab: InstanceStatusTabName
    updatedInstanceConfigCount: number | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface systemStatusLogicActions {
    clearInstanceConfigEditing: () => {
        value: true
    }
    increaseUpdatedInstanceConfigCount: () => {
        value: true
    }
    loadInstanceSettings: () => any
    loadInstanceSettingsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInstanceSettingsSuccess: (
        instanceSettings: InstanceSetting[],
        payload?: any
    ) => {
        instanceSettings: InstanceSetting[]
        payload?: any
    }
    loadQueries: () => any
    loadQueriesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadQueriesSuccess: (
        queries: SystemStatusQueriesResult | null,
        payload?: any
    ) => {
        queries: SystemStatusQueriesResult | null
        payload?: any
    }
    loadSystemStatus: () => any
    loadSystemStatusFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSystemStatusSuccess: (
        systemStatus: SystemStatus | null,
        payload?: any
    ) => {
        systemStatus: SystemStatus | null
        payload?: any
    }
    saveInstanceConfig: () => {
        value: true
    }
    setInstanceConfigMode: (mode: ConfigMode) => {
        mode: ConfigMode
    }
    setOpenSections: (sections: string[]) => {
        sections: string[]
    }
    setTab: (tab: InstanceStatusTabName) => {
        tab: InstanceStatusTabName
    }
    setUpdatedInstanceConfigCount: (count: number | null) => {
        count: number | null
    }
    updateInstanceConfigValue: (
        key: string,
        value?: boolean | number | string
    ) => {
        key: string
        value: boolean | number | string | undefined
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface systemStatusLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        overview: (systemStatus: SystemStatus | null) => SystemStatusRow[]
        editableInstanceSettings: (instanceSettings: InstanceSetting[]) => InstanceSetting[]
    }
}

export type systemStatusLogicType = MakeLogicType<
    systemStatusLogicValues,
    systemStatusLogicActions,
    Record<string, any>,
    systemStatusLogicMeta
>

// Note: This logic does some heavy calculations - avoid connecting it outside of system status pages!
export const systemStatusLogic = kea<systemStatusLogicType>([
    path(['scenes', 'instance', 'SystemStatus', 'systemStatusLogic']),
    actions({
        setTab: (tab: InstanceStatusTabName) => ({ tab }),
        setOpenSections: (sections: string[]) => ({ sections }),
        setInstanceConfigMode: (mode: ConfigMode) => ({ mode }),
        updateInstanceConfigValue: (key: string, value?: string | boolean | number) => ({ key, value }),
        clearInstanceConfigEditing: true,
        saveInstanceConfig: true,
        setUpdatedInstanceConfigCount: (count: number | null) => ({ count }),
        increaseUpdatedInstanceConfigCount: true,
    }),
    loaders(() => ({
        systemStatus: [
            null as SystemStatus | null,
            {
                loadSystemStatus: async () => {
                    if (!isUserLoggedIn()) {
                        // If user is anonymous (i.e. viewing a shared dashboard logged out), don't load authenticated stuff
                        return null
                    }

                    if (preflightLogic.values.preflight?.cloud && !userLogic.values.user?.is_staff) {
                        return null
                    }

                    // 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.
                    return (await api.get('api/instance_status')).results ?? null
                },
            },
        ],
        instanceSettings: [
            [] as InstanceSetting[],
            {
                loadInstanceSettings: async () => {
                    // 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.
                    return (await api.get('api/instance_settings')).results ?? []
                },
            },
        ],
        queries: [
            null as SystemStatusQueriesResult | null,
            {
                // 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.
                loadQueries: async () => (await api.get('api/instance_status/queries')).results,
            },
        ],
    })),
    reducers({
        tab: [
            'overview' as InstanceStatusTabName,
            {
                setTab: (_, { tab }) => tab,
            },
        ],
        error: [
            null as null | string,
            {
                loadSystemStatusFailure: (_, { error }) => error,
            },
        ],
        openSections: [
            ['0'] as string[],
            { persist: true },
            {
                setOpenSections: (_, { sections }) => sections,
            },
        ],
        instanceConfigMode: [
            // Determines whether the Instance Configuration table on "Configuration" tab is on edit or view mode
            ConfigMode.View as ConfigMode,
            {
                setInstanceConfigMode: (_, { mode }) => mode,
            },
        ],
        instanceConfigEditingState: [
            {} as Record<string, string | boolean | number>,
            {
                updateInstanceConfigValue: (s, { key, value }) => {
                    if (value !== undefined) {
                        return { ...s, [key]: value }
                    }
                    const newState = { ...s }
                    delete newState[key]
                    return newState
                },
                clearInstanceConfigEditing: () => ({}),
            },
        ],
        updatedInstanceConfigCount: [
            null as number | null, // Number of config items that have been updated; `null` means no update is in progress
            {
                setUpdatedInstanceConfigCount: (_, { count }) => count,
                loadInstanceSettings: () => null,
                increaseUpdatedInstanceConfigCount: (state) => (state ?? 0) + 1,
            },
        ],
    }),
    selectors(() => ({
        overview: [
            (s) => [s.systemStatus],
            (status: SystemStatus | null): SystemStatusRow[] => (status ? status.overview : []),
        ],
        editableInstanceSettings: [
            (s) => [s.instanceSettings],
            (instanceSettings: InstanceSetting[]): InstanceSetting[] =>
                instanceSettings.filter((item) => item.editable && EDITABLE_INSTANCE_SETTINGS.includes(item.key)),
        ],
    })),
    listeners(({ actions, values }) => ({
        setTab: ({ tab }: { tab: InstanceStatusTabName }) => {
            if (tab === 'metrics') {
                actions.loadQueries()
            }
            actions.setInstanceConfigMode(ConfigMode.View)
        },
        updateInstanceConfigValue: ({ key, value }) => {
            const previousValue = values.editableInstanceSettings.find((item) => item.key === key)?.value
            if (value && previousValue == value) {
                actions.updateInstanceConfigValue(key, undefined)
            }
        },
        saveInstanceConfig: async (_, breakpoint) => {
            actions.setUpdatedInstanceConfigCount(0)
            await Promise.all(
                Object.entries(values.instanceConfigEditingState).map(async ([key, value]) => {
                    // 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.
                    await api.update(`api/instance_settings/${key}`, {
                        value,
                    })
                    posthog.capture('instance setting change', { name: key, value: value })
                    actions.increaseUpdatedInstanceConfigCount()
                })
            )
            await breakpoint(1000)
            if (values.updatedInstanceConfigCount === Object.keys(values.instanceConfigEditingState).length) {
                actions.loadInstanceSettings()
                actions.clearInstanceConfigEditing()
                actions.setInstanceConfigMode(ConfigMode.View)
                lemonToast.success('Instance settings updated')
            }
        },
    })),
    actionToUrl(({ values }) => ({
        setTab: () => '/instance/' + (values.tab === 'overview' ? 'status' : values.tab),
    })),
    urlToAction(({ actions, values }) => ({
        '/instance(/:tab)': ({ tab }: { tab?: InstanceStatusTabName }) => {
            const currentTab = tab && ['metrics', 'settings', 'staff_users'].includes(tab) ? tab : 'overview'
            if (currentTab !== values.tab) {
                actions.setTab(currentTab)
            }
        },
    })),
    events(({ actions }) => ({
        afterMount: () => {
            actions.loadSystemStatus()
        },
    })),
])