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.

8.4 KB
Raw Blame
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { logger } from '~/common/utils/logger'
import { castTimestampOrNow } from '~/common/utils/utils'
import { FeatureEndResult } from '~/ingestion/pipelines/sessionreplay/sessions/session-feature-recorder'
import { SESSION_FEATURES_OUTPUT, SessionFeaturesOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { TimestampFormat } from '~/types'

import { SessionFeatureStoreMetrics } from './metrics'

interface KafkaMessage {
    key: string
    value: string
}

/** Ad-hoc sanity check. Should never be exceeded. Messages should stay < 50KB */
const filterOversizedMessages = (messages: KafkaMessage[]): KafkaMessage[] => {
    const MAX_MESSAGE_SIZE_BYTES = 256 * 1024
    const kept: KafkaMessage[] = []
    for (const message of messages) {
        const size = Buffer.byteLength(message.value, 'utf8')
        if (size > MAX_MESSAGE_SIZE_BYTES) {
            SessionFeatureStoreMetrics.incrementOversizedMessagesDropped()
            logger.warn('🧠', 'session_feature_store_message_dropped_oversized', {
                sessionId: message.key,
                size,
                limit: MAX_MESSAGE_SIZE_BYTES,
            })
            continue
        }
        kept.push(message)
    }
    return kept
}

export interface SessionFeatureBlock {
    sessionId: string
    teamId: number
    distinctId: string
    batchId: string
    features: FeatureEndResult
    isDeleted?: boolean
}

export interface DeletionFeatureBlock {
    sessionId: string
    teamId: number
}

export class SessionFeatureStore {
    constructor(
        private outputs: IngestionOutputs<SessionFeaturesOutput>,
        private enabled: boolean = false
    ) {
        logger.debug('🧠', 'session_feature_store_created', { enabled })
    }

    public async storeSessionFeatures(blocks: SessionFeatureBlock[]): Promise<void> {
        if (!this.enabled || blocks.length === 0) {
            return
        }

        logger.info('🧠', 'session_feature_store_storing', { count: blocks.length })

        const events = blocks.map((block) => ({
            session_id: block.sessionId,
            team_id: block.teamId,
            distinct_id: block.distinctId,
            batch_id: block.batchId,
            first_timestamp: castTimestampOrNow(block.features.startDateTime, TimestampFormat.ClickHouse),
            last_timestamp: castTimestampOrNow(block.features.endDateTime, TimestampFormat.ClickHouse),
            event_count: block.features.eventCount,
            mouse_position_count: block.features.mousePositionCount,
            mouse_sum_x: block.features.mouseSumX,
            mouse_sum_x_squared: block.features.mouseSumXSquared,
            mouse_sum_y: block.features.mouseSumY,
            mouse_sum_y_squared: block.features.mouseSumYSquared,
            mouse_distance_traveled: block.features.mouseDistanceTraveled,
            mouse_direction_change_count: block.features.mouseDirectionChangeCount,
            mouse_velocity_sum: block.features.mouseVelocitySum,
            mouse_velocity_sum_of_squares: block.features.mouseVelocitySumOfSquares,
            mouse_velocity_count: block.features.mouseVelocityCount,
            scroll_event_count: block.features.scrollEventCount,
            total_scroll_magnitude: block.features.totalScrollMagnitude,
            scroll_direction_reversal_count: block.features.scrollDirectionReversalCount,
            rapid_scroll_reversal_count: block.features.rapidScrollReversalCount,
            scroll_to_top_count: block.features.scrollToTopCount,
            click_count: block.features.clickCount,
            keypress_count: block.features.keypressCount,
            mouse_activity_count: block.features.mouseActivityCount,
            rage_click_count: block.features.rageClickCount,
            dead_click_count: block.features.deadClickCount,
            backspace_count: block.features.backspaceCount,
            inter_action_gap_count: block.features.interActionGapCount,
            inter_action_gap_sum_ms: block.features.interActionGapSumMs,
            inter_action_gap_sum_of_squares_ms: block.features.interActionGapSumOfSquaresMs,
            max_idle_gap_ms: block.features.maxIdleGapMs,
            long_idle_gap_count: block.features.longIdleGapCount,
            quick_back_count: block.features.quickBackCount,
            page_visit_count: block.features.pageVisitCount,
            visited_urls: block.features.visitedUrls,
            login_path_visit_count: block.features.pathTokenCounts.login,
            signup_path_visit_count: block.features.pathTokenCounts.signup,
            checkout_path_visit_count: block.features.pathTokenCounts.checkout,
            cart_path_visit_count: block.features.pathTokenCounts.cart,
            billing_path_visit_count: block.features.pathTokenCounts.billing,
            settings_path_visit_count: block.features.pathTokenCounts.settings,
            account_path_visit_count: block.features.pathTokenCounts.account,
            error_path_visit_count: block.features.pathTokenCounts.error,
            not_found_path_visit_count: block.features.pathTokenCounts['404'],
            admin_path_visit_count: block.features.pathTokenCounts.admin,
            dashboard_path_visit_count: block.features.pathTokenCounts.dashboard,
            onboarding_path_visit_count: block.features.pathTokenCounts.onboarding,
            cancel_path_visit_count: block.features.pathTokenCounts.cancel,
            refund_path_visit_count: block.features.pathTokenCounts.refund,
            console_error_count: block.features.consoleErrorCount,
            console_error_after_click_count: block.features.consoleErrorAfterClickCount,
            console_warn_count: block.features.consoleWarnCount,
            network_request_count: block.features.networkRequestCount,
            network_failed_request_count: block.features.networkFailedRequestCount,
            network_4xx_count: block.features.network4xxCount,
            network_5xx_count: block.features.network5xxCount,
            network_request_duration_sum: block.features.networkRequestDurationSum,
            network_request_duration_sum_of_squares: block.features.networkRequestDurationSumOfSquares,
            network_request_duration_count: block.features.networkRequestDurationCount,
            mutation_count: block.features.mutationCount,
            viewport_resize_count: block.features.viewportResizeCount,
            touch_event_count: block.features.touchEventCount,
            max_scroll_y: block.features.maxScrollY,
            click_target_ids: block.features.clickTargetIds,
            form_field_ids: block.features.formFieldIds,
            text_selection_count: block.features.textSelectionCount,
            selection_copy_count: block.features.selectionCopyCount,
            is_deleted: block.isDeleted ? 1 : 0,
        }))

        const messages = filterOversizedMessages(
            events.map((event) => ({
                key: event.session_id,
                value: JSON.stringify(event),
            }))
        )

        if (messages.length === 0) {
            return
        }

        // queueMessages awaits delivery acks for every message, so no separate flush is needed
        // to guarantee messages are on Kafka before the batch offset is committed.
        await this.outputs.queueMessages(
            SESSION_FEATURES_OUTPUT,
            messages.map((message) => ({
                key: message.key,
                value: Buffer.from(message.value),
            }))
        )

        logger.info('🧠', 'session_feature_store_stored', { count: messages.length })
    }

    public async storeDeletionMarkers(blocks: DeletionFeatureBlock[]): Promise<void> {
        const events = blocks.map((block) => ({
            session_id: block.sessionId,
            team_id: block.teamId,
            is_deleted: 1,
        }))

        const messages = filterOversizedMessages(
            events.map((event) => ({
                key: event.session_id,
                value: JSON.stringify(event),
            }))
        )

        if (messages.length === 0) {
            return
        }

        await this.outputs.queueMessages(
            SESSION_FEATURES_OUTPUT,
            messages.map((message) => ({
                key: message.key,
                value: Buffer.from(message.value),
            }))
        )

        logger.info('🧠', 'session_feature_store_deletion_markers_stored', { count: messages.length })
    }
}