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.

19.7 KB
Raw Blame
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { NodeHttpHandler } from '@smithy/node-http-handler'

import {
    KAFKA_SESSION_REPLAY_IMAGE_FETCH,
    KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,
    KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M,
    KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,
    KAFKA_SESSION_REPLAY_IMAGE_SCRUB,
} from '~/common/config/kafka-topics'
import {
    EachBatch,
    KafkaConsumerV2,
    KafkaConsumerV2Config,
    RdKafkaConsumerOverrides,
} from '~/common/kafka/consumer/consumer-v2'
import { KafkaProducer } from '~/common/kafka/producer'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
import { logger } from '~/common/utils/logger'
import { TopHog } from '~/ingestion/framework/tophog/tophog'
import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'
import {
    ConfigurationPolicyService,
    HttpConfigurationFetcher,
} from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy'
import { DynamoDBCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history'
import { FetchCandidatePool } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool'
import { FetchRunner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner'
import { KafkaFrontierDeadLetterSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink'
import { FrontierPublisher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher'
import { HostBudget } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget'
import {
    ImageFetchBatchJoiner,
    assertImageFetchBatchTarget,
} from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner'
import { HttpImageFetcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'
import { OriginRequestScheduler } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler'
import { assertUrlPolicyLoaded } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key'
import { createPoolWindowBatchHandler } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/pool-window-batch-handler'
import { ImageFetchTopHogMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/tophog-metrics'
import { UrlFetchConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer'
import { VersionedCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history'
import { createWebBotAuthRequestSigner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth'
import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
import { createOutputsRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/registry'
import { CaptureWatermark, capturedRecords } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'
import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
import { HealthCheckResultOk } from '~/types'

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

/**
 * How long the store may spend on one batch, well inside Kafka's max.poll.interval.ms of 300s.
 *
 * The poll interval binds rather than the health check, because the heartbeat above keeps the health
 * check satisfied through a long batch. A batch that passes the poll interval loses the partition
 * mid-batch to a pod that will be just as slow, so the lane sheds the rest of the batch instead.
 */
const STORE_BATCH_BUDGET_MS = 50_000
const IMAGE_FETCH_KAFKA_QUEUE_BUDGET_KBYTES = 102_400
const IMAGE_FETCH_MIN_CONSUMER_QUEUE_KBYTES = 25_600
/**
 * The pool window paces a member in continuous-pool mode. This limit stays above that window at typical
 * batch sizes, and it is the hard bound on a member's resident URLs and crash replay when batches are large.
 */
const POOL_MAX_BATCHES_IN_FLIGHT_PER_MEMBER = 4

/** Matches MAX_URL_LEN in the crate, which is what the collector applied to the first candidate. */
const MAX_REDIRECT_URL_LENGTH = 2048

const BLOCKED_IMAGE_FETCH_DEAD_LETTER_TOPICS = [
    KAFKA_SESSION_REPLAY_IMAGE_FETCH,
    KAFKA_SESSION_REPLAY_IMAGE_SCRUB,
    KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M,
    KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,
    KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,
]

/** The addon holds a 15 MB native library and `index.ts` imports every server, so it loads on first use. */
let anonymizer: typeof import('@posthog/replay-anonymizer') | undefined
function getAnonymizer(): typeof import('@posthog/replay-anonymizer') {
    if (!anonymizer) {
        anonymizer = require('@posthog/replay-anonymizer') as typeof import('@posthog/replay-anonymizer')
        if (typeof anonymizer.isPublicHost !== 'function') {
            throw new Error('the replay-anonymizer addon has no isPublicHost: rebuild index.node')
        }
    }
    return anonymizer
}

export function buildFrontierPublisher(
    producer: KafkaProducer,
    maxConcurrentImagePublishes: number
): FrontierPublisher {
    return new FrontierPublisher(producer, {
        frontierTopic: KAFKA_SESSION_REPLAY_IMAGE_FETCH,
        scrubTopic: KAFKA_SESSION_REPLAY_IMAGE_SCRUB,
        delayTiers: [
            { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M, delayMs: 60_000, metricTopic: 'retry_1m' },
            { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M, delayMs: 600_000, metricTopic: 'retry_10m' },
            { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H, delayMs: 3_600_000, metricTopic: 'retry_1h' },
        ],
        maxConcurrentImagePublishes,
        maxConcurrentRepublishes: maxConcurrentImagePublishes,
    })
}

export function buildFetchRunner(
    config: IngestionSessionReplayMlMirrorServerConfig,
    publisher: FrontierPublisher,
    topHogMetrics: ImageFetchTopHogMetrics
): FetchRunner {
    const webBotAuthSigner = createWebBotAuthRequestSigner(config.WEB_BOT_AUTH_PRIVATE_KEYS)
    const budget = new HostBudget({
        requestsPerSecond: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND,
        burst: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST,
        maxConcurrent: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN,
        breakerFailures: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_FAILURES,
        breakerCooldownMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_COOLDOWN_MS,
        breakerMaxCooldownMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_MAX_COOLDOWN_MS,
        maxTrackedRegistrableDomains: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_REGISTRABLE_DOMAINS,
        maxTrackedOrigins: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_ORIGINS,
    })
    const scheduler = new OriginRequestScheduler(
        budget,
        config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS,
        topHogMetrics
    )
    const configurationPolicy = new ConfigurationPolicyService(
        new HttpConfigurationFetcher(
            webBotAuthSigner,
            scheduler,
            config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS
        )
    )
    return new FetchRunner(
        new HttpImageFetcher(
            {
                maxUrlLength: MAX_REDIRECT_URL_LENGTH,
                // The crate's rule, so a redirect target meets the check the collector already applied
                // to the first candidate rather than a second answer to the same question.
                isPublicHost: (host) => getAnonymizer().isPublicHost(host),
            },
            webBotAuthSigner
        ),
        budget,
        scheduler,
        configurationPolicy,
        {
            maxConcurrentPerRegistrableDomain:
                config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN,
            maxInFlightRequests: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS,
            batchBudgetMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS,
            maxBytes: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES,
            requestTimeoutMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS,
            maxRedirects: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_REDIRECTS,
            seenTtlSeconds: config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS,
            continuousPool: config.SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL
                ? {
                      refillRunnableUrls: config.SESSION_RECORDING_ML_IMAGE_FETCH_POOL_REFILL_RUNNABLE_URLS,
                      maxQueuedUrlsPerOwner: config.SESSION_RECORDING_ML_IMAGE_FETCH_POOL_MAX_QUEUED_URLS_PER_MEMBER,
                  }
                : undefined,
        },
        publisher,
        topHogMetrics
    )
}

export function buildImageFetchConsumerConfigs(
    config: IngestionSessionReplayMlMirrorServerConfig
): KafkaConsumerV2Config[] {
    const targetBatchCount = config.SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH
    assertImageFetchBatchTarget(targetBatchCount)
    return Array.from({ length: targetBatchCount }, () => ({
        topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH,
        groupId: config.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID,
        autoCommit: true,
        autoOffsetStore: true,
        fetchBatchSize: config.SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE,
        maxBackgroundTasks: config.SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL
            ? POOL_MAX_BATCHES_IN_FLIGHT_PER_MEMBER
            : 2,
        backgroundTaskTimeoutMs: 240_000,
    }))
}

export function imageFetchBatchesPerPass(
    config: IngestionSessionReplayMlMirrorServerConfig,
    consumerCount: number
): number {
    return config.SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES ? consumerCount : 1
}

export function buildImageFetchConsumerOverrides(
    config: IngestionSessionReplayMlMirrorServerConfig,
    consumerCount: number
): RdKafkaConsumerOverrides {
    assertImageFetchBatchTarget(consumerCount)
    const maximumRecordBytes = config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES * 2 + 64 * 1024
    return {
        'fetch.message.max.bytes': maximumRecordBytes,
        'max.partition.fetch.bytes': maximumRecordBytes,
        'queued.max.messages.kbytes': Math.max(
            IMAGE_FETCH_MIN_CONSUMER_QUEUE_KBYTES,
            Math.ceil(maximumRecordBytes / 1024),
            Math.floor(IMAGE_FETCH_KAFKA_QUEUE_BUDGET_KBYTES / consumerCount)
        ),
    }
}

export interface ImageFetchBatchHandlers {
    handlers: EachBatch[]
    /** Resolves once every batch started so far has settled, including pooled batches that the Kafka drain gave up on. */
    waitForProcessing(): Promise<void>
}

export function buildImageFetchBatchHandlers(
    consumerCount: number,
    fetchConsumer: Pick<UrlFetchConsumer, 'handleBatch'>,
    fetchRunner: { candidatePool?: Pick<FetchCandidatePool<unknown>, 'createOwner'> },
    batchJoiner: Pick<ImageFetchBatchJoiner, 'handleBatch' | 'waitForProcessing'>
): ImageFetchBatchHandlers {
    const pool = fetchRunner.candidatePool
    const pooledBatches = new Set<Promise<void>>()
    const trackPooledBatch = (batch: Promise<void>): Promise<void> => {
        pooledBatches.add(batch)
        const forget = (): void => {
            pooledBatches.delete(batch)
        }
        batch.then(forget, forget)
        return batch
    }
    const handlers = Array.from({ length: consumerCount }, (): EachBatch => {
        if (!pool) {
            return (messages) => batchJoiner.handleBatch(messages)
        }
        return createPoolWindowBatchHandler(pool.createOwner(), (messages, admission) =>
            trackPooledBatch(fetchConsumer.handleBatch(messages, Date.now(), admission))
        )
    })
    return {
        handlers,
        waitForProcessing: async () => {
            await batchJoiner.waitForProcessing()
            await Promise.allSettled([...pooledBatches])
        },
    }
}

export async function shutdownImageFetchConsumers(
    consumers: Pick<KafkaConsumerV2, 'stopConsuming' | 'disconnect'>[],
    startedBatches: Pick<ImageFetchBatchHandlers, 'waitForProcessing'>,
    fetchRunner?: Pick<FetchRunner, 'close'>
): Promise<void> {
    await Promise.allSettled(consumers.map((consumer) => consumer.stopConsuming()))
    await startedBatches.waitForProcessing()
    await Promise.allSettled(consumers.map((consumer) => consumer.disconnect()))
    await fetchRunner?.close()
}

/**
 * The image fetch lane.
 *
 * It scales separately because fetching waits on network IO while scrubbing needs CPU and ML models.
 */
export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerServer {
    private keyManager?: MlKeyManager
    private crawlHistoryClient?: DynamoDBClient
    private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
    private topHog?: TopHog

    protected async startServices(): Promise<void> {
        // Here rather than on the first record. The parser calls into this addon for every URL, and
        // it must answer with a reason rather than raise, so a build that shipped without the addon
        // has to stop the pod at startup instead.
        assertUrlPolicyLoaded()

        const dryRun = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN

        const tableName = this.config.AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE
        if (!tableName) {
            throw new Error('AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE must be set for the image-fetch consumer')
        }
        const dynamoDBTimeoutMs = this.config.AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS
        if (!Number.isFinite(dynamoDBTimeoutMs) || dynamoDBTimeoutMs <= 0) {
            throw new Error(
                `AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS must be a positive number, got ${dynamoDBTimeoutMs}`
            )
        }
        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 legacyCrawlHistory = new DynamoDBCrawlHistory(
            this.crawlHistoryClient,
            tableName,
            dynamoDBTimeoutMs,
            STORE_BATCH_BUDGET_MS
        )
        await legacyCrawlHistory.validateAccess(Date.now())
        let crawlHistory =
            legacyCrawlHistory as import('~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history').CrawlHistoryStore
        if (this.config.AI_RESEARCH_REPLAY_KEY_TABLE) {
            if (
                !this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE ||
                this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE === tableName
            ) {
                throw new Error('ML v3 requires a separate image fetch history table')
            }
            this.keyManager = new MlKeyManager(this.config)
            await this.keyManager.start()
            const v3 = new DynamoDBCrawlHistory(
                this.crawlHistoryClient,
                this.config.AI_RESEARCH_REPLAY_IMAGE_FETCH_V2_DYNAMODB_TABLE,
                dynamoDBTimeoutMs,
                STORE_BATCH_BUDGET_MS
            )
            await v3.validateAccess(Date.now())
            crawlHistory = new VersionedCrawlHistory(legacyCrawlHistory, v3)
        }

        // Built even in dry run, so the wiring is exercised by every start rather than only by the
        // one that clears the flag.
        this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)
        const outputs = createOutputsRegistry().build(this.producerRegistry, this.config)
        this.topHog = new TopHog({
            outputs,
            pipeline: this.config.INGESTION_PIPELINE ?? 'unknown',
            lane: this.config.INGESTION_LANE ?? 'unknown',
        })
        this.topHog.start()
        const topHogMetrics = new ImageFetchTopHogMetrics(this.topHog)
        const producer = this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER)
        const publisher = buildFrontierPublisher(
            producer,
            this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_PENDING_PUBLISHES
        )
        const deadLetterTopic = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DLQ_TOPIC
        const deadLetters = deadLetterTopic
            ? new KafkaFrontierDeadLetterSink(producer, deadLetterTopic, BLOCKED_IMAGE_FETCH_DEAD_LETTER_TOPICS)
            : null

        const fetchRunner = buildFetchRunner(this.config, publisher, topHogMetrics)
        const fetchConsumer = new UrlFetchConsumer(
            crawlHistory,
            publisher,
            {
                seenTtlSeconds: this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS,
                dryRun,
            },
            fetchRunner,
            deadLetters,
            topHogMetrics,
            this.keyManager?.kafka
        )
        logger.info('🌐', 'ml_image_fetch_started', {
            dryRun,
            continuousPool: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL,
        })

        const consumerConfigs = buildImageFetchConsumerConfigs(this.config)
        const batchJoiner = new ImageFetchBatchJoiner(
            imageFetchBatchesPerPass(this.config, consumerConfigs.length),
            (messages) => fetchConsumer.handleBatch(messages, Date.now())
        )
        const batchHandlers = buildImageFetchBatchHandlers(
            consumerConfigs.length,
            fetchConsumer,
            fetchRunner,
            batchJoiner
        )
        const consumerOverrides = buildImageFetchConsumerOverrides(this.config, consumerConfigs.length)
        const consumers = consumerConfigs.map(
            (consumerConfig) => new KafkaConsumerV2(consumerConfig, consumerOverrides)
        )

        this.lifecycle.services.push({
            id: 'session-replay-ml-image-fetch',
            onShutdown: () => shutdownImageFetchConsumers(consumers, batchHandlers, fetchRunner),
            healthcheck: () => {
                for (const consumer of consumers) {
                    const health = consumer.isHealthy()
                    if (health.isError()) {
                        return health
                    }
                }
                return new HealthCheckResultOk()
            },
        })
        const watermark = new CaptureWatermark('image_fetch')
        await Promise.all(
            consumers.map((consumer, index) =>
                consumer.connect(
                    (messages) => {
                        watermark.hold(capturedRecords(messages, () => 'image_urls'))
                        return batchHandlers.handlers[index](messages)
                    },
                    (partitions) => {
                        watermark.forget(partitions)
                        return Promise.resolve()
                    },
                    (offsets) => watermark.release(offsets)
                )
            )
        )
    }

    protected getCleanupResources(): CleanupResources {
        return {
            kafkaProducers: [],
            redisPools: [],
            additionalCleanup: async () => {
                this.keyManager?.stop()
                this.crawlHistoryClient?.destroy()
                try {
                    await this.topHog?.stop()
                } finally {
                    await this.producerRegistry?.disconnectAll()
                }
            },
        }
    }
}