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.8 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'

import { teamLogic } from 'scenes/teamLogic'

import type { DateRange } from '~/queries/schema/schema-general'

import { serviceViewerUrl } from 'products/logs/frontend/components/LogsServices/serviceViewerUrl'
import { logsAnomaliesSeriesBandsCreate } from 'products/logs/frontend/generated/api'
import type { LogsSeriesBandSeriesApi, LogsSeriesBandsResponseApi } from 'products/logs/frontend/generated/api.schemas'

export const DEFAULT_VISIBLE_SERIES = 12
// Shared with the URL sync in logsSceneLogic, which drops the param at this value.
export const DEFAULT_ANOMALIES_DATE_RANGE: DateRange = { date_from: '-7d' }

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAnomaliesLogicValues {
    currentTeamId: number | null // teamLogic
    dateRange: DateRange
    hiddenSeriesCount: number
    seriesBands: LogsSeriesBandsResponseApi | null
    seriesBandsError: string | null
    seriesBandsLoading: boolean
    serviceName: string | null
    visibleSeries: LogsSeriesBandSeriesApi[]
    visibleSeriesCount: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAnomaliesLogicActions {
    loadSeriesBands: (_: any) => any
    loadSeriesBandsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSeriesBandsSuccess: (
        seriesBands: LogsSeriesBandsResponseApi | null,
        payload?: any
    ) => {
        seriesBands: LogsSeriesBandsResponseApi | null
        payload?: any
    }
    openLogsForBucket: (
        severity: string,
        dateRange: DateRange
    ) => {
        dateRange: DateRange
        severity: string
    }
    setDateRange: (dateRange: DateRange) => {
        dateRange: DateRange
    }
    setServiceName: (serviceName: string | null) => {
        serviceName: string | null
    }
    showMoreSeries: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAnomaliesLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        visibleSeries: (
            seriesBands: LogsSeriesBandsResponseApi | null,
            visibleSeriesCount: number
        ) => LogsSeriesBandSeriesApi[]
        hiddenSeriesCount: (seriesBands: LogsSeriesBandsResponseApi | null, visibleSeriesCount: number) => number
    }
}

export type logsAnomaliesLogicType = MakeLogicType<
    logsAnomaliesLogicValues,
    logsAnomaliesLogicActions,
    Record<string, any>,
    logsAnomaliesLogicMeta
>

export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
    path(['products', 'logs', 'frontend', 'logsAnomaliesLogic']),
    connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
    actions({
        setServiceName: (serviceName: string | null) => ({ serviceName }),
        setDateRange: (dateRange: DateRange) => ({ dateRange }),
        showMoreSeries: true,
        openLogsForBucket: (severity: string, dateRange: DateRange) => ({ severity, dateRange }),
    }),

    loaders(({ values }) => ({
        seriesBands: [
            null as LogsSeriesBandsResponseApi | null,
            {
                loadSeriesBands: async (_, breakpoint) => {
                    if (!values.serviceName || !values.currentTeamId) {
                        return null
                    }
                    const response = await logsAnomaliesSeriesBandsCreate(String(values.currentTeamId), {
                        serviceName: values.serviceName,
                        dateRange: values.dateRange,
                    })
                    // A slow service can resolve after the user has moved to another one. Without
                    // this the late response would chart itself under the new service's name.
                    breakpoint()
                    return response
                },
            },
        ],
    })),
    reducers({
        serviceName: [
            null as string | null,
            {
                setServiceName: (_, { serviceName }) => serviceName,
            },
        ],
        dateRange: [
            DEFAULT_ANOMALIES_DATE_RANGE as DateRange,
            {
                setDateRange: (_, { dateRange }) => dateRange,
            },
        ],
        // Charts from the previous service would misread as the new one, so a
        // service switch drops straight to the loading state.
        seriesBands: {
            setServiceName: () => null,
        },
        // The loader leaves the value null on failure, which reads the same as "still loading",
        // so the failure needs its own value for the tab to show a retry instead of a spinner.
        seriesBandsError: [
            null as string | null,
            {
                setServiceName: () => null,
                loadSeriesBands: () => null,
                loadSeriesBandsSuccess: () => null,
                // A rejected window is the user's to fix, so the backend's sentence has to reach
                // the banner ahead of the generic "Non-OK response" message.
                loadSeriesBandsFailure: (_, { error, errorObject }) =>
                    errorObject?.data?.error || errorObject?.detail || error || 'The request did not complete.',
            },
        ],
        visibleSeriesCount: [
            DEFAULT_VISIBLE_SERIES as number,
            {
                setServiceName: () => DEFAULT_VISIBLE_SERIES,
                showMoreSeries: (state) => state + DEFAULT_VISIBLE_SERIES,
            },
        ],
    }),
    selectors({
        visibleSeries: [
            (s) => [s.seriesBands, s.visibleSeriesCount],
            (seriesBands: LogsSeriesBandsResponseApi | null, visibleSeriesCount: number): LogsSeriesBandSeriesApi[] =>
                seriesBands ? seriesBands.series.slice(0, visibleSeriesCount) : [],
        ],
        hiddenSeriesCount: [
            (s) => [s.seriesBands, s.visibleSeriesCount],
            (seriesBands: LogsSeriesBandsResponseApi | null, visibleSeriesCount: number): number =>
                seriesBands ? Math.max(0, seriesBands.series.length - visibleSeriesCount) : 0,
        ],
    }),
    listeners(({ actions, values }) => ({
        setServiceName: ({ serviceName }) => {
            if (serviceName) {
                actions.loadSeriesBands({})
            }
        },
        setDateRange: () => {
            if (values.serviceName) {
                actions.loadSeriesBands({})
            }
        },
        openLogsForBucket: ({ severity, dateRange }) => {
            if (!values.serviceName) {
                return
            }
            router.actions.push(serviceViewerUrl(values.serviceName, { severityLevels: [severity], dateRange }))
        },
    })),
])