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.

8.0 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { lemonToast } from '@posthog/lemon-ui'

import { teamLogic } from 'scenes/teamLogic'

import {
    logsSamplingRulesList,
    logsSamplingRulesPartialUpdate,
    logsSamplingRulesReorderCreate,
} from 'products/logs/frontend/generated/api'
import { LogsSamplingRuleApi } from 'products/logs/frontend/generated/api.schemas'

import { type SamplingRuleDropTotals, fetchSamplingRuleDropTotalsLast24h } from './samplingRuleDropImpact'

// Background refresh cadence for the per-rule 24h drop counts. The underlying
// `app_metrics2` table flushes every ~1 min, so a 30s tick is fast enough that
// the user sees the new numbers shortly after they arrive without spamming
// HogQL. The disposables plugin pauses the timer while the tab is hidden.
const IMPACT_POLL_INTERVAL_MS = 30_000

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsSamplingSectionLogicValues {
    currentTeamId: number | null // teamLogic
    ruleDropImpact: Record<string, SamplingRuleDropTotals>
    ruleDropImpactCellState: 'error' | 'loading' | 'ok' | 'unknown'
    ruleDropImpactLoading: boolean
    ruleDropImpactStatus: 'error' | 'idle' | 'loading' | 'ok'
    ruleEnabledTogglePendingId: string | null
    rules: LogsSamplingRuleApi[]
    rulesLoading: boolean
    saveRulesOrderPending: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsSamplingSectionLogicActions {
    loadRuleDropImpact: (_: any) => any
    loadRuleDropImpactFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRuleDropImpactSuccess: (
        ruleDropImpact: Record<string, SamplingRuleDropTotals>,
        payload?: any
    ) => {
        ruleDropImpact: Record<string, SamplingRuleDropTotals>
        payload?: any
    }
    loadRules: () => any
    loadRulesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRulesSuccess: (
        rules: LogsSamplingRuleApi[],
        payload?: any
    ) => {
        rules: LogsSamplingRuleApi[]
        payload?: any
    }
    saveRulesOrder: (orderedIds: string[]) => {
        orderedIds: string[]
    }
    saveRulesOrderFinished: () => {
        value: true
    }
    setRuleEnabled: (
        ruleId: string,
        enabled: boolean
    ) => {
        enabled: boolean
        ruleId: string
    }
    setRuleEnabledFinished: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsSamplingSectionLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        ruleDropImpactCellState: (
            ruleDropImpactStatus: 'error' | 'idle' | 'loading' | 'ok',
            ruleDropImpactLoading: boolean,
            rules: LogsSamplingRuleApi[]
        ) => 'error' | 'loading' | 'ok' | 'unknown'
    }
}

export type logsSamplingSectionLogicType = MakeLogicType<
    logsSamplingSectionLogicValues,
    logsSamplingSectionLogicActions,
    Record<string, any>,
    logsSamplingSectionLogicMeta
>

export const logsSamplingSectionLogic = kea<logsSamplingSectionLogicType>([
    path(['products', 'logs', 'frontend', 'components', 'LogsSampling', 'logsSamplingSectionLogic']),

    connect({
        values: [teamLogic, ['currentTeamId']],
    }),

    actions({
        saveRulesOrder: (orderedIds: string[]) => ({ orderedIds }),
        saveRulesOrderFinished: true,
        setRuleEnabled: (ruleId: string, enabled: boolean) => ({ ruleId, enabled }),
        setRuleEnabledFinished: true,
    }),

    reducers({
        saveRulesOrderPending: [
            false,
            {
                saveRulesOrder: () => true,
                saveRulesOrderFinished: () => false,
            },
        ],
        ruleEnabledTogglePendingId: [
            null as string | null,
            {
                setRuleEnabled: (_, { ruleId }) => ruleId,
                setRuleEnabledFinished: () => null,
            },
        ],
    }),

    loaders(({ values }) => ({
        rules: [
            [] as LogsSamplingRuleApi[],
            {
                loadRules: async () => {
                    const projectId = String(values.currentTeamId)
                    const page = await logsSamplingRulesList(projectId)
                    return page.results
                },
            },
        ],
        ruleDropImpact: [
            {} as Record<string, SamplingRuleDropTotals>,
            {
                loadRuleDropImpact: async (_, breakpoint) => {
                    const rules = values.rules
                    const ids = rules.map((r) => r.id)
                    if (ids.length === 0) {
                        return {}
                    }
                    await breakpoint(1)
                    return await fetchSamplingRuleDropTotalsLast24h(ids)
                },
            },
        ],
    })),

    reducers({
        ruleDropImpactStatus: [
            'idle' as 'idle' | 'loading' | 'ok' | 'error',
            {
                loadRuleDropImpact: () => 'loading',
                loadRuleDropImpactSuccess: () => 'ok',
                loadRuleDropImpactFailure: () => 'error',
            },
        ],
    }),

    selectors({
        ruleDropImpactCellState: [
            (s) => [s.ruleDropImpactStatus, s.ruleDropImpactLoading, s.rules],
            (
                status: 'idle' | 'loading' | 'ok' | 'error',
                loading: boolean,
                rules: LogsSamplingRuleApi[]
            ): 'loading' | 'ok' | 'error' | 'unknown' => {
                if (loading || (status === 'idle' && rules.length > 0)) {
                    return 'loading'
                }
                if (status === 'error') {
                    return 'error'
                }
                if (status === 'ok') {
                    return 'ok'
                }
                return 'unknown'
            },
        ],
    }),

    listeners(({ actions, values }) => ({
        loadRulesSuccess: () => {
            actions.loadRuleDropImpact(undefined)
        },
        saveRulesOrder: async ({ orderedIds }) => {
            const projectId = values.currentTeamId
            if (projectId === null) {
                actions.saveRulesOrderFinished()
                return
            }
            try {
                await logsSamplingRulesReorderCreate(String(projectId), { ordered_ids: orderedIds })
                lemonToast.success('Evaluation order updated')
                await actions.loadRules()
            } catch (e: unknown) {
                const err = e as { detail?: string; message?: string }
                lemonToast.error(err?.detail ?? err?.message ?? 'Failed to update order')
                await actions.loadRules()
            } finally {
                actions.saveRulesOrderFinished()
            }
        },
        setRuleEnabled: async ({ ruleId, enabled }) => {
            const projectId = values.currentTeamId
            if (projectId === null) {
                actions.setRuleEnabledFinished()
                return
            }
            try {
                await logsSamplingRulesPartialUpdate(String(projectId), ruleId, { enabled })
                await actions.loadRules()
            } catch (e: unknown) {
                const err = e as { detail?: string; message?: string }
                lemonToast.error(err?.detail ?? err?.message ?? 'Failed to update rule')
                await actions.loadRules()
            } finally {
                actions.setRuleEnabledFinished()
            }
        },
    })),

    afterMount(({ actions, cache }) => {
        actions.loadRules()
        cache.disposables.add(() => {
            const pollTimer = window.setInterval(() => {
                actions.loadRuleDropImpact(undefined)
            }, IMPACT_POLL_INTERVAL_MS)
            return () => clearInterval(pollTimer)
        }, 'impactPoller')
    }),
])