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.5 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import posthog from 'posthog-js'

import { ApiError } from 'lib/api-error'
import { dayjs } from 'lib/dayjs'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'

import { HogFunctionType, HogFunctionTypeType } from '~/types'

import {
    hogFunctionsDiscardDraftCreate,
    hogFunctionsPublishCreate,
    hogFunctionsRetrieve,
} from 'products/cdp/frontend/generated/api'
import type { HogFunctionApi, HogFunctionPublishResponseApi } from 'products/cdp/frontend/generated/api.schemas'

import { buildHogFunctionDraftDiff } from './hogFunctionConfigDiffUtils'
import { HogFunctionConfigurationLogicProps, hogFunctionConfigurationLogic } from './hogFunctionConfigurationLogic'
import { openHogFunctionPublishDraftDialog } from './HogFunctionPublishDraftDialog'

export type HogFunctionDraftAction = 'publish' | 'discard'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogFunctionDraftLogicValues {
    configurationChanged: boolean // hogFunctionConfigurationLogic
    hogFunction: HogFunctionType | null // hogFunctionConfigurationLogic
    type: HogFunctionTypeType // hogFunctionConfigurationLogic
    currentTeamIdStrict: number | string // teamLogic
    draftActionDisabledReason: string | undefined
    draftActionPending: HogFunctionDraftAction | null
    hasStagedDraft: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogFunctionDraftLogicActions {
    loadHogFunction: () => any // hogFunctionConfigurationLogic
    loadHogFunctionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // hogFunctionConfigurationLogic
    loadHogFunctionSuccess: (
        hogFunction: HogFunctionType | null,
        payload?: any
    ) => {
        hogFunction: HogFunctionType | null
        payload?: any
    } // hogFunctionConfigurationLogic
    confirmDiscardDraft: () => {
        value: true
    }
    confirmPublishDraft: (confirmToken: string) => {
        confirmToken: string
    }
    discardDraft: () => {
        value: true
    }
    publishDraft: () => {
        value: true
    }
    setDraftActionPending: (pending: HogFunctionDraftAction | null) => {
        pending: HogFunctionDraftAction | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogFunctionDraftLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        hasStagedDraft: (hogFunction: HogFunctionType | null) => boolean
        draftActionDisabledReason: (
            configurationChanged: boolean,
            draftActionPending: HogFunctionDraftAction | null
        ) => string | undefined
    }
}

export type hogFunctionDraftLogicType = MakeLogicType<
    hogFunctionDraftLogicValues,
    hogFunctionDraftLogicActions,
    HogFunctionConfigurationLogicProps,
    hogFunctionDraftLogicMeta
>

/**
 * The staged-draft lifecycle of an existing function: review, publish, discard. Agents (MCP) stage
 * config edits to an enabled destination as a draft instead of changing it live, and this is where a
 * person promotes or throws away that draft.
 */
export const hogFunctionDraftLogic = kea<hogFunctionDraftLogicType>([
    path((key) => ['scenes', 'hog-functions', 'configuration', 'hogFunctionDraftLogic', key]),
    props({} as HogFunctionConfigurationLogicProps),
    key(({ id, logicKey }) => (logicKey ? `${logicKey}_${id ?? 'new'}` : (id ?? 'new'))),
    connect((props: HogFunctionConfigurationLogicProps) => ({
        values: [
            teamLogic,
            ['currentTeamIdStrict'],
            hogFunctionConfigurationLogic(props),
            ['hogFunction', 'configurationChanged', 'type'],
        ],
        actions: [
            hogFunctionConfigurationLogic(props),
            ['loadHogFunction', 'loadHogFunctionSuccess', 'loadHogFunctionFailure'],
        ],
    })),
    actions({
        publishDraft: true,
        confirmPublishDraft: (confirmToken: string) => ({ confirmToken }),
        discardDraft: true,
        confirmDiscardDraft: true,
        setDraftActionPending: (pending: HogFunctionDraftAction | null) => ({ pending }),
    }),
    reducers({
        // Drives the buttons' loading and disabled state, so publish and discard can't race each other
        // or double-submit. The configuration page locks the form while it is set. It clears only once
        // fresh function data lands: a failed reload keeps the lock, because the form would hold config
        // that is no longer live, and saving it would undo the publish.
        draftActionPending: [
            null as HogFunctionDraftAction | null,
            {
                setDraftActionPending: (_, { pending }) => pending,
                loadHogFunctionSuccess: () => null,
            },
        ],
    }),
    selectors({
        hasStagedDraft: [
            (s) => [s.hogFunction],
            (hogFunction: HogFunctionType | null): boolean => !!hogFunction?.draft,
        ],
        draftActionDisabledReason: [
            (s) => [s.configurationChanged, s.draftActionPending],
            (configurationChanged: boolean, draftActionPending: HogFunctionDraftAction | null): string | undefined =>
                // Publish and discard reload the function, and the reload resets the form.
                configurationChanged
                    ? 'Save or clear your edits first'
                    : draftActionPending
                      ? 'Another draft action is in progress'
                      : undefined,
        ],
    }),
    listeners(({ actions, values }) => ({
        loadHogFunctionFailure: () => {
            if (values.draftActionPending) {
                lemonToast.error('Could not reload this destination. Refresh the page before you edit it.')
            }
        },
        publishDraft: async (_, breakpoint) => {
            const id = values.hogFunction?.id
            const type = values.type
            if (!id || values.draftActionPending) {
                return
            }
            actions.setDraftActionPending('publish')
            const projectId = String(values.currentTeamIdStrict)
            let preview: HogFunctionPublishResponseApi
            let latest: HogFunctionApi
            try {
                // Two-step publish: the unconfirmed call only previews what changes and mints the token
                // a confirmed publish must return, so a draft that moved since can't go live blind.
                preview = await hogFunctionsPublishCreate(projectId, id, { confirm: false })
                // Read after the preview, so the diff shows the draft the token signs. A draft edit in
                // between fails the stamp check below, and a live edit fails the token on confirm.
                latest = await hogFunctionsRetrieve(projectId, id)
            } catch {
                lemonToast.error('Could not load the publish preview. Try again.')
                return
            } finally {
                actions.setDraftActionPending(null)
            }
            // Stops here if the scene unmounted during the requests, so no dialog opens for a dead logic.
            breakpoint()
            const { draft, draft_updated_at } = latest
            if (
                !draft ||
                !draft_updated_at ||
                !preview.draft_updated_at ||
                !dayjs(draft_updated_at).isSame(preview.draft_updated_at)
            ) {
                lemonToast.warning('The draft changed while the preview loaded. Review it and publish again.')
                // Applies the read already in hand, so no reload leaves the form open to edits it would reset.
                actions.loadHogFunctionSuccess(latest as unknown as HogFunctionType)
                return
            }
            const changedFields = preview.changed_fields ?? []
            openHogFunctionPublishDraftDialog({
                diffs: buildHogFunctionDraftDiff(
                    latest as unknown as Record<string, unknown>,
                    draft as Record<string, unknown>
                ).filter((diff) => changedFields.includes(diff.field)),
                changedFields,
                enabled: !!latest.enabled,
                onConfirm: () => actions.confirmPublishDraft(preview.confirm_token ?? ''),
            })
            // pinned: analytics event name
            posthog.capture('hog function draft publish previewed', { type })
        },
        confirmPublishDraft: async ({ confirmToken }) => {
            const id = values.hogFunction?.id
            const type = values.type
            // draftActionPending also guards the dialog's close animation, where a fast double-click
            // on the confirm button dispatches twice.
            if (!id || values.draftActionPending) {
                return
            }
            actions.setDraftActionPending('publish')
            try {
                const response = await hogFunctionsPublishCreate(String(values.currentTeamIdStrict), id, {
                    confirm: true,
                    confirm_token: confirmToken,
                })
                lemonToast.success('Changes published')
                // pinned: analytics event name
                posthog.capture('hog function draft published', { type })
                // The response carries the published function, so the form gets the new live config
                // without a second request that could fail.
                if (response.function) {
                    actions.loadHogFunctionSuccess(response.function as unknown as HogFunctionType)
                    return
                }
            } catch (error) {
                lemonToast.error(
                    error instanceof ApiError && error.status !== 409 && error.detail
                        ? error.detail
                        : 'Publishing failed. Review the staged changes and try again.'
                )
            }
            actions.loadHogFunction()
        },
        discardDraft: () => {
            if (values.draftActionPending) {
                return
            }
            LemonDialog.open({
                title: 'Discard staged changes?',
                description: 'This deletes the staged changes. The live version does not change.',
                primaryButton: {
                    children: 'Discard',
                    status: 'danger',
                    onClick: () => actions.confirmDiscardDraft(),
                    'data-attr': 'hog-function-draft-discard-confirm',
                },
                secondaryButton: {
                    children: 'Cancel',
                },
            })
        },
        confirmDiscardDraft: async () => {
            const id = values.hogFunction?.id
            const type = values.type
            if (!id || values.draftActionPending) {
                return
            }
            actions.setDraftActionPending('discard')
            try {
                const hogFunction = await hogFunctionsDiscardDraftCreate(String(values.currentTeamIdStrict), id)
                lemonToast.success('Staged changes discarded')
                // pinned: analytics event name
                posthog.capture('hog function draft discarded', { type })
                actions.loadHogFunctionSuccess(hogFunction as unknown as HogFunctionType)
            } catch {
                lemonToast.error('Could not discard the staged changes. Try again.')
                actions.loadHogFunction()
            }
        },
    })),
])