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.

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

import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic, FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { teamLogic } from 'scenes/teamLogic'

import { metricsNamesRetrieve } from 'products/metrics/frontend/generated/api'
import type { _MetricPickerNameApi } from 'products/metrics/frontend/generated/api.schemas'
import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'

export type MetricNameItem = _MetricPickerNameApi

// The API maximum. Most teams have fewer names, so one load holds the whole list
// and search filters it locally without a request.
export const METRIC_NAMES_LIMIT = 1000
const SEARCH_LIMIT = 100
// Opening the picker reloads a list older than this, so names that started reporting since show up.
const STALE_AFTER_MS = 60_000

/** Same rank as the backend search: exact, then prefix, then suffix, then server order. */
export function filterMetricNames(items: MetricNameItem[], search: string): MetricNameItem[] {
    const needle = search.trim().toLowerCase()
    if (!needle) {
        return items
    }
    const rank = (name: string): number =>
        name === needle ? 0 : name.startsWith(needle) ? 1 : name.endsWith(needle) ? 2 : 3
    return items
        .map((item) => ({ item, name: item.name.toLowerCase() }))
        .filter(({ name }) => name.includes(needle))
        .sort((a, b) => rank(a.name) - rank(b.name))
        .map(({ item }) => item)
}

/** The typed name to offer when no listed metric has it, for a metric with no data in the picker's 24 hours. */
export function customMetricName(items: MetricNameItem[], search: string): string | null {
    const name = search.trim()
    return name && !items.some((item) => item.name === name) ? name : null
}

