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.

2.0 KB
Raw Blame
import { Message } from 'node-rdkafka'

import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import {
    SessionReplayPipeline,
    SessionReplayPipelineConfig,
    runSessionReplayPipeline,
} from '~/ingestion/pipelines/sessionreplay'

import { AdmittedBatch } from './batch-stages'
import { SessionRecordingIngesterMetrics } from './metrics'
import { splitByDecodedBytes } from './parse-message-step'
import { BatchCommitter, StagedBatchRunner } from './staged-batch'

/** Builds the session replay pipeline for a deployment. */
export type SessionReplayPipelineFactory = (config: SessionReplayPipelineConfig) => SessionReplayPipeline

/** Runs each poll batch through the session replay pipeline in one stage, so batches never overlap. */
export class SessionReplayPipelineRunner implements StagedBatchRunner {
    public readonly stages = ['ingest'] as const
    private pipeline!: SessionReplayPipeline
    private maxDecodedBytesPerWrite = 0

    constructor(
        private readonly createPipeline: SessionReplayPipelineFactory,
        private readonly scheduler: PromiseScheduler
    ) {}

    public start(config: SessionReplayPipelineConfig): void {
        this.pipeline = this.createPipeline(config)
        this.maxDecodedBytesPerWrite = config.maxDecodedBytesPerWrite ?? 0
    }

    public run(messages: Message[], batch: AdmittedBatch<void>, committer: BatchCommitter): Promise<void> {
        return batch
            .stage('ingest', async () => {
                const parts = splitByDecodedBytes(messages, this.maxDecodedBytesPerWrite)
                if (this.maxDecodedBytesPerWrite > 0 && messages.length > 0) {
                    SessionRecordingIngesterMetrics.observeKafkaBatchWriteParts(parts.length)
                }
                for (const part of parts) {
                    await committer.commit((recorder) =>
                        runSessionReplayPipeline(this.pipeline, part, recorder, this.scheduler)
                    )
                }
            })
            .done()
    }
}