: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(cdp): share one parse loop across the cdp consumers (#122229)
Phil Haackf1c647727166
diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.tsindex e99fbd91c9a0..c27500666b02 100644--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts@@ -5,7 +5,7 @@ import { GeoIPService } from '~/common/utils/geoip'import { logger } from '~/common/utils/logger'import type { CommonConfig } from '../../common/config'-import { HealthCheckResult, PluginServerService, TeamId } from '../../types'+import { HealthCheckResult, PluginServerService, Team, TeamId } from '../../types'import {CdpCoreServicesConfig,CdpCoreServicesDeps,@@ -34,6 +34,7 @@ import { HogWatcherService } from '../services/monitoring/hog-watcher.service'import { NativeDestinationExecutorService } from '../services/native-destination-executor.service'import { SegmentDestinationExecutorService } from '../services/segment-destination-executor.service'import { CdpUsageReporterService } from '../services/usage/cdp-usage-reporter.service'+import { HogFunctionTypeType } from '../types'export type CdpConsumerBaseConfig = CdpCoreServicesConfig &Pick<CommonConfig, 'KAFKA_CLIENT_RACK'> &@@ -124,6 +125,19 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd}}+ /** The team, or null when it has no hog function of these types and no hog flow. */+ protected async loadTeamWithHogFunctionsOrFlows(+ teamId: TeamId,+ hogTypes: HogFunctionTypeType[]+ ): Promise<Team | null> {+ const [teamHogFunctions, teamHogFlows, team] = await Promise.all([+ this.hogFunctionManager.getHogFunctionsForTeam(teamId, hogTypes),+ this.hogFlowManager.getHogFlowsForTeam(teamId),+ this.deps.teamManager.getTeam(teamId),+ ])+ return teamHogFunctions.length || teamHogFlows.length ? team : null+ }+public async start(): Promise<void> {// Outputs are resolved in the constructor via `createCdpCoreServices` — no// per-consumer producer lifecycle. The outer server owns producer shutdowndiff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.tsindex d638ae6cbe5b..2fe93daf3416 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts@@ -20,7 +20,7 @@ import {HogFunctionTypeType,} from '../types'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'-import { assertTeamId, skipIfMalformed } from './message-parsing'+import { parseBatch } from './message-parsing'// Filter source / trigger type each kind of warehouse row matches against.const TRIGGER_TYPE_BY_TABLE_TYPE = {@@ -148,38 +148,18 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {- const events: HogFunctionInvocationGlobals[] = []-- await Promise.all(- messages.map(async (message) => {- const event = skipIfMalformed('Error parsing message', () =>- assertTeamId(CdpDataWarehouseEventSchema.parse(parseJSON(message.value!.toString())))- )- if (!event) {- return- }-- // Outside skipIfMalformed: a lookup error fails the batch, so the consumer reads the batch again.- const [teamHogFunctions, teamHogFlows, team] = await Promise.all([- this.hogFunctionManager.getHogFunctionsForTeam(event.team_id, this.hogTypes),- this.hogFlowManager.getHogFlowsForTeam(event.team_id),- this.deps.teamManager.getTeam(event.team_id),- ])-- if ((!teamHogFunctions.length && !teamHogFlows.length) || !team) {- return- }-- const globals = skipIfMalformed('Error parsing message', () =>- convertDataWarehouseEventToHogFunctionInvocationGlobals(event, team, this.config.SITE_URL)- )- if (globals) {- events.push(globals)+ return await parseBatch(messages, {+ errorLog: 'Error parsing message',+ parse: (message) => {+ const event = CdpDataWarehouseEventSchema.parse(parseJSON(message.value!.toString()))+ return {+ teamId: event.team_id,+ toGlobals: (team) =>+ convertDataWarehouseEventToHogFunctionInvocationGlobals(event, team, this.config.SITE_URL),}- })- )-- return events+ },+ loadTeam: (teamId) => this.loadTeamWithHogFunctionsOrFlows(teamId, this.hogTypes),+ })}public override async start(): Promise<void> {diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex da5507b1e174..657d0796d2dc 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -15,7 +15,7 @@ import { HogFunctionInvocationPipeline } from '../services/hog-function-invocatiimport { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'-import { assertTeamId, skipIfMalformed } from './message-parsing'+import { parseBatch } from './message-parsing'import { PUSH_NOTIFICATION_OPENED_EVENT, buildPushOpenedMetric } from './push-open-tracking'export class CdpEventsConsumer<@@ -181,68 +181,37 @@ export class CdpEventsConsumer<@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {- const events: HogFunctionInvocationGlobals[] = []-- await Promise.all(- messages.map(async (message) => {- // Parked rather than dropped: a schema we cannot read today is often one a later- // version can.- const park = (error: string): boolean =>- this.deadLetterService.recordMessageFailure(message, { step: 'parse', error })-- const clickHouseEvent = skipIfMalformed(- 'Error parsing message',- () => assertTeamId(parseJSON(message.value!.toString()) as RawClickHouseEvent),- park- )- if (!clickHouseEvent) {- return- }-- // A retriable error fails the batch, so the consumer reads the batch again. Any other- // lookup error parks the message for a replay, because failing the batch on an error- // that repeats stops the partition. The loaders send the team ids of the whole batch- // in one query, so one failed query parks every message in it. With the dead-letter- // topic off, nothing keeps the message, so the error fails the batch too.- const lookups = await Promise.all([- this.hogFunctionManager.getHogFunctionsForTeam(clickHouseEvent.team_id, this.hogTypes),- this.hogFlowManager.getHogFlowsForTeam(clickHouseEvent.team_id),- this.deps.teamManager.getTeam(clickHouseEvent.team_id),- ]).catch((e) => {- if (e?.isRetriable === true) {- throw e- }- if (!park(e instanceof Error ? e.message : String(e))) {- throw e- }- logger.error('Error looking up team data', e)- return null- })- if (!lookups) {- return+ const park = (message: Message, error: string): boolean =>+ this.deadLetterService.recordMessageFailure(message, { step: 'parse', error })+ return await parseBatch(messages, {+ errorLog: 'Error parsing message',+ parse: (message) => {+ const clickHouseEvent = parseJSON(message.value!.toString()) as RawClickHouseEvent+ return {+ teamId: clickHouseEvent.team_id,+ toGlobals: (team) => {+ const globals = convertToHogFunctionInvocationGlobals(+ clickHouseEvent,+ team,+ this.config.SITE_URL+ )+ // The one place holding both. A failure found later in the pipeline carries+ // these globals, and this is how it gets back to the bytes to park.+ this.messageByGlobals.set(globals, message)+ return globals+ },}- const [teamHogFunctions, teamHogFlows, team] = lookups-- if ((!teamHogFunctions.length && !teamHogFlows.length) || !team) {- return- }-- const globals = skipIfMalformed(- 'Error parsing message',- () => convertToHogFunctionInvocationGlobals(clickHouseEvent, team, this.config.SITE_URL),- park- )- if (!globals) {- return- }- // The one place holding both. A failure found later in the pipeline carries- // these globals, and this is how it gets back to the bytes to park.- this.messageByGlobals.set(globals, message)- events.push(globals)- })- )-- return events+ },+ loadTeam: (teamId) => this.loadTeamWithHogFunctionsOrFlows(teamId, this.hogTypes),+ // Parked rather than dropped: a schema we cannot read today is often one a later+ // version can.+ onError: park,+ // A lookup error that repeats stops the partition when it fails the batch, so this parks the+ // message for a replay. The loaders send the team ids of the whole batch in one query, so one+ // failed query parks every message in it. With the dead-letter topic off, nothing keeps the+ // message, so the error fails the batch.+ parkLookupError: park,+ })}protected async startQueueProducers(): Promise<void> {diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.tsindex 41a105cfded7..99c5aee4baf4 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts@@ -10,7 +10,11 @@ import * as posthogUtils from '~/common/utils/posthog'import { HogFunctionInvocationGlobals } from '../types'import * as hogExec from '../utils/hog-exec'-import { CdpHogflowSubscriptionMatcherConsumer } from './cdp-hogflow-subscription-matcher.consumer'+import {+ CdpHogflowSubscriptionMatcherConsumer,+ counterHogflowMatcherEventSkipped,+} from './cdp-hogflow-subscription-matcher.consumer'+import { counterParseError } from './metrics'jest.mock('./cdp-base.consumer', () => {return {@@ -1282,6 +1286,12 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {})describe('message and lookup failures', () => {+ const invalidTeamIdParseErrors = async (): Promise<number> =>+ (await counterParseError.get()).values.find((v) => v.labels.error === 'invalid_team_id')?.value ?? 0+ const invalidTeamIdSkips = async (): Promise<number> =>+ (await counterHogflowMatcherEventSkipped.get()).values.find((v) => v.labels.reason === 'invalid_team_id')+ ?.value ?? 0+beforeEach(() => {matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1', team_id: 1 }) })// Postgres rejects a team id outside int4 on every read. The valid messages here all use team 1.@@ -1300,12 +1310,14 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {parse: '_parseKafkaBatch',bad: rawEvent({ team_id: teamId }),good: rawEvent({}),+ expectedInvalidTeamIdSkips: 1,},{name: `a person with team_id ${teamId}`,parse: '_parsePersonBatch',bad: rawPerson({ team_id: teamId }),good: rawPerson({}),+ expectedInvalidTeamIdSkips: 1,},]),// The schema already rejects a missing, null or string team_id.@@ -1316,35 +1328,45 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {parse: '_parseInternalEventsBatch',bad: rawInternalEvent({ team_id: teamId }),good: rawInternalEvent(),+ expectedInvalidTeamIdSkips: 1,})),{name: 'an event that is not JSON',parse: '_parseKafkaBatch',bad: { value: Buffer.from('not json') },good: rawEvent({}),+ expectedInvalidTeamIdSkips: 0,},{name: 'an event whose properties are not JSON',parse: '_parseKafkaBatch',bad: rawEvent({ properties: 'not json' }),good: rawEvent({}),+ expectedInvalidTeamIdSkips: 0,},{name: 'a person whose properties are not JSON',parse: '_parsePersonBatch',bad: rawPerson({ properties: 'not json' }),good: rawPerson({}),+ expectedInvalidTeamIdSkips: 0,},{name: 'an internal event without its required event',parse: '_parseInternalEventsBatch',bad: { value: Buffer.from(JSON.stringify({ team_id: 1 })) },good: rawInternalEvent(),+ expectedInvalidTeamIdSkips: 0,},- ])('skips $name and keeps the rest of the batch', async ({ parse, bad, good }) => {+ ])('skips $name and keeps the rest of the batch', async ({ parse, bad, good, expectedInvalidTeamIdSkips }) => {+ const parseErrorsBefore = await invalidTeamIdParseErrors()+ const skipsBefore = await invalidTeamIdSkips()+const result = await (matcher as any)[parse]([bad, good])expect(result).toHaveLength(1)+ expect(await invalidTeamIdParseErrors()).toBe(parseErrorsBefore)+ expect(await invalidTeamIdSkips()).toBe(skipsBefore + expectedInvalidTeamIdSkips)})const streams = [diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.tsindex 64ccb664ebe7..7316a8d90f95 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts@@ -46,7 +46,7 @@ import {} from '../utils'import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'-import { skipIfMalformed } from './message-parsing'+import { ParseBatchOptions, parseBatch, skipIfMalformed } from './message-parsing'// A waker only needs signals that arrive after a job parks, never history. auto.offset.reset=latest// makes a fresh consumer group start at the tip instead of replaying the (unconsumable at prod@@ -138,7 +138,7 @@ const histogramHogflowMatcherFindParkedJobs = new Histogram({// internal-event query load is distinguishable from the events firehose on the shared cyclotron DB.type WakeSource = 'events' | 'person' | 'internal_events'-const counterHogflowMatcherEventSkipped = new Counter({+export const counterHogflowMatcherEventSkipped = new Counter({name: 'cdp_hogflow_matcher_event_skipped',help: 'An incoming event was dropped before matching: no identifiers (distinct_id or person_id), an invalid team id, or unknown team.',labelNames: ['reason'],@@ -187,13 +187,6 @@ type MatchedJob = {type FilterGlobals = ReturnType<typeof convertToHogFunctionFilterGlobal>-// What a stream parser reads from one message: the team to look up, and how to build the globals-// once the team has loaded.-type ParsedMessage = {- teamId: unknown- toGlobals: (team: Team) => HogFunctionInvocationGlobals-}-// Emitted by Django when a run a workflow step dispatched ends; `origin_key` names the parked job.export const WORKFLOW_STEP_RESUME_EVENT = '$workflow_step_resume'@@ -776,7 +769,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<@instrumented('cdpHogflowSubscriptionMatcher.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {- return await this.parseBatch(messages, 'Error parsing message', (message) => {+ return await this.parseMatcherBatch(messages, 'Error parsing message', (message) => {const clickHouseEvent = parseJSON(message.value!.toString()) as RawClickHouseEvent// A job can be parked by distinct_id or person_id, so an event needs at least// one of them to match anything. Drop only events that carry neither.@@ -793,7 +786,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<@instrumented('cdpHogflowSubscriptionMatcher.parsePersonMessages')public async _parsePersonBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {- return await this.parseBatch(messages, 'Error parsing person message', (message) => {+ return await this.parseMatcherBatch(messages, 'Error parsing person message', (message) => {const data = parseJSON(message.value!.toString()) as ClickHousePerson// A deleted person can never satisfy a wait, so skip tombstones.if (data.is_deleted) {@@ -812,47 +805,32 @@ export class CdpHogflowSubscriptionMatcherConsumer<})}- /**- * Parsing and building the globals do no I/O. They read only the message and the loaded team, so an- * error there means the message is malformed. It fails the same way every time it is read, so this- * skips it. This also skips a team id that the lookups cannot query, for the same reason.- *- * The team gate and the team lookup read Postgres. Their errors fail the batch, so the consumer- * does not store the batch's offsets and reads the batch again after the pod restarts. Skipping- * the message instead would lose the event, and the wait or conversion goal it should satisfy- * would time out.- */- private async parseBatch(+ private async parseMatcherBatch(messages: Message[],errorLog: string,- parse: (message: Message) => ParsedMessage | null+ parse: ParseBatchOptions['parse']): Promise<HogFunctionInvocationGlobals[]> {- const events = await Promise.all(- messages.map(async (message) => {- const parsed = skipIfMalformed(errorLog, () => parse(message))- if (!parsed) {- return null- }- if (!isValidTeamId(parsed.teamId)) {- counterHogflowMatcherEventSkipped.labels({ reason: 'invalid_team_id' }).inc()- return null- }+ return await parseBatch(messages, {+ errorLog,+ parse,+ onInvalidTeamId: () => counterHogflowMatcherEventSkipped.labels({ reason: 'invalid_team_id' }).inc(),+ // Do not catch a lookup error here. A skipped event leaves the wait or conversion goal that it+ // should satisfy to time out.+ loadTeam: async (teamId) => {// The vast majority of messages belong to teams with no wait_until_condition step and// no conversion goal. Bail on those via the in-memory hogflow cache before paying for// getTeam + full globals conversion.- if (!(await this.teamIsActionable(parsed.teamId))) {+ if (!(await this.teamIsActionable(teamId))) {counterHogflowMatcherEventSkipped.labels({ reason: 'no_actionable_flow' }).inc()return null}- const team = await this.deps.teamManager.getTeam(parsed.teamId)+ const team = await this.deps.teamManager.getTeam(teamId)if (!team) {counterHogflowMatcherEventSkipped.labels({ reason: 'no_team' }).inc()- return null}- return skipIfMalformed(errorLog, () => parsed.toGlobals(team))- })- )- return events.filter((globals): globals is HogFunctionInvocationGlobals => globals !== null)+ return team+ },+ })}// Step resumes name their job, so they skip the person and team gates the event parser applies.@@ -889,7 +867,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<@instrumented('cdpHogflowSubscriptionMatcher.parseInternalEventMessages')public async _parseInternalEventsBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {- return await this.parseBatch(messages, 'Error parsing internal event message', (message) => {+ return await this.parseMatcherBatch(messages, 'Error parsing internal event message', (message) => {const parsed = CdpInternalEventSchema.parse(parseJSON(message.value!.toString()))if (!parsed.event.distinct_id && !parsed.person?.id) {counterHogflowMatcherEventSkipped.labels({ reason: 'no_identifiers' }).inc()diff --git a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.tsindex 80fa95d11a70..22c703c741a3 100644--- a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts@@ -21,7 +21,7 @@ import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { convertInternalEventToHogFunctionInvocationGlobals } from '../utils'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'-import { assertTeamId, skipIfMalformed } from './message-parsing'+import { parseBatch } from './message-parsing'/*** Whether a GitHub delivery is a write PostHog's own GitHub App made, resolved from the `own_app`@@ -180,37 +180,18 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {- const events: HogFunctionInvocationGlobals[] = []- await Promise.all(- messages.map(async (message) => {- const event = skipIfMalformed('Error parsing message', () =>- assertTeamId(CdpInternalEventSchema.parse(parseJSON(message.value!.toString())))- )- if (!event) {- return+ return await parseBatch(messages, {+ errorLog: 'Error parsing message',+ parse: (message) => {+ const event = CdpInternalEventSchema.parse(parseJSON(message.value!.toString()))+ return {+ teamId: event.team_id,+ toGlobals: (team) =>+ convertInternalEventToHogFunctionInvocationGlobals(event, team, this.config.SITE_URL),}-- // Outside skipIfMalformed: a lookup error fails the batch, so the consumer reads the batch again.- const [teamHogFunctions, teamHogFlows, team] = await Promise.all([- this.hogFunctionManager.getHogFunctionsForTeam(event.team_id, this.hogTypes),- this.hogFlowManager.getHogFlowsForTeam(event.team_id),- this.deps.teamManager.getTeam(event.team_id),- ])-- if ((!teamHogFunctions.length && !teamHogFlows.length) || !team) {- return- }-- const globals = skipIfMalformed('Error parsing message', () =>- convertInternalEventToHogFunctionInvocationGlobals(event, team, this.config.SITE_URL)- )- if (globals) {- events.push(globals)- }- })- )-- return events+ },+ loadTeam: (teamId) => this.loadTeamWithHogFunctionsOrFlows(teamId, this.hogTypes),+ })}public override async start(): Promise<void> {diff --git a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.tsindex 095749449cc8..fd1c3bae57df 100644--- a/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-legacy-event.consumer.ts@@ -17,6 +17,7 @@ import {PostIngestionEvent,ProjectId,RawClickHouseEvent,+ Team,} from '../../types'import { LegacyWebhookService } from '../legacy-webhooks/legacy-webhook-service'import { LegacyPluginExecutorService } from '../services/legacy-plugin-executor.service'@@ -29,7 +30,7 @@ import type {import { convertToHogFunctionInvocationGlobals } from '../utils'import { createInvocation } from '../utils/invocation-utils'import { CdpConsumerBase, CdpConsumerBaseConfig, CdpConsumerBaseDeps } from './cdp-base.consumer'-import { assertTeamId, skipIfMalformed } from './message-parsing'+import { parseBatch } from './message-parsing'export type LightweightPluginConfig = {id: number@@ -51,6 +52,8 @@ type PluginConfigHogFunction = {hogFunction: HogFunctionType}+type TeamWithPluginConfigs = { team: Team; pluginConfigs: PluginConfigHogFunction[] }+const legacyPluginExecutionResultCounter = new Counter({name: 'cdp_legacy_event_consumer_execution_result_total',help: 'The number of times we have executed a legacy plugin',@@ -381,41 +384,32 @@ export class CdpLegacyEventsConsumer extends CdpConsumerBase<CdpLegacyEventsCons// This consumer always parses from kafka@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {- const events: HogFunctionInvocationGlobals[] = []-- await Promise.all(- messages.map(async (message) => {- const clickHouseEvent = skipIfMalformed('Error parsing message', () =>- assertTeamId(parseJSON(message.value!.toString()) as RawClickHouseEvent)- )- if (!clickHouseEvent) {- return+ return await parseBatch<TeamWithPluginConfigs>(messages, {+ errorLog: 'Error parsing message',+ parse: (message) => {+ const clickHouseEvent = parseJSON(message.value!.toString()) as RawClickHouseEvent+ return {+ teamId: clickHouseEvent.team_id,+ toGlobals: ({ team, pluginConfigs }) => {+ const globals = convertToHogFunctionInvocationGlobals(+ clickHouseEvent,+ team,+ this.config.SITE_URL+ )+ this.pluginConfigsByGlobals.set(globals, pluginConfigs)+ return globals+ },}-- // Outside skipIfMalformed: a lookup error fails the batch, so the consumer reads the batch again.- const team = await this.deps.teamManager.getTeam(clickHouseEvent.team_id)-+ },+ loadTeam: async (teamId) => {+ const team = await this.deps.teamManager.getTeam(teamId)if (!team) {- return+ return null}-- const pluginConfigHogFunctions = await this.pluginConfigsLoader.get(team.id.toString())-- if (!pluginConfigHogFunctions?.length) {- return- }-- const globals = skipIfMalformed('Error parsing message', () =>- convertToHogFunctionInvocationGlobals(clickHouseEvent, team, this.config.SITE_URL)- )- if (globals) {- this.pluginConfigsByGlobals.set(globals, pluginConfigHogFunctions)- events.push(globals)- }- })- )-- return events+ const pluginConfigs = await this.pluginConfigsLoader.get(team.id.toString())+ return pluginConfigs?.length ? { team, pluginConfigs } : null+ },+ })}private async getLegacyPluginHogFunctionInvocations(diff --git a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.test.tsindex 9a6534795fab..ad46cce8614b 100644--- a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.test.ts@@ -74,6 +74,14 @@ describe('CDP Person Updates Consumer', () => {expect(events).toHaveLength(0)})+ it('should ignore a message for a team with no person-updates destination', async () => {+ jest.spyOn(processor['hogFunctionManager'], 'getHogFunctionsForTeam').mockResolvedValue([+ { ...hogFunction, filters: { ...hogFunction.filters, source: 'events' } },+ ])+ const events = await processor._parseKafkaBatch([createKafkaMessage(createClickhousePerson(team.id, {}))])+ expect(events).toHaveLength(0)+ })+const lookupError = new Error('canceling statement due to conflict with recovery')it.each([diff --git a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.tsindex 639b0ec00bd1..eb17c87b75b3 100644--- a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts@@ -14,7 +14,7 @@ import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, CyclotronPerson, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { getPersonDisplayName } from '../utils'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'-import { assertTeamId, skipIfMalformed } from './message-parsing'+import { parseBatch } from './message-parsing'export class CdpPersonUpdatesConsumer extends CdpConsumerBase {protected name = 'CdpPersonUpdatesConsumer'@@ -79,38 +79,23 @@ export class CdpPersonUpdatesConsumer extends CdpConsumerBase {@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {- const globals: HogFunctionInvocationGlobals[] = []- await Promise.all(- messages.map(async (message) => {- const data = skipIfMalformed('Error parsing message', () =>- assertTeamId(parseJSON(message.value!.toString()) as ClickHousePerson)- )- if (!data) {- return+ return await parseBatch(messages, {+ errorLog: 'Error parsing message',+ parse: (message) => {+ const data = parseJSON(message.value!.toString()) as ClickHousePerson+ return {+ teamId: data.team_id,+ toGlobals: (team) => convertClickhousePersonToInvocationGlobals(data, team, this.config.SITE_URL),}-- // Outside skipIfMalformed: a lookup error fails the batch, so the consumer reads the batch again.+ },+ loadTeam: async (teamId) => {const [teamHogFunctions, team] = await Promise.all([- this.hogFunctionManager.getHogFunctionsForTeam(data.team_id, this.hogTypes),- this.deps.teamManager.getTeam(data.team_id),+ this.hogFunctionManager.getHogFunctionsForTeam(teamId, this.hogTypes),+ this.deps.teamManager.getTeam(teamId),])-- const filteredHogFunctions = teamHogFunctions.filter((fn) => fn.filters?.source === 'person-updates')-- if (!filteredHogFunctions.length || !team) {- return- }-- const invocationGlobals = skipIfMalformed('Error parsing message', () =>- convertClickhousePersonToInvocationGlobals(data, team, this.config.SITE_URL)- )- if (invocationGlobals) {- globals.push(invocationGlobals)- }- })- )-- return globals+ return teamHogFunctions.some((fn) => fn.filters?.source === 'person-updates') ? team : null+ },+ })}public override async start(): Promise<void> {diff --git a/nodejs/src/cdp/consumers/message-parsing.ts b/nodejs/src/cdp/consumers/message-parsing.tsindex 7e13130d4e7e..85fffeed9523 100644--- a/nodejs/src/cdp/consumers/message-parsing.ts+++ b/nodejs/src/cdp/consumers/message-parsing.ts@@ -1,6 +1,10 @@+import { Message } from 'node-rdkafka'+import { logger } from '~/common/utils/logger'import { isValidTeamId } from '~/common/utils/team-manager'+import { Team } from '../../types'+import { HogFunctionInvocationGlobals } from '../types'import { counterParseError } from './metrics'// The loaders batch team ids from many messages into one query. One invalid id fails that query for@@ -12,6 +16,10 @@ export function assertTeamId<T extends { team_id: unknown }>(message: T): T {return message}+function errorMessage(e: unknown): string {+ return e instanceof Error ? e.message : String(e)+}+/*** If the step throws, this logs the error and counts it as a parse error. It then returns null, and* the caller skips the message. Wrap only a step that reads the message. A dependency lookup must not@@ -21,10 +29,91 @@ export function skipIfMalformed<T>(errorLog: string, step: () => T, onError?: (etry {return step()} catch (e) {- const error = e instanceof Error ? e.message : String(e)+ const error = errorMessage(e)logger.error(errorLog, e)counterParseError.labels({ error }).inc()onError?.(error)return null}}++// What a parse step reads from one message: the team to look up, and how to build the globals once+// the team has loaded.+type ParsedMessage<TLoaded> = {+ teamId: unknown+ toGlobals: (loaded: TLoaded) => HogFunctionInvocationGlobals+}++export type ParseBatchOptions<TLoaded = Team> = {+ errorLog: string+ /** Reads only the message. Returns null to skip it. */+ parse: (message: Message) => ParsedMessage<TLoaded> | null+ /** Returns the team, or the team with what the consumer loads alongside it. Returns null to skip the message. */+ loadTeam: (teamId: number) => Promise<TLoaded | null>+ /** Skips a message whose team id is invalid. Without it, an invalid team id counts as a parse error. */+ onInvalidTeamId?: () => void+ /** Runs on each parse error. */+ onError?: (message: Message, error: string) => void+ /**+ * Keeps a message whose lookup failed with an error that is not retriable. Returns true when it kept+ * the message, so the batch skips it. Without it, or when it returns false, the error fails the batch.+ */+ parkLookupError?: (message: Message, error: string) => boolean+}++/**+ * Builds the globals for each message in a batch, in message order.+ *+ * `parse` and `toGlobals` do no I/O. They read only the message and the loaded team, so an error there+ * means the message is malformed. It fails the same way every time it is read, so this skips it. This+ * also skips a team id that `loadTeam` cannot query, for the reason `assertTeamId` gives.+ *+ * `loadTeam` reads Postgres. A retriable error from it fails the batch, so the consumer does not store+ * the batch's offsets and reads the batch again after the pod restarts. Skipping the message instead+ * would lose the event. Any other lookup error fails the batch too, unless `parkLookupError` keeps the+ * message.+ */+export async function parseBatch<TLoaded = Team>(+ messages: Message[],+ { errorLog, parse, loadTeam, onInvalidTeamId, onError, parkLookupError }: ParseBatchOptions<TLoaded>+): Promise<HogFunctionInvocationGlobals[]> {+ const results = await Promise.all(+ messages.map(async (message) => {+ const reportError = onError && ((error: string) => onError(message, error))+ const parsed = skipIfMalformed(+ errorLog,+ () => {+ const parsed = parse(message)+ if (!parsed) {+ return null+ }+ const { teamId, toGlobals } = parsed+ if (isValidTeamId(teamId)) {+ return { teamId, toGlobals }+ }+ if (!onInvalidTeamId) {+ throw new Error('invalid_team_id')+ }+ onInvalidTeamId()+ return null+ },+ reportError+ )+ if (!parsed) {+ return null+ }+ const loaded = await loadTeam(parsed.teamId).catch((e) => {+ if (e?.isRetriable === true || !parkLookupError?.(message, errorMessage(e))) {+ throw e+ }+ logger.error('Error looking up team data', e)+ return null+ })+ if (!loaded) {+ return null+ }+ return skipIfMalformed(errorLog, () => parsed.toGlobals(loaded), reportError)+ })+ )+ return results.filter((globals): globals is HogFunctionInvocationGlobals => globals !== null)+}