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.5 KB
Raw Blame
import { DateTime } from 'luxon'

import {
    IngestionWarningsOutput,
    PersonDistinctIdsOutput,
    PersonMergeEventsOutput,
    PersonsOutput,
} from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PersonMessage } from '~/common/persons/person-message'
import { PluginEvent, Properties } from '~/plugin-scaffold'
import { Team } from '~/types'

import type { MergeFoldPlan } from './person-merge-fold'
import { MergeMode } from './person-merge-types'
import { PersonsStoreForBatch } from './persons-store-for-batch'

export type PersonOutputs = IngestionOutputs<
    PersonsOutput | PersonDistinctIdsOutput | IngestionWarningsOutput | PersonMergeEventsOutput
>

/**
 * Lightweight data holder containing all the context needed for person processing.
 * This replaces the previous PersonState class which mixed data and business logic.
 */
export class PersonContext {
    public readonly eventProperties: Properties
    public updateIsIdentified: boolean = false

    constructor(
        public readonly event: PluginEvent,
        public readonly team: Team,
        public readonly distinctId: string,
        public readonly timestamp: DateTime,
        public readonly processPerson: boolean, // $process_person_profile flag from the event
        public readonly outputs: PersonOutputs,
        public readonly personStore: PersonsStoreForBatch,
        public readonly measurePersonJsonbSize: number = 0,
        public readonly mergeMode: MergeMode,
        public readonly updateAllProperties: boolean = false, // When true, all property changes trigger person updates
        public readonly shouldUpdateLastSeenAt: boolean = false,
        /** Fold plan shared by this event's consecutive $identify run; see person-merge-fold.ts. */
        public readonly mergeFoldPlan?: MergeFoldPlan,
        /** The personhog identity service publishes the merge verdict warnings it settles, so this consumer must not. */
        public readonly identityEmitsMergeWarnings: boolean = false,
        /** Per-batch wall-clock budget for re-sending merges the backend refused before they ran; 0 escalates at once. */
        public readonly mergeNotAppliedWaitMs: number = 0
    ) {
        this.eventProperties = event.properties!
    }

    async produceMessages(messages: PersonMessage[]): Promise<void> {
        await Promise.all(
            messages.map((msg) =>
                this.outputs.produce(msg.output, { value: msg.value, key: null, teamId: this.team.id })
            )
        )
    }
}