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.

20.7 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { projectLogic } from 'scenes/projectLogic'

import { HogFunctionType, IntegrationType } from '~/types'

import {
    AlertNotificationUrlInput,
    AlertPagerDutyRegion,
    AlertPagerDutySeverity,
} from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'
import {
    logsAlertsDestinationsCreate,
    logsAlertsDestinationsDeleteCreate,
    logsAlertsRetrieve,
} from 'products/logs/frontend/generated/api'
import { LogsAlertCreateDestinationApi } from 'products/logs/frontend/generated/api.schemas'

import {
    buildLogsAlertFilterConfig,
    groupLogsAlertDestinations,
    LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY,
    LOGS_ALERT_NOTIFICATION_TYPE_SLACK,
    LOGS_ALERT_NOTIFICATION_TYPE_TEAMS,
    LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK,
    LogsAlertDestinationGroup,
    LogsAlertNotificationType,
    PAGERDUTY_ROUTING_KEY_PATTERN,
    PendingLogsAlertNotification,
} from './logsAlertUtils'

export const LOGS_ALERT_NOTIFICATION_TYPE_OPTIONS = [
    { label: 'Slack', value: LOGS_ALERT_NOTIFICATION_TYPE_SLACK },
    { label: 'Microsoft Teams', value: LOGS_ALERT_NOTIFICATION_TYPE_TEAMS },
    { label: 'PagerDuty', value: LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY },
    { label: 'Webhook', value: LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK },
]

function destinationCreateBody(notification: PendingLogsAlertNotification): LogsAlertCreateDestinationApi {
    switch (notification.type) {
        case LOGS_ALERT_NOTIFICATION_TYPE_SLACK:
            return {
                type: notification.type,
                slack_workspace_id: notification.slackWorkspaceId,
                slack_channel_id: notification.slackChannelId,
                slack_channel_name: notification.slackChannelName,
            }
        case LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY:
            return {
                type: notification.type,
                pagerduty_routing_key: notification.routingKey,
                pagerduty_severity: notification.severity,
                pagerduty_region: notification.region,
            }
        default:
            return { type: notification.type, webhook_url: notification.webhookUrl }
    }
}

