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.9 KB
Raw Blame
import {
    MakeLogicType,
    BindLogic,
    actions,
    kea,
    key,
    path,
    props,
    reducers,
    selectors,
    useActions,
    useMountedLogic,
    useValues,
} from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'

import { LemonDivider, LemonSkeleton } from '@posthog/lemon-ui'

import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { BatchExportBackfills } from 'scenes/data-pipelines/batch-exports/BatchExportBackfills'
import { BatchExportRuns } from 'scenes/data-pipelines/batch-exports/BatchExportRuns'
import { LogsViewer } from 'scenes/hog-functions/logs/LogsViewer'
import { HogFunctionSkeleton } from 'scenes/hog-functions/misc/HogFunctionSkeleton'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ActivityScope, BATCH_EXPORT_SERVICE_NAMES, BatchExportService, Breadcrumb } from '~/types'

import { BatchExportConfigFormLogicProps, batchExportConfigFormLogic } from './batchExportConfigFormLogic'
import { BatchExportConfiguration } from './BatchExportConfiguration'
import {
    BatchExportConfigurationClearChangesButton,
    BatchExportConfigurationSaveButton,
} from './BatchExportConfigurationButtons'
import { RenderBatchExportIcon } from './BatchExportIcon'
import { BatchExportNotifications } from './BatchExportNotifications'
import { BatchExportsMetrics } from './BatchExportsMetrics'
import { QuillBatchExportSceneActions } from './QuillBatchExportSceneActions'
import { humanizeBatchExportName, normalizeBatchExportService } from './utils'

