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.

6.0 KB
Raw Blame
import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import api from 'lib/api'
import { isDefinitionStale } from 'lib/utils/definitions'

import { EventDefinition } from '~/types'

/** Why an action match group matches nothing new, or is about to stop. */
export type EventHealthIssue = { status: 'stale'; lastSeenAt: string } | { status: 'missing' }

/** Definitions found, keyed by event name. A name that resolved to nothing maps to `null`. */
export type EventDefinitionsByName = Record<string, EventDefinition | null>

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface actionEventHealthLogicValues {
    definitions: EventDefinitionsByName
    definitionsLoading: boolean
    eventHealthIssues: Record<string, EventHealthIssue>
    requestedNames: string[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface actionEventHealthLogicActions {
    requestEventNames: (names: (string | null | undefined)[]) => {
        names: (string | null | undefined)[]
    }
    requestEventNamesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    requestEventNamesSuccess: (
        definitions: EventDefinitionsByName,
        payload?: {
            names: (string | null | undefined)[]
        }
    ) => {
        definitions: EventDefinitionsByName
        payload?: {
            names: (string | null | undefined)[]
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface actionEventHealthLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        eventHealthIssues: (definitions: EventDefinitionsByName) => Record<string, EventHealthIssue>
    }
}

export type actionEventHealthLogicType = MakeLogicType<
    actionEventHealthLogicValues,
    actionEventHealthLogicActions,
    Record<string, any>,
    actionEventHealthLogicMeta
>

/**
 * The `names` filter on `event_definitions` splits every value it receives on commas, so an event
 * name that contains one is asked about as two different names and never comes back. PostHog cannot
 * answer for such a name, and no tag is better than a "Not seen" tag on a step that matches fine.
 */
function isResolvableName(name: string | null | undefined): name is string {
    return !!name && !name.includes(',')
}

/**
 * Proxies reject a request line longer than about 4k, the limit `propertyDefinitionsModel` already
 * batches against. One batch spends `names=` plus the encoded name on every event, and an event
 * name holds up to 400 characters, so a count cap alone would not bound the URL. Budget for the
 * names and leave the rest of the 4k for the path and `limit`.
 */
const MAX_NAMES_QUERY_LENGTH = 3000

function chunkByQueryLength(names: string[]): string[][] {
    const chunks: string[][] = []
    let chunk: string[] = []
    let length = 0
    for (const name of names) {
        const cost = 'names='.length + encodeURIComponent(name).length + 1
        if (chunk.length > 0 && length + cost > MAX_NAMES_QUERY_LENGTH) {
            chunks.push(chunk)
            chunk = []
            length = 0
        }
        chunk.push(name)
        length += cost
    }
    if (chunk.length > 0) {
        chunks.push(chunk)
    }
    return chunks
}

export const actionEventHealthLogic = kea<actionEventHealthLogicType>([
    path(['products', 'actions', 'actionEventHealthLogic']),
    actions({
        requestEventNames: (names: (string | null | undefined)[]) => ({ names }),
    }),
    reducers({
        requestedNames: [
            [] as string[],
            {
                requestEventNames: (state, { names }) => [...new Set([...state, ...names.filter(isResolvableName)])],
            },
        ],
    }),
    loaders(({ values }) => ({
        definitions: [
            // Event names come from the customer, so one can be `constructor` or `__proto__`. These
            // maps carry no prototype, so `in` and an indexed read see only names PostHog resolved,
            // and a write to `__proto__` adds a key instead of re-parenting the map.
            Object.create(null) as EventDefinitionsByName,
            {
                requestEventNames: async (_, breakpoint) => {
                    // One page of actions asks for its events row by row, so wait for the burst to settle.
                    await breakpoint(50)
                    const missing = values.requestedNames.filter((name) => !(name in values.definitions))
                    if (!missing.length) {
                        return values.definitions
                    }
                    const resolved: EventDefinitionsByName = Object.assign(Object.create(null), values.definitions)
                    for (const name of missing) {
                        resolved[name] = null
                    }
                    for (const chunk of chunkByQueryLength(missing)) {
                        const response = await api.eventDefinitions.list({ names: chunk, limit: chunk.length })
                        breakpoint()
                        for (const definition of response.results) {
                            resolved[definition.name] = definition
                        }
                    }
                    return resolved
                },
            },
        ],
    })),
    selectors({
        eventHealthIssues: [
            (s) => [s.definitions],
            (definitions: EventDefinitionsByName): Record<string, EventHealthIssue> => {
                const issues: Record<string, EventHealthIssue> = Object.create(null)
                for (const [name, definition] of Object.entries(definitions)) {
                    if (!definition) {
                        issues[name] = { status: 'missing' }
                    } else if (definition.last_seen_at && isDefinitionStale(definition)) {
                        issues[name] = { status: 'stale', lastSeenAt: definition.last_seen_at }
                    }
                }
                return issues
            },
        ],
    }),
])