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.5 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'

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

import type { TeamLogsConfigApi } from './generated/api.schemas'

// Mirrors the backend default in products/logs/backend/models.py — the convention
// documented at https://posthog.com/docs/logs/link-session-replay. Used as the
// pre-load fallback for the attribute-key caption in `PersonLogsTab` before
// `logs_config` resolves.
export const DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY = 'posthogDistinctId'

export const DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS = [DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY]

// Mirrors the backend default in products/logs/backend/models.py. Ordered: session ID
// detection checks keys in list order and the first match wins.
export const DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS = ['sessionId']

export const DEFAULT_LOGS_PATTERN_MESSAGE_KEYS = ['message', 'msg', 'event']

async function saveLogsConfig(teamId: number | null, patch: Partial<TeamLogsConfigApi>): Promise<TeamLogsConfigApi> {
    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use organizationsProjectsLogsConfigPartialUpdate() from 'products/logs/frontend/generated/api' instead.
    return await api.update(`api/projects/${teamId}/logs_config/`, patch)
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsConfigLogicValues {
    currentTeamId: number | null // teamLogic
    configuredDistinctIdKeys: string[] | undefined
    configuredSessionIdKeys: string[] | undefined
    isPatternMessageKeysSubmitting: boolean
    isPatternMessageKeysValid: boolean
    logsConfig: TeamLogsConfigApi | null
    logsConfigLoading: boolean
    patternMessageKeys: {
        keys: string[]
    }
    patternMessageKeysAllErrors: Record<string, any>
    patternMessageKeysChanged: boolean
    patternMessageKeysErrors: DeepPartialMap<
        {
            keys: string[]
        },
        ValidationErrorType
    >
    patternMessageKeysHasErrors: boolean
    patternMessageKeysManualErrors: Record<string, any>
    patternMessageKeysTouched: boolean
    patternMessageKeysTouches: Record<string, boolean>
    patternMessageKeysValidationErrors: DeepPartialMap<
        {
            keys: string[]
        },
        ValidationErrorType
    >
    showPatternMessageKeysErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsConfigLogicActions {
    loadLogsConfig: () => any
    loadLogsConfigFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadLogsConfigSuccess: (
        logsConfig: TeamLogsConfigApi,
        payload?: any
    ) => {
        logsConfig: TeamLogsConfigApi
        payload?: any
    }
    resetPatternMessageKeys: (values?: { keys: string[] }) => {
        values?: {
            keys: string[]
        }
    }
    setPatternMessageKeysManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setPatternMessageKeysValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setPatternMessageKeysValues: (
        values: DeepPartial<{
            keys: string[]
        }>
    ) => {
        values: DeepPartial<{
            keys: string[]
        }>
    }
    submitPatternMessageKeys: () => {
        value: boolean
    }
    submitPatternMessageKeysFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitPatternMessageKeysRequest: (patternMessageKeys: { keys: string[] }) => {
        patternMessageKeys: {
            keys: string[]
        }
    }
    submitPatternMessageKeysSuccess: (patternMessageKeys: { keys: string[] }) => {
        patternMessageKeys: {
            keys: string[]
        }
    }
    touchPatternMessageKeysField: (key: string) => {
        key: string
    }
    updateLogsConfig: (patch: Partial<TeamLogsConfigApi>) => Partial<TeamLogsConfigApi>
    updateLogsConfigFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateLogsConfigSuccess: (
        logsConfig: TeamLogsConfigApi,
        payload?: Partial<TeamLogsConfigApi>
    ) => {
        logsConfig: TeamLogsConfigApi
        payload?: Partial<TeamLogsConfigApi>
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsConfigLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        configuredDistinctIdKeys: (logsConfig: TeamLogsConfigApi | null) => string[] | undefined
        configuredSessionIdKeys: (logsConfig: TeamLogsConfigApi | null) => string[] | undefined
    }
}

export type logsConfigLogicType = MakeLogicType<
    logsConfigLogicValues,
    logsConfigLogicActions,
    Record<string, any>,
    logsConfigLogicMeta
>

export const logsConfigLogic = kea<logsConfigLogicType>([
    path(['products', 'logs', 'frontend', 'logsConfigLogic']),
    connect({ values: [teamLogic, ['currentTeamId']] }),
    forms(({ actions, values }) => ({
        patternMessageKeys: {
            defaults: { keys: DEFAULT_LOGS_PATTERN_MESSAGE_KEYS },
            errors: ({ keys }) => {
                const cleaned = keys.map((key) => key.trim())
                const error =
                    cleaned.length > 10
                        ? 'Use at most 10 keys.'
                        : cleaned.some((key) => !key)
                          ? 'Keys cannot be blank.'
                          : cleaned.some((key) => key.length > 200)
                            ? 'Each key must be 200 characters or fewer.'
                            : new Set(cleaned).size !== cleaned.length
                              ? 'Keys must be unique.'
                              : undefined
                return { keys: error ? [error] : undefined }
            },
            submit: async ({ keys }) => {
                const config = await saveLogsConfig(values.currentTeamId, {
                    logs_pattern_message_keys: keys.map((key) => key.trim()),
                })
                actions.updateLogsConfigSuccess(config)
            },
        },
    })),
    loaders(({ values }) => ({
        logsConfig: [
            null as TeamLogsConfigApi | null,
            {
                loadLogsConfig: async (): Promise<TeamLogsConfigApi> => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use organizationsProjectsLogsConfigRetrieve() from 'products/logs/frontend/generated/api' instead.
                    return await api.get(`api/projects/${values.currentTeamId}/logs_config/`)
                },
                updateLogsConfig: async (patch: Partial<TeamLogsConfigApi>): Promise<TeamLogsConfigApi> => {
                    return await saveLogsConfig(values.currentTeamId, patch)
                },
            },
        ],
    })),
    selectors({
        // Undefined until logs_config resolves — distinct-id detection falls back to its
        // built-in convention list (which contains the default) in the meantime.
        configuredDistinctIdKeys: [
            (s) => [s.logsConfig],
            (logsConfig: TeamLogsConfigApi | null): string[] | undefined => logsConfig?.logs_distinct_id_attribute_keys,
        ],
        // Undefined until logs_config resolves — session detection falls back to its
        // built-in convention list (which contains the default) in the meantime.
        configuredSessionIdKeys: [
            (s) => [s.logsConfig],
            (logsConfig: TeamLogsConfigApi | null): string[] | undefined => logsConfig?.logs_session_id_attribute_keys,
        ],
    }),
    listeners(({ actions }) => ({
        loadLogsConfigSuccess: ({ logsConfig }) => {
            actions.resetPatternMessageKeys({
                keys: logsConfig.logs_pattern_message_keys ?? DEFAULT_LOGS_PATTERN_MESSAGE_KEYS,
            })
        },
        updateLogsConfigSuccess: ({ logsConfig }) => {
            actions.resetPatternMessageKeys({
                keys: logsConfig.logs_pattern_message_keys ?? DEFAULT_LOGS_PATTERN_MESSAGE_KEYS,
            })
        },
    })),
    afterMount(({ actions }) => {
        actions.loadLogsConfig()
    }),
])