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.1 KB
Raw Blame
import { MakeLogicType, afterMount, kea, path, selectors } from 'kea'
import { loaders } from 'kea-loaders'

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

import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'

import type { PatchedTeamTracingConfigApi, TeamTracingConfigApi } from 'products/tracing/frontend/generated/api.schemas'

/** Mirrors `DEFAULT_TRACES_RETENTION_DAYS` in products/tracing/backend/models.py. */
export const TRACES_RETENTION_DEFAULT_DAYS = 14

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingRetentionConfigLogicValues {
    retentionDays: number
    retentionLastUpdated: string | null
    tracingConfig: TeamTracingConfigApi | null
    tracingConfigLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingRetentionConfigLogicActions {
    loadTracingConfig: () => any
    loadTracingConfigFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTracingConfigSuccess: (
        tracingConfig: TeamTracingConfigApi,
        payload?: any
    ) => {
        tracingConfig: TeamTracingConfigApi
        payload?: any
    }
    updateRetentionDays: (retentionDays: number) => number
    updateRetentionDaysFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateRetentionDaysSuccess: (
        tracingConfig: TeamTracingConfigApi,
        payload?: number
    ) => {
        tracingConfig: TeamTracingConfigApi
        payload?: number
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingRetentionConfigLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        retentionDays: (tracingConfig: TeamTracingConfigApi | null) => number
        retentionLastUpdated: (tracingConfig: TeamTracingConfigApi | null) => string | null
    }
}

export type tracingRetentionConfigLogicType = MakeLogicType<
    tracingRetentionConfigLogicValues,
    tracingRetentionConfigLogicActions,
    Record<string, any>,
    tracingRetentionConfigLogicMeta
>

/**
 * The environment's default span retention.
 *
 * Separate from `tracingCorrelationConfigLogic`, which reads the same endpoint but only loads
 * when the person/session link flag is on — retention must load either way.
 */
export const tracingRetentionConfigLogic = kea<tracingRetentionConfigLogicType>([
    path(['products', 'tracing', 'frontend', 'components', 'TracingRetention', 'tracingRetentionConfigLogic']),

    loaders(() => ({
        tracingConfig: [
            null as TeamTracingConfigApi | null,
            {
                // The flat /api/projects/:team_id/ route is the canonical per-environment one.
                // The generated client only exposes the nested variant, whose viewset rejects
                // every request, so these URLs are deliberately hand-built (same as
                // tracingCorrelationConfigLogic).
                loadTracingConfig: async (): Promise<TeamTracingConfigApi> => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use organizationsProjectsTracingConfigRetrieve() from 'products/tracing/frontend/generated/api' instead.
                    return await api.get(`api/projects/${teamLogic.values.currentTeamId}/tracing_config/`)
                },
                updateRetentionDays: async (retentionDays: number): Promise<TeamTracingConfigApi> => {
                    const patch: PatchedTeamTracingConfigApi = { retention_days: retentionDays }
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use organizationsProjectsTracingConfigPartialUpdate() from 'products/tracing/frontend/generated/api' instead.
                        const updated: TeamTracingConfigApi = await api.update(
                            `api/projects/${teamLogic.values.currentTeamId}/tracing_config/`,
                            patch
                        )
                        lemonToast.success('Traces retention updated')
                        return updated
                    } catch (e: unknown) {
                        const err = e as { detail?: string; message?: string }
                        lemonToast.error(err?.detail ?? err?.message ?? 'Failed to update retention')
                        throw e
                    }
                },
            },
        ],
    })),

    selectors({
        retentionDays: [
            (s) => [s.tracingConfig],
            (tracingConfig: TeamTracingConfigApi | null): number =>
                tracingConfig?.retention_days ?? TRACES_RETENTION_DEFAULT_DAYS,
        ],
        retentionLastUpdated: [
            (s) => [s.tracingConfig],
            (tracingConfig: TeamTracingConfigApi | null): string | null =>
                tracingConfig?.retention_last_updated ?? null,
        ],
    }),

    afterMount(({ actions }) => {
        actions.loadTracingConfig()
    }),
])