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.

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

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

import { teamLogic } from 'scenes/teamLogic'

import { LogsRetentionRuleApi } from 'products/logs/frontend/generated/api.schemas'

import { LOGS_RETENTION_PRODUCT, RetentionRulesProduct } from './retentionRulesProduct'

export interface LogsRetentionSectionLogicProps {
    /** Which product's rules this instance shows. Defaults to logs. */
    product?: RetentionRulesProduct
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsRetentionSectionLogicValues {
    currentTeamId: number | null // teamLogic
    product: RetentionRulesProduct
    ruleEnabledTogglePendingId: string | null
    rules: LogsRetentionRuleApi[]
    rulesLoading: boolean
    saveRulesOrderPending: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsRetentionSectionLogicActions {
    loadRules: () => any
    loadRulesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRulesSuccess: (
        rules: LogsRetentionRuleApi[],
        payload?: any
    ) => {
        rules: LogsRetentionRuleApi[]
        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 logsRetentionSectionLogicMeta {
    key: 'logs' | 'spans'
    __keaTypeGenInternalSelectorTypes: {
        product: (arg: RetentionRulesProduct | undefined) => RetentionRulesProduct
    }
}

export type logsRetentionSectionLogicType = MakeLogicType<
    logsRetentionSectionLogicValues,
    logsRetentionSectionLogicActions,
    LogsRetentionSectionLogicProps,
    logsRetentionSectionLogicMeta
>

export const logsRetentionSectionLogic = kea<logsRetentionSectionLogicType>([
    path(['products', 'logs', 'frontend', 'components', 'LogsRetention', 'logsRetentionSectionLogic']),
    props({} as LogsRetentionSectionLogicProps),
    // Keyed so the logs and traces settings can be mounted at the same time without sharing rules.
    key(({ product }) => product?.source ?? LOGS_RETENTION_PRODUCT.source),

    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,
            },
        ],
    }),

    selectors({
        product: [
            () => [(_, props: LogsRetentionSectionLogicProps) => props.product],
            (product: RetentionRulesProduct | undefined): RetentionRulesProduct => product ?? LOGS_RETENTION_PRODUCT,
        ],
    }),

    loaders(({ values }) => ({
        rules: [
            [] as LogsRetentionRuleApi[],
            {
                loadRules: async () => {
                    const page = await values.product.api.list(String(values.currentTeamId))
                    return page.results
                },
            },
        ],
    })),

    listeners(({ actions, values }) => ({
        saveRulesOrder: async ({ orderedIds }) => {
            const projectId = values.currentTeamId
            if (projectId === null) {
                actions.saveRulesOrderFinished()
                return
            }
            try {
                await values.product.api.reorder(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 values.product.api.partialUpdate(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 }) => {
        actions.loadRules()
    }),
])