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.

18.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'

import { ApiError } from 'lib/api-error'
import { projectLogic } from 'scenes/projectLogic'

import {
    featureFlagsAnalyzeCodeCreate,
    featureFlagsCodeAnalysisRetrieve,
    featureFlagsCodeAnalysisTargetRetrieve,
    featureFlagsOpenCleanupPrCreate,
} from './generated/api'
import type { FeatureFlagCodeAnalysisApi, FeatureFlagCodeAnalysisTargetApi } from './generated/api.schemas'

export interface FeatureFlagCodeAnalysisLogicProps {
    id: number
}

const POLL_INTERVAL_MS = 5000
const MAX_POLL_FAILURES = 3
const POLL_KEY = 'codeAnalysisPoll'
// Keep in sync with CODE_ANALYSIS_UNAVAILABLE_CODE in products/feature_flags/backend/api/code_analysis.py.
const UNAVAILABLE_ERROR_CODE = 'code_analysis_unavailable'

function isUnavailableError(error: unknown): boolean {
    return error instanceof ApiError && error.status === 404 && error.code === UNAVAILABLE_ERROR_CODE
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagCodeAnalysisLogicValues {
    currentProjectId: number | null // projectLogic
    analysis: FeatureFlagCodeAnalysisApi | null
    analysisLoadError: string | null
    analysisLoaded: boolean
    analysisLoading: boolean
    cleanupError: string | null
    cleanupOutcome: string | null
    isCleanupRunning: boolean
    isRunning: boolean
    openingCleanupPr: boolean
    pollingStopped: boolean
    repository: string | null
    selectedCleanupOutcome: string | null
    selectedRepository: string | null
    startError: string | null
    startingAnalysis: boolean
    target: FeatureFlagCodeAnalysisTargetApi | null
    targetLoading: boolean
    unavailable: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagCodeAnalysisLogicActions {
    loadAnalysis: () => any
    loadAnalysisFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAnalysisSuccess: (
        analysis: FeatureFlagCodeAnalysisApi | null,
        payload?: any
    ) => {
        analysis: FeatureFlagCodeAnalysisApi | null
        payload?: any
    }
    loadTarget: () => any
    loadTargetFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTargetSuccess: (
        target: FeatureFlagCodeAnalysisTargetApi | null,
        payload?: any
    ) => {
        target: FeatureFlagCodeAnalysisTargetApi | null
        payload?: any
    }
    markUnavailable: () => {
        value: true
    }
    openCleanupPr: () => {
        value: true
    }
    openCleanupPrConflict: () => {
        value: true
    }
    openCleanupPrFailure: (error: string) => {
        error: string
    }
    openCleanupPrSuccess: (analysis: FeatureFlagCodeAnalysisApi) => {
        analysis: FeatureFlagCodeAnalysisApi
    }
    pollingFailed: () => {
        value: true
    }
    reportGitHubLinkClicked: () => {
        value: true
    }
    selectCleanupOutcome: (outcome: string) => {
        outcome: string
    }
    selectRepository: (repository: string) => {
        repository: string
    }
    startAnalysis: () => {
        value: true
    }
    startAnalysisConflict: () => {
        value: true
    }
    startAnalysisFailure: (error: string) => {
        error: string
    }
    startAnalysisSuccess: (analysis: FeatureFlagCodeAnalysisApi) => {
        analysis: FeatureFlagCodeAnalysisApi
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagCodeAnalysisLogicMeta {
    key: number
    __keaTypeGenInternalSelectorTypes: {
        repository: (
            selectedRepository: string | null,
            target: FeatureFlagCodeAnalysisTargetApi | null,
            analysis: FeatureFlagCodeAnalysisApi | null
        ) => string | null
        isRunning: (analysis: FeatureFlagCodeAnalysisApi | null) => boolean
        isCleanupRunning: (analysis: FeatureFlagCodeAnalysisApi | null) => boolean
        cleanupOutcome: (
            selectedCleanupOutcome: string | null,
            analysis: FeatureFlagCodeAnalysisApi | null
        ) => string | null
    }
}

export type featureFlagCodeAnalysisLogicType = MakeLogicType<
    featureFlagCodeAnalysisLogicValues,
    featureFlagCodeAnalysisLogicActions,
    FeatureFlagCodeAnalysisLogicProps,
    featureFlagCodeAnalysisLogicMeta
>

export const featureFlagCodeAnalysisLogic = kea<featureFlagCodeAnalysisLogicType>([
    path((key) => ['products', 'feature_flags', 'frontend', 'featureFlagCodeAnalysisLogic', key]),
    props({} as FeatureFlagCodeAnalysisLogicProps),
    key((props) => props.id),
    connect(() => ({ values: [projectLogic, ['currentProjectId']] })),

    actions({
        startAnalysis: true,
        startAnalysisSuccess: (analysis: FeatureFlagCodeAnalysisApi) => ({ analysis }),
        startAnalysisFailure: (error: string) => ({ error }),
        startAnalysisConflict: true,
        selectRepository: (repository: string) => ({ repository }),
        reportGitHubLinkClicked: true,
        pollingFailed: true,
        selectCleanupOutcome: (outcome: string) => ({ outcome }),
        openCleanupPr: true,
        openCleanupPrSuccess: (analysis: FeatureFlagCodeAnalysisApi) => ({ analysis }),
        openCleanupPrFailure: (error: string) => ({ error }),
        openCleanupPrConflict: true,
        markUnavailable: true,
    }),

    loaders(({ props, values, actions }) => ({
        target: [
            null as FeatureFlagCodeAnalysisTargetApi | null,
            {
                loadTarget: async () => {
                    try {
                        return await featureFlagsCodeAnalysisTargetRetrieve(String(values.currentProjectId), props.id)
                    } catch (error) {
                        if (isUnavailableError(error)) {
                            actions.markUnavailable()
                            return null
                        }
                        throw error
                    }
                },
            },
        ],
        analysis: [
            null as FeatureFlagCodeAnalysisApi | null,
            {
                loadAnalysis: async () => {
                    try {
                        return await featureFlagsCodeAnalysisRetrieve(String(values.currentProjectId), props.id)
                    } catch (error) {
                        if (isUnavailableError(error)) {
                            actions.markUnavailable()
                            return null
                        }
                        // Any other 404 means the flag was never analyzed, which is the empty state.
                        if (error instanceof ApiError && error.status === 404) {
                            return null
                        }
                        throw error
                    }
                },
            },
        ],
    })),

    reducers({
        analysis: {
            startAnalysisSuccess: (_, { analysis }) => analysis,
            openCleanupPrSuccess: (_, { analysis }) => analysis,
        },
        // `analysis` is null both before the first load and when the flag was never analyzed.
        analysisLoaded: [
            false,
            {
                loadAnalysisSuccess: () => true,
                startAnalysisSuccess: () => true,
            },
        ],
        analysisLoadError: [
            null as string | null,
            {
                loadAnalysisSuccess: () => null,
                loadAnalysisFailure: (_, { error }) => error,
                startAnalysisSuccess: () => null,
            },
        ],
        startingAnalysis: [
            false,
            {
                startAnalysis: () => true,
                startAnalysisSuccess: () => false,
                startAnalysisFailure: () => false,
                startAnalysisConflict: () => false,
                markUnavailable: () => false,
            },
        ],
        startError: [
            null as string | null,
            {
                startAnalysis: () => null,
                startAnalysisFailure: (_, { error }) => error,
            },
        ],
        selectedRepository: [
            null as string | null,
            {
                selectRepository: (_, { repository }) => repository,
            },
        ],
        openingCleanupPr: [
            false,
            {
                openCleanupPr: () => true,
                openCleanupPrSuccess: () => false,
                openCleanupPrFailure: () => false,
                openCleanupPrConflict: () => false,
                markUnavailable: () => false,
            },
        ],
        cleanupError: [
            null as string | null,
            {
                openCleanupPr: () => null,
                openCleanupPrFailure: (_, { error }) => error,
                startAnalysisSuccess: () => null,
            },
        ],
        selectedCleanupOutcome: [
            null as string | null,
            {
                selectCleanupOutcome: (_, { outcome }) => outcome,
                startAnalysisSuccess: () => null,
            },
        ],
        unavailable: [
            false,
            {
                markUnavailable: () => true,
            },
        ],
        // Polling gave up while the run may still be going, so the page offers a manual check.
        pollingStopped: [
            false,
            {
                pollingFailed: () => true,
                loadAnalysisSuccess: () => false,
                startAnalysisSuccess: () => false,
                openCleanupPrSuccess: () => false,
            },
        ],
    }),

    selectors({
        repository: [
            (s) => [s.selectedRepository, s.target, s.analysis],
            (
                selectedRepository: string | null,
                target: FeatureFlagCodeAnalysisTargetApi | null,
                analysis: FeatureFlagCodeAnalysisApi | null
            ): string | null => selectedRepository ?? target?.repository ?? analysis?.repository ?? null,
        ],
        isRunning: [
            (s) => [s.analysis],
            (analysis: FeatureFlagCodeAnalysisApi | null): boolean => !!analysis && !analysis.is_terminal,
        ],
        isCleanupRunning: [
            (s) => [s.analysis],
            (analysis: FeatureFlagCodeAnalysisApi | null): boolean =>
                !!analysis?.cleanup.run && !analysis.cleanup.run.is_terminal,
        ],
        // The suggested outcome is what every user gets today, so it is the default code to keep.
        cleanupOutcome: [
            (s) => [s.selectedCleanupOutcome, s.analysis],
            (selectedCleanupOutcome: string | null, analysis: FeatureFlagCodeAnalysisApi | null): string | null => {
                const cleanup = analysis?.cleanup
                if (!cleanup) {
                    return null
                }
                // A choice made against an earlier analysis may no longer be an option.
                return selectedCleanupOutcome && cleanup.outcome_options.includes(selectedCleanupOutcome)
                    ? selectedCleanupOutcome
                    : cleanup.suggested_outcome
            },
        ],
    }),

    listeners(({ actions, values, props, cache }) => {
        const startPolling = (): void => {
            cache.pollFailures = 0
            cache.disposables.add(() => {
                const id = setInterval(() => actions.loadAnalysis(), POLL_INTERVAL_MS)
                return () => clearInterval(id)
            }, POLL_KEY)
            cache.polling = true
        }
        const stopPolling = (): void => {
            cache.disposables.dispose(POLL_KEY)
            cache.polling = false
        }
        // Report only runs this page watched finish, not results loaded from an earlier visit.
        const reportFinishedRuns = (analysis: FeatureFlagCodeAnalysisApi): void => {
            if (analysis.is_terminal && cache.watchingAnalysis) {
                cache.watchingAnalysis = false
                // pinned: analytics event names, renaming breaks dashboards
                posthog.capture(
                    analysis.run_status === 'completed'
                        ? 'feature flag code analysis completed'
                        : 'feature flag code analysis failed',
                    {
                        flag_id: props.id,
                        run_status: analysis.run_status,
                        reference_count: analysis.result?.references.length ?? null,
                    }
                )
            }
            const cleanupRun = analysis.cleanup.run
            if (cleanupRun?.is_terminal && cache.watchingCleanup) {
                cache.watchingCleanup = false
                // pinned: analytics event name, renaming breaks dashboards
                posthog.capture('feature flag code cleanup pr finished', {
                    flag_id: props.id,
                    run_status: cleanupRun.run_status,
                    pr_opened: !!cleanupRun.pr_url,
                })
            }
        }
        const followAnalysis = (analysis: FeatureFlagCodeAnalysisApi | null): void => {
            if (!analysis) {
                stopPolling()
                return
            }
            reportFinishedRuns(analysis)
            const analysisRunning = !analysis.is_terminal
            const cleanupRunning = !!analysis.cleanup.run && !analysis.cleanup.run.is_terminal
            cache.watchingAnalysis = cache.watchingAnalysis || analysisRunning
            cache.watchingCleanup = cache.watchingCleanup || cleanupRunning
            if (!analysisRunning && !cleanupRunning) {
                stopPolling()
            } else if (!cache.polling) {
                startPolling()
            }
        }

        return {
            loadAnalysisSuccess: ({ analysis }) => {
                cache.pollFailures = 0
                followAnalysis(analysis)
            },
            loadAnalysisFailure: () => {
                // Tolerate transient errors, the run may still finish. Stop only when the endpoint keeps failing.
                cache.pollFailures = (cache.pollFailures ?? 0) + 1
                if (cache.polling && cache.pollFailures >= MAX_POLL_FAILURES) {
                    stopPolling()
                    actions.pollingFailed()
                }
            },
            startAnalysis: async () => {
                const repository = values.repository
                try {
                    const analysis = await featureFlagsAnalyzeCodeCreate(
                        String(values.currentProjectId),
                        props.id,
                        repository ? { repository } : {}
                    )
                    posthog.capture('feature flag code analysis started', {
                        flag_id: props.id,
                        repository_source: values.target?.source ?? null,
                    })
                    actions.startAnalysisSuccess(analysis)
                } catch (error) {
                    if (isUnavailableError(error)) {
                        actions.markUnavailable()
                        return
                    }
                    // Another run is in progress, so follow that one instead of failing.
                    if (error instanceof ApiError && error.status === 409) {
                        actions.startAnalysisConflict()
                        return
                    }
                    const detail =
                        error instanceof ApiError && error.detail
                            ? error.detail
                            : "Couldn't start the analysis. Try again in a moment."
                    actions.startAnalysisFailure(detail)
                }
            },
            startAnalysisSuccess: ({ analysis }) => {
                // A new run restarts tracking even if the previous one was still being watched.
                stopPolling()
                cache.watchingAnalysis = false
                followAnalysis(analysis)
            },
            startAnalysisConflict: () => {
                actions.loadAnalysis()
            },
            openCleanupPr: async () => {
                const keepOutcome = values.cleanupOutcome
                try {
                    const analysis = await featureFlagsOpenCleanupPrCreate(
                        String(values.currentProjectId),
                        props.id,
                        keepOutcome ? { keep_outcome: keepOutcome } : {}
                    )
                    // pinned: analytics event name, renaming breaks dashboards
                    posthog.capture('feature flag code cleanup pr requested', {
                        flag_id: props.id,
                        kept_suggested_outcome: keepOutcome === values.analysis?.cleanup.suggested_outcome,
                    })
                    actions.openCleanupPrSuccess(analysis)
                } catch (error) {
                    if (isUnavailableError(error)) {
                        actions.markUnavailable()
                        return
                    }
                    // Another request already opened one, so show that run instead of failing.
                    if (error instanceof ApiError && error.status === 409) {
                        actions.openCleanupPrConflict()
                        return
                    }
                    const detail =
                        error instanceof ApiError && error.detail
                            ? error.detail
                            : "Couldn't open the cleanup pull request. Try again in a moment."
                    actions.openCleanupPrFailure(detail)
                }
            },
            openCleanupPrSuccess: ({ analysis }) => {
                followAnalysis(analysis)
            },
            openCleanupPrConflict: () => {
                actions.loadAnalysis()
            },
            markUnavailable: () => {
                stopPolling()
            },
            reportGitHubLinkClicked: () => {
                posthog.capture('feature flag code analysis github link clicked', { flag_id: props.id })
            },
        }
    }),

    afterMount(({ actions }) => {
        actions.loadTarget()
        actions.loadAnalysis()
    }),
])