const BATCH_EXPORT_SCENE_TABS = [
    'configuration',
    'metrics',
    'logs',
    'runs',
    'backfills',
    'notifications',
    'history',
] as const
export type BatchExportSceneTab = (typeof BATCH_EXPORT_SCENE_TABS)[number]

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchExportSceneLogicValues {
    breadcrumbs: Breadcrumb[]
    currentTab: BatchExportSceneTab
    logicProps: any
    sidePanelContext: SidePanelSceneContext | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchExportSceneLogicActions {
    setCurrentTab: (tab: BatchExportSceneTab) => {
        tab: 'backfills' | 'configuration' | 'history' | 'logs' | 'metrics' | 'notifications' | 'runs'
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchExportSceneLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        logicProps: (arg: any) => any
        sidePanelContext: (arg: any) => SidePanelSceneContext | null
    }
}

export type batchExportSceneLogicType = MakeLogicType<
    batchExportSceneLogicValues,
    batchExportSceneLogicActions,
    BatchExportConfigFormLogicProps,
    batchExportSceneLogicMeta
>

export const batchExportSceneLogic = kea<batchExportSceneLogicType>([
    props({} as BatchExportConfigFormLogicProps),
    key(({ id }: BatchExportConfigFormLogicProps) => id ?? 'new'),
    path((key) => ['scenes', 'data-pipelines', 'batch-exports', 'batchExportSceneLogic', key]),
    actions({
        setCurrentTab: (tab: BatchExportSceneTab) => ({ tab }),
    }),
    reducers(() => ({
        currentTab: [
            'configuration' as BatchExportSceneTab,
            {
                setCurrentTab: (_, { tab }) => tab,
            },
        ],
    })),
    selectors({
        logicProps: [() => [(_, props) => props], (props) => props],
        breadcrumbs: [
            () => [],
            (): Breadcrumb[] => {
                return [
                    {
                        key: Scene.Destinations,
                        name: 'Destinations',
                        path: urls.destinations('batch'),
                        iconType: 'data_pipeline',
                    },
                    {
                        key: Scene.BatchExport,
                        name: 'Batch export',
                        iconType: 'data_pipeline',
                    },
                ]
            },
        ],
        [SIDE_PANEL_CONTEXT_KEY]: [
            () => [(_, props) => props],
            (props: BatchExportConfigFormLogicProps): SidePanelSceneContext | null =>
                props.id ? { activity_scope: ActivityScope.BATCH_EXPORT, activity_item_id: props.id } : null,
        ],
    }),
    actionToUrl(({ values }) => ({
        setCurrentTab: () => {
            return [
                router.values.location.pathname,
                {
                    ...router.values.searchParams,
                    tab: values.currentTab,
                },
                router.values.hashParams,
            ]
        },
    })),
    urlToAction(({ actions, values }) => {
        const reactToTabChange = (_: any, search: Record<string, string>): void => {
            const possibleTab = (search.tab ?? 'configuration') as BatchExportSceneTab

            const tab = BATCH_EXPORT_SCENE_TABS.includes(possibleTab) ? possibleTab : 'configuration'
            if (tab !== values.currentTab) {
                actions.setCurrentTab(tab)
            }
        }

        return {
            // All possible routes for this scene need to be listed here
            [urls.batchExport(':id')]: reactToTabChange,
            [urls.batchExportNew(':service')]: reactToTabChange,
        }
    }),
])

export const scene: SceneExport = {
    component: BatchExportScene,
    logic: batchExportSceneLogic,
    paramsToProps: ({ params: { id, service } }): (typeof batchExportSceneLogic)['props'] => ({
        id: id === 'new' ? null : id,
        service: service ? normalizeBatchExportService(service) : null,
    }),
}

function BatchExportSceneHeader(): JSX.Element {
    const { configuration, batchExportConfigLoading } = useValues(batchExportConfigFormLogic)
    const { setConfigurationValue, deleteBatchExport } = useActions(batchExportConfigFormLogic)
    const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')

    return (
        <>
            <SceneTitleSection
                name={humanizeBatchExportName(configuration.name)}
                description={null}
                // TODO: follow up at some point and add description support
                // description={configuration.description || ''}
                resourceType={{
                    type: 'data_pipelines',
                    forceIcon: configuration.destination ? (
                        <RenderBatchExportIcon size="small" type={configuration.destination} />
                    ) : undefined,
                }}
                isLoading={batchExportConfigLoading}
                onNameChange={(value) => setConfigurationValue('name', value)}
                onDescriptionChange={(value) => setConfigurationValue('description', value)}
                canEdit
                actions={
                    todayRailNav ? (
                        <QuillBatchExportSceneActions />
                    ) : (
                        <>
                            <More
                                size="small"
                                overlay={
                                    <>
                                        <LemonButton status="danger" fullWidth onClick={() => deleteBatchExport()}>
                                            Delete
                                        </LemonButton>
                                    </>
                                }
                            />
                            <LemonDivider vertical />
                            <BatchExportConfigurationClearChangesButton />
                            <BatchExportConfigurationSaveButton />
                        </>
                    )
                }
            />
        </>
    )
}

export function BatchExportScene(componentProps: any): JSX.Element {
    const { id, service: serviceParam } = componentProps
    const logicProps: BatchExportConfigFormLogicProps = {
        id: id ?? null,
        service: serviceParam ? normalizeBatchExportService(serviceParam) : null,
    }

    const logic = useMountedLogic(batchExportSceneLogic(logicProps))

    return <BatchExportSceneContent logic={logic} logicProps={logicProps} />
}

export function BatchExportSceneContent({
    logic,
    logicProps,
}: {
    logic: any
    logicProps: BatchExportConfigFormLogicProps
}): JSX.Element {
    const { currentTab } = useValues(logic)
    const { setCurrentTab } = useActions(logic)

    return (
        <BindLogic logic={batchExportConfigFormLogic} props={logicProps}>
            <BatchExportSceneContentInner
                currentTab={currentTab}
                setCurrentTab={setCurrentTab}
                id={logicProps.id}
                service={logicProps.service}
            />
        </BindLogic>
    )
}

function BatchExportSceneContentInner({
    currentTab,
    setCurrentTab,
    id,
    service,
}: {
    currentTab: BatchExportSceneTab
    setCurrentTab: (tab: BatchExportSceneTab) => void
    id: string | null
    service: BatchExportService['type'] | null
}): JSX.Element {
    const { batchExportConfig, loading } = useValues(batchExportConfigFormLogic)
    const notificationsEnabled = useFeatureFlag('BATCH_EXPORT_ALERTS')

    if (loading && !batchExportConfig) {
        return (
            <div className="flex flex-col gap-4">
                <LemonSkeleton className="w-full h-12" />
                <HogFunctionSkeleton />
            </div>
        )
    }

    if (id && !batchExportConfig) {
        return <NotFound object="Batch export" />
    }

    if (service && !BATCH_EXPORT_SERVICE_NAMES.includes(service as BatchExportService['type'])) {
        return <NotFound object={`batch export service ${service}`} />
    }

    const tabs: (LemonTab<BatchExportSceneTab> | null)[] = [
        {
            label: 'Configuration',
            key: 'configuration',
            content: <BatchExportConfiguration />,
        },
        id
            ? {
                  label: 'Metrics',
                  key: 'metrics',
                  content: <BatchExportsMetrics id={id} />,
              }
            : null,
        id
            ? {
                  label: 'Logs',
                  key: 'logs',
                  content: (
                      <LogsViewer
                          sourceType="batch_exports"
                          sourceId={id}
                          instanceLabel="run"
                          defaultFilters={{ levels: ['LOG', 'INFO', 'WARN', 'ERROR'] }}
                      />
                  ),
              }
            : null,
        id
            ? {
                  label: 'Runs',
                  key: 'runs',
                  content: <BatchExportRuns id={id} />,
              }
            : null,
        id
            ? {
                  label: 'Backfills',
                  key: 'backfills',
                  content: <BatchExportBackfills id={id} />,
              }
            : null,
        id && notificationsEnabled
            ? {
                  label: 'Notifications',
                  key: 'notifications',
                  content: <BatchExportNotifications id={id} />,
              }
            : null,
        id
            ? {
                  label: 'History',
                  key: 'history',
                  content: <ActivityLog id={id} scope={ActivityScope.BATCH_EXPORT} />,
              }
            : null,
    ]

    return (
        <SceneContent>
            <BatchExportSceneHeader />
            <LemonTabs activeKey={currentTab} tabs={tabs} onChange={setCurrentTab} sceneInset />
        </SceneContent>
    )
}