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.

5.0 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, reducers } from 'kea'
import { disposables } from 'kea-disposables'
import { loaders } from 'kea-loaders'

import { Source, Sources, Workflow, sourceNames } from './infrastructureTypes'

async function readSource<T>(name: string, imageId?: string): Promise<Source<T>> {
    const url = new URL(window.location.href)
    url.search = new URLSearchParams({ source: name, ...(imageId ? { image_id: imageId } : {}) }).toString()
    const response = await fetch(url, { signal: AbortSignal.timeout(60_000), credentials: 'same-origin' })
    if (!response.ok || !response.headers.get('content-type')?.includes('application/json')) {
        throw new Error('Source unavailable. Refresh the page to check your admin session.')
    }
    return response.json()
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface infrastructureLogicValues {
    now: number
    paused: boolean
    selected: string
    showSources: boolean
    sources: Sources | null
    sourcesLoading: boolean
    workflow: {
        id: string
        source: Source<Workflow>
    } | null
    workflowLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface infrastructureLogicActions {
    loadSources: () => any
    loadSourcesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSourcesSuccess: (
        sources: Sources,
        payload?: any
    ) => {
        sources: Sources
        payload?: any
    }
    loadWorkflow: ({ id }: { id: string }) => {
        id: string
    }
    loadWorkflowFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadWorkflowSuccess: (
        workflow: {
            id: string
            source: Source<Workflow>
        },
        payload?: {
            id: string
        }
    ) => {
        workflow: {
            id: string
            source: Source<Workflow>
        }
        payload?: {
            id: string
        }
    }
    setPaused: (paused: boolean) => {
        paused: boolean
    }
    setSelected: (selected: string) => { selected: string }
    setShowSources: (showSources: boolean) => { showSources: boolean }
    tick: () => {
        now: number
    }
}

export type infrastructureLogicType = MakeLogicType<infrastructureLogicValues, infrastructureLogicActions>

export const infrastructureLogic = kea<infrastructureLogicType>([
    actions({
        setPaused: (paused: boolean) => ({ paused }),
        setSelected: (selected: string) => ({ selected }),
        setShowSources: (showSources: boolean) => ({ showSources }),
        tick: () => ({ now: Date.now() }),
    }),
    reducers({
        paused: [false, { setPaused: (_, { paused }) => paused }],
        selected: ['custom', { setSelected: (_, { selected }) => selected }],
        showSources: [false, { setShowSources: (_, { showSources }) => showSources }],
        now: [Date.now(), { tick: (_, { now }) => now }],
    }),
    loaders(({ values }) => ({
        sources: [
            null as Sources | null,
            {
                loadSources: async () =>
                    Object.fromEntries(
                        await Promise.all(
                            sourceNames.map(async (name) => {
                                try {
                                    return [name, await readSource(name)]
                                } catch {
                                    return [name, { ...values.sources?.[name], status: 'error' }]
                                }
                            })
                        )
                    ) as Sources,
            },
        ],
        workflow: [
            null as { id: string; source: Source<Workflow> } | null,
            {
                loadWorkflow: async ({ id }: { id: string }, breakpoint) => {
                    let source: Source<Workflow>
                    try {
                        source = await readSource<Workflow>('workflow', id)
                    } catch {
                        source = { status: 'error', data: null, observed_at: null }
                    }
                    breakpoint()
                    return { id, source }
                },
            },
        ],
    })),
    disposables(({ actions, values }) => ({
        clock: () => {
            const timer = setInterval(() => actions.tick(), 10_000)
            return () => clearInterval(timer)
        },
        poll: () => {
            const timer = setInterval(() => {
                if (!values.paused && !values.sourcesLoading) {
                    actions.loadSources()
                    if (values.workflow && !values.workflowLoading) {
                        actions.loadWorkflow({ id: values.workflow.id })
                    }
                }
            }, 60_000)
            return () => clearInterval(timer)
        },
    })),
    afterMount(({ actions }) => actions.loadSources()),
])