: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
import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, urlToAction } from 'kea-router'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { systemStatusLogic } from 'scenes/instance/SystemStatus/systemStatusLogic'
import { userLogic } from 'scenes/userLogic'
import { InstanceSetting } from '~/types'
import type { PreflightStatus } from '../../../types'
export type TabName = 'overview' | 'internal_metrics'
// keep in sync with MigrationStatus in posthog/models/async_migration.py
export enum AsyncMigrationStatus {
NotStarted = 0,
Running = 1,
CompletedSuccessfully = 2,
Errored = 3,
RolledBack = 4,
Starting = 5,
FailedAtStartup = 6,
}
export enum AsyncMigrationsTab {
Management = 'management',
FutureMigrations = 'future',
Settings = 'settings',
}
export const migrationStatusNumberToMessage = {
0: 'Not started',
1: 'Running',
2: 'Complete',
3: 'Error',
4: 'Rolled back',
5: 'Starting',
6: 'Failed at startup',
}
export interface AsyncMigrationError {
id: number
description: string
created_at: string
}
export interface AsyncMigration {
id: number
name: string
description: string
progress: number
status: AsyncMigrationStatus
current_operation_index: number
current_query_id: string
celery_task_id: string
started_at: string
finished_at: string
posthog_min_version: string
posthog_max_version: string
error_count: number
parameters: Record<string, number>
parameter_definitions: Record<string, [string | number | null, string]>
is_available: boolean
}
export interface AsyncMigrationModalProps {
migration: AsyncMigration
endpoint: string
message: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface asyncMigrationsLogicValues {
preflight: PreflightStatus | null // preflightLogic
actionableMigrations: AsyncMigration[]
activeAsyncMigrationModal: AsyncMigrationModalProps | null
activeTab: AsyncMigrationsTab
asyncMigrationErrors: Record<number, AsyncMigrationError[]>
asyncMigrationErrorsLoading: Record<number, boolean>
asyncMigrationSettings: InstanceSetting[]
asyncMigrationSettingsLoading: boolean
asyncMigrations: AsyncMigration[]
asyncMigrationsLoading: boolean
futureMigrations: AsyncMigration[]
isAnyMigrationRunning: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface asyncMigrationsLogicActions {
closeAsyncMigrationsModal: () => {
value: true
}
forceStopMigration: (migration: AsyncMigration) => {
migration: AsyncMigration
}
forceStopMigrationWithoutRollback: (migration: AsyncMigration) => {
migration: AsyncMigration
}
loadAsyncMigrationErrors: (migrationId: number) => {
migrationId: number
}
loadAsyncMigrationErrorsFailure: (
migrationId: number,
error: any
) => {
error: any
migrationId: number
}
loadAsyncMigrationErrorsSuccess: (
migrationId: number,
errors: AsyncMigrationError[]
) => {
errors: AsyncMigrationError[]
migrationId: number
}
loadAsyncMigrationSettings: () => any
loadAsyncMigrationSettingsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadAsyncMigrationSettingsSuccess: (
asyncMigrationSettings: InstanceSetting[],
payload?: any
) => {
asyncMigrationSettings: InstanceSetting[]
payload?: any
}
loadAsyncMigrations: () => any
loadAsyncMigrationsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadAsyncMigrationsSuccess: (
asyncMigrations: AsyncMigration[],
payload?: any
) => {
asyncMigrations: AsyncMigration[]
payload?: any
}
openAsyncMigrationsModal: (
migration: AsyncMigration,
endpoint: string,
message: string
) => {
endpoint: string
message: string
migration: AsyncMigration
}
resumeMigration: (migration: AsyncMigration) => {
migration: AsyncMigration
}
rollbackMigration: (migration: AsyncMigration) => {
migration: AsyncMigration
}
setActiveTab: (tab: AsyncMigrationsTab) => {
tab: AsyncMigrationsTab
}
triggerMigration: (migration: AsyncMigration) => {
migration: AsyncMigration
}
updateMigrationStatus: (
migration: AsyncMigration,
endpoint: string,
message: string
) => {
endpoint: string
message: string
migration: AsyncMigration
}
updateSetting: (
settingKey: string,
newValue: string
) => {
newValue: string
settingKey: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface asyncMigrationsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
isAnyMigrationRunning: (asyncMigrations: AsyncMigration[]) => boolean
actionableMigrations: (asyncMigrations: AsyncMigration[]) => AsyncMigration[]
futureMigrations: (asyncMigrations: AsyncMigration[]) => AsyncMigration[]
}
}
export type asyncMigrationsLogicType = MakeLogicType<
asyncMigrationsLogicValues,
asyncMigrationsLogicActions,
Record<string, any>,
asyncMigrationsLogicMeta
>
export const asyncMigrationsLogic = kea<asyncMigrationsLogicType>([
path(['scenes', 'instance', 'AsyncMigrations', 'asyncMigrationsLogic']),
connect(() => ({
values: [preflightLogic, ['preflight']],
})),
actions({
triggerMigration: (migration: AsyncMigration) => ({ migration }),
resumeMigration: (migration: AsyncMigration) => ({ migration }),
rollbackMigration: (migration: AsyncMigration) => ({ migration }),
forceStopMigration: (migration: AsyncMigration) => ({ migration }),
forceStopMigrationWithoutRollback: (migration: AsyncMigration) => ({ migration }),
updateMigrationStatus: (migration: AsyncMigration, endpoint: string, message: string) => ({
migration,
endpoint,
message,
}),
setActiveTab: (tab: AsyncMigrationsTab) => ({ tab }),
updateSetting: (settingKey: string, newValue: string) => ({ settingKey, newValue }),
loadAsyncMigrationErrors: (migrationId: number) => ({ migrationId }),
loadAsyncMigrationErrorsSuccess: (migrationId: number, errors: AsyncMigrationError[]) => ({
migrationId,
errors,
}),
loadAsyncMigrationErrorsFailure: (migrationId: number, error: any) => ({ migrationId, error }),
openAsyncMigrationsModal: (migration: AsyncMigration, endpoint: string, message: string) => ({
migration,
endpoint,
message,
}),
closeAsyncMigrationsModal: true,
}),
reducers({
activeTab: [AsyncMigrationsTab.Management as AsyncMigrationsTab, { setActiveTab: (_, { tab }) => tab }],
asyncMigrationErrors: [
{} as Record<number, AsyncMigrationError[]>,
{
loadAsyncMigrationErrorsSuccess: (state, { migrationId, errors }) => {
return { ...state, [migrationId]: errors }
},
},
],
asyncMigrationErrorsLoading: [
{} as Record<number, boolean>,
{
loadAsyncMigrationErrors: (state, { migrationId }) => {
return { ...state, [migrationId]: true }
},
loadAsyncMigrationErrorsSuccess: (state, { migrationId }) => {
return { ...state, [migrationId]: false }
},
loadAsyncMigrationErrorsFailure: (state, { migrationId }) => {
return { ...state, [migrationId]: false }
},
},
],
activeAsyncMigrationModal: [
null as AsyncMigrationModalProps | null,
{
openAsyncMigrationsModal: (_, payload) => payload,
closeAsyncMigrationsModal: () => null,
updateMigrationStatus: () => null,
},
],
}),
loaders(() => ({
asyncMigrations: [
[] as AsyncMigration[],
{
loadAsyncMigrations: async () => {
if (!userLogic.values.user?.is_staff) {
return []
}
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
return (await api.get('api/async_migrations')).results
},
},
],
asyncMigrationSettings: [
[] as InstanceSetting[],
{
loadAsyncMigrationSettings: async (): Promise<InstanceSetting[]> => {
if (!userLogic.values.user?.is_staff) {
return []
}
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
const settings: InstanceSetting[] = (await api.get('api/instance_settings')).results
return settings.filter((setting) => setting.key.includes('ASYNC_MIGRATIONS'))
},
},
],
})),
selectors({
isAnyMigrationRunning: [
(s) => [s.asyncMigrations],
(asyncMigrations: AsyncMigration[]) =>
asyncMigrations.some((migration) =>
[AsyncMigrationStatus.Running, AsyncMigrationStatus.Starting].includes(migration.status)
),
],
actionableMigrations: [
(s) => [s.asyncMigrations],
(asyncMigrations: AsyncMigration[]) => asyncMigrations.filter((migration) => migration.is_available),
],
futureMigrations: [
(s) => [s.asyncMigrations],
(asyncMigrations: AsyncMigration[]) => asyncMigrations.filter((migration) => !migration.is_available),
],
}),
listeners(({ actions }) => ({
triggerMigration: async ({ migration }) => {
if (Object.keys(migration.parameter_definitions).length > 0) {
actions.openAsyncMigrationsModal(migration, 'trigger', 'Migration triggered successfully')
} else {
actions.updateMigrationStatus(migration, 'trigger', 'Migration triggered successfully')
}
},
resumeMigration: async ({ migration }) => {
if (Object.keys(migration.parameter_definitions).length > 0) {
actions.openAsyncMigrationsModal(migration, 'resume', 'Migration resume triggered successfully')
} else {
actions.updateMigrationStatus(migration, 'resume', 'Migration resume triggered successfully')
}
},
rollbackMigration: async ({ migration }) => {
actions.updateMigrationStatus(migration, 'rollback', 'Migration rollback triggered successfully')
},
forceStopMigration: async ({ migration }) => {
actions.updateMigrationStatus(migration, 'force_stop', 'Force stop triggered successfully')
},
forceStopMigrationWithoutRollback: async ({ migration }) => {
actions.updateMigrationStatus(
migration,
'force_stop_without_rollback',
'Force stop without rollback triggered successfully'
)
},
updateMigrationStatus: async ({ migration, endpoint, message }) => {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
const res = await api.create(`/api/async_migrations/${migration.id}/${endpoint}`, {
parameters: migration.parameters,
})
if (res.success) {
lemonToast.success(message)
actions.loadAsyncMigrations()
} else {
lemonToast.error(res.error)
}
},
updateSetting: async ({ settingKey, newValue }) => {
// TODO: Use systemStatusLogic.ts for consistency
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
await api.update(`/api/instance_settings/${settingKey}`, {
value: newValue,
})
lemonToast.success(`Instance setting ${settingKey} updated`)
actions.loadAsyncMigrationSettings()
actions.loadAsyncMigrations()
systemStatusLogic.actions.loadSystemStatus()
} catch {
lemonToast.error('Failed to trigger migration')
}
},
loadAsyncMigrationErrors: async ({ migrationId }) => {
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
const errorsForMigration = await api.get(`api/async_migrations/${migrationId}/errors`)
actions.loadAsyncMigrationErrorsSuccess(migrationId, errorsForMigration)
} catch (error) {
actions.loadAsyncMigrationErrorsFailure(migrationId, error)
}
},
})),
events(({ actions }) => ({
afterMount: () => {
actions.loadAsyncMigrations()
actions.loadAsyncMigrationSettings()
},
})),
actionToUrl(({ values }) => ({
setActiveTab: () =>
`/instance/async_migrations${
values.activeTab === AsyncMigrationsTab.Management ? '' : '/' + values.activeTab
}`,
})),
urlToAction(({ actions, values }) => ({
'/instance/async_migrations(/:tab)': ({ tab }: { tab?: AsyncMigrationsTab }) => {
if (tab && tab !== values.activeTab && tab !== AsyncMigrationsTab.Management) {
actions.setActiveTab(tab)
}
},
})),
])