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.

10.7 KB
Raw Blame
import { DateTime } from 'luxon'

import { PersonMessage } from '~/common/persons/person-message'
import { PersonUpdate } from '~/common/persons/person-update-batch'
import {
    InternalPersonWithDistinctId,
    LifecycleMarkPerson,
    PersonDistinctIdMapping,
    PersonRepository,
} from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
import { CreatePersonResult } from '~/common/utils/db/db'
import { logger } from '~/common/utils/logger'
import { Properties } from '~/plugin-scaffold'
import {
    InternalPerson,
    PersonUpdateFields,
    PropertiesLastOperation,
    PropertiesLastUpdatedAt,
    Team,
    TeamId,
} from '~/types'

import { PersonHogClient, shouldUseGrpcForTeam, shouldUseGrpcForTeamItems } from './client'
import { timedGrpc, timedPostgres } from './metrics'

export class PersonHogPersonRepository implements PersonRepository {
    constructor(
        private postgres: PersonRepository,
        private grpcClient: PersonHogClient,
        private grpcPercentage: number,
        private rolloutTeamIds: ReadonlySet<number>,
        private clientLabel: string
    ) {}

    // Read operations — route to gRPC based on percentage

    async fetchPerson(
        teamId: Team['id'],
        distinctId: string,
        options?: { forUpdate?: boolean; useReadReplica?: boolean; callerTag?: string }
    ): Promise<InternalPerson | undefined> {
        // Only route to gRPC for eventually-consistent replica reads
        if (
            options?.forUpdate ||
            !options?.useReadReplica ||
            !shouldUseGrpcForTeam(this.rolloutTeamIds, teamId, this.grpcPercentage)
        ) {
            return timedPostgres(this.clientLabel, 'fetchPerson', () =>
                this.postgres.fetchPerson(teamId, distinctId, options)
            )
        }

        try {
            const results = await timedGrpc(this.clientLabel, 'fetchPerson', () =>
                this.grpcClient.persons.fetchPersonsByDistinctIds([{ teamId, distinctId }], options?.callerTag)
            )
            if (results.length === 0) {
                return undefined
            }
            return results[0]
        } catch (error) {
            logger.warn('[PersonHog] gRPC fetchPerson failed, falling back to Postgres', {
                teamId,
                error: String(error),
            })
            return timedPostgres(this.clientLabel, 'fetchPerson', () =>
                this.postgres.fetchPerson(teamId, distinctId, options)
            )
        }
    }

    async fetchPersonsByDistinctIds(
        teamPersons: { teamId: TeamId; distinctId: string }[],
        useReadReplica?: boolean,
        callerTag?: string
    ): Promise<InternalPersonWithDistinctId[]> {
        // Default matches PostgresPersonRepository (useReadReplica=true)
        if (
            useReadReplica === false ||
            !shouldUseGrpcForTeamItems(this.rolloutTeamIds, teamPersons, this.grpcPercentage)
        ) {
            return timedPostgres(this.clientLabel, 'fetchPersonsByDistinctIds', () =>
                this.postgres.fetchPersonsByDistinctIds(teamPersons, useReadReplica, callerTag)
            )
        }

        try {
            return await timedGrpc(this.clientLabel, 'fetchPersonsByDistinctIds', () =>
                this.grpcClient.persons.fetchPersonsByDistinctIds(teamPersons, callerTag)
            )
        } catch (error) {
            logger.warn('[PersonHog] gRPC fetchPersonsByDistinctIds failed, falling back to Postgres', {
                count: teamPersons.length,
                error: String(error),
            })
            return timedPostgres(this.clientLabel, 'fetchPersonsByDistinctIds', () =>
                this.postgres.fetchPersonsByDistinctIds(teamPersons, useReadReplica, callerTag)
            )
        }
    }

    async fetchPersonsByPersonIds(
        teamPersons: { teamId: TeamId; personId: string }[],
        useReadReplica?: boolean,
        callerTag?: string
    ): Promise<InternalPerson[]> {
        // Default matches PostgresPersonRepository (useReadReplica=true)
        if (
            useReadReplica === false ||
            !shouldUseGrpcForTeamItems(this.rolloutTeamIds, teamPersons, this.grpcPercentage)
        ) {
            return timedPostgres(this.clientLabel, 'fetchPersonsByPersonIds', () =>
                this.postgres.fetchPersonsByPersonIds(teamPersons, useReadReplica, callerTag)
            )
        }

        try {
            return await timedGrpc(this.clientLabel, 'fetchPersonsByPersonIds', () =>
                this.grpcClient.persons.fetchPersonsByPersonIds(teamPersons, callerTag)
            )
        } catch (error) {
            logger.warn('[PersonHog] gRPC fetchPersonsByPersonIds failed, falling back to Postgres', {
                count: teamPersons.length,
                error: String(error),
            })
            return timedPostgres(this.clientLabel, 'fetchPersonsByPersonIds', () =>
                this.postgres.fetchPersonsByPersonIds(teamPersons, useReadReplica, callerTag)
            )
        }
    }

