: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
refactor(cdp): break events consumer inheritance with pipeline services (#59343)
Meikel Ratz7640c9c95a82
diff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.tsindex 5d31a94531f1..9103c4aa39f7 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts@@ -1,34 +1,85 @@import { DateTime } from 'luxon'import { Message } from 'node-rdkafka'-import { instrumented } from '~/common/tracing/tracing-utils'+import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'-import { PluginsServerConfig, Team } from '../../types'+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'+import { HealthCheckResult, PluginsServerConfig, Team } from '../../types'import { parseJSON } from '../../utils/json-parse'import { logger } from '../../utils/logger'+import { captureException } from '../../utils/posthog'import { CdpDataWarehouseEvent, CdpDataWarehouseEventSchema } from '../schema'-import { HogFunctionInvocationGlobals, HogFunctionType, HogFunctionTypeType } from '../types'-import { CdpConsumerBaseDeps } from './cdp-base.consumer'-import { CdpEventsConsumer } from './cdp-events.consumer'+import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'+import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'+import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'/* NOTE: This is not released yet - outstanding work to be done:* Make it clear that Workflows are not supported / add support (the filter hog function logic is the key part)*/-export class CdpDatawarehouseEventsConsumer extends CdpEventsConsumer {- protected override name = 'CdpDatawarehouseEventsConsumer'- protected override hogTypes: HogFunctionTypeType[] = ['destination']+export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {+ protected name = 'CdpDatawarehouseEventsConsumer'+ protected hogTypes: HogFunctionTypeType[] = ['destination']++ protected cyclotronJobQueue: CyclotronJobQueue+ protected kafkaConsumer: KafkaConsumerInterface+ private hogFunctionPipeline: HogFunctionInvocationPipelineconstructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {- super(config, deps, 'cdp_data_warehouse_source_table', 'cdp-data-warehouse-events-consumer')+ super(config, deps)+ this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.kafkaConsumer = createKafkaConsumer({+ groupId: 'cdp-data-warehouse-events-consumer',+ topic: 'cdp_data_warehouse_source_table',+ })+ this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {+ hogFunctionManager: this.hogFunctionManager,+ hogExecutor: this.hogExecutor,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ })}- protected override filterHogFunction(hogFunction: HogFunctionType): boolean {- return (hogFunction.filters?.source ?? 'events') === 'data-warehouse-table'+ public async processBatch(+ invocationGlobals: HogFunctionInvocationGlobals[]+ ): Promise<{ backgroundTask: Promise<any>; invocations: CyclotronJobInvocation[] }> {+ if (!invocationGlobals.length) {+ return { backgroundTask: Promise.resolve(), invocations: [] }+ }++ await this.groupsManager.addGroupsToGlobalsList(invocationGlobals)++ const invocationsToBeQueued = await this.hogFunctionPipeline.buildInvocations(invocationGlobals, {+ hogTypes: this.hogTypes,+ filterFn: (fn) => (fn.filters?.source ?? 'events') === 'data-warehouse-table',+ })++ return {+ backgroundTask: Promise.all([+ instrumentFn({ key: 'cdp.background_task.queue_invocations', sendException: false }, () =>+ this.cyclotronJobQueue.queueInvocations(invocationsToBeQueued)+ ),+ instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {+ try {+ await this.hogFunctionMonitoringService.flush()+ } catch (err) {+ captureException(err)+ logger.error('🔴', 'Error producing queued messages for monitoring', { err })+ }+ }),+ ]),+ invocations: invocationsToBeQueued,+ }}@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')- public override async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {+ public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {const events: HogFunctionInvocationGlobals[] = []await Promise.all(@@ -37,13 +88,12 @@ export class CdpDatawarehouseEventsConsumer extends CdpEventsConsumer {const kafkaEvent = parseJSON(message.value!.toString()) as unknownconst event = CdpDataWarehouseEventSchema.parse(kafkaEvent)- const [teamHogFunctions, teamHogFlows, team] = await Promise.all([+ const [teamHogFunctions, 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) {+ if (!teamHogFunctions.length || !team) {return}@@ -59,6 +109,30 @@ export class CdpDatawarehouseEventsConsumer extends CdpEventsConsumer {return events}++ public override async start(): Promise<void> {+ await super.start()+ await this.cyclotronJobQueue.startAsProducer()+ await this.kafkaConsumer.connect(async (messages) => {+ logger.info('🔁', `${this.name} - handling batch`, { size: messages.length })+ return await instrumentFn('cdpConsumer.handleEachBatch', async () => {+ const invocationGlobals = await this._parseKafkaBatch(messages)+ const { backgroundTask } = await this.processBatch(invocationGlobals)+ return { backgroundTask }+ })+ })+ }++ public override async stop(): Promise<void> {+ logger.info('💤', 'Stopping consumer...')+ await this.kafkaConsumer.disconnect()+ await this.cyclotronJobQueue.stop()+ await super.stop()+ }++ public isHealthy(): HealthCheckResult {+ return this.kafkaConsumer.isHealthy()+ }}function convertDataWarehouseEventToHogFunctionInvocationGlobals(diff --git a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-events-consumer.test.tsindex 2acae9a12e89..66549992953b 100644--- a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts@@ -73,19 +73,19 @@ describe.each([processor = new Consumer(hub, createCdpConsumerDeps(hub))// NOTE: We don't want to actually connect to Kafka for these tests as it is slow and we are testing the core logic only- processor['kafkaConsumer'] = {+ // `as any` required because `processor` is a union type — TS doesn't expose protected members on unions+ ;(processor as any)['kafkaConsumer'] = {connect: jest.fn(),disconnect: jest.fn(),isHealthy: jest.fn(),} as any-- processor['cyclotronJobQueue'] = {+ ;(processor as any)['cyclotronJobQueue'] = {queueInvocations: jest.fn(),startAsProducer: jest.fn(() => Promise.resolve()),stop: jest.fn(),} as unknown as jest.Mocked<CyclotronJobQueue>- mockQueueInvocations = jest.mocked(processor['cyclotronJobQueue']['queueInvocations'])+ mockQueueInvocations = jest.mocked((processor as any)['cyclotronJobQueue']['queueInvocations'])await processor.start()})@@ -595,7 +595,6 @@ describe('hog flow processing', () => {disconnect: jest.fn(),isHealthy: jest.fn(),} as any-processor['cyclotronJobQueue'] = {queueInvocations: jest.fn(),startAsProducer: jest.fn(() => Promise.resolve()),@@ -639,7 +638,7 @@ describe('hog flow processing', () => {hogFlow.trigger = {} as anyawait insertHogFlow(hogFlow)- const invocations = await processor['createHogFlowInvocations']([globals])+ const invocations = await (processor as any)['hogFlowPipeline']['buildInvocations']([globals])expect(invocations).toHaveLength(0)})@@ -656,7 +655,7 @@ describe('hog flow processing', () => {.build()await insertHogFlow(hogFlow)- const invocations = await processor['createHogFlowInvocations']([globals])+ const invocations = await (processor as any)['hogFlowPipeline']['buildInvocations']([globals])expect(invocations).toHaveLength(0)})@@ -673,7 +672,7 @@ describe('hog flow processing', () => {.build())- const noInvocations = await processor['createHogFlowInvocations']([+ const noInvocations = await (processor as any)['hogFlowPipeline']['buildInvocations']([{...globals,event: {@@ -685,7 +684,7 @@ describe('hog flow processing', () => {expect(noInvocations).toHaveLength(0)- const invocations = await processor['createHogFlowInvocations']([globals])+ const invocations = await (processor as any)['hogFlowPipeline']['buildInvocations']([globals])expect(invocations).toHaveLength(1)expect(invocations[0]).toMatchObject({functionId: hogFlow.id,@@ -716,7 +715,7 @@ describe('hog flow processing', () => {.build())- await processor['createHogFlowInvocations']([globals])+ await (processor as any)['hogFlowPipeline']['buildInvocations']([globals])const producedMetrics =mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_app_metrics2_test')@@ -793,7 +792,7 @@ describe('hog flow processing', () => {.build())- const invocations = await processor['createHogFlowInvocations']([globals])+ const invocations = await (processor as any)['hogFlowPipeline']['buildInvocations']([globals])// Should have no invocations returned due to quota limitingexpect(invocations).toHaveLength(0)@@ -870,7 +869,7 @@ describe('hog flow processing', () => {.build())- const invocations = await processor['createHogFlowInvocations']([globals])+ const invocations = await (processor as any)['hogFlowPipeline']['buildInvocations']([globals])expect(invocations).toHaveLength(0)expect((processor as any)['deps'].quotaLimiting.isTeamQuotaLimited).toHaveBeenCalledWith(@@ -917,7 +916,7 @@ describe('hog flow processing', () => {.build())- const invocations = await processor['createHogFlowInvocations']([globals])+ const invocations = await (processor as any)['hogFlowPipeline']['buildInvocations']([globals])// Should process the workflow since it doesn't have email or destination actionsexpect(invocations).toHaveLength(1)@@ -967,7 +966,7 @@ describe('hog flow processing', () => {.build())- const invocations = await processor['createHogFlowInvocations']([globals])+ const invocations = await (processor as any)['hogFlowPipeline']['buildInvocations']([globals])expect(invocations).toHaveLength(1)expect(invocations[0]).toMatchObject({diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex 61c02d98eac6..d8e4ea341bf5 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -1,32 +1,20 @@-import { DateTime } from 'luxon'import { Message } from 'node-rdkafka'import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'import { convertToHogFunctionInvocationGlobals } from '../../cdp/utils'-import { KeyedRateLimitRequest, KeyedRateLimiterService } from '../../common/services/keyed-rate-limiter.service'import { KAFKA_EVENTS_JSON } from '../../config/kafka-topics'import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'import { HealthCheckResult, PluginsServerConfig, RawClickHouseEvent } from '../../types'import { parseJSON } from '../../utils/json-parse'import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'-import { shouldBlockHogFlowDueToQuota } from '../services/hogflows/hogflow-quota-limiting'+import { HogFlowInvocationPipeline } from '../services/hog-flow-invocation-pipeline.service'+import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'import { CyclotronJobQueue } from '../services/job-queue/job-queue'-import { HogWatcherState } from '../services/monitoring/hog-watcher.service'-import {- CyclotronJobInvocation,- CyclotronJobInvocationHogFunction,- HogFunctionInvocationGlobals,- HogFunctionType,- HogFunctionTypeType,- LogEntry,- MinimalAppMetric,-} from '../types'-import { mirrorCall } from '../utils/mirror-call'+import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'-import { counterHogFunctionStateOnEvent, counterParseError, counterRateLimited } from './metrics'-import { shouldBlockInvocationDueToQuota } from './quota-limiting-helper'+import { counterParseError } from './metrics'export class CdpEventsConsumer<TConfig extends PluginsServerConfig = PluginsServerConfig,@@ -36,8 +24,8 @@ export class CdpEventsConsumer<private cyclotronJobQueue: CyclotronJobQueueprotected kafkaConsumer: KafkaConsumerInterface- private hogRateLimiter: KeyedRateLimiterService- private hogRateLimiterMirror: KeyedRateLimiterService | null+ private hogFunctionPipeline: HogFunctionInvocationPipeline+ private hogFlowPipeline: HogFlowInvocationPipelineconstructor(config: TConfig,@@ -48,16 +36,28 @@ export class CdpEventsConsumer<super(config, deps)this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)this.kafkaConsumer = createKafkaConsumer({ groupId, topic })- const rateLimiterConfig = {- name: 'hog-rate-limiter',- bucketSize: config.CDP_RATE_LIMITER_BUCKET_SIZE,- refillRate: config.CDP_RATE_LIMITER_REFILL_RATE,- ttlSeconds: config.CDP_RATE_LIMITER_TTL,- }- this.hogRateLimiter = new KeyedRateLimiterService(rateLimiterConfig, this.redis)- this.hogRateLimiterMirror = this.valkeyShadow- ? new KeyedRateLimiterService(rateLimiterConfig, this.valkeyShadow.writer)- : null+ this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {+ hogFunctionManager: this.hogFunctionManager,+ hogExecutor: this.hogExecutor,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ })+ this.hogFlowPipeline = new HogFlowInvocationPipeline(config, {+ hogFlowManager: this.hogFlowManager,+ hogFlowExecutor: this.hogFlowExecutor,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ })}public async processBatch(@@ -70,10 +70,15 @@ export class CdpEventsConsumer<// TODO: Add a helper to hog functions to determine if they require groups or not and then only load thoseawait this.groupsManager.addGroupsToGlobalsList(invocationGlobals)- const invocationsToBeQueued = [- ...(await this.createHogFunctionInvocations(invocationGlobals)),- ...(await this.createHogFlowInvocations(invocationGlobals)),- ]+ const [hogInvocations, hogflowInvocations] = await Promise.all([+ this.hogFunctionPipeline.buildInvocations(invocationGlobals, {+ hogTypes: this.hogTypes,+ filterFn: (fn) => (fn.filters?.source ?? 'events') === 'events',+ }),+ this.hogFlowPipeline.buildInvocations(invocationGlobals),+ ])++ const invocationsToBeQueued = [...hogInvocations, ...hogflowInvocations]// Emit a `running` lifecycle row for each freshly-created invocation.// This fires ONCE per invocation_id at creation — not on every dequeue@@ -108,349 +113,6 @@ export class CdpEventsConsumer<}}- protected filterHogFunction(hogFunction: HogFunctionType): boolean {- // By default we filter for those with no filters or filters specifically for events- return (hogFunction.filters?.source ?? 'events') === 'events'- }-- /**- * Finds all matching hog functions for the given globals.- * Filters them for their disabled state as well as masking configs- */- @instrumented('cdpConsumer.handleEachBatch.queueMatchingFunctions')- protected async createHogFunctionInvocations(- invocationGlobals: HogFunctionInvocationGlobals[]- ): Promise<CyclotronJobInvocation[]> {- const teamsToLoad = [...new Set(invocationGlobals.map((x) => x.project.id))]- const hogFunctionsByTeam = await this.hogFunctionManager.getHogFunctionsForTeams(- teamsToLoad,- this.hogTypes,- this.filterHogFunction- )-- const possibleInvocations = (- await Promise.all(- invocationGlobals.map(async (globals) => {- const teamHogFunctions = hogFunctionsByTeam[globals.project.id]-- const { invocations, metrics, logs } = await this.hogExecutor.buildHogFunctionInvocations(- teamHogFunctions,- globals- )-- this.hogFunctionMonitoringService.queueAppMetrics(metrics, 'hog_function')- this.hogFunctionMonitoringService.queueLogs(logs, 'hog_function')-- return invocations- })- )- ).flat()-- const hogFunctionIds = possibleInvocations.map((x) => x.hogFunction.id)- const [states] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {- return await this.hogWatcher.getEffectiveStates(hogFunctionIds)- }),- mirrorCall('hog-watcher.getEffectiveStates', () =>- this.hogWatcherMirror?.getEffectiveStates(hogFunctionIds)- ),- ])-- const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({- id: x.hogFunction.id,- cost: 1,- }))- const [rateLimits] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {- return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)- }),- mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>- this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)- ),- ])-- const validInvocations: CyclotronJobInvocationHogFunction[] = []-- // Iterate over adding them to the list and updating their priority- await Promise.all(- possibleInvocations.map(async (item, index) => {- try {- const rateLimit = rateLimits[index][1]- if (rateLimit.isRateLimited) {- counterRateLimited.labels({ kind: 'hog_function', function_id: item.functionId }).inc()- // NOTE: We don't return here as we are just monitoring this feature currently- // this.hogFunctionMonitoringService.queueAppMetric(- // {- // team_id: item.teamId,- // app_source_id: item.functionId,- // metric_kind: 'failure',- // metric_name: 'rate_limited',- // count: 1,- // },- // 'hog_function'- // )- // return- }- } catch (e) {- captureException(e)- logger.error('🔴', 'Error checking rate limit for hog function', { err: e })- }-- const isQuotaLimited = await shouldBlockInvocationDueToQuota(item, {- quotaLimiting: this.deps.quotaLimiting,- hogFunctionMonitoringService: this.hogFunctionMonitoringService,- })-- if (isQuotaLimited) {- return- }-- const state = states[item.hogFunction.id].state-- counterHogFunctionStateOnEvent- .labels({- state: HogWatcherState[state],- kind: item.hogFunction.type,- })- .inc()-- if (state === HogWatcherState.disabled) {- this.hogFunctionMonitoringService.queueAppMetric(- {- team_id: item.teamId,- app_source_id: item.functionId,- metric_kind: 'failure',- metric_name: 'disabled_permanently',- count: 1,- },- 'hog_function'- )- return- }-- if (state === HogWatcherState.degraded) {- item.queuePriority = 2- if (this.config.CDP_OVERFLOW_QUEUE_ENABLED) {- item.queue = 'hogoverflow'- }- }-- validInvocations.push(item)- })- )-- // Now we can filter by masking configs- const { masked, notMasked: notMaskedInvocations } = await this.hogMasker.filterByMasking(validInvocations)-- this.hogFunctionMonitoringService.queueAppMetrics(- masked.map((item) => ({- team_id: item.teamId,- app_source_id: item.functionId,- metric_kind: 'other',- metric_name: 'masked',- count: 1,- })),- 'hog_function'- )-- const triggeredInvocationsMetrics: MinimalAppMetric[] = []-- // Track unique events that have been billed (billing is per-event, not per-destination)- const billedEventUuids = new Set<string>()-- notMaskedInvocations.forEach((item) => {- triggeredInvocationsMetrics.push({- team_id: item.teamId,- app_source_id: item.functionId,- metric_kind: 'other',- metric_name: 'triggered',- count: 1,- })-- // Bill once per triggering event, not per destination- if (item.hogFunction.type === 'destination') {- const eventUuid = item.state?.globals?.event?.uuid- if (eventUuid && !billedEventUuids.has(eventUuid)) {- billedEventUuids.add(eventUuid)- triggeredInvocationsMetrics.push({- team_id: item.teamId,- app_source_id: '_event_trigger',- instance_id: eventUuid,- metric_kind: 'billing',- metric_name: 'billable_invocation',- count: 1,- })- }- }- })-- this.hogFunctionMonitoringService.queueAppMetrics(triggeredInvocationsMetrics, 'hog_function')-- return notMaskedInvocations- }-- /**- * Finds all matching hog flows for the given globals.- * Filters them for their disabled state as well as masking configs- */- @instrumented('cdpConsumer.handleEachBatch.queueMatchingFlows')- protected async createHogFlowInvocations(- invocationGlobals: HogFunctionInvocationGlobals[]- ): Promise<CyclotronJobInvocation[]> {- const teamsToLoad = [...new Set(invocationGlobals.map((x) => x.project.id))]- const hogFlowsByTeam = await this.hogFlowManager.getHogFlowsForTeams(teamsToLoad)-- const possibleInvocations = (- await Promise.all(- invocationGlobals.map(async (globals) => {- const teamHogFlows = hogFlowsByTeam[globals.project.id]-- const { invocations, metrics, logs } = await this.hogFlowExecutor.buildHogFlowInvocations(- teamHogFlows,- globals- )-- this.hogFunctionMonitoringService.queueAppMetrics(metrics, 'hog_flow')- this.hogFunctionMonitoringService.queueLogs(logs, 'hog_flow')-- return invocations- })- )- ).flat()-- const hogFlowIds = possibleInvocations.map((x) => x.hogFlow.id)- const [states] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {- return await this.hogWatcher.getEffectiveStates(hogFlowIds)- }),- mirrorCall('hog-watcher.getEffectiveStates', () => this.hogWatcherMirror?.getEffectiveStates(hogFlowIds)),- ])-- const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({- id: x.hogFlow.id,- cost: 1,- }))- const [rateLimits] = await Promise.all([- instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {- return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)- }),- mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>- this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)- ),- ])- const validInvocations: CyclotronJobInvocation[] = []-- // Iterate over adding them to the list and updating their priority- await Promise.all(- possibleInvocations.map(async (item, index) => {- try {- const rateLimit = rateLimits[index][1]- if (rateLimit.isRateLimited) {- counterRateLimited.labels({ kind: 'hog_flow', function_id: item.functionId }).inc()- this.hogFunctionMonitoringService.queueAppMetric(- {- team_id: item.teamId,- app_source_id: item.functionId,- metric_kind: 'failure',- metric_name: 'rate_limited',- count: 1,- },- 'hog_flow'- )-- const eventUuid = item.state?.event?.uuid- const personId = item.person?.id-- const logEntry: LogEntry = {- timestamp: DateTime.now(),- level: 'warn',- message: `Workflow invocation dropped due to rate limiting for [Person:${personId ?? 'unknown'}] on [Event:${eventUuid ?? 'unknown'}]`,- team_id: item.teamId,- log_source: 'hog_flow',- log_source_id: item.functionId,- instance_id: item.id,- }- this.hogFunctionMonitoringService.queueLogs([logEntry], 'hog_flow')-- logger.warn('⚠️', 'Hogflow invocation rate limited', {- teamId: item.teamId,- hogFlowId: item.functionId,- hogFlowName: item.hogFlow.name,- eventUuid,- personId,- })-- return- }- } catch (e) {- captureException(e)- logger.error('🔴', 'Error checking rate limit for hog flow', { err: e })- }-- // Check quota limits for workflow actions- const isQuotaLimited = await shouldBlockHogFlowDueToQuota(item, {- quotaLimiting: this.deps.quotaLimiting,- hogFunctionMonitoringService: this.hogFunctionMonitoringService,- })-- if (isQuotaLimited) {- return- }-- const state = states[item.hogFlow.id].state- if (state === HogWatcherState.disabled) {- this.hogFunctionMonitoringService.queueAppMetric(- {- team_id: item.teamId,- app_source_id: item.functionId,- metric_kind: 'failure',- metric_name: 'disabled_permanently',- count: 1,- },- 'hog_flow'- )- return- }-- if (state === HogWatcherState.degraded) {- item.queuePriority = 2- }-- validInvocations.push(item)- })- )-- // Now we can filter by masking configs- const { masked, notMasked: notMaskedInvocations } = await this.hogMasker.filterByMasking(validInvocations)-- this.hogFunctionMonitoringService.queueAppMetrics(- masked.map((item) => ({- team_id: item.teamId,- app_source_id: item.functionId,- metric_kind: 'other',- metric_name: 'masked',- count: 1,- })),- 'hog_flow'- )-- const triggeredInvocationsMetrics: MinimalAppMetric[] = []-- notMaskedInvocations.forEach((item) => {- triggeredInvocationsMetrics.push({- team_id: item.teamId,- app_source_id: item.functionId,- metric_kind: 'other',- metric_name: 'triggered',- count: 1,- })- })-- this.hogFunctionMonitoringService.queueAppMetrics(triggeredInvocationsMetrics, 'hog_flow')-- return notMaskedInvocations- }-@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {const events: HogFunctionInvocationGlobals[] = []diff --git a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.tsindex dfc3668ad4e5..926b5ee32074 100644--- a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts@@ -1,39 +1,92 @@import { Message } from 'node-rdkafka'-import { instrumented } from '~/common/tracing/tracing-utils'+import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'import { KAFKA_CDP_INTERNAL_EVENTS } from '../../config/kafka-topics'-import { PluginsServerConfig } from '../../types'+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'+import { HealthCheckResult, PluginsServerConfig } from '../../types'import { parseJSON } from '../../utils/json-parse'import { logger } from '../../utils/logger'+import { captureException } from '../../utils/posthog'import { CdpInternalEventSchema } from '../schema'-import { HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'+import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'+import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { convertInternalEventToHogFunctionInvocationGlobals } from '../utils'-import { CdpConsumerBaseDeps } from './cdp-base.consumer'-import { CdpEventsConsumer } from './cdp-events.consumer'+import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'-export class CdpInternalEventsConsumer extends CdpEventsConsumer {- protected override name = 'CdpInternalEventsConsumer'- protected override hogTypes: HogFunctionTypeType[] = ['internal_destination']+export class CdpInternalEventsConsumer extends CdpConsumerBase {+ protected name = 'CdpInternalEventsConsumer'+ protected hogTypes: HogFunctionTypeType[] = ['internal_destination']++ protected cyclotronJobQueue: CyclotronJobQueue+ protected kafkaConsumer: KafkaConsumerInterface+ private hogFunctionPipeline: HogFunctionInvocationPipelineconstructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {- super(config, deps, KAFKA_CDP_INTERNAL_EVENTS, 'cdp-internal-events-consumer')+ super(config, deps)+ this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.kafkaConsumer = createKafkaConsumer({+ groupId: 'cdp-internal-events-consumer',+ topic: KAFKA_CDP_INTERNAL_EVENTS,+ })+ this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {+ hogFunctionManager: this.hogFunctionManager,+ hogExecutor: this.hogExecutor,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ })+ }++ public async processBatch(+ invocationGlobals: HogFunctionInvocationGlobals[]+ ): Promise<{ backgroundTask: Promise<any>; invocations: CyclotronJobInvocation[] }> {+ if (!invocationGlobals.length) {+ return { backgroundTask: Promise.resolve(), invocations: [] }+ }++ await this.groupsManager.addGroupsToGlobalsList(invocationGlobals)++ const invocationsToBeQueued = await this.hogFunctionPipeline.buildInvocations(invocationGlobals, {+ hogTypes: this.hogTypes,+ filterFn: () => true,+ })++ return {+ backgroundTask: Promise.all([+ instrumentFn({ key: 'cdp.background_task.queue_invocations', sendException: false }, () =>+ this.cyclotronJobQueue.queueInvocations(invocationsToBeQueued)+ ),+ instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {+ try {+ await this.hogFunctionMonitoringService.flush()+ } catch (err) {+ captureException(err)+ logger.error('🔴', 'Error producing queued messages for monitoring', { err })+ }+ }),+ ]),+ invocations: invocationsToBeQueued,+ }}- // This consumer always parses from kafka@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')- public override async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {+ public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {const events: HogFunctionInvocationGlobals[] = []await Promise.all(messages.map(async (message) => {try {const kafkaEvent = parseJSON(message.value!.toString()) as unknown- // This is the input stream from elsewhere so we want to do some proper validationconst event = CdpInternalEventSchema.parse(kafkaEvent)const [teamHogFunctions, team] = await Promise.all([- this.hogFunctionManager.getHogFunctionsForTeam(event.team_id, ['internal_destination']),+ this.hogFunctionManager.getHogFunctionsForTeam(event.team_id, this.hogTypes),this.deps.teamManager.getTeam(event.team_id),])@@ -51,4 +104,28 @@ export class CdpInternalEventsConsumer extends CdpEventsConsumer {return events}++ public override async start(): Promise<void> {+ await super.start()+ await this.cyclotronJobQueue.startAsProducer()+ await this.kafkaConsumer.connect(async (messages) => {+ logger.info('🔁', `${this.name} - handling batch`, { size: messages.length })+ return await instrumentFn('cdpConsumer.handleEachBatch', async () => {+ const invocationGlobals = await this._parseKafkaBatch(messages)+ const { backgroundTask } = await this.processBatch(invocationGlobals)+ return { backgroundTask }+ })+ })+ }++ public override async stop(): Promise<void> {+ logger.info('💤', 'Stopping consumer...')+ await this.kafkaConsumer.disconnect()+ await this.cyclotronJobQueue.stop()+ await super.stop()+ }++ public isHealthy(): HealthCheckResult {+ return this.kafkaConsumer.isHealthy()+ }}diff --git a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.tsindex 412d0d337806..e181d22c70ce 100644--- a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts@@ -1,34 +1,83 @@import { Message } from 'node-rdkafka'-import { instrumented } from '~/common/tracing/tracing-utils'+import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'import { UUIDT } from '~/utils/utils'import { KAFKA_PERSON } from '../../config/kafka-topics'-import { ClickHousePerson, Team } from '../../types'-import { PluginsServerConfig } from '../../types'+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'+import { ClickHousePerson, HealthCheckResult, PluginsServerConfig, Team } from '../../types'import { parseJSON } from '../../utils/json-parse'import { logger } from '../../utils/logger'-import { CyclotronPerson, HogFunctionInvocationGlobals, HogFunctionType, HogFunctionTypeType } from '../types'+import { captureException } from '../../utils/posthog'+import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'+import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { CyclotronJobInvocation, CyclotronPerson, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { getPersonDisplayName } from '../utils'-import { CdpConsumerBaseDeps } from './cdp-base.consumer'-import { CdpEventsConsumer } from './cdp-events.consumer'+import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'-export class CdpPersonUpdatesConsumer extends CdpEventsConsumer {- protected override name = 'CdpPersonUpdatesConsumer'- protected override hogTypes: HogFunctionTypeType[] = ['destination']+export class CdpPersonUpdatesConsumer extends CdpConsumerBase {+ protected name = 'CdpPersonUpdatesConsumer'+ protected hogTypes: HogFunctionTypeType[] = ['destination']++ protected cyclotronJobQueue: CyclotronJobQueue+ protected kafkaConsumer: KafkaConsumerInterface+ private hogFunctionPipeline: HogFunctionInvocationPipelineconstructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {- super(config, deps, KAFKA_PERSON, 'cdp-person-updates-consumer')+ super(config, deps)+ this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.kafkaConsumer = createKafkaConsumer({+ groupId: 'cdp-person-updates-consumer',+ topic: KAFKA_PERSON,+ })+ this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {+ hogFunctionManager: this.hogFunctionManager,+ hogExecutor: this.hogExecutor,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ })}- protected override filterHogFunction(hogFunction: HogFunctionType): boolean {- return hogFunction.filters?.source === 'person-updates'+ public async processBatch(+ invocationGlobals: HogFunctionInvocationGlobals[]+ ): Promise<{ backgroundTask: Promise<any>; invocations: CyclotronJobInvocation[] }> {+ if (!invocationGlobals.length) {+ return { backgroundTask: Promise.resolve(), invocations: [] }+ }++ await this.groupsManager.addGroupsToGlobalsList(invocationGlobals)++ const invocationsToBeQueued = await this.hogFunctionPipeline.buildInvocations(invocationGlobals, {+ hogTypes: this.hogTypes,+ filterFn: (fn) => fn.filters?.source === 'person-updates',+ })++ return {+ backgroundTask: Promise.all([+ instrumentFn({ key: 'cdp.background_task.queue_invocations', sendException: false }, () =>+ this.cyclotronJobQueue.queueInvocations(invocationsToBeQueued)+ ),+ instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {+ try {+ await this.hogFunctionMonitoringService.flush()+ } catch (err) {+ captureException(err)+ logger.error('🔴', 'Error producing queued messages for monitoring', { err })+ }+ }),+ ]),+ invocations: invocationsToBeQueued,+ }}- // This consumer always parses from kafka@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')- public override async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {+ public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {const globals: HogFunctionInvocationGlobals[] = []await Promise.all(messages.map(async (message) => {@@ -36,11 +85,13 @@ export class CdpPersonUpdatesConsumer extends CdpEventsConsumer {const data = parseJSON(message.value!.toString()) as ClickHousePersonconst [teamHogFunctions, team] = await Promise.all([- this.hogFunctionManager.getHogFunctionsForTeam(data.team_id, ['destination']),+ this.hogFunctionManager.getHogFunctionsForTeam(data.team_id, this.hogTypes),this.deps.teamManager.getTeam(data.team_id),])- const filteredHogFunctions = teamHogFunctions.filter(this.filterHogFunction)+ const filteredHogFunctions = teamHogFunctions.filter(+ (fn) => fn.filters?.source === 'person-updates'+ )if (!filteredHogFunctions.length || !team) {return@@ -56,6 +107,30 @@ export class CdpPersonUpdatesConsumer extends CdpEventsConsumer {return globals}++ public override async start(): Promise<void> {+ await super.start()+ await this.cyclotronJobQueue.startAsProducer()+ await this.kafkaConsumer.connect(async (messages) => {+ logger.info('🔁', `${this.name} - handling batch`, { size: messages.length })+ return await instrumentFn('cdpConsumer.handleEachBatch', async () => {+ const invocationGlobals = await this._parseKafkaBatch(messages)+ const { backgroundTask } = await this.processBatch(invocationGlobals)+ return { backgroundTask }+ })+ })+ }++ public override async stop(): Promise<void> {+ logger.info('💤', 'Stopping consumer...')+ await this.kafkaConsumer.disconnect()+ await this.cyclotronJobQueue.stop()+ await super.stop()+ }++ public isHealthy(): HealthCheckResult {+ return this.kafkaConsumer.isHealthy()+ }}function convertClickhousePersonToInvocationGlobals(diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.tsnew file mode 100644index 000000000000..28d3baccc92d--- /dev/null+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts@@ -0,0 +1,188 @@+import { QuotaLimiting } from '../../common/services/quota-limiting.service'+import { HogFunctionInvocationGlobals } from '../types'+import { HogFlowInvocationPipeline } from './hog-flow-invocation-pipeline.service'+import { HogFlowExecutorService } from './hogflows/hogflow-executor.service'+import { HogFlowManagerService } from './hogflows/hogflow-manager.service'+import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'+import { HogMaskerService } from './monitoring/hog-masker.service'+import { HogWatcherService, HogWatcherState } from './monitoring/hog-watcher.service'++jest.mock('../../common/services/keyed-rate-limiter.service', () => ({+ KeyedRateLimiterService: jest.fn().mockImplementation(() => ({+ rateLimitGrouped: jest.fn(),+ })),+}))++const config = {+ CDP_RATE_LIMITER_BUCKET_SIZE: 100,+ CDP_RATE_LIMITER_REFILL_RATE: 10,+ CDP_RATE_LIMITER_TTL: 60,+}++function makeHogFlowInvocation(hogFlowId = 'flow-1', overrides: { billable_action_types?: string[] } = {}) {+ return {+ id: `inv-${hogFlowId}`,+ teamId: 1,+ functionId: hogFlowId,+ queue: 'hogflow',+ queuePriority: 0,+ hogFlow: { id: hogFlowId, name: 'test flow', billable_action_types: overrides.billable_action_types ?? [] },+ state: { event: { uuid: 'evt-1' } },+ person: undefined,+ } as any+}++function makeGlobals(teamId = 1): HogFunctionInvocationGlobals {+ return { project: { id: teamId } } as HogFunctionInvocationGlobals+}++describe('HogFlowInvocationPipeline', () => {+ let hogFlowManager: jest.Mocked<HogFlowManagerService>+ let hogFlowExecutor: jest.Mocked<HogFlowExecutorService>+ let hogWatcher: jest.Mocked<HogWatcherService>+ let hogMasker: jest.Mocked<HogMaskerService>+ let hogFunctionMonitoringService: jest.Mocked<HogFunctionMonitoringService>+ let quotaLimiting: jest.Mocked<QuotaLimiting>+ let pipeline: HogFlowInvocationPipeline+ let rateLimitGroupedMock: jest.Mock++ beforeEach(() => {+ hogFlowManager = {+ getHogFlowsForTeams: jest.fn().mockResolvedValue({}),+ } as unknown as jest.Mocked<HogFlowManagerService>++ hogFlowExecutor = {+ buildHogFlowInvocations: jest.fn().mockResolvedValue({ invocations: [], metrics: [], logs: [] }),+ } as unknown as jest.Mocked<HogFlowExecutorService>++ hogWatcher = {+ getEffectiveStates: jest.fn().mockResolvedValue({}),+ } as unknown as jest.Mocked<HogWatcherService>++ hogMasker = {+ filterByMasking: jest.fn((invocations) => Promise.resolve({ masked: [], notMasked: invocations })),+ } as unknown as jest.Mocked<HogMaskerService>++ hogFunctionMonitoringService = {+ queueAppMetrics: jest.fn(),+ queueAppMetric: jest.fn(),+ queueLogs: jest.fn(),+ } as unknown as jest.Mocked<HogFunctionMonitoringService>++ quotaLimiting = {+ isTeamQuotaLimited: jest.fn().mockResolvedValue(false),+ } as unknown as jest.Mocked<QuotaLimiting>++ pipeline = new HogFlowInvocationPipeline(config, {+ hogFlowManager,+ hogFlowExecutor,+ hogWatcher,+ hogWatcherMirror: null,+ hogMasker,+ hogFunctionMonitoringService,+ quotaLimiting,+ redis: {} as any,+ valkeyShadow: null,+ })++ rateLimitGroupedMock = (pipeline as any).hogRateLimiter.rateLimitGrouped as jest.Mock+ rateLimitGroupedMock.mockResolvedValue([])+ })++ it('returns empty when no hogflows match', async () => {+ const result = await pipeline.buildInvocations([makeGlobals()])+ expect(result).toEqual([])+ expect(hogFlowManager.getHogFlowsForTeams).toHaveBeenCalledWith([1])+ })++ it('returns invocations for matching hogflows and queues triggered metric', async () => {+ const inv = makeHogFlowInvocation()+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [inv.hogFlow.id]: { state: HogWatcherState.healthy } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])++ const result = await pipeline.buildInvocations([makeGlobals()])++ expect(result).toEqual([inv])+ expect(hogFunctionMonitoringService.queueAppMetrics).toHaveBeenCalledWith(+ expect.arrayContaining([expect.objectContaining({ metric_name: 'triggered' })]),+ 'hog_flow'+ )+ })++ it('drops rate-limited invocations with metric + log', async () => {+ const inv = makeHogFlowInvocation()+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [inv.hogFlow.id]: { state: HogWatcherState.healthy } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: true }]])++ const result = await pipeline.buildInvocations([makeGlobals()])++ expect(result).toEqual([])+ expect(hogFunctionMonitoringService.queueAppMetric).toHaveBeenCalledWith(+ expect.objectContaining({ metric_name: 'rate_limited' }),+ 'hog_flow'+ )+ expect(hogFunctionMonitoringService.queueLogs).toHaveBeenCalled()+ })++ it('drops quota-limited invocations', async () => {+ // hogflow quota helper short-circuits when billable_action_types is empty+ const inv = makeHogFlowInvocation('flow-1', { billable_action_types: ['function_email'] })+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [inv.hogFlow.id]: { state: HogWatcherState.healthy } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])+ quotaLimiting.isTeamQuotaLimited.mockResolvedValue(true)++ const result = await pipeline.buildInvocations([makeGlobals()])+ expect(result).toEqual([])+ })++ it('drops invocations for disabled hogflows', async () => {+ const inv = makeHogFlowInvocation()+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({+ [inv.hogFlow.id]: { state: HogWatcherState.disabled },+ } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])++ const result = await pipeline.buildInvocations([makeGlobals()])++ expect(result).toEqual([])+ expect(hogFunctionMonitoringService.queueAppMetric).toHaveBeenCalledWith(+ expect.objectContaining({ metric_name: 'disabled_permanently' }),+ 'hog_flow'+ )+ })++ it('sets queuePriority=2 for degraded hogflows but does not change queue', async () => {+ const inv = makeHogFlowInvocation()+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({+ [inv.hogFlow.id]: { state: HogWatcherState.degraded },+ } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])++ const result = await pipeline.buildInvocations([makeGlobals()])++ expect(result).toHaveLength(1)+ expect(result[0].queuePriority).toBe(2)+ expect(result[0].queue).toBe('hogflow')+ })++ it('drops masked invocations', async () => {+ const inv = makeHogFlowInvocation()+ hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [inv.hogFlow.id]: { state: HogWatcherState.healthy } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])+ hogMasker.filterByMasking.mockResolvedValue({ masked: [inv], notMasked: [] })++ const result = await pipeline.buildInvocations([makeGlobals()])++ expect(result).toEqual([])+ expect(hogFunctionMonitoringService.queueAppMetrics).toHaveBeenCalledWith(+ expect.arrayContaining([expect.objectContaining({ metric_name: 'masked' })]),+ 'hog_flow'+ )+ })+})diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.tsnew file mode 100644index 000000000000..6eabf01c9c49--- /dev/null+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts@@ -0,0 +1,222 @@+import { DateTime } from 'luxon'++import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'++import { RedisV2 } from '../../common/redis/redis-v2'+import { KeyedRateLimitRequest, KeyedRateLimiterService } from '../../common/services/keyed-rate-limiter.service'+import { QuotaLimiting } from '../../common/services/quota-limiting.service'+import { logger } from '../../utils/logger'+import { captureException } from '../../utils/posthog'+import { CdpValkeyShadowPools } from '../cdp-services'+import { counterRateLimited } from '../consumers/metrics'+import { CyclotronJobInvocation, HogFunctionInvocationGlobals, LogEntry, MinimalAppMetric } from '../types'+import { mirrorCall } from '../utils/mirror-call'+import { HogFlowExecutorService } from './hogflows/hogflow-executor.service'+import { HogFlowManagerService } from './hogflows/hogflow-manager.service'+import { shouldBlockHogFlowDueToQuota } from './hogflows/hogflow-quota-limiting'+import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'+import { HogMaskerService } from './monitoring/hog-masker.service'+import { HogWatcherService, HogWatcherState } from './monitoring/hog-watcher.service'++export interface HogFlowInvocationPipelineConfig {+ CDP_RATE_LIMITER_BUCKET_SIZE: number+ CDP_RATE_LIMITER_REFILL_RATE: number+ CDP_RATE_LIMITER_TTL: number+}++export interface HogFlowInvocationPipelineDeps {+ hogFlowManager: HogFlowManagerService+ hogFlowExecutor: HogFlowExecutorService+ hogWatcher: HogWatcherService+ hogWatcherMirror: HogWatcherService | null+ hogMasker: HogMaskerService+ hogFunctionMonitoringService: HogFunctionMonitoringService+ quotaLimiting: QuotaLimiting+ redis: RedisV2+ valkeyShadow: CdpValkeyShadowPools | null+}++/**+ * Encapsulates the pipeline that turns event globals into hog flow invocations:+ * load hogflows → execute filters → watcher state → rate limit → quota → masking → metrics.+ *+ * Consumers compose this service rather than inheriting it.+ */+export class HogFlowInvocationPipeline {+ private hogRateLimiter: KeyedRateLimiterService+ private hogRateLimiterMirror: KeyedRateLimiterService | null++ constructor(+ private config: HogFlowInvocationPipelineConfig,+ private deps: HogFlowInvocationPipelineDeps+ ) {+ const rateLimiterConfig = {+ name: 'hog-rate-limiter',+ bucketSize: config.CDP_RATE_LIMITER_BUCKET_SIZE,+ refillRate: config.CDP_RATE_LIMITER_REFILL_RATE,+ ttlSeconds: config.CDP_RATE_LIMITER_TTL,+ }+ this.hogRateLimiter = new KeyedRateLimiterService(rateLimiterConfig, deps.redis)+ this.hogRateLimiterMirror = deps.valkeyShadow+ ? new KeyedRateLimiterService(rateLimiterConfig, deps.valkeyShadow.writer)+ : null+ }++ @instrumented('cdpConsumer.handleEachBatch.queueMatchingFlows')+ public async buildInvocations(+ invocationGlobals: HogFunctionInvocationGlobals[]+ ): Promise<CyclotronJobInvocation[]> {+ const teamsToLoad = [...new Set(invocationGlobals.map((x) => x.project.id))]+ const hogFlowsByTeam = await this.deps.hogFlowManager.getHogFlowsForTeams(teamsToLoad)++ const possibleInvocations = (+ await Promise.all(+ invocationGlobals.map(async (globals) => {+ const teamHogFlows = hogFlowsByTeam[globals.project.id]++ const { invocations, metrics, logs } = await this.deps.hogFlowExecutor.buildHogFlowInvocations(+ teamHogFlows,+ globals+ )++ this.deps.hogFunctionMonitoringService.queueAppMetrics(metrics, 'hog_flow')+ this.deps.hogFunctionMonitoringService.queueLogs(logs, 'hog_flow')++ return invocations+ })+ )+ ).flat()++ const hogFlowIds = possibleInvocations.map((x) => x.hogFlow.id)+ const [states] = await Promise.all([+ instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {+ return await this.deps.hogWatcher.getEffectiveStates(hogFlowIds)+ }),+ mirrorCall('hog-watcher.getEffectiveStates', () =>+ this.deps.hogWatcherMirror?.getEffectiveStates(hogFlowIds)+ ),+ ])++ const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({+ id: x.hogFlow.id,+ cost: 1,+ }))+ const [rateLimits] = await Promise.all([+ instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {+ return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)+ }),+ mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>+ this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)+ ),+ ])+ const validInvocations: CyclotronJobInvocation[] = []++ await Promise.all(+ possibleInvocations.map(async (item, index) => {+ try {+ const rateLimit = rateLimits[index][1]+ if (rateLimit.isRateLimited) {+ counterRateLimited.labels({ kind: 'hog_flow', function_id: item.functionId }).inc()+ this.deps.hogFunctionMonitoringService.queueAppMetric(+ {+ team_id: item.teamId,+ app_source_id: item.functionId,+ metric_kind: 'failure',+ metric_name: 'rate_limited',+ count: 1,+ },+ 'hog_flow'+ )++ const eventUuid = item.state?.event?.uuid+ const personId = item.person?.id++ const logEntry: LogEntry = {+ timestamp: DateTime.now(),+ level: 'warn',+ message: `Workflow invocation dropped due to rate limiting for [Person:${personId ?? 'unknown'}] on [Event:${eventUuid ?? 'unknown'}]`,+ team_id: item.teamId,+ log_source: 'hog_flow',+ log_source_id: item.functionId,+ instance_id: item.id,+ }+ this.deps.hogFunctionMonitoringService.queueLogs([logEntry], 'hog_flow')++ logger.warn('⚠️', 'Hogflow invocation rate limited', {+ teamId: item.teamId,+ hogFlowId: item.functionId,+ hogFlowName: item.hogFlow.name,+ eventUuid,+ personId,+ })++ return+ }+ } catch (e) {+ captureException(e)+ logger.error('🔴', 'Error checking rate limit for hog flow', { err: e })+ }++ // Check quota limits for workflow actions+ const isQuotaLimited = await shouldBlockHogFlowDueToQuota(item, {+ quotaLimiting: this.deps.quotaLimiting,+ hogFunctionMonitoringService: this.deps.hogFunctionMonitoringService,+ })++ if (isQuotaLimited) {+ return+ }++ const state = states[item.hogFlow.id].state+ if (state === HogWatcherState.disabled) {+ this.deps.hogFunctionMonitoringService.queueAppMetric(+ {+ team_id: item.teamId,+ app_source_id: item.functionId,+ metric_kind: 'failure',+ metric_name: 'disabled_permanently',+ count: 1,+ },+ 'hog_flow'+ )+ return+ }++ if (state === HogWatcherState.degraded) {+ item.queuePriority = 2+ }++ validInvocations.push(item)+ })+ )++ const { masked, notMasked: notMaskedInvocations } = await this.deps.hogMasker.filterByMasking(validInvocations)++ this.deps.hogFunctionMonitoringService.queueAppMetrics(+ masked.map((item) => ({+ team_id: item.teamId,+ app_source_id: item.functionId,+ metric_kind: 'other',+ metric_name: 'masked',+ count: 1,+ })),+ 'hog_flow'+ )++ const triggeredInvocationsMetrics: MinimalAppMetric[] = []++ notMaskedInvocations.forEach((item) => {+ triggeredInvocationsMetrics.push({+ team_id: item.teamId,+ app_source_id: item.functionId,+ metric_kind: 'other',+ metric_name: 'triggered',+ count: 1,+ })+ })++ this.deps.hogFunctionMonitoringService.queueAppMetrics(triggeredInvocationsMetrics, 'hog_flow')++ return notMaskedInvocations+ }+}diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.tsnew file mode 100644index 000000000000..570557310a10--- /dev/null+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts@@ -0,0 +1,255 @@+import { QuotaLimiting } from '../../common/services/quota-limiting.service'+import { CyclotronJobInvocationHogFunction, HogFunctionInvocationGlobals, HogFunctionType } from '../types'+import { HogExecutorService } from './hog-executor.service'+import { HogFunctionInvocationPipeline } from './hog-function-invocation-pipeline.service'+import { HogFunctionManagerService } from './managers/hog-function-manager.service'+import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'+import { HogMaskerService } from './monitoring/hog-masker.service'+import { HogWatcherService, HogWatcherState } from './monitoring/hog-watcher.service'++// Mock the rate limiter to give us deterministic control+jest.mock('../../common/services/keyed-rate-limiter.service', () => ({+ KeyedRateLimiterService: jest.fn().mockImplementation(() => ({+ rateLimitGrouped: jest.fn(),+ })),+}))++const config = {+ CDP_RATE_LIMITER_BUCKET_SIZE: 100,+ CDP_RATE_LIMITER_REFILL_RATE: 10,+ CDP_RATE_LIMITER_TTL: 60,+ CDP_OVERFLOW_QUEUE_ENABLED: true,+}++function makeHogFunction(overrides: Partial<HogFunctionType> = {}): HogFunctionType {+ return {+ id: overrides.id ?? 'fn-1',+ team_id: 1,+ type: 'destination',+ filters: { source: 'events' },+ enabled: true,+ deleted: false,+ ...overrides,+ } as HogFunctionType+}++function makeInvocation(hogFunction: HogFunctionType, eventUuid = 'evt-1'): CyclotronJobInvocationHogFunction {+ return {+ id: `inv-${hogFunction.id}`,+ teamId: hogFunction.team_id,+ functionId: hogFunction.id,+ queue: 'hog',+ queuePriority: 0,+ state: {+ globals: { event: { uuid: eventUuid } },+ } as any,+ hogFunction,+ } as CyclotronJobInvocationHogFunction+}++function makeGlobals(teamId = 1): HogFunctionInvocationGlobals {+ return { project: { id: teamId } } as HogFunctionInvocationGlobals+}++describe('HogFunctionInvocationPipeline', () => {+ let hogFunctionManager: jest.Mocked<HogFunctionManagerService>+ let hogExecutor: jest.Mocked<HogExecutorService>+ let hogWatcher: jest.Mocked<HogWatcherService>+ let hogMasker: jest.Mocked<HogMaskerService>+ let hogFunctionMonitoringService: jest.Mocked<HogFunctionMonitoringService>+ let quotaLimiting: jest.Mocked<QuotaLimiting>+ let pipeline: HogFunctionInvocationPipeline+ let rateLimitGroupedMock: jest.Mock++ beforeEach(() => {+ hogFunctionManager = {+ getHogFunctionsForTeams: jest.fn().mockResolvedValue({}),+ } as unknown as jest.Mocked<HogFunctionManagerService>++ hogExecutor = {+ buildHogFunctionInvocations: jest.fn().mockResolvedValue({ invocations: [], metrics: [], logs: [] }),+ } as unknown as jest.Mocked<HogExecutorService>++ hogWatcher = {+ getEffectiveStates: jest.fn().mockResolvedValue({}),+ } as unknown as jest.Mocked<HogWatcherService>++ hogMasker = {+ filterByMasking: jest.fn((invocations) => Promise.resolve({ masked: [], notMasked: invocations })),+ } as unknown as jest.Mocked<HogMaskerService>++ hogFunctionMonitoringService = {+ queueAppMetrics: jest.fn(),+ queueAppMetric: jest.fn(),+ queueLogs: jest.fn(),+ } as unknown as jest.Mocked<HogFunctionMonitoringService>++ quotaLimiting = {+ isTeamQuotaLimited: jest.fn().mockResolvedValue(false),+ } as unknown as jest.Mocked<QuotaLimiting>++ pipeline = new HogFunctionInvocationPipeline(config, {+ hogFunctionManager,+ hogExecutor,+ hogWatcher,+ hogWatcherMirror: null,+ hogMasker,+ hogFunctionMonitoringService,+ quotaLimiting,+ redis: {} as any,+ valkeyShadow: null,+ })++ rateLimitGroupedMock = (pipeline as any).hogRateLimiter.rateLimitGrouped as jest.Mock+ rateLimitGroupedMock.mockResolvedValue([])+ })++ it('returns empty when no hog functions match', async () => {+ const result = await pipeline.buildInvocations([makeGlobals()], {+ hogTypes: ['destination'],+ filterFn: () => true,+ })+ expect(result).toEqual([])+ expect(hogFunctionManager.getHogFunctionsForTeams).toHaveBeenCalledWith(+ [1],+ ['destination'],+ expect.any(Function)+ )+ })++ it('returns invocations for matching hog functions and queues triggered + billing metrics', async () => {+ const fn = makeHogFunction()+ const inv = makeInvocation(fn, 'evt-uuid-1')+ hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])++ const result = await pipeline.buildInvocations([makeGlobals()], {+ hogTypes: ['destination'],+ filterFn: () => true,+ })++ expect(result).toEqual([inv])+ const metricsCall = hogFunctionMonitoringService.queueAppMetrics.mock.calls.find((c) =>+ c[0].some((m: any) => m.metric_name === 'triggered')+ )+ expect(metricsCall).toBeDefined()+ const billingCall = hogFunctionMonitoringService.queueAppMetrics.mock.calls.find((c) =>+ c[0].some((m: any) => m.metric_name === 'billable_invocation')+ )+ expect(billingCall).toBeDefined()+ })++ it('drops invocations in disabled watcher state', async () => {+ const fn = makeHogFunction()+ const inv = makeInvocation(fn)+ hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.disabled } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])++ const result = await pipeline.buildInvocations([makeGlobals()], {+ hogTypes: ['destination'],+ filterFn: () => true,+ })++ expect(result).toEqual([])+ expect(hogFunctionMonitoringService.queueAppMetric).toHaveBeenCalledWith(+ expect.objectContaining({ metric_name: 'disabled_permanently' }),+ 'hog_function'+ )+ })++ it('routes degraded invocations to hogoverflow queue when overflow enabled', async () => {+ const fn = makeHogFunction()+ const inv = makeInvocation(fn)+ hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.degraded } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])++ const result = await pipeline.buildInvocations([makeGlobals()], {+ hogTypes: ['destination'],+ filterFn: () => true,+ })++ expect(result).toHaveLength(1)+ expect(result[0].queuePriority).toBe(2)+ expect(result[0].queue).toBe('hogoverflow')+ })++ it('drops quota-limited invocations', async () => {+ const fn = makeHogFunction()+ const inv = makeInvocation(fn)+ hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])+ quotaLimiting.isTeamQuotaLimited.mockResolvedValue(true)++ const result = await pipeline.buildInvocations([makeGlobals()], {+ hogTypes: ['destination'],+ filterFn: () => true,+ })++ expect(result).toEqual([])+ })++ it('drops masked invocations', async () => {+ const fn = makeHogFunction()+ const inv = makeInvocation(fn)+ hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])+ hogMasker.filterByMasking.mockResolvedValue({ masked: [inv], notMasked: [] })++ const result = await pipeline.buildInvocations([makeGlobals()], {+ hogTypes: ['destination'],+ filterFn: () => true,+ })++ expect(result).toEqual([])+ expect(hogFunctionMonitoringService.queueAppMetrics).toHaveBeenCalledWith(+ expect.arrayContaining([expect.objectContaining({ metric_name: 'masked' })]),+ 'hog_function'+ )+ })++ it('bills only once per unique event uuid even with multiple destinations', async () => {+ const fn1 = makeHogFunction({ id: 'fn-1' })+ const fn2 = makeHogFunction({ id: 'fn-2' })+ const inv1 = makeInvocation(fn1, 'evt-same')+ const inv2 = makeInvocation(fn2, 'evt-same')+ hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv1, inv2], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({+ [fn1.id]: { state: HogWatcherState.healthy },+ [fn2.id]: { state: HogWatcherState.healthy },+ } as any)+ rateLimitGroupedMock.mockResolvedValue([+ [null, { isRateLimited: false }],+ [null, { isRateLimited: false }],+ ])++ await pipeline.buildInvocations([makeGlobals()], {+ hogTypes: ['destination'],+ filterFn: () => true,+ })++ const billingMetrics = hogFunctionMonitoringService.queueAppMetrics.mock.calls+ .flatMap((c) => c[0])+ .filter((m: any) => m.metric_name === 'billable_invocation')+ expect(billingMetrics).toHaveLength(1)+ })++ it('does not drop rate-limited invocations (monitoring-only)', async () => {+ const fn = makeHogFunction()+ const inv = makeInvocation(fn)+ hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })+ hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)+ rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: true }]])++ const result = await pipeline.buildInvocations([makeGlobals()], {+ hogTypes: ['destination'],+ filterFn: () => true,+ })++ expect(result).toHaveLength(1)+ })+})diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.tsnew file mode 100644index 000000000000..5fbe7ce20cec--- /dev/null+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts@@ -0,0 +1,234 @@+import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'++import { RedisV2 } from '../../common/redis/redis-v2'+import { KeyedRateLimitRequest, KeyedRateLimiterService } from '../../common/services/keyed-rate-limiter.service'+import { QuotaLimiting } from '../../common/services/quota-limiting.service'+import { logger } from '../../utils/logger'+import { captureException } from '../../utils/posthog'+import { CdpValkeyShadowPools } from '../cdp-services'+import { counterHogFunctionStateOnEvent, counterRateLimited } from '../consumers/metrics'+import { shouldBlockInvocationDueToQuota } from '../consumers/quota-limiting-helper'+import {+ CyclotronJobInvocationHogFunction,+ HogFunctionInvocationGlobals,+ HogFunctionType,+ HogFunctionTypeType,+ MinimalAppMetric,+} from '../types'+import { mirrorCall } from '../utils/mirror-call'+import { HogExecutorService } from './hog-executor.service'+import { HogFunctionManagerService } from './managers/hog-function-manager.service'+import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'+import { HogMaskerService } from './monitoring/hog-masker.service'+import { HogWatcherService, HogWatcherState } from './monitoring/hog-watcher.service'++export interface HogFunctionInvocationPipelineConfig {+ CDP_RATE_LIMITER_BUCKET_SIZE: number+ CDP_RATE_LIMITER_REFILL_RATE: number+ CDP_RATE_LIMITER_TTL: number+ CDP_OVERFLOW_QUEUE_ENABLED: boolean+}++export interface HogFunctionInvocationPipelineDeps {+ hogFunctionManager: HogFunctionManagerService+ hogExecutor: HogExecutorService+ hogWatcher: HogWatcherService+ hogWatcherMirror: HogWatcherService | null+ hogMasker: HogMaskerService+ hogFunctionMonitoringService: HogFunctionMonitoringService+ quotaLimiting: QuotaLimiting+ redis: RedisV2+ valkeyShadow: CdpValkeyShadowPools | null+}++export interface BuildHogFunctionInvocationsOptions {+ hogTypes: HogFunctionTypeType[]+ filterFn: (fn: HogFunctionType) => boolean+}++/**+ * Encapsulates the pipeline that turns event globals into hog function invocations:+ * load functions → execute filters → watcher state → rate limit → quota → masking → metrics.+ *+ * Consumers compose this service rather than inheriting it.+ */+export class HogFunctionInvocationPipeline {+ private hogRateLimiter: KeyedRateLimiterService+ private hogRateLimiterMirror: KeyedRateLimiterService | null++ constructor(+ private config: HogFunctionInvocationPipelineConfig,+ private deps: HogFunctionInvocationPipelineDeps+ ) {+ const rateLimiterConfig = {+ name: 'hog-rate-limiter',+ bucketSize: config.CDP_RATE_LIMITER_BUCKET_SIZE,+ refillRate: config.CDP_RATE_LIMITER_REFILL_RATE,+ ttlSeconds: config.CDP_RATE_LIMITER_TTL,+ }+ this.hogRateLimiter = new KeyedRateLimiterService(rateLimiterConfig, deps.redis)+ this.hogRateLimiterMirror = deps.valkeyShadow+ ? new KeyedRateLimiterService(rateLimiterConfig, deps.valkeyShadow.writer)+ : null+ }++ @instrumented('cdpConsumer.handleEachBatch.queueMatchingFunctions')+ public async buildInvocations(+ invocationGlobals: HogFunctionInvocationGlobals[],+ opts: BuildHogFunctionInvocationsOptions+ ): Promise<CyclotronJobInvocationHogFunction[]> {+ const teamsToLoad = [...new Set(invocationGlobals.map((x) => x.project.id))]+ const hogFunctionsByTeam = await this.deps.hogFunctionManager.getHogFunctionsForTeams(+ teamsToLoad,+ opts.hogTypes,+ opts.filterFn+ )++ const possibleInvocations = (+ await Promise.all(+ invocationGlobals.map(async (globals) => {+ const teamHogFunctions = hogFunctionsByTeam[globals.project.id]++ const { invocations, metrics, logs } = await this.deps.hogExecutor.buildHogFunctionInvocations(+ teamHogFunctions,+ globals+ )++ this.deps.hogFunctionMonitoringService.queueAppMetrics(metrics, 'hog_function')+ this.deps.hogFunctionMonitoringService.queueLogs(logs, 'hog_function')++ return invocations+ })+ )+ ).flat()++ const hogFunctionIds = possibleInvocations.map((x) => x.hogFunction.id)+ const [states] = await Promise.all([+ instrumentFn('cdpConsumer.handleEachBatch.hogWatcher.getEffectiveStates', async () => {+ return await this.deps.hogWatcher.getEffectiveStates(hogFunctionIds)+ }),+ mirrorCall('hog-watcher.getEffectiveStates', () =>+ this.deps.hogWatcherMirror?.getEffectiveStates(hogFunctionIds)+ ),+ ])++ const rateLimitInputs: KeyedRateLimitRequest[] = possibleInvocations.map((x) => ({+ id: x.hogFunction.id,+ cost: 1,+ }))+ const [rateLimits] = await Promise.all([+ instrumentFn('cdpConsumer.handleEachBatch.hogRateLimiter.rateLimitGrouped', async () => {+ return await this.hogRateLimiter.rateLimitGrouped(rateLimitInputs)+ }),+ mirrorCall('hog-rate-limiter.rateLimitGrouped', () =>+ this.hogRateLimiterMirror?.rateLimitGrouped(rateLimitInputs)+ ),+ ])++ const validInvocations: CyclotronJobInvocationHogFunction[] = []++ await Promise.all(+ possibleInvocations.map(async (item, index) => {+ try {+ const rateLimit = rateLimits[index][1]+ if (rateLimit.isRateLimited) {+ counterRateLimited.labels({ kind: 'hog_function', function_id: item.functionId }).inc()+ // NOTE: We don't return here as we are just monitoring this feature currently+ }+ } catch (e) {+ captureException(e)+ logger.error('🔴', 'Error checking rate limit for hog function', { err: e })+ }++ const isQuotaLimited = await shouldBlockInvocationDueToQuota(item, {+ quotaLimiting: this.deps.quotaLimiting,+ hogFunctionMonitoringService: this.deps.hogFunctionMonitoringService,+ })++ if (isQuotaLimited) {+ return+ }++ const state = states[item.hogFunction.id].state++ counterHogFunctionStateOnEvent+ .labels({+ state: HogWatcherState[state],+ kind: item.hogFunction.type,+ })+ .inc()++ if (state === HogWatcherState.disabled) {+ this.deps.hogFunctionMonitoringService.queueAppMetric(+ {+ team_id: item.teamId,+ app_source_id: item.functionId,+ metric_kind: 'failure',+ metric_name: 'disabled_permanently',+ count: 1,+ },+ 'hog_function'+ )+ return+ }++ if (state === HogWatcherState.degraded) {+ item.queuePriority = 2+ if (this.config.CDP_OVERFLOW_QUEUE_ENABLED) {+ item.queue = 'hogoverflow'+ }+ }++ validInvocations.push(item)+ })+ )++ const { masked, notMasked: notMaskedInvocations } = await this.deps.hogMasker.filterByMasking(validInvocations)++ this.deps.hogFunctionMonitoringService.queueAppMetrics(+ masked.map((item) => ({+ team_id: item.teamId,+ app_source_id: item.functionId,+ metric_kind: 'other',+ metric_name: 'masked',+ count: 1,+ })),+ 'hog_function'+ )++ const triggeredInvocationsMetrics: MinimalAppMetric[] = []++ // Track unique events that have been billed (billing is per-event, not per-destination)+ const billedEventUuids = new Set<string>()++ notMaskedInvocations.forEach((item) => {+ triggeredInvocationsMetrics.push({+ team_id: item.teamId,+ app_source_id: item.functionId,+ metric_kind: 'other',+ metric_name: 'triggered',+ count: 1,+ })++ // Bill once per triggering event, not per destination+ if (item.hogFunction.type === 'destination') {+ const eventUuid = item.state?.globals?.event?.uuid+ if (eventUuid && !billedEventUuids.has(eventUuid)) {+ billedEventUuids.add(eventUuid)+ triggeredInvocationsMetrics.push({+ team_id: item.teamId,+ app_source_id: '_event_trigger',+ instance_id: eventUuid,+ metric_kind: 'billing',+ metric_name: 'billable_invocation',+ count: 1,+ })+ }+ }+ })++ this.deps.hogFunctionMonitoringService.queueAppMetrics(triggeredInvocationsMetrics, 'hog_function')++ return notMaskedInvocations+ }+}