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.

10.8 KB
Raw Blame
// Loads and manages batch export backfills — listing, cancellation, and polling for estimates.
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import api, { PaginatedResponse } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'

import { BatchExportBackfill, RawBatchExportBackfill } from '~/types'

import type { Dayjs } from '../../../lib/dayjs'
import type { BatchExportConfiguration } from '../../../types'
import { batchExportBackfillModalLogic } from './batchExportBackfillModalLogic'
import { batchExportDataLogic } from './batchExportDataLogic'
import { BatchExportContext } from './types'

export interface BatchExportBackfillsLogicProps {
    id: string
    context?: BatchExportContext
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchExportBackfillsLogicValues {
    batchExportConfig: BatchExportConfiguration | null // batchExportDataLogic
    batchExportConfigLoading: boolean // batchExportDataLogic
    currentTeamId: number | null // teamLogic
    backfillsPaginatedResponse: PaginatedResponse<RawBatchExportBackfill> | null
    backfillsPaginatedResponseLoading: boolean
    hasMoreBackfillsToLoad: boolean
    latestBackfills: BatchExportBackfill[]
    loading: boolean
    recordLabel: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchExportBackfillsLogicActions {
    backfillCreated: (backfillId: string) => {
        backfillId: string
    } // batchExportBackfillModalLogic
    openBackfillModal: () => {
        value: true
    } // batchExportBackfillModalLogic
    submitBackfillFormSuccess: (backfillForm: {
        earliest_backfill: boolean
        end_at?: Dayjs | undefined
        start_at?: Dayjs | undefined
    }) => {
        backfillForm: {
            earliest_backfill: boolean
            end_at?: Dayjs | undefined
            start_at?: Dayjs | undefined
        }
    } // batchExportBackfillModalLogic
    cancelBackfill: (backfill: BatchExportBackfill) => {
        backfill: BatchExportBackfill
    }
    loadBackfills: () => {
        value: true
    }
    loadBackfillsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadBackfillsSuccess: (
        backfillsPaginatedResponse: PaginatedResponse<RawBatchExportBackfill>,
        payload?: {
            value: true
        }
    ) => {
        backfillsPaginatedResponse: PaginatedResponse<RawBatchExportBackfill>
        payload?: {
            value: true
        }
    }
    loadOlderBackfills: () => any
    loadOlderBackfillsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadOlderBackfillsSuccess: (
        backfillsPaginatedResponse: PaginatedResponse<RawBatchExportBackfill> | null,
        payload?: any
    ) => {
        backfillsPaginatedResponse: PaginatedResponse<RawBatchExportBackfill> | null
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchExportBackfillsLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        recordLabel: (arg: any) => string
        hasMoreBackfillsToLoad: (
            backfillsPaginatedResponse: PaginatedResponse<RawBatchExportBackfill> | null
        ) => boolean
        loading: (backfillsPaginatedResponseLoading: boolean) => boolean
        latestBackfills: (
            backfillsPaginatedResponse: PaginatedResponse<RawBatchExportBackfill> | null
        ) => BatchExportBackfill[]
    }
}

export type batchExportBackfillsLogicType = MakeLogicType<
    batchExportBackfillsLogicValues,
    batchExportBackfillsLogicActions,
    BatchExportBackfillsLogicProps,
    batchExportBackfillsLogicMeta
>

export const batchExportBackfillsLogic = kea<batchExportBackfillsLogicType>([
    props({} as BatchExportBackfillsLogicProps),
    key(({ id }) => id),
    path((key) => ['scenes', 'pipeline', 'batchExportBackfillsLogic', key]),
    connect((props: BatchExportBackfillsLogicProps) => ({
        values: [
            teamLogic(),
            ['currentTeamId'],
            batchExportDataLogic({ id: props.id }),
            ['batchExportConfig', 'batchExportConfigLoading'],
        ],
        actions: [
            batchExportBackfillModalLogic(props),
            ['submitBackfillFormSuccess', 'openBackfillModal', 'backfillCreated'],
        ],
    })),
    actions({
        loadBackfills: true,
        cancelBackfill: (backfill: BatchExportBackfill) => ({ backfill }),
    }),
    loaders(({ props, values }) => ({
        backfillsPaginatedResponse: [
            null as PaginatedResponse<RawBatchExportBackfill> | null,
            {
                loadBackfills: async () => {
                    try {
                        return await api.batchExports.listBackfills(props.id, {
                            ordering: '-created_at',
                        })
                    } catch (e) {
                        lemonToast.error('Unknown error occurred when fetching backfills')
                        throw e
                    }
                },
                loadOlderBackfills: async () => {
                    const nextUrl = values.backfillsPaginatedResponse?.next

                    if (!nextUrl) {
                        return values.backfillsPaginatedResponse
                    }
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                        const res = await api.get<PaginatedResponse<RawBatchExportBackfill>>(nextUrl)
                        res.results = [...(values.backfillsPaginatedResponse?.results ?? []), ...res.results]

                        return res
                    } catch (e) {
                        lemonToast.error('Unknown error occurred when fetching backfills')
                        throw e
                    }
                },
            },
        ],
    })),
    selectors({
        recordLabel: [
            () => [(_, props) => props],
            (props: BatchExportBackfillsLogicProps): string => (props.context === 'hog_function' ? 'events' : 'rows'),
        ],
        hasMoreBackfillsToLoad: [
            (s) => [s.backfillsPaginatedResponse],
            (backfillsPaginatedResponse: PaginatedResponse<RawBatchExportBackfill> | null) =>
                !!backfillsPaginatedResponse?.next,
        ],
        loading: [
            (s) => [s.backfillsPaginatedResponseLoading],
            (backfillsPaginatedResponseLoading: boolean) => backfillsPaginatedResponseLoading,
        ],
        latestBackfills: [
            (s) => [s.backfillsPaginatedResponse],
            (backfillsPaginatedResponse: PaginatedResponse<RawBatchExportBackfill> | null): BatchExportBackfill[] => {
                const backfills = backfillsPaginatedResponse?.results ?? []
                return backfills.map((backfill) => {
                    const parseDateSafely = (date: string | null | undefined): dayjs.Dayjs | undefined => {
                        if (!date) {
                            return undefined
                        }
                        const parsed = dayjs(date)
                        return parsed.isValid() ? parsed : undefined
                    }
                    return {
                        ...backfill,
                        created_at: parseDateSafely(backfill.created_at),
                        finished_at: parseDateSafely(backfill.finished_at),
                        start_at: parseDateSafely(backfill.start_at),
                        end_at: parseDateSafely(backfill.end_at),
                        last_updated_at: parseDateSafely(backfill.last_updated_at),
                    }
                })
            },
        ],
    }),
    listeners(({ actions, props, values }) => ({
        cancelBackfill: async ({ backfill }) => {
            try {
                await api.batchExports.cancelBackfill(props.id, backfill.id)
                lemonToast.success('Backfill has been cancelled.')
                actions.loadBackfills()
            } catch {
                lemonToast.error('Failed to cancel backfill. Please try again.')
            }
        },
        submitBackfillFormSuccess: () => {
            setTimeout(() => {
                actions.loadBackfills()
            }, 1000)
        },
        backfillCreated: async ({ backfillId }, breakpoint) => {
            const MAX_POLL_ATTEMPTS = 10
            const POLL_INTERVAL_MS = 1000

            for (let i = 0; i < MAX_POLL_ATTEMPTS; i++) {
                await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS))
                // Abort if the logic was unmounted or a newer backfillCreated action fired
                breakpoint()

                try {
                    const backfill = await api.batchExports.getBackfill(props.id, backfillId)

                    if (backfill?.total_records_count != null) {
                        if (backfill.total_records_count === 0) {
                            lemonToast.warning(
                                `No ${values.recordLabel} found to export for the selected time range. The backfill will finish with nothing to export.`
                            )
                        } else {
                            lemonToast.info(
                                `Estimated ~${backfill.total_records_count.toLocaleString()} ${values.recordLabel} to export`,
                                {
                                    button: {
                                        label: 'Cancel backfill',
                                        action: async () => {
                                            try {
                                                await api.batchExports.cancelBackfill(props.id, backfill.id)
                                                lemonToast.success('Backfill cancelled')
                                                actions.loadBackfills()
                                            } catch {
                                                lemonToast.error('Failed to cancel backfill')
                                            }
                                        },
                                    },
                                }
                            )
                        }
                        actions.loadBackfills()
                        return
                    }
                } catch (e) {
                    console.warn('Failed to poll for backfill estimate', e)
                }
            }
        },
    })),
    afterMount(({ actions }) => {
        actions.loadBackfills()
    }),
])