export interface LogsAlertNotificationLogicProps {
    alertId?: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertNotificationLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    integrationsLoading: boolean // integrationsLogic
    slackIntegrations: IntegrationType[] | undefined // integrationsLogic
    currentProjectId: number | null // projectLogic
    addDisabledReason: string | undefined
    customizedDestinationKeys: Set<string>
    customizedHogFunctionIds: string[]
    customizedHogFunctionIdsLoading: boolean
    destinationGroups: LogsAlertDestinationGroup[]
    existingHogFunctions: HogFunctionType[]
    existingHogFunctionsLoading: boolean
    firstSlackIntegration: IntegrationType | undefined
    integrationsFailed: boolean
    pagerDutyRegion: AlertPagerDutyRegion
    pagerDutyRoutingKey: string
    pagerDutySeverity: AlertPagerDutySeverity
    pendingNotifications: PendingLogsAlertNotification[]
    selectedType: LogsAlertNotificationType
    slackChannelValue: string | null
    urlInput: AlertNotificationUrlInput | undefined
    webhookUrl: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertNotificationLogicActions {
    setFeatureFlags: (
        flags: string[],
        variants: Record<string, boolean | string>
    ) => {
        flags: string[]
        variants: Record<string, boolean | string>
    } // featureFlagLogic
    loadIntegrations: (_?: any) => any // integrationsLogic
    loadIntegrationsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // integrationsLogic
    loadIntegrationsSuccess: (
        integrations: IntegrationType[],
        payload?: any
    ) => {
        integrations: IntegrationType[]
        payload?: any
    } // integrationsLogic
    addPendingNotification: (notification: PendingLogsAlertNotification) => {
        notification: PendingLogsAlertNotification
    }
    addSelectedNotification: () => {
        value: true
    }
    clearPendingNotifications: () => {
        value: true
    }
    createPendingHogFunctions: (alertId: string) => {
        alertId: string
    }
    deleteExistingDestination: (group: LogsAlertDestinationGroup) => {
        group: LogsAlertDestinationGroup
    }
    destinationsChanged: () => {
        value: true
    }
    loadCustomizedHogFunctionIds: (alertId?: string) => string
    loadCustomizedHogFunctionIdsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCustomizedHogFunctionIdsSuccess: (
        customizedHogFunctionIds: string[],
        payload?: string
    ) => {
        customizedHogFunctionIds: string[]
        payload?: string
    }
    loadExistingHogFunctions: (alertId?: string) => string
    loadExistingHogFunctionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadExistingHogFunctionsSuccess: (
        existingHogFunctions: HogFunctionType[],
        payload?: string
    ) => {
        existingHogFunctions: HogFunctionType[]
        payload?: string
    }
    removePendingNotification: (index: number) => {
        index: number
    }
    setPagerDutyRegion: (pagerDutyRegion: AlertPagerDutyRegion) => {
        pagerDutyRegion: AlertPagerDutyRegion
    }
    setPagerDutyRoutingKey: (pagerDutyRoutingKey: string) => {
        pagerDutyRoutingKey: string
    }
    setPagerDutySeverity: (pagerDutySeverity: AlertPagerDutySeverity) => {
        pagerDutySeverity: AlertPagerDutySeverity
    }
    setPendingNotifications: (notifications: PendingLogsAlertNotification[]) => {
        notifications: PendingLogsAlertNotification[]
    }
    setSelectedType: (selectedType: LogsAlertNotificationType) => {
        selectedType: LogsAlertNotificationType
    }
    setSlackChannelValue: (slackChannelValue: string | null) => {
        slackChannelValue: string | null
    }
    setWebhookUrl: (webhookUrl: string) => {
        webhookUrl: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertNotificationLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        firstSlackIntegration: (slackIntegrations: IntegrationType[] | undefined) => IntegrationType | undefined
        urlInput: (selectedType: LogsAlertNotificationType) => AlertNotificationUrlInput | undefined
        addDisabledReason: (
            selectedType: LogsAlertNotificationType,
            firstSlackIntegration: IntegrationType | undefined,
            slackChannelValue: string | null,
            webhookUrl: string,
            pagerDutyRoutingKey: string
        ) => string | undefined
        destinationGroups: (existingHogFunctions: HogFunctionType[]) => LogsAlertDestinationGroup[]
        customizedDestinationKeys: (
            destinationGroups: LogsAlertDestinationGroup[],
            customizedHogFunctionIds: string[],
            featureFlags: FeatureFlagsSet
        ) => Set<string>
    }
}

export type logsAlertNotificationLogicType = MakeLogicType<
    logsAlertNotificationLogicValues,
    logsAlertNotificationLogicActions,
    LogsAlertNotificationLogicProps,
    logsAlertNotificationLogicMeta
>

export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([
    path(['products', 'logs', 'frontend', 'components', 'LogsAlerting', 'logsAlertNotificationLogic']),
    props({} as LogsAlertNotificationLogicProps),
    key(({ alertId }) => alertId ?? 'new'),

    connect({
        values: [
            projectLogic,
            ['currentProjectId'],
            integrationsLogic,
            ['integrationsLoading', 'slackIntegrations'],
            featureFlagLogic,
            ['featureFlags'],
        ],
        actions: [
            integrationsLogic,
            ['loadIntegrations', 'loadIntegrationsFailure', 'loadIntegrationsSuccess'],
            featureFlagLogic,
            ['setFeatureFlags'],
        ],
    }),

    actions({
        addPendingNotification: (notification: PendingLogsAlertNotification) => ({ notification }),
        addSelectedNotification: true,
        removePendingNotification: (index: number) => ({ index }),
        clearPendingNotifications: true,
        setPendingNotifications: (notifications: PendingLogsAlertNotification[]) => ({ notifications }),
        deleteExistingDestination: (group: LogsAlertDestinationGroup) => ({ group }),
        createPendingHogFunctions: (alertId: string) => ({ alertId }),
        destinationsChanged: true,
        setSelectedType: (selectedType: LogsAlertNotificationType) => ({ selectedType }),
        setSlackChannelValue: (slackChannelValue: string | null) => ({ slackChannelValue }),
        setWebhookUrl: (webhookUrl: string) => ({ webhookUrl }),
        setPagerDutyRoutingKey: (pagerDutyRoutingKey: string) => ({ pagerDutyRoutingKey }),
        setPagerDutySeverity: (pagerDutySeverity: AlertPagerDutySeverity) => ({ pagerDutySeverity }),
        setPagerDutyRegion: (pagerDutyRegion: AlertPagerDutyRegion) => ({ pagerDutyRegion }),
    }),

    reducers({
        pendingNotifications: [
            [] as PendingLogsAlertNotification[],
            {
                addPendingNotification: (state, { notification }) => [...state, notification],
                removePendingNotification: (state, { index }) => state.filter((_, i) => i !== index),
                clearPendingNotifications: () => [],
                setPendingNotifications: (_, { notifications }) => notifications,
            },
        ],
        integrationsFailed: [
            false,
            {
                loadIntegrations: () => false,
                loadIntegrationsFailure: () => true,
                loadIntegrationsSuccess: () => false,
            },
        ],
        slackChannelValue: [
            null as string | null,
            {
                setSlackChannelValue: (_, { slackChannelValue }) => slackChannelValue,
            },
        ],
        webhookUrl: [
            '' as string,
            {
                setWebhookUrl: (_, { webhookUrl }) => webhookUrl,
            },
        ],
        pagerDutyRoutingKey: [
            '' as string,
            {
                setPagerDutyRoutingKey: (_, { pagerDutyRoutingKey }) => pagerDutyRoutingKey,
            },
        ],
        pagerDutySeverity: [
            'critical' as AlertPagerDutySeverity,
            {
                setPagerDutySeverity: (_, { pagerDutySeverity }) => pagerDutySeverity,
            },
        ],
        pagerDutyRegion: [
            'us' as AlertPagerDutyRegion,
            {
                setPagerDutyRegion: (_, { pagerDutyRegion }) => pagerDutyRegion,
            },
        ],
        selectedType: [
            LOGS_ALERT_NOTIFICATION_TYPE_SLACK as LogsAlertNotificationType,
            {
                setSelectedType: (_, { selectedType }) => selectedType,
            },
        ],
    }),

    loaders(({ props, values }) => ({
        customizedHogFunctionIds: [
            [] as string[],
            {
                loadCustomizedHogFunctionIds: async (alertId?: string) => {
                    const id = alertId ?? props.alertId
                    if (!id) {
                        return []
                    }
                    const alert = await logsAlertsRetrieve(String(values.currentProjectId), id)
                    return alert.destinations
                        .filter((destination) => destination.message_customized)
                        .flatMap((destination) => destination.hog_function_ids)
                },
            },
        ],
        existingHogFunctions: [
            [] as HogFunctionType[],
            {
                loadExistingHogFunctions: async (alertId?: string) => {
                    const id = alertId ?? props.alertId
                    if (!id) {
                        return []
                    }
                    const response = await api.hogFunctions.list({
                        types: ['internal_destination'],
                        filter_groups: [buildLogsAlertFilterConfig(id)],
                        full: true,
                    })
                    return response.results
                },
            },
        ],
    })),

    selectors({
        firstSlackIntegration: [
            (s) => [s.slackIntegrations],
            (slackIntegrations: IntegrationType[] | undefined): IntegrationType | undefined => slackIntegrations?.[0],
        ],
        urlInput: [
            (s) => [s.selectedType],
            (selectedType: LogsAlertNotificationType): AlertNotificationUrlInput | undefined => {
                if (selectedType === LOGS_ALERT_NOTIFICATION_TYPE_TEAMS) {
                    return {
                        placeholder: 'https://prod-00.westus.logic.azure.com:443/workflows/...',
                        helpText:
                            'Paste the URL from a Teams "Workflows" (Power Automate) or incoming webhook connector. We send a formatted Adaptive Card to it.',
                    }
                }
                if (selectedType === LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK) {
                    return { placeholder: 'https://example.com/webhook' }
                }
                return undefined
            },
        ],
        addDisabledReason: [
            (s) => [s.selectedType, s.firstSlackIntegration, s.slackChannelValue, s.webhookUrl, s.pagerDutyRoutingKey],
            (
                selectedType: LogsAlertNotificationType,
                firstSlackIntegration: IntegrationType | undefined,
                slackChannelValue: string | null,
                webhookUrl: string,
                pagerDutyRoutingKey: string
            ): string | undefined => {
                if (selectedType === LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY) {
                    if (!pagerDutyRoutingKey.trim()) {
                        return 'Enter the PagerDuty integration key'
                    }
                    return PAGERDUTY_ROUTING_KEY_PATTERN.test(pagerDutyRoutingKey.trim())
                        ? undefined
                        : 'The integration key is 32 letters and digits'
                }
                if (selectedType !== LOGS_ALERT_NOTIFICATION_TYPE_SLACK) {
                    return webhookUrl ? undefined : 'Enter a webhook URL'
                }
                if (!firstSlackIntegration) {
                    return 'Connect Slack first'
                }
                return slackChannelValue ? undefined : 'Select a Slack channel'
            },
        ],
        // Channel-name resolution happens in the view — slackChannels lives in a dynamically-keyed logic.
        destinationGroups: [
            (s) => [s.existingHogFunctions],
            (hogFunctions: HogFunctionType[]): LogsAlertDestinationGroup[] =>
                groupLogsAlertDestinations(hogFunctions, () => null),
        ],
        customizedDestinationKeys: [
            (s) => [s.destinationGroups, s.customizedHogFunctionIds, s.featureFlags],
            (
                groups: LogsAlertDestinationGroup[],
                customizedIds: string[],
                featureFlags: FeatureFlagsSet
            ): Set<string> => {
                if (!featureFlags[FEATURE_FLAGS.ALERTS_DESTINATION_CUSTOMIZATION]) {
                    return new Set()
                }
                const customized = new Set(customizedIds)
                return new Set(
                    groups
                        .filter((group) => group.hogFunctions.some((hogFunction) => customized.has(hogFunction.id)))
                        .map((group) => group.key)
                )
            },
        ],
    }),

    listeners(({ actions, values, props }) => ({
        loadExistingHogFunctions: (alertId) => {
            if (values.featureFlags[FEATURE_FLAGS.ALERTS_DESTINATION_CUSTOMIZATION]) {
                actions.loadCustomizedHogFunctionIds(alertId)
            }
        },
        // Flags that are not persisted arrive after mount, so the first load may have skipped the ids.
        setFeatureFlags: () => {
            if (props.alertId && values.featureFlags[FEATURE_FLAGS.ALERTS_DESTINATION_CUSTOMIZATION]) {
                actions.loadCustomizedHogFunctionIds()
            }
        },
        addSelectedNotification: () => {
            if (values.selectedType === LOGS_ALERT_NOTIFICATION_TYPE_SLACK) {
                if (!values.slackChannelValue || !values.firstSlackIntegration) {
                    return
                }
                const [channelId, channelLabel] = values.slackChannelValue.split('|')
                actions.addPendingNotification({
                    type: LOGS_ALERT_NOTIFICATION_TYPE_SLACK,
                    slackWorkspaceId: values.firstSlackIntegration.id,
                    slackChannelId: channelId,
                    slackChannelName: channelLabel?.replace('#', '') ?? channelId,
                })
                actions.setSlackChannelValue(null)
                return
            }
            if (values.selectedType === LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY) {
                const routingKey = values.pagerDutyRoutingKey.trim()
                if (!PAGERDUTY_ROUTING_KEY_PATTERN.test(routingKey)) {
                    return
                }
                actions.addPendingNotification({
                    type: LOGS_ALERT_NOTIFICATION_TYPE_PAGERDUTY,
                    routingKey,
                    severity: values.pagerDutySeverity,
                    region: values.pagerDutyRegion,
                })
                actions.setPagerDutyRoutingKey('')
                return
            }
            if (!values.webhookUrl) {
                return
            }
            actions.addPendingNotification({ type: values.selectedType, webhookUrl: values.webhookUrl })
            actions.setWebhookUrl('')
        },
        addPendingNotification: () => {
            if (props.alertId) {
                actions.createPendingHogFunctions(props.alertId)
            }
        },
        loadIntegrationsSuccess: () => {
            if (!values.firstSlackIntegration) {
                actions.setSelectedType(LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK)
            }
        },
        deleteExistingDestination: async ({ group }) => {
            if (!props.alertId) {
                return
            }
            try {
                await logsAlertsDestinationsDeleteCreate(String(values.currentProjectId), props.alertId, {
                    hog_function_ids: group.hogFunctions.map((hf) => hf.id),
                })
                lemonToast.success(`Removed ${group.label}`)
                actions.loadExistingHogFunctions()
                actions.destinationsChanged()
            } catch {
                lemonToast.error(`Failed to remove ${group.label}`)
                actions.loadExistingHogFunctions()
            }
        },

        createPendingHogFunctions: async ({ alertId }) => {
            const pending = values.pendingNotifications
            if (pending.length === 0) {
                return
            }

            const projectId = String(values.currentProjectId)
            const results = await Promise.allSettled(
                pending.map((notification) =>
                    logsAlertsDestinationsCreate(projectId, alertId, destinationCreateBody(notification))
                )
            )

            const failedNotifications = pending.filter((_, i) => results[i].status === 'rejected')

            actions.loadExistingHogFunctions(alertId)
            actions.destinationsChanged()

            if (failedNotifications.length > 0) {
                lemonToast.error(
                    `Alert saved, but ${failedNotifications.length} notification(s) failed to create. Reopen the alert to add them again.`
                )
                actions.setPendingNotifications(failedNotifications)
            } else {
                if (pending.length > 0) {
                    lemonToast.success(`${pending.length} notification destination(s) created.`)
                }
                actions.clearPendingNotifications()
            }
        },
    })),

    afterMount(({ actions, props }) => {
        if (props.alertId) {
            actions.loadExistingHogFunctions()
        }
    }),
])