: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, afterMount, connect, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import { lemonToast } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'
import { resolveSnoozeUntil } from 'products/alerts/frontend/utils'
import {
logsAlertsDestroy,
logsAlertsList,
logsAlertsPartialUpdate,
logsAlertsResetCreate,
} from 'products/logs/frontend/generated/api'
import {
LogsAlertConfigurationApi,
PatchedLogsAlertConfigurationApi,
} from 'products/logs/frontend/generated/api.schemas'
import { alertFiltersForPreEnableCheck, dispatchPreEnableCheck, runPreEnableChecks } from './logsAlertUtils'
const ALERT_POLL_INTERVAL_MS = 30_000
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertingLogicValues {
currentTeamId: number | null // teamLogic
alerts: LogsAlertConfigurationApi[]
alertsLoaded: boolean
alertsLoading: boolean
createdByFilter: string | null
editingAlert: LogsAlertConfigurationApi | null
isCreateAlertModalOpen: boolean
resettingAlertIds: Set<string>
snoozingAlertIds: Set<string>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertingLogicActions {
closeCreateAlertModal: () => {
value: true
}
closeEditAlertModal: () => {
value: true
}
deleteAlert: (
id: string,
onSuccess?: () => void
) => {
id: string
onSuccess: (() => void) | undefined
}
loadAlerts: (_?: any) => any
loadAlertsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadAlertsSuccess: (
alerts: LogsAlertConfigurationApi[],
payload?: any
) => {
alerts: LogsAlertConfigurationApi[]
payload?: any
}
openCreateAlertModal: () => {
value: true
}
openEditAlertModal: (alert: LogsAlertConfigurationApi) => {
alert: LogsAlertConfigurationApi
}
resetAlert: (id: string) => {
id: string
}
setCreatedByFilter: (createdByFilter: string | null) => {
createdByFilter: string | null
}
setResettingAlertId: (
id: string,
resetting: boolean
) => {
id: string
resetting: boolean
}
setSnoozingAlertId: (
id: string,
snoozing: boolean
) => {
id: string
snoozing: boolean
}
snoozeAlert: (
alertId: string,
durationMinutes: number
) => {
alertId: string
durationMinutes: number
}
snoozeAlertUntil: (
alertId: string,
snoozeUntil: string
) => {
alertId: string
snoozeUntil: string
}
toggleAlertEnabled: (alert: LogsAlertConfigurationApi) => {
alert: LogsAlertConfigurationApi
}
unsnoozeAlert: (alertId: string) => {
alertId: string
}
updateEditingAlert: (alert: LogsAlertConfigurationApi) => {
alert: LogsAlertConfigurationApi
}
}
export type logsAlertingLogicType = MakeLogicType<logsAlertingLogicValues, logsAlertingLogicActions>
export const logsAlertingLogic = kea<logsAlertingLogicType>([
path(['products', 'logs', 'frontend', 'components', 'LogsAlerting', 'logsAlertingLogic']),
connect({
values: [teamLogic, ['currentTeamId']],
}),
actions({
setCreatedByFilter: (createdByFilter: string | null) => ({ createdByFilter }),
deleteAlert: (id: string, onSuccess?: () => void) => ({ id, onSuccess }),
toggleAlertEnabled: (alert: LogsAlertConfigurationApi) => ({ alert }),
resetAlert: (id: string) => ({ id }),
setResettingAlertId: (id: string, resetting: boolean) => ({ id, resetting }),
setSnoozingAlertId: (id: string, snoozing: boolean) => ({ id, snoozing }),
snoozeAlert: (alertId: string, durationMinutes: number) => ({ alertId, durationMinutes }),
snoozeAlertUntil: (alertId: string, snoozeUntil: string) => ({ alertId, snoozeUntil }),
unsnoozeAlert: (alertId: string) => ({ alertId }),
openCreateAlertModal: true,
closeCreateAlertModal: true,
openEditAlertModal: (alert: LogsAlertConfigurationApi) => ({ alert }),
closeEditAlertModal: true,
updateEditingAlert: (alert: LogsAlertConfigurationApi) => ({ alert }),
}),
reducers({
// An empty list only means the team has no alerts once a load for the current filter succeeds.
alertsLoaded: [
false,
{
setCreatedByFilter: () => false,
loadAlertsSuccess: () => true,
},
],
createdByFilter: [
null as string | null,
{
setCreatedByFilter: (_, { createdByFilter }) => createdByFilter,
},
],
resettingAlertIds: [
new Set<string>(),
{
setResettingAlertId: (state, { id, resetting }) =>
resetting ? new Set([...state, id]) : new Set([...state].filter((x) => x !== id)),
},
],
snoozingAlertIds: [
new Set<string>(),
{
setSnoozingAlertId: (state, { id, snoozing }) =>
snoozing ? new Set([...state, id]) : new Set([...state].filter((x) => x !== id)),
},
],
isCreateAlertModalOpen: [
false,
{
openCreateAlertModal: () => true,
closeCreateAlertModal: () => false,
},
],
editingAlert: [
null as LogsAlertConfigurationApi | null,
{
openEditAlertModal: (_, { alert }) => alert,
closeEditAlertModal: () => null,
updateEditingAlert: (editingAlert, { alert }) => (editingAlert?.id === alert.id ? alert : editingAlert),
},
],
}),
loaders(({ values }) => ({
alerts: [
[] as LogsAlertConfigurationApi[],
{
loadAlerts: async (_ = null, breakpoint) => {
const projectId = String(values.currentTeamId)
const response = await logsAlertsList(projectId, {
limit: 500,
...(values.createdByFilter ? { created_by: values.createdByFilter } : {}),
})
breakpoint()
return response.results
},
},
],
})),
listeners(({ actions, values }) => ({
setCreatedByFilter: () => actions.loadAlerts(),
deleteAlert: async ({ id, onSuccess }) => {
const projectId = String(values.currentTeamId)
try {
await logsAlertsDestroy(projectId, id)
lemonToast.success('Alert deleted')
actions.loadAlerts()
onSuccess?.()
} catch {
lemonToast.error('Failed to delete alert')
}
},
toggleAlertEnabled: ({ alert }) => {
const isEnabling = !(alert.enabled ?? true)
const projectId = String(values.currentTeamId)
const performToggle = async (): Promise<void> => {
const update: PatchedLogsAlertConfigurationApi = { enabled: !(alert.enabled ?? true) }
if (!update.enabled) {
update.snooze_until = null
}
try {
const updatedAlert = await logsAlertsPartialUpdate(projectId, alert.id, update)
actions.updateEditingAlert(updatedAlert)
actions.loadAlerts()
} catch {
lemonToast.error('Failed to update alert')
}
}
if (!isEnabling) {
void performToggle()
return
}
dispatchPreEnableCheck(runPreEnableChecks(alertFiltersForPreEnableCheck(alert)), () => void performToggle())
},
resetAlert: async ({ id }) => {
const projectId = String(values.currentTeamId)
actions.setResettingAlertId(id, true)
try {
await logsAlertsResetCreate(projectId, id)
lemonToast.success('Alert reset — next check will run shortly.')
actions.loadAlerts()
} catch {
lemonToast.error('Failed to reset alert')
} finally {
actions.setResettingAlertId(id, false)
}
},
snoozeAlert: async ({ alertId, durationMinutes }) => {
const projectId = String(values.currentTeamId)
const snoozeUntil = dayjs().add(durationMinutes, 'minute').toISOString()
actions.setSnoozingAlertId(alertId, true)
try {
const updatedAlert = await logsAlertsPartialUpdate(projectId, alertId, { snooze_until: snoozeUntil })
actions.updateEditingAlert(updatedAlert)
lemonToast.success('Alert snoozed')
actions.loadAlerts()
} catch {
lemonToast.error('Failed to snooze alert')
} finally {
actions.setSnoozingAlertId(alertId, false)
}
},
snoozeAlertUntil: async ({ alertId, snoozeUntil }) => {
const projectId = String(values.currentTeamId)
actions.setSnoozingAlertId(alertId, true)
try {
const updatedAlert = await logsAlertsPartialUpdate(projectId, alertId, {
snooze_until: resolveSnoozeUntil(snoozeUntil),
})
actions.updateEditingAlert(updatedAlert)
actions.loadAlerts()
} catch {
lemonToast.error('Failed to snooze alert')
} finally {
actions.setSnoozingAlertId(alertId, false)
}
},
unsnoozeAlert: async ({ alertId }) => {
const projectId = String(values.currentTeamId)
actions.setSnoozingAlertId(alertId, true)
try {
const updatedAlert = await logsAlertsPartialUpdate(projectId, alertId, { snooze_until: null })
actions.updateEditingAlert(updatedAlert)
lemonToast.success('Alert unsnoozed')
actions.loadAlerts()
} catch {
lemonToast.error('Failed to unsnooze alert')
} finally {
actions.setSnoozingAlertId(alertId, false)
}
},
})),
subscriptions(({ actions }) => ({
currentTeamId: (currentTeamId, previousTeamId) => {
if (previousTeamId !== null && currentTeamId !== previousTeamId) {
actions.setCreatedByFilter(null)
}
},
})),
afterMount(({ actions, cache }) => {
actions.loadAlerts()
cache.disposables.add(() => {
const intervalId = window.setInterval(() => {
actions.loadAlerts()
}, ALERT_POLL_INTERVAL_MS)
return () => clearInterval(intervalId)
}, 'pollAlerts')
}),
])