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, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { ProjectSecretAPIKeyApi } from '~/generated/core/api.schemas'

import { GatewayCredentialSpend, fetchGatewaySpendByCredential } from './gatewayKeySpendQuery'
import { projectSecretAPIKeysLogic } from './projectSecretAPIKeysLogic'

export const GATEWAY_SCOPE = 'llm_gateway:read'

export interface GatewayKeySpendRow {
    id: string
    label: string
    maskValue: string | null
    requests: number
    costUsd: number
}

export interface GatewayKeySpendSummary {
    rows: GatewayKeySpendRow[]
    /** Spend whose credential matches no current key: the key was rolled or deleted since. */
    unmatchedCostUsd: number
    /** Spend from generations made before the gateway attributed keys. */
    untaggedCostUsd: number
}

// A key is listed when it can call the gateway or has spend to show, so a key that lost the scope
// still accounts for what it spent while it had it.
export function buildGatewayKeySpendSummary(
    keys: ProjectSecretAPIKeyApi[],
    spend: GatewayCredentialSpend[] | null
): GatewayKeySpendSummary {
    const byCredential = new Map<string, GatewayCredentialSpend>()
    for (const entry of spend ?? []) {
        if (entry.credential) {
            byCredential.set(entry.credential, entry)
        }
    }
    const matched = new Set<string>()
    const rows: GatewayKeySpendRow[] = []
    for (const key of keys) {
        const hit = key.ai_credential ? byCredential.get(key.ai_credential) : undefined
        if (!hit && !key.scopes.includes(GATEWAY_SCOPE)) {
            continue
        }
        if (key.ai_credential) {
            matched.add(key.ai_credential)
        }
        rows.push({
            id: key.id,
            label: key.label,
            maskValue: key.mask_value,
            requests: hit?.requests ?? 0,
            costUsd: hit?.costUsd ?? 0,
        })
    }
    rows.sort((a, b) => b.costUsd - a.costUsd)

    let unmatchedCostUsd = 0
    let untaggedCostUsd = 0
    for (const entry of spend ?? []) {
        if (!entry.credential) {
            untaggedCostUsd += entry.costUsd
        } else if (!matched.has(entry.credential)) {
            unmatchedCostUsd += entry.costUsd
        }
    }
    return { rows, unmatchedCostUsd, untaggedCostUsd }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface gatewayKeySpendLogicValues {
    keys: ProjectSecretAPIKeyApi[] // projectSecretAPIKeysLogic
    hasGatewayKeys: boolean
    spend: GatewayCredentialSpend[] | null
    spendFailed: boolean
    spendLoading: boolean
    summary: GatewayKeySpendSummary
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface gatewayKeySpendLogicActions {
    loadKeysSuccess: (
        keys: ProjectSecretAPIKeyApi[],
        payload?:
            | {
                  value: true
              }
            | undefined
    ) => {
        keys: ProjectSecretAPIKeyApi[]
        payload?: {
            value: true
        }
    } // projectSecretAPIKeysLogic
    loadSpend: () => any
    loadSpendFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSpendSuccess: (
        spend: GatewayCredentialSpend[],
        payload?: any
    ) => {
        spend: GatewayCredentialSpend[]
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface gatewayKeySpendLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        hasGatewayKeys: (keys: ProjectSecretAPIKeyApi[]) => boolean
        summary: (keys: ProjectSecretAPIKeyApi[], spend: GatewayCredentialSpend[] | null) => GatewayKeySpendSummary
    }
}

export type gatewayKeySpendLogicType = MakeLogicType<
    gatewayKeySpendLogicValues,
    gatewayKeySpendLogicActions,
    Record<string, any>,
    gatewayKeySpendLogicMeta
>

export const gatewayKeySpendLogic = kea<gatewayKeySpendLogicType>([
    path(['scenes', 'settings', 'project', 'gatewayKeySpendLogic']),
    connect(() => ({
        values: [projectSecretAPIKeysLogic, ['keys']],
        actions: [projectSecretAPIKeysLogic, ['loadKeysSuccess']],
    })),
    // null until the first query answers, so the table shows skeletons rather than zeros.
    loaders(() => ({
        spend: [
            null as GatewayCredentialSpend[] | null,
            {
                loadSpend: async () => await fetchGatewaySpendByCredential(),
            },
        ],
    })),
    reducers({
        spendFailed: [false, { loadSpend: () => false, loadSpendFailure: () => true }],
    }),
    selectors({
        hasGatewayKeys: [
            (s) => [s.keys],
            (keys: ProjectSecretAPIKeyApi[]): boolean => keys.some((key) => key.scopes.includes(GATEWAY_SCOPE)),
        ],
        summary: [
            (s) => [s.keys, s.spend],
            (keys: ProjectSecretAPIKeyApi[], spend: GatewayCredentialSpend[] | null): GatewayKeySpendSummary =>
                buildGatewayKeySpendSummary(keys, spend),
        ],
    }),
    // The query runs only for a project with a gateway key, so every other settings visit skips it.
    listeners(({ actions, values }) => ({
        loadKeysSuccess: () => {
            if (values.hasGatewayKeys) {
                actions.loadSpend()
            }
        },
    })),
    afterMount(({ actions, values }) => {
        if (values.hasGatewayKeys) {
            actions.loadSpend()
        }
    }),
])