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.6 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 { resolveTeamGitHubIntegration } from 'lib/integrations/GitHubIntegrationHelpers'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { uuid } from 'lib/utils/dom'
import { onboardingLogic } from 'scenes/onboarding/onboardingLogic'
import { wizardInstallStepLogic } from 'scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic'

import type { IntegrationType } from '~/types'

import { getIntegrationsAuthorizeRetrieveUrl } from 'products/integrations/frontend/generated/api'

import { wizardRegistryList, wizardRunsCreate } from '../../generated/api'
import type { WizardProgramApi, WizardRunApi, WizardRunCreateRequestApi } from '../../generated/api.schemas'
import { wizardEventProperties } from '../../lib/wizardAnalytics'
import { wizardRunIsActive } from '../../lib/wizardRunDisplay'
import { wizardRunSyncLogic } from '../../logics/wizardRunSyncLogic'
import { onboardingWizardRunLogic } from './onboardingWizardRunLogic'

export interface WizardOnboardingCloudRunProps {
    projectId: string
    userId: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface wizardOnboardingCloudRunLogicValues {
    githubIntegrations: IntegrationType[] // integrationsLogic
    integrations: IntegrationType[] | null // integrationsLogic
    integrationsLoading: boolean // integrationsLogic
    installStepReturnUrl: string // onboardingLogic
    run: WizardRunApi | null // onboardingWizardRunLogic
    cloudRunEnabled: boolean // wizardInstallStepLogic
    connectGitHubUrl: string
    createError: string | null
    createRunRequest: WizardRunApi | null
    createRunRequestLoading: boolean
    githubIntegration: IntegrationType | null
    idempotencyKey: string
    mode: 'cloud' | 'local'
    program: WizardProgramApi | null
    registry: WizardProgramApi[] | null
    registryError: boolean
    registryLoading: boolean
    repository: string
    runActive: boolean
    setupError: string | null
    setupLoading: boolean
    startLabel: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface wizardOnboardingCloudRunLogicActions {
    loadIntegrations: (_?: any) => any // integrationsLogic
    createRunRequest: (body: WizardRunCreateRequestApi) => WizardRunCreateRequestApi
    createRunRequestFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createRunRequestSuccess: (
        createRunRequest: WizardRunApi,
        payload?: WizardRunCreateRequestApi
    ) => {
        createRunRequest: WizardRunApi
        payload?: WizardRunCreateRequestApi
    }
    loadRegistry: () => any
    loadRegistryFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRegistrySuccess: (
        registry: WizardProgramApi[],
        payload?: any
    ) => {
        registry: WizardProgramApi[]
        payload?: any
    }
    retrySetup: () => {
        value: true
    }
    rotateIdempotencyKey: () => {
        value: true
    }
    setMode: (mode: 'cloud' | 'local') => {
        mode: 'cloud' | 'local'
    }
    setRepository: (repository: string) => {
        idempotencyKey: string
        repository: string
    }
    startCloudRun: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface wizardOnboardingCloudRunLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        githubIntegration: (githubIntegrations: IntegrationType[]) => IntegrationType | null
        program: (registry: WizardProgramApi[] | null) => WizardProgramApi | null
        setupLoading: (
            integrationsLoading: boolean,
            registryLoading: boolean,
            registry: WizardProgramApi[] | null,
            registryError: boolean
        ) => boolean
        setupError: (integrations: IntegrationType[] | null, registryError: boolean) => string | null
        startLabel: (run: WizardRunApi | null) => string
        runActive: (run: WizardRunApi | null) => boolean
        connectGitHubUrl: (installStepReturnUrl: string) => string
    }
}

export type wizardOnboardingCloudRunLogicType = MakeLogicType<
    wizardOnboardingCloudRunLogicValues,
    wizardOnboardingCloudRunLogicActions,
    WizardOnboardingCloudRunProps,
    wizardOnboardingCloudRunLogicMeta
>

export const wizardOnboardingCloudRunLogic = kea<wizardOnboardingCloudRunLogicType>([
    props({} as WizardOnboardingCloudRunProps),
    key(({ projectId, userId }) => `${projectId}.${userId}`),
    path((key) => ['products', 'wizard', 'wizardOnboardingCloudRunLogic', key]),
    connect((props: WizardOnboardingCloudRunProps) => ({
        values: [
            integrationsLogic,
            ['githubIntegrations', 'integrations', 'integrationsLoading'],
            wizardInstallStepLogic,
            ['cloudRunEnabled'],
            onboardingLogic,
            ['installStepReturnUrl'],
            onboardingWizardRunLogic(props),
            ['run'],
        ],
        actions: [integrationsLogic, ['loadIntegrations']],
    })),
    actions({
        setMode: (mode: 'cloud' | 'local') => ({ mode }),
        setRepository: (repository: string) => ({ repository, idempotencyKey: uuid() }),
        rotateIdempotencyKey: true,
        startCloudRun: true,
        retrySetup: true,
    }),
    reducers({
        mode: ['cloud' as 'cloud' | 'local', { setMode: (_, { mode }) => mode }],
        repository: ['', { setRepository: (_, { repository }) => repository }],
        idempotencyKey: [
            () => uuid(),
            {
                setRepository: (_, { idempotencyKey }) => idempotencyKey,
                createRunRequestSuccess: () => uuid(),
                rotateIdempotencyKey: () => uuid(),
            },
        ],
        registryError: [false, { loadRegistry: () => false, loadRegistryFailure: () => true }],
        createError: [
            null as string | null,
            {
                createRunRequest: () => null,
                setRepository: () => null,
                // The API explains limits and invalid input in `detail`. Network failures have none.
                createRunRequestFailure: (_, { errorObject }) =>
                    errorObject instanceof ApiError && errorObject.detail
                        ? errorObject.detail
                        : 'Could not start the cloud run. Check the repository and try again.',
            },
        ],
    }),
    loaders(({ props }) => ({
        registry: [
            null as WizardProgramApi[] | null,
            {
                loadRegistry: async () =>
                    (await wizardRegistryList(props.projectId, { limit: 100, offset: 0 })).results,
            },
        ],
        createRunRequest: [
            null as WizardRunApi | null,
            {
                createRunRequest: async (body: WizardRunCreateRequestApi) => wizardRunsCreate(props.projectId, body),
            },
        ],
    })),
    selectors(({ props }) => ({
        githubIntegration: [
            (s) => [s.githubIntegrations],
            (integrations: IntegrationType[]): IntegrationType | null =>
                resolveTeamGitHubIntegration(integrations) ?? null,
        ],
        program: [
            (s) => [s.registry],
            (registry: WizardProgramApi[] | null): WizardProgramApi | null =>
                registry?.find(
                    (program) =>
                        program.id === 'posthog-integration' && program.supported_environments.includes('cloud')
                ) ?? null,
        ],
        setupLoading: [
            (s) => [s.integrationsLoading, s.registryLoading, s.registry, s.registryError],
            (
                integrationsLoading: boolean,
                registryLoading: boolean,
                registry: WizardProgramApi[] | null,
                registryError: boolean
            ): boolean => integrationsLoading || registryLoading || (registry === null && !registryError),
        ],
        setupError: [
            (s) => [s.integrations, s.registryError],
            (integrations: IntegrationType[] | null, registryError: boolean): string | null =>
                !integrations
                    ? 'Could not check the GitHub connection. Retry or run it yourself.'
                    : registryError
                      ? 'Could not load the setup program. Retry or run it yourself.'
                      : null,
        ],
        startLabel: [
            (s) => [s.run],
            (run: WizardRunApi | null): string =>
                run && ['failed', 'cancelled'].includes(run.status) ? 'Retry cloud setup' : 'Install PostHog here',
        ],
        runActive: [(s) => [s.run], (run: WizardRunApi | null): boolean => !!run && wizardRunIsActive(run)],
        connectGitHubUrl: [
            (s) => [s.installStepReturnUrl],
            (returnUrl: string): string =>
                `${getIntegrationsAuthorizeRetrieveUrl(props.projectId)}?${new URLSearchParams({ kind: 'github', next: returnUrl })}`,
        ],
    })),
    listeners(({ actions, values, props, cache }) => ({
        retrySetup: () => {
            if (!values.integrations) {
                actions.loadIntegrations()
            } else {
                actions.loadRegistry()
            }
        },
        setMode: ({ mode }) => {
            posthog.capture('onboarding install mode selected', { mode })
        },
        startCloudRun: () => {
            if (
                !values.cloudRunEnabled ||
                values.runActive ||
                values.createRunRequestLoading ||
                !values.githubIntegration ||
                !values.repository ||
                !values.program
            ) {
                return
            }
            // A create request whose response got lost keeps its key, so a retry with that key
            // returns the same run. A retry of a terminal run must start a new run, so rotate the
            // key once per terminal run. Later retries of the same run reuse the key and stay idempotent.
            if (values.run && !wizardRunIsActive(values.run) && cache.retriedRunId !== values.run.id) {
                cache.retriedRunId = values.run.id
                actions.rotateIdempotencyKey()
            }
            posthog.capture('wizard run create requested', {
                ...wizardEventProperties(props.projectId, 'cloud'),
                location: 'onboarding',
                program_id: values.program.id,
            })
            actions.createRunRequest({
                program_id: values.program.id,
                wizard_version: values.program.wizard_version,
                environment: 'cloud',
                workspace: { type: 'git_repository', repository: values.repository },
                idempotency_key: values.idempotencyKey,
            })
        },
        createRunRequestSuccess: ({ createRunRequest: run }) => {
            const onboarding = onboardingWizardRunLogic(props)
            onboarding.actions.acceptCreatedRun(run)
            wizardRunSyncLogic({ projectId: props.projectId }).actions.runsLoaded([run], true)
        },
        createRunRequestFailure: () => {
            posthog.capture('wizard run create failed', {
                ...wizardEventProperties(props.projectId, 'cloud'),
                location: 'onboarding',
            })
        },
    })),
    afterMount(({ actions }) => {
        actions.loadIntegrations()
        actions.loadRegistry()
    }),
])