    fetchPersonsForUpdateByDistinctIds(
        teamId: TeamId,
        distinctIds: string[],
        callerTag?: string
    ): Promise<InternalPersonWithDistinctId[]> {
        // Locking read — always Postgres, like fetchPerson({forUpdate: true}).
        return this.postgres.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, callerTag)
    }

    async fetchDistinctIdsForPersons(
        teamId: TeamId,
        personIntIds: string[],
        options?: { limitPerPerson?: number; useReadReplica?: boolean }
    ): Promise<Record<string, string[]>> {
        const useReadReplica = options?.useReadReplica ?? true

        if (useReadReplica === false || !shouldUseGrpcForTeam(this.rolloutTeamIds, teamId, this.grpcPercentage)) {
            return timedPostgres(this.clientLabel, 'fetchDistinctIdsForPersons', () =>
                this.postgres.fetchDistinctIdsForPersons(teamId, personIntIds, options)
            )
        }

        try {
            return await timedGrpc(this.clientLabel, 'fetchDistinctIdsForPersons', () =>
                this.grpcClient.persons.getDistinctIdsForPersons(teamId, personIntIds, options?.limitPerPerson)
            )
        } catch (error) {
            logger.warn('[PersonHog] gRPC fetchDistinctIdsForPersons failed, falling back to Postgres', {
                count: personIntIds.length,
                error: String(error),
            })
            return timedPostgres(this.clientLabel, 'fetchDistinctIdsForPersons', () =>
                this.postgres.fetchDistinctIdsForPersons(teamId, personIntIds, options)
            )
        }
    }

    fetchPersonDistinctIdMappings(_teamId: TeamId, _distinctIds: string[]): Promise<PersonDistinctIdMapping[]> {
        // The personhog identity service produces the ClickHouse mapping messages
        // itself, so mapping re-emission has nothing to heal on this backend.
        // Returning no rows disables it without failing the merge.
        return Promise.resolve([])
    }

    // All write operations delegate directly to Postgres

    createPerson(
        createdAt: DateTime,
        properties: Properties,
        propertiesLastUpdatedAt: PropertiesLastUpdatedAt,
        propertiesLastOperation: PropertiesLastOperation,
        teamId: Team['id'],
        isUserId: number | null,
        isIdentified: boolean,
        uuid: string,
        primaryDistinctId: { distinctId: string; version?: number },
        extraDistinctIds?: { distinctId: string; version?: number }[]
    ): Promise<CreatePersonResult> {
        return this.postgres.createPerson(
            createdAt,
            properties,
            propertiesLastUpdatedAt,
            propertiesLastOperation,
            teamId,
            isUserId,
            isIdentified,
            uuid,
            primaryDistinctId,
            extraDistinctIds
        )
    }

    updatePerson(
        person: InternalPerson,
        update: PersonUpdateFields,
        tag?: string
    ): Promise<[InternalPerson, PersonMessage[], boolean]> {
        return this.postgres.updatePerson(person, update, tag)
    }

    handleOversizedPersonProperties(
        person: InternalPerson,
        update: PersonUpdateFields
    ): Promise<[InternalPerson, PersonMessage[], boolean]> {
        return this.postgres.handleOversizedPersonProperties(person, update)
    }

    updatePersonAssertVersion(personUpdate: PersonUpdate): Promise<[number | undefined, PersonMessage[]]> {
        return this.postgres.updatePersonAssertVersion(personUpdate)
    }

    updatePersonsBatch(personUpdates: PersonUpdate[]): Promise<
        Map<
            string,
            {
                success: boolean
                version?: number
                kafkaMessage?: PersonMessage
                person?: InternalPerson
                error?: Error
            }
        >
    > {
        return this.postgres.updatePersonsBatch(personUpdates)
    }

    deletePerson(person: InternalPerson): Promise<PersonMessage[]> {
        return this.postgres.deletePerson(person)
    }

    deletePersons(persons: InternalPerson[]): Promise<PersonMessage[]> {
        return this.postgres.deletePersons(persons)
    }

    claimLifecycleMarks(opId: string, teamId: number, persons: LifecycleMarkPerson[]): Promise<void> {
        return this.postgres.claimLifecycleMarks(opId, teamId, persons)
    }

    releaseLifecycleMarks(opId: string, teamId: number): Promise<void> {
        return this.postgres.releaseLifecycleMarks(opId, teamId)
    }

    isPersonLive(person: InternalPerson): Promise<boolean> {
        return this.postgres.isPersonLive(person)
    }

    addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {
        return this.postgres.addDistinctId(person, distinctId, version)
    }

    personPropertiesSize(personId: string, teamId: number): Promise<number> {
        return this.postgres.personPropertiesSize(personId, teamId)
    }

    updateCohortsAndFeatureFlagsForMergeBatch(
        teamID: Team['id'],
        sourcePersonIDs: InternalPerson['id'][],
        targetPersonID: InternalPerson['id']
    ): Promise<void> {
        return this.postgres.updateCohortsAndFeatureFlagsForMergeBatch(teamID, sourcePersonIDs, targetPersonID)
    }

    updateCohortsAndFeatureFlagsForMerge(
        teamID: Team['id'],
        sourcePersonID: InternalPerson['id'],
        targetPersonID: InternalPerson['id']
    ): Promise<void> {
        return this.postgres.updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID)
    }

    inTransaction<T>(description: string, transaction: (tx: PersonRepositoryTransaction) => Promise<T>): Promise<T> {
        return this.postgres.inTransaction(description, transaction)
    }
}