: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
// Loads and manages batch export runs — grouping by date, retry, cancel, and pagination logic.
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api, { PaginatedResponse } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { BatchExportRun, GroupedBatchExportRuns, RawBatchExportRun } 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'
import { BatchExportRunStatusGroup, BatchExportStatus, batchExportRunStatusesForGroups } from './utils'
const DEFAULT_DATE_FROM = '-2d'
export interface BatchExportRunsLogicProps {
id: string
context?: BatchExportContext
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchExportRunsLogicValues {
batchExportConfig: BatchExportConfiguration | null // batchExportDataLogic
batchExportConfigLoading: boolean // batchExportDataLogic
dateRange: {
from: string
to: string | null
}
groupedRuns: GroupedBatchExportRuns[]
hasMoreRunsToLoad: boolean
latestRuns: BatchExportRun[]
loading: boolean
recordLabel: string
runsPaginatedResponse: PaginatedResponse<RawBatchExportRun> | null
runsPaginatedResponseLoading: boolean
statusFilter: BatchExportRunStatusGroup[]
statusFilterActive: boolean
statusFilterStatuses: BatchExportStatus[]
usingLatestRuns: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchExportRunsLogicActions {
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
cancelRun: (run: BatchExportRun) => {
run: BatchExportRun
}
loadOlderRuns: () => any
loadOlderRunsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadOlderRunsSuccess: (
runsPaginatedResponse: PaginatedResponse<RawBatchExportRun> | null,
payload?: any
) => {
runsPaginatedResponse: PaginatedResponse<RawBatchExportRun> | null
payload?: any
}
loadRuns: () => {
value: true
}
loadRunsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadRunsSuccess: (
runsPaginatedResponse: PaginatedResponse<RawBatchExportRun>,
payload?: {
value: true
}
) => {
runsPaginatedResponse: PaginatedResponse<RawBatchExportRun>
payload?: {
value: true
}
}
retryRun: (run: BatchExportRun) => {
run: BatchExportRun
}
setDateRange: (
from: string | null,
to: string | null
) => {
from: string | null
to: string | null
}
setStatusFilter: (statuses: BatchExportRunStatusGroup[]) => {
statuses: BatchExportRunStatusGroup[]
}
switchLatestRuns: (enabled: boolean) => {
enabled: boolean
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchExportRunsLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
recordLabel: (arg: any) => string
hasMoreRunsToLoad: (runsPaginatedResponse: PaginatedResponse<RawBatchExportRun> | null) => boolean
loading: (runsPaginatedResponseLoading: boolean) => boolean
latestRuns: (runsPaginatedResponse: PaginatedResponse<RawBatchExportRun> | null) => BatchExportRun[]
groupedRuns: (
runsPaginatedResponse: PaginatedResponse<RawBatchExportRun> | null,
usingLatestRuns: boolean
) => GroupedBatchExportRuns[]
statusFilterActive: (statusFilter: BatchExportRunStatusGroup[]) => boolean
statusFilterStatuses: (statusFilter: BatchExportRunStatusGroup[]) => BatchExportStatus[]
}
}
export type batchExportRunsLogicType = MakeLogicType<
batchExportRunsLogicValues,
batchExportRunsLogicActions,
BatchExportRunsLogicProps,
batchExportRunsLogicMeta
>
export const batchExportRunsLogic = kea<batchExportRunsLogicType>([
props({} as BatchExportRunsLogicProps),
key(({ id }) => id),
path((key) => ['scenes', 'pipeline', 'batchExportRunsLogic', key]),
connect((props: BatchExportRunsLogicProps) => ({
values: [batchExportDataLogic({ id: props.id }), ['batchExportConfig', 'batchExportConfigLoading']],
actions: [batchExportBackfillModalLogic(props), ['submitBackfillFormSuccess', 'openBackfillModal']],
})),
actions({
setDateRange: (from: string | null, to: string | null) => ({ from, to }),
setStatusFilter: (statuses: BatchExportRunStatusGroup[]) => ({ statuses }),
switchLatestRuns: (enabled: boolean) => ({ enabled }),
loadRuns: true,
retryRun: (run: BatchExportRun) => ({ run }),
cancelRun: (run: BatchExportRun) => ({ run }),
}),
loaders(({ props, values }) => ({
runsPaginatedResponse: [
null as PaginatedResponse<RawBatchExportRun> | null,
{
loadRuns: async () => {
// Leave the key out entirely when nothing is selected, as a blank status is rejected.
const statusParams = values.statusFilterStatuses.length
? { status: values.statusFilterStatuses }
: {}
// TODO: loading and combining the data could be more efficient
if (values.usingLatestRuns) {
return await api.batchExports.listRuns(props.id, statusParams)
}
return await api.batchExports.listRuns(props.id, {
start: values.dateRange.from,
end: values.dateRange.to, // TODO: maybe add 1 day
ordering: '-data_interval_start',
...statusParams,
})
},
loadOlderRuns: async () => {
const nextUrl = values.runsPaginatedResponse?.next
if (!nextUrl) {
return values.runsPaginatedResponse
}
// 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<RawBatchExportRun>>(nextUrl)
res.results = [...(values.runsPaginatedResponse?.results ?? []), ...res.results]
return res
},
},
],
})),
reducers({
dateRange: [
{ from: DEFAULT_DATE_FROM, to: null } as { from: string; to: string | null },
{
setDateRange: (_, { from, to }) => ({ from: from ?? DEFAULT_DATE_FROM, to: to }),
},
],
// TODO: move this, the date range, and the latest-runs toggle into the URL together, so a
// filtered view can be shared.
statusFilter: [
[] as BatchExportRunStatusGroup[],
{
setStatusFilter: (_, { statuses }) => statuses,
},
],
usingLatestRuns: [
true,
{
switchLatestRuns: (_, { enabled }) => enabled,
},
],
}),
selectors({
recordLabel: [
() => [(_, props) => props],
(props: BatchExportRunsLogicProps): string => (props.context === 'hog_function' ? 'events' : 'rows'),
],
hasMoreRunsToLoad: [
(s) => [s.runsPaginatedResponse],
(runsPaginatedResponse: PaginatedResponse<RawBatchExportRun> | null) => !!runsPaginatedResponse?.next,
],
loading: [
(s) => [s.runsPaginatedResponseLoading],
(runsPaginatedResponseLoading: boolean) => runsPaginatedResponseLoading,
],
latestRuns: [
// These aren't grouped because they might not include all runs for a time interval
(s) => [s.runsPaginatedResponse],
(runsPaginatedResponse: PaginatedResponse<RawBatchExportRun> | null): BatchExportRun[] => {
const runs = runsPaginatedResponse?.results ?? []
return runs.map((run) => {
return {
...run,
created_at: dayjs(run.created_at),
data_interval_start: run.data_interval_start ? dayjs(run.data_interval_start) : undefined,
data_interval_end: dayjs(run.data_interval_end),
last_updated_at: run.last_updated_at ? dayjs(run.last_updated_at) : undefined,
}
})
},
],
groupedRuns: [
(s) => [s.runsPaginatedResponse, s.usingLatestRuns],
(
runsPaginatedResponse: PaginatedResponse<RawBatchExportRun> | null,
usingLatestRuns: boolean
): GroupedBatchExportRuns[] => {
if (usingLatestRuns) {
return []
}
const runs = runsPaginatedResponse?.results ?? []
// Runs are grouped by the date range they cover
const groupedRuns: Record<string, GroupedBatchExportRuns> = {}
runs.forEach((run) => {
if (!run.data_interval_start) {
// For now, don't include backfill runs in here as it gets
// complicated to sort and group.
return
}
const key = `${run.data_interval_start}-${run.data_interval_end}`
if (!groupedRuns[key]) {
groupedRuns[key] = {
data_interval_start: dayjs(run.data_interval_start),
data_interval_end: dayjs(run.data_interval_end),
runs: [],
last_run_at: dayjs(run.created_at),
}
}
groupedRuns[key].runs.push({
...run,
created_at: dayjs(run.created_at),
data_interval_start: run.data_interval_start ? dayjs(run.data_interval_start) : undefined,
data_interval_end: dayjs(run.data_interval_end),
last_updated_at: run.last_updated_at ? dayjs(run.last_updated_at) : undefined,
})
groupedRuns[key].runs.sort((a, b) => b.created_at.diff(a.created_at))
groupedRuns[key].last_run_at = groupedRuns[key].runs[0].created_at
})
return Object.values(groupedRuns)
},
],
statusFilterActive: [
(s) => [s.statusFilter],
(statusFilter: BatchExportRunStatusGroup[]): boolean => statusFilter.length > 0,
],
statusFilterStatuses: [
(s) => [s.statusFilter],
(statusFilter: BatchExportRunStatusGroup[]): BatchExportStatus[] =>
batchExportRunStatusesForGroups(statusFilter),
],
}),
listeners(({ actions, props }) => ({
setDateRange: () => {
actions.loadRuns()
},
setStatusFilter: () => {
actions.loadRuns()
},
switchLatestRuns: () => {
actions.loadRuns()
},
retryRun: async ({ run }) => {
await api.batchExports.retryRun(props.id, run.id)
lemonToast.success('Retry has been scheduled.')
},
cancelRun: async ({ run }) => {
await api.batchExports.cancelRun(props.id, run.id)
lemonToast.success('Run has been cancelled.')
},
submitBackfillFormSuccess: () => {
actions.loadRuns()
},
})),
afterMount(({ actions }) => {
actions.loadRuns()
}),
])