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.

13.2 KB
Raw Blame
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { NodeHttpHandler } from '@smithy/node-http-handler'

import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
import { threadpoolConcurrency } from '~/common/utils/threadpool-concurrency'
import { AllowListFetcher, loadAllowLists } from '~/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader'
import { type SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'
import {
    SessionRecordingIngester,
    SessionRecordingIngesterCollaborators,
} from '~/ingestion/pipelines/sessionreplay/consumer'
import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'
import { DynamoDBCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history'
import { VersionedCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history'
import { ML_BLOCK_COMPRESSION } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-compression'
import { resolveMlMirrorRedisConnection } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'
import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'
import { MlBlockMetadataSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink'
import { resolvePseudonymKey } from '~/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key'
import { SessionFormatFileStorage } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-format-file-storage'
import { MlMirrorStagedBatchRunner } from '~/ingestion/pipelines/sessionreplay/ml-mirror/staged-batch-runner'
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
import { createOutputsRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/registry'
import { BlackholeSessionBatchFileStorage } from '~/ingestion/pipelines/sessionreplay/sessions/blackhole-session-batch-writer'
import { S3SessionBatchFileStorage } from '~/ingestion/pipelines/sessionreplay/sessions/s3-session-batch-writer'
import { SessionConsoleLogStore } from '~/ingestion/pipelines/sessionreplay/sessions/session-console-log-store'
import { CaptureWatermark } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'
import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'
import { RedisPool } from '~/types'

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

export { type IngestionSessionReplayMlMirrorServerConfig, buildMlMirrorServerConfig } from './ml-mirror-server-config'

/** Boot-time smoke test so a broken addon crashes startup instead of dropping all traffic later. */
export async function assertAnonymizerHealthy(anonymizer: typeof import('@posthog/replay-anonymizer')): Promise<void> {
    const inner = JSON.stringify({
        event: '$snapshot_items',
        properties: {
            $session_id: 's',
            $window_id: 'w',
            $snapshot_source: 'web',
            $snapshot_items: [{ type: 3, timestamp: Date.now(), data: { source: 5, id: 1, text: 'health check' } }],
        },
    })
    const payload = Buffer.from(JSON.stringify({ distinct_id: 'd', data: inner }))
    const result = await anonymizer.anonymizeKafkaPayload(payload)
    if (result.failed) {
        throw new Error(`replay-anonymizer startup self-test failed: ${result.reason ?? 'unknown'}`)
    }
}

export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer {
    private readonly keyManager = new MlKeyManager(this.config)
    private postgres?: PostgresRouter
    private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
    private crawlHistoryClient?: DynamoDBClient
    private redisPool?: RedisPool
    private restrictionRedisPool?: RedisPool

    protected async startServices(): Promise<void> {
        this.postgres = new PostgresRouter(this.config, this.config.PLUGIN_SERVER_MODE ?? undefined)
        this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)
        const outputs = createOutputsRegistry().build(this.producerRegistry, this.config)

        // Another system writes the event restriction list, so every lane reads one copy of it.
        const pools = buildSessionReplayRedisPools(this.config, resolveMlMirrorRedisConnection(this.config))
        this.redisPool = pools.redisPool
        this.restrictionRedisPool = pools.restrictionRedisPool

        const s3Client = buildSessionRecordingS3Client(this.config)
        const bucket = this.config.SESSION_RECORDING_V2_S3_BUCKET
        const prefix = this.config.AI_RESEARCH_REPLAY_S3_PREFIX
        const v3Bucket = this.config.AI_RESEARCH_REPLAY_S3_BUCKET
        const v3Prefix = this.config.AI_RESEARCH_REPLAY_S3_V3_PREFIX
        if (!v3Bucket) {
            throw new Error(
                'AI_RESEARCH_REPLAY_S3_BUCKET must be set: sessions started after the v3 cutoff write there'
            )
        }

        const pseudonymSecret = await resolvePseudonymKey(this.config)

        // A session keeps its storage prefix across flushes and late arrivals.
        const rawStorage = (month?: string) =>
            new S3SessionBatchFileStorage(
                s3Client!,
                bucket,
                month ? `${prefix}/${month}` : prefix,
                this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS
            )
        const fileStorage = s3Client
            ? new SessionFormatFileStorage(
                  new S3SessionBatchFileStorage(
                      s3Client,
                      bucket,
                      this.config.SESSION_RECORDING_V2_S3_PREFIX,
                      this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS
                  ),
                  rawStorage,
                  (month) =>
                      new S3SessionBatchFileStorage(
                          s3Client,
                          v3Bucket,
                          month ? `${v3Prefix}/${month}` : v3Prefix,
                          this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS
                      )
              )
            : new BlackholeSessionBatchFileStorage()

        const allow = await loadAllowLists(this.buildAllowListFetcher(s3Client, bucket))
        // Lazy require so only ml-mirror deployments load (and need to ship) the native addon; the
        // addon holds its own copy of the immutable allow lists, set once at startup.
        const anonymizer = require('@posthog/replay-anonymizer') as typeof import('@posthog/replay-anonymizer')
        anonymizer.initAnonymizer(allow.entries())
        // The addon's scrub runs on the libuv threadpool (UV_THREADPOOL_SIZE, default 4) shared
        // with the recorder's snappy compression — size it for the deployment if scrub backs up.
        await assertAnonymizerHealthy(anonymizer)
        logger.info('🦀', 'ml_mirror_rust_anonymizer_initialized')

        // Block metadata is produced to Kafka; the dedicated Parquet-sink deployment writes it to the ML bucket.
        await this.keyManager.start()
        const metadataStore = new MlBlockMetadataSink(outputs, pseudonymSecret, this.keyManager.reader)
        const urlProducerEnabled =
            this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED &&
            this.config.SESSION_RECORDING_ML_URL_PRODUCER_ENABLED
        const urlCrawlHistory = urlProducerEnabled ? this.buildUrlCrawlHistory() : undefined

        const keyManager = this.keyManager.controller
        const collaborators: SessionRecordingIngesterCollaborators = {
            fileStorage,
            metadataStore,
            // Console logs and ML features are not mirrored.
            consoleLogStore: new SessionConsoleLogStore(outputs, {
                messageLimit: this.config.SESSION_RECORDING_V2_CONSOLE_LOG_STORE_SYNC_BATCH_LIMIT,
                enabled: false,
            }),
            featureStore: new SessionFeatureStore(outputs, false),
            keyStore: keyManager,
            encryptor: keyManager,
            compression: ML_BLOCK_COMPRESSION,
            runner: new MlMirrorStagedBatchRunner(
                {
                    keyManager,
                    anonymizeMaxConcurrency: threadpoolConcurrency(),
                },
                this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED
                    ? {
                          outputs,
                          producedRefCacheMax: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCED_REF_CACHE_MAX,
                      }
                    : undefined,
                {
                    pseudonymSecret,
                    // Producing the images is what makes collecting them useful, so the image
                    // lane follows its producer flag. The URL lane collects on its own flag,
                    // because collecting alone measures without sending anything anywhere.
                    collectImages: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED,
                    maxImageBytes: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGE_BYTES,
                    collectUrls: this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED,
                },
                // Producing needs collection: without it the anonymizer returns no URLs, and
                // the step would have nothing to send.
                urlProducerEnabled
                    ? {
                          outputs,
                          producedRefCacheMax: this.config.SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX,
                          producedRefCacheWindowMs:
                              (this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS * 1000) / 2,
                          crawlHistory: urlCrawlHistory,
                      }
                    : undefined
            ),
            // Isolate the mirror's session tracker/filter keys from the main lane. Sharing them would let
            // the cleartext mirror mark a session seen without the main lane's KMS key, so the main lane
            // would then fetch a missing key and record cleartext.
            redisKeyNamespace: 'ml-mirror',
            captureWatermark: new CaptureWatermark('ml_mirror'),
            reportUsage: false,
        }

        const ingester = new SessionRecordingIngester(
            this.config,
            this.postgres,
            outputs,
            this.redisPool,
            this.restrictionRedisPool,
            collaborators
        )
        await ingester.start()
        this.lifecycle.services.push(ingester.service)
    }

    private buildAllowListFetcher(s3Client: S3Client | null, bucket: string): AllowListFetcher | undefined {
        const key = this.config.SESSION_RECORDING_ML_ALLOW_LIST_S3_KEY
        if (!s3Client || !key) {
            return undefined
        }
        return async () => {
            const response = await s3Client.send(new GetObjectCommand({ Bucket: bucket, Key: key }))
            const body = await response.Body?.transformToString()
            return body ? parseJSON(body) : {}
        }
    }

    private buildUrlCrawlHistory(): Pick<CrawlHistoryStore, 'read'> | undefined {
        if (!this.config.SESSION_RECORDING_ML_URL_CRAWL_HISTORY_PRECHECK_ENABLED) {
            return undefined
        }
        const tableName = this.config.AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE
        const timeoutMs = this.config.SESSION_RECORDING_ML_URL_CRAWL_HISTORY_PRECHECK_TIMEOUT_MS
        if (!tableName || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
            logger.warn('🌐', 'ml_image_fetch_crawl_history_precheck_disabled', { tableConfigured: Boolean(tableName) })
            return undefined
        }
        this.crawlHistoryClient = new DynamoDBClient({
            region: this.config.SESSION_RECORDING_V2_S3_REGION || 'us-east-1',
            endpoint: this.config.SESSION_RECORDING_DYNAMODB_ENDPOINT,
            maxAttempts: 5,
            requestHandler: new NodeHttpHandler(),
        })
        const legacy = new DynamoDBCrawlHistory(this.crawlHistoryClient, tableName, timeoutMs, timeoutMs)
        const v3TableName = this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE
        if (!v3TableName) {
            return legacy
        }
        return new VersionedCrawlHistory(
            legacy,
            new DynamoDBCrawlHistory(this.crawlHistoryClient, v3TableName, timeoutMs, timeoutMs)
        )
    }

    protected getCleanupResources(): CleanupResources {
        return {
            kafkaProducers: [],
            redisPools: [this.redisPool, this.restrictionRedisPool].filter(Boolean) as RedisPool[],
            postgres: this.postgres,
            additionalCleanup: async () => {
                this.keyManager.stop()
                this.crawlHistoryClient?.destroy()
                await this.producerRegistry?.disconnectAll()
            },
        }
    }
}