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.

4.7 KB
Raw Blame
import { S3Client } from '@aws-sdk/client-s3'

import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'
import { logger } from '~/common/utils/logger'
import { BlockMetadataBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher'
import { BlockMetadataParquetStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store'
import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'
import {
    CaptureWatermark,
    capturedRecords,
    releasingOffsetStore,
} from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'
import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'

import { CleanupResources } from './base-server'
import { IngestionSessionReplayMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
import { MlMirrorConsumerServer } from './ml-mirror-consumer-server'

/** The Parquet sink writes unencrypted data, so a misconfigured (absent) S3 client must fail loudly, not silently no-op. */
export function requireS3Client(client: S3Client | null): S3Client {
    if (!client) {
        throw new Error('SESSION_RECORDING_V2_S3_* must be configured for the ML Parquet sink')
    }
    return client
}

/**
 * Manual offsets + callEachBatchWhenEmpty: the batcher rolls rows up across batches and stores offsets only after a
 * flush lands in S3, so a failed write replays the window (at-least-once) and idle polls still flush.
 */
export function buildSinkConsumerConfig(config: IngestionSessionReplayMlMirrorServerConfig): KafkaConsumerConfig {
    return {
        topic: config.INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC,
        groupId: config.SESSION_RECORDING_ML_PARQUET_SINK_GROUP_ID,
        autoCommit: true,
        autoOffsetStore: false,
        callEachBatchWhenEmpty: true,
    }
}

/** Drains the ML block-metadata topic, rolling rows up into one Parquet object per flush interval in the ML bucket. */
export class IngestionSessionReplayMlParquetSinkServer extends MlMirrorConsumerServer {
    private keyManager?: MlKeyManager

    protected async startServices(): Promise<void> {
        if (this.config.AI_RESEARCH_REPLAY_KEY_TABLE) {
            this.keyManager = new MlKeyManager(this.config)
            await this.keyManager.start()
        }
        const s3Client = requireS3Client(buildSessionRecordingS3Client(this.config))
        if (!this.config.AI_RESEARCH_REPLAY_S3_BUCKET) {
            throw new Error(
                'AI_RESEARCH_REPLAY_S3_BUCKET must be set: sessions started after the v3 cutoff write there'
            )
        }
        const store = new BlockMetadataParquetStore(
            s3Client,
            { v2: this.config.SESSION_RECORDING_V2_S3_BUCKET, v3: this.config.AI_RESEARCH_REPLAY_S3_BUCKET },
            this.config.SESSION_RECORDING_ML_METADATA_PREFIX
        )

        const consumer = new KafkaConsumer(buildSinkConsumerConfig(this.config))
        const watermark = new CaptureWatermark('parquet_sink')
        const batcher = new BlockMetadataBatcher(
            store,
            releasingOffsetStore(consumer, watermark),
            {
                flushIntervalMs: this.config.SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS,
                maxRows: this.config.SESSION_RECORDING_ML_PARQUET_MAX_ROWS,
            },
            Date.now(),
            this.keyManager?.kafka
        )
        await consumer.connect(
            (messages) => {
                consumer.heartbeat()
                watermark.hold(capturedRecords(messages, () => 'event_metadata'))
                return batcher.handleBatch(messages, Date.now())
            },
            (partitions) => {
                watermark.forget(partitions)
                return Promise.resolve()
            }
        )

        this.lifecycle.services.push({
            id: 'session-replay-ml-parquet-sink',
            // Flush the buffer so a graceful restart doesn't re-process it, then disconnect.
            // A failed final flush is non-fatal (the window replays on restart) but must be visible.
            onShutdown: async () => {
                try {
                    await batcher.flush(Date.now())
                } catch (error) {
                    logger.warn('🪶', 'ml_parquet_sink_shutdown_flush_failed', { error: String(error) })
                }
                await consumer.disconnect()
            },
            healthcheck: () => consumer.isHealthy(),
        })
    }

    protected getCleanupResources(): CleanupResources {
        return {
            kafkaProducers: [],
            redisPools: [],
            additionalCleanup: () => {
                this.keyManager?.stop()
                return Promise.resolve()
            },
        }
    }
}