function mergeMetricNames(items: MetricNameItem[], incoming: MetricNameItem[]): MetricNameItem[] {
    const known = new Set(items.map((item) => item.name))
    const added = incoming.filter((item) => !known.has(item.name))
    return added.length ? [...items, ...added] : items
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricNamePickerLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentTeamId: number | null // teamLogic
    filteredItems: MetricNameItem[]
    fullItems: MetricNameItem[]
    fullItemsLoading: boolean
    items: MetricNameItem[]
    itemsComplete: boolean
    scopeLoading: boolean
    search: string
    searchedItems: MetricNameItem[]
    searchedItemsLoading: boolean
    services: string[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricNamePickerLogicActions {
    dropSearchedItems: (names: string[]) => {
        names: string[]
    }
    loadItems: (_: void) => void
    loadItemsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadItemsSuccess: (
        fullItems: _MetricPickerNameApi[],
        payload?: void
    ) => {
        fullItems: _MetricPickerNameApi[]
        payload?: void
    }
    openPicker: () => {
        value: true
    }
    primeItems: () => {
        value: true
    }
    searchItems: (_: void) => void
    searchItemsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    searchItemsSuccess: (
        searchedItems: _MetricPickerNameApi[],
        payload?: void
    ) => {
        searchedItems: _MetricPickerNameApi[]
        payload?: void
    }
    setSearch: (search: string) => {
        search: string
    }
    setServices: (services: string[]) => {
        services: string[]
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricNamePickerLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        items: (fullItems: _MetricPickerNameApi[], searchedItems: _MetricPickerNameApi[]) => MetricNameItem[]
        filteredItems: (items: _MetricPickerNameApi[], search: string, scopeLoading: boolean) => MetricNameItem[]
    }
}

export type metricNamePickerLogicType = MakeLogicType<
    metricNamePickerLogicValues,
    metricNamePickerLogicActions,
    Record<string, any>,
    metricNamePickerLogicMeta
>

export const metricNamePickerLogic = kea<metricNamePickerLogicType>([
    path(['products', 'metrics', 'frontend', 'components', 'metricNamePickerLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],
    })),
    actions({
        // Loads the list once per mount. The scene gate calls it again after the feature preview is on,
        // because the scene logic mounts this logic before the gate renders.
        primeItems: true,
        openPicker: true,
        dropSearchedItems: (names: string[]) => ({ names }),
        setSearch: (search: string) => ({ search }),
        // Pushed in by the viewer rather than read from it: the viewer already
        // reads this logic's `items`, so a connection the other way would cycle.
        setServices: (services: string[]) => ({ services }),
    }),
    reducers({
        search: ['' as string, { setSearch: (_, { search }) => search }],
        services: [[] as string[], { setServices: (_, { services }) => services }],
        // True when the full load fit under the limit: then local filtering sees
        // every name in the scope, and a search with local matches needs no request.
        itemsComplete: [
            false,
            {
                setServices: () => false,
                loadItemsSuccess: (_, { fullItems }) => fullItems.length < METRIC_NAMES_LIMIT,
            },
        ],
    }),
    loaders(({ values, cache }) => {
        const fetchNames = async (
            search: string,
            limit: number,
            breakpoint: BreakPointFunction
        ): Promise<{ results: MetricNameItem[] }> => {
            try {
                return await metricsNamesRetrieve(String(values.currentTeamId), {
                    value: search,
                    limit,
                    // Joined here rather than passed as an array: the generated
                    // client stringifies params, and an empty array would send
                    // `service=`, which the API reads as the unnamed-sender scope.
                    ...(values.services.length ? { service: values.services.join(',') } : {}),
                })
            } finally {
                // Also on a failure: a request a newer call replaced must not end that call's loading state.
                breakpoint()
            }
        }
        return {
            // The full list for the current scope.
            fullItems: [
                [] as MetricNameItem[],
                {
                    loadItems: async (_: void, breakpoint) => {
                        if (!canViewMetrics()) {
                            return []
                        }
                        const response = await fetchNames('', METRIC_NAMES_LIMIT, breakpoint)
                        return response.results
                    },
                },
            ],
            // Names a server search found past the full list. Kept apart from the full list, so a
            // search never ends the full load's loading state or replaces its names.
            searchedItems: [
                [] as MetricNameItem[],
                {
                    // Runs on every search change, so a newer call cancels a pending one even when it sends nothing.
                    searchItems: async (_: void, breakpoint) => {
                        const search = values.search.trim()
                        if (!canViewMetrics() || !search || (values.itemsComplete && values.filteredItems.length > 0)) {
                            return values.searchedItems
                        }
                        // Keystrokes only — matches the 300ms cadence used in the viewer logic.
                        await breakpoint(300)
                        const services = values.services
                        const response = await fetchNames(search, SEARCH_LIMIT, breakpoint)
                        // A scope change while this ran cleared the list; old-scope names must not join it.
                        if (services !== values.services) {
                            return values.searchedItems
                        }
                        // Per name: a later search can find old-scope names again in the new scope.
                        cache.searchScopes ??= new Map<string, string[]>()
                        for (const item of response.results) {
                            cache.searchScopes.set(item.name, services)
                        }
                        // The newest reply replaces older entries, so a name keeps its type in the current scope.
                        const replied = new Set(response.results.map((item) => item.name))
                        return mergeMetricNames(
                            values.searchedItems.filter((item) => !replied.has(item.name)),
                            response.results
                        )
                    },
                },
            ],
        }
    }),
    reducers({
        searchedItems: {
            dropSearchedItems: (state, { names }) => {
                const dropped = new Set(names)
                return state.filter((item) => !dropped.has(item.name))
            },
        },
        // The old scope's names stay in `items` until the new list arrives, so the viewer can still
        // read the type of a name picked as the scope changes. The dropdown hides them meanwhile.
        scopeLoading: [
            false,
            { setServices: () => true, loadItemsSuccess: () => false, loadItemsFailure: () => false },
        ],
    }),
    selectors({
        items: [
            (s) => [s.fullItems, s.searchedItems],
            (fullItems: MetricNameItem[], searchedItems: MetricNameItem[]): MetricNameItem[] =>
                mergeMetricNames(fullItems, searchedItems),
        ],
        filteredItems: [
            (s) => [s.items, s.search, s.scopeLoading],
            (items: MetricNameItem[], search: string, scopeLoading: boolean): MetricNameItem[] =>
                scopeLoading ? [] : filterMetricNames(items, search),
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        primeItems: () => {
            if (cache.primed || !canViewMetrics()) {
                return
            }
            cache.primed = true
            actions.loadItems()
        },
        openPicker: () => {
            const stale = !cache.loadedAt || Date.now() - cache.loadedAt > STALE_AFTER_MS
            if (cache.primed && !values.fullItemsLoading && (stale || values.fullItems.length === 0)) {
                actions.loadItems()
            }
        },
        setSearch: () => {
            actions.searchItems()
        },
        // Not debounced: the scope changes on a click, not a keystroke.
        setServices: () => {
            actions.loadItems()
        },
        loadItemsSuccess: () => {
            cache.loadedAt = Date.now()
            const stale = values.searchedItems
                .map((item) => item.name)
                .filter((name) => cache.searchScopes?.get(name) !== values.services)
            if (stale.length) {
                actions.dropSearchedItems(stale)
            }
            if (values.search.trim()) {
                actions.searchItems()
            }
        },
    })),
    afterMount(({ actions, values }) => {
        // Prime the list so the dropdown isn't empty on first open. Mirrors
        // serviceFilterLogic's afterMount in logs. Without the flag the API rejects the request.
        if (values.featureFlags[FEATURE_FLAGS.METRICS]) {
            actions.primeItems()
        }
    }),
])