: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
feat(metrics): run metrics ingestion on the pipeline framework (#102896)
Frank Hamanda1c29df01529
diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.tsindex 5bb4224ce450..63fdc882d73a 100644--- a/nodejs/src/common/config/kafka-topics.ts+++ b/nodejs/src/common/config/kafka-topics.ts@@ -119,7 +119,6 @@ export const KAFKA_TRACES_CLICKHOUSE = `${prefix}clickhouse_traces${suffix}`// Metrics ingestion topicsexport const KAFKA_METRICS_INGESTION = `${prefix}metrics_ingestion${suffix}`export const KAFKA_METRICS_INGESTION_DLQ = `${prefix}metrics_ingestion_dlq${suffix}`-export const KAFKA_METRICS_INGESTION_OVERFLOW = `${prefix}metrics_ingestion_overflow${suffix}`export const KAFKA_METRICS_CLICKHOUSE = `${prefix}clickhouse_metrics${suffix}`// TopHog metricsdiff --git a/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts b/nodejs/src/ingestion/framework/docs/07-result-handling.test.tsindex aef1b6f546ad..60074f6280d4 100644--- a/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts+++ b/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts@@ -46,7 +46,7 @@* ## Configuration** `handleResults()` requires a `PipelineConfig` with:- * - `outputs`: IngestionOutputs containing DLQ, ingestion warnings, and any redirect outputs+ * - `outputs`: IngestionOutputs containing the DLQ and any redirect outputs* - `promiseScheduler`: For scheduling async operations** ## Required: handleSideEffects()diff --git a/nodejs/src/ingestion/framework/result-handling-helpers.test.ts b/nodejs/src/ingestion/framework/result-handling-helpers.test.tsindex 78bcb152e9b0..deb9d3ab5b96 100644--- a/nodejs/src/ingestion/framework/result-handling-helpers.test.ts+++ b/nodejs/src/ingestion/framework/result-handling-helpers.test.ts@@ -44,6 +44,19 @@ describe('produceMessageToDLQ', () => {} as Message})+ it('rethrows a failed DLQ produce after logging it when rethrowOnFailure is set', async () => {+ const dlqError = new Error('broker down')+ mockOutputs.produce.mockRejectedValueOnce(dlqError)++ await expect(+ produceMessageToDLQ(mockOutputs, mockMessage, new Error('Test error'), 'test-step', {+ rethrowOnFailure: true,+ })+ ).rejects.toBe(dlqError)+ expect(mockLogger.error).toHaveBeenCalledWith('Failed to send event to DLQ', expect.anything())+ expect(mockCaptureException).toHaveBeenCalledWith(dlqError, expect.anything())+ })+it('should send message to DLQ with proper headers and logging', async () => {const error = new Error('Test error')const stepName = 'test-step'diff --git a/nodejs/src/ingestion/framework/result-handling-helpers.ts b/nodejs/src/ingestion/framework/result-handling-helpers.tsindex e603b22319d2..68dbf74be19d 100644--- a/nodejs/src/ingestion/framework/result-handling-helpers.ts+++ b/nodejs/src/ingestion/framework/result-handling-helpers.ts@@ -68,6 +68,11 @@ function getEventMetadata(message: Message): { teamId?: string; distinctId?: str}}+export interface ProduceToDLQOptions {+ /** Rethrow a failed DLQ produce. Set it only when the caller stores no offsets after the error. */+ rethrowOnFailure?: boolean+}+/*** Send a Kafka message to the dead letter queue with proper logging and metrics.*/@@ -75,7 +80,8 @@ export async function produceMessageToDLQ(outputs: IngestionOutputs<DlqOutput>,originalMessage: Message,error: unknown,- stepName: string+ stepName: string,+ options: ProduceToDLQOptions = {}): Promise<void> {const step = stepNameconst messageInfo = getEventMetadata(originalMessage)@@ -115,6 +121,9 @@ export async function produceMessageToDLQ(tags: { team_id: messageInfo.teamId, pipeline_step: step },extra: { originalMessage, error: dlqError },})+ if (options.rethrowOnFailure) {+ throw dlqError+ }}}diff --git a/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts b/nodejs/src/ingestion/framework/result-handling-pipeline.test.tsindex c2bec1d10ee6..9e9162ec0f37 100644--- a/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts@@ -261,6 +261,24 @@ describe('ResultHandlingPipeline', () => {expect(mockProduceMessageToDLQ).toHaveBeenCalledWith(config.outputs, messages[1], testError, 'unknown')})+ it('passes rethrowOnFailure to the DLQ produce when rejectOnDlqFailure is set', async () => {+ const dlqError = new Error('broker down')+ mockProduceMessageToDLQ.mockRejectedValueOnce(dlqError)+ const message = { value: Buffer.from('dlq'), topic: 'test', partition: 0, offset: 1 } as Message+ const testError = new Error('test error')++ const resultPipeline = new ResultHandlingPipeline(+ createMockPipeline([createContext(dlq('test dlq reason', testError), { message })]),+ { ...config, rejectOnDlqFailure: true }+ )+ const results = await resultPipeline.next()++ await expect(Promise.all(results![0].context.sideEffects)).rejects.toBe(dlqError)+ expect(mockProduceMessageToDLQ).toHaveBeenCalledWith(config.outputs, message, testError, 'unknown', {+ rethrowOnFailure: true,+ })+ })+it('should send DLQ messages with event and uuid headers', async () => {mockProduceMessageToDLQ.mockResolvedValue(undefined)diff --git a/nodejs/src/ingestion/framework/result-handling-pipeline.ts b/nodejs/src/ingestion/framework/result-handling-pipeline.tsindex 9dbc777bdb1a..55c9a78137b8 100644--- a/nodejs/src/ingestion/framework/result-handling-pipeline.ts+++ b/nodejs/src/ingestion/framework/result-handling-pipeline.ts@@ -1,6 +1,6 @@import { Message } from 'node-rdkafka'-import { DlqOutput, IngestionWarningsOutput } from '~/common/outputs'+import { DlqOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { PromiseScheduler } from '~/common/utils/promise-scheduler'import { ingestionPipelineResultCounter } from '~/ingestion/common/metrics'@@ -22,8 +22,10 @@ import {} from './results'export type PipelineConfig<R extends string = never> = {- outputs: IngestionOutputs<DlqOutput | IngestionWarningsOutput | R>+ outputs: IngestionOutputs<DlqOutput | R>promiseScheduler: PromiseScheduler+ /** Reject the side effect when the DLQ produce fails. Set it only when the consumer stores no offsets after a rejected side effect. */+ rejectOnDlqFailure?: boolean}/**@@ -92,12 +94,10 @@ export class ResultHandlingPipeline<const sideEffects: Promise<unknown>[] = []if (isDlqResult(result)) {- const dlqPromise = produceMessageToDLQ(- this.config.outputs,- originalMessage,- result.error || new Error(result.reason),- stepName- )+ const error = result.error || new Error(result.reason)+ const dlqPromise = this.config.rejectOnDlqFailure+ ? produceMessageToDLQ(this.config.outputs, originalMessage, error, stepName, { rethrowOnFailure: true })+ : produceMessageToDLQ(this.config.outputs, originalMessage, error, stepName)sideEffects.push(dlqPromise)} else if (isDropResult(result)) {logDroppedMessage(originalMessage, result.reason, stepName)diff --git a/nodejs/src/ingestion/pipelines/metrics/config.ts b/nodejs/src/ingestion/pipelines/metrics/config.tsindex 1df4442829b7..7fc7d098b800 100644--- a/nodejs/src/ingestion/pipelines/metrics/config.ts+++ b/nodejs/src/ingestion/pipelines/metrics/config.ts@@ -3,7 +3,6 @@ import {KAFKA_METRICS_CLICKHOUSE,KAFKA_METRICS_INGESTION,KAFKA_METRICS_INGESTION_DLQ,- KAFKA_METRICS_INGESTION_OVERFLOW,} from '~/common/config/kafka-topics'import { isProdEnv } from '~/common/utils/env-utils'@@ -28,9 +27,9 @@ export function getDefaultMetricsIngestionOutputsConfig(): MetricsIngestionOutpuexport type MetricsIngestionConsumerConfig = {METRICS_INGESTION_CONSUMER_GROUP_ID: stringMETRICS_INGESTION_CONSUMER_CONSUME_TOPIC: string- METRICS_INGESTION_CONSUMER_OVERFLOW_TOPIC: stringMETRICS_INGESTION_CONSUMER_DLQ_TOPIC: stringMETRICS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC: string+ METRICS_INGESTION_USE_PIPELINE_FRAMEWORK: booleanMETRICS_REDIS_HOST: stringMETRICS_REDIS_PORT: numberMETRICS_REDIS_PASSWORD: string@@ -52,9 +51,9 @@ export function getDefaultMetricsIngestionConsumerConfig(): MetricsIngestionConsreturn {METRICS_INGESTION_CONSUMER_GROUP_ID: 'ingestion-metrics',METRICS_INGESTION_CONSUMER_CONSUME_TOPIC: KAFKA_METRICS_INGESTION,- METRICS_INGESTION_CONSUMER_OVERFLOW_TOPIC: KAFKA_METRICS_INGESTION_OVERFLOW,METRICS_INGESTION_CONSUMER_DLQ_TOPIC: KAFKA_METRICS_INGESTION_DLQ,METRICS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC: KAFKA_METRICS_CLICKHOUSE,+ METRICS_INGESTION_USE_PIPELINE_FRAMEWORK: false,METRICS_REDIS_HOST: '127.0.0.1',METRICS_REDIS_PORT: 6379,METRICS_REDIS_PASSWORD: '',diff --git a/nodejs/src/ingestion/pipelines/metrics/drop-quota-limited-step.ts b/nodejs/src/ingestion/pipelines/metrics/drop-quota-limited-step.tsnew file mode 100644index 000000000000..91ba532ddf58--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/drop-quota-limited-step.ts@@ -0,0 +1,27 @@+import { QuotaLimiting } from '~/common/services/quota-limiting.service'+import { drop, ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import { metricMessageDroppedCounter } from './metrics'+import { MetricsUsageAccumulator } from './metrics-usage'++export interface DropQuotaLimitedInput {+ token: string+ teamId: number+ bytesUncompressed: number+ recordCount: number+ usage: MetricsUsageAccumulator+}++export function createDropQuotaLimitedStep<T extends DropQuotaLimitedInput>(+ quotaLimiting: Pick<QuotaLimiting, 'isTeamTokenQuotaLimited'>+): ProcessingStep<T, T> {+ return async function dropQuotaLimitedStep(input) {+ if (await quotaLimiting.isTeamTokenQuotaLimited(input.token, 'metrics_mb_ingested')) {+ input.usage.recordDropped(input.teamId, input.bytesUncompressed, input.recordCount)+ metricMessageDroppedCounter.inc({ reason: 'quota_limited', team_id: input.teamId.toString() })+ return drop('quota_limited')+ }+ return ok(input)+ }+}diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.test.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.test.tsindex c189bc38853e..04cdb91be7a2 100644--- a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.test.ts@@ -15,8 +15,14 @@ import { createTestTeamFixture } from '~/tests/helpers/sql'import { Hub, Team } from '~/types'import { getDefaultMetricsIngestionConsumerConfig } from './config'-import { DEFAULT_METRICS_RETENTION_DAYS, MetricsIngestionConsumer } from './metrics-ingestion-consumer'-import { METRICS_DLQ_OUTPUT, METRICS_OUTPUT, MetricsDlqOutput, MetricsOutput } from './outputs/outputs'+import { MetricsIngestionConsumer } from './metrics-ingestion-consumer'+import {+ DEFAULT_METRICS_RETENTION_DAYS,+ METRICS_DLQ_OUTPUT,+ METRICS_OUTPUT,+ MetricsDlqOutput,+ MetricsOutput,+} from './outputs/outputs'const createKafkaMessage = (headers: Record<string, string>): Message => {// The consumer passes the Avro payload through without decoding it.diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.tsindex 7ec9b02a03ca..c3820fccf464 100644--- a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts@@ -1,10 +1,9 @@import { Message } from 'node-rdkafka'-import { Counter } from 'prom-client'import { KafkaConsumerInterface, createKafkaConsumer, parseKafkaHeaders } from '~/common/kafka/consumer'import { AppMetricsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'-import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'+import { RedisV2 } from '~/common/redis/redis-v2'import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'import { QuotaLimiting } from '~/common/services/quota-limiting.service'import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'@@ -15,8 +14,26 @@ import { HealthCheckResult, PluginServerService } from '~/types'import { MetricsIngestionConsumerConfig } from './config'import { recordMetricsIngested } from './ingestion-otel-metrics'-import { METRICS_DLQ_OUTPUT, METRICS_OUTPUT, MetricsDlqOutput, MetricsOutput } from './outputs/outputs'+import {+ metricMessageDlqCounter,+ metricMessageDroppedCounter,+ metricsBytesAllowedCounter,+ metricsBytesDroppedCounter,+ metricsBytesReceivedCounter,+ metricsRecordsAllowedCounter,+ metricsRecordsDroppedCounter,+ metricsRecordsReceivedCounter,+} from './metrics'+import { DEFAULT_USAGE_STATS, UsageStatsByTeam } from './metrics-usage'+import {+ DEFAULT_METRICS_RETENTION_DAYS,+ METRICS_DLQ_OUTPUT,+ METRICS_OUTPUT,+ MetricsDlqOutput,+ MetricsOutput,+} from './outputs/outputs'import { MetricsRateLimiterService } from './services/metrics-rate-limiter.service'+import { createMetricsRateLimiterRedis } from './services/metrics-redis'import { MetricsIngestionMessage } from './types'export interface MetricsIngestionConsumerDeps {@@ -31,73 +48,7 @@ export interface MetricsIngestionConsumerDeps {outputs: IngestionOutputs<MetricsOutput | MetricsDlqOutput | AppMetricsOutput>}-export type UsageStats = {- bytesReceived: number- recordsReceived: number- bytesAllowed: number- recordsAllowed: number- bytesDropped: number- recordsDropped: number-}--const DEFAULT_USAGE_STATS: UsageStats = {- bytesReceived: 0,- recordsReceived: 0,- bytesAllowed: 0,- recordsAllowed: 0,- bytesDropped: 0,- recordsDropped: 0,-}--export type UsageStatsByTeam = Map<number, UsageStats>--/** Retention stamped on every produced batch; metrics has no per-team setting yet. ClickHouse falls back to `DEFAULT_RETENTION_DAYS` in `posthog/clickhouse/metrics/metrics2.py` only when this header is absent. */-export const DEFAULT_METRICS_RETENTION_DAYS = 30--export const metricMessageDroppedCounter = new Counter({- name: 'metrics_ingestion_message_dropped_count',- help: 'The number of metrics ingestion messages dropped',- labelNames: ['reason', 'team_id'],-})--export const metricMessageDlqCounter = new Counter({- name: 'metrics_ingestion_message_dlq_count',- help: 'The number of metrics ingestion messages sent to DLQ',- labelNames: ['reason', 'team_id'],-})--export const metricsBytesReceivedCounter = new Counter({- name: 'metrics_ingestion_bytes_received_total',- help: 'Total uncompressed bytes received for metrics ingestion',-})--export const metricsBytesAllowedCounter = new Counter({- name: 'metrics_ingestion_bytes_allowed_total',- help: 'Total uncompressed bytes allowed through quota and rate limiting',-})--export const metricsBytesDroppedCounter = new Counter({- name: 'metrics_ingestion_bytes_dropped_total',- help: 'Total uncompressed bytes dropped due to quota or rate limiting',- labelNames: ['team_id'],-})--export const metricsRecordsReceivedCounter = new Counter({- name: 'metrics_ingestion_records_received_total',- help: 'Total metric records received',-})--export const metricsRecordsAllowedCounter = new Counter({- name: 'metrics_ingestion_records_allowed_total',- help: 'Total metric records allowed through quota and rate limiting',-})--export const metricsRecordsDroppedCounter = new Counter({- name: 'metrics_ingestion_records_dropped_total',- help: 'Total metric records dropped due to quota or rate limiting',- labelNames: ['team_id'],-})-+/** Replaced by `MetricsPipelineConsumer`. Remove it when every environment sets `METRICS_INGESTION_USE_PIPELINE_FRAMEWORK`. */export class MetricsIngestionConsumer {protected name = 'MetricsIngestionConsumer'protected kafkaConsumer: KafkaConsumerInterface@@ -120,25 +71,8 @@ export class MetricsIngestionConsumer {this.appMetricsAggregator = new AppMetricsAggregator(deps.outputs)this.kafkaConsumer = createKafkaConsumer({ groupId: this.groupId, topic: this.topic })- this.redis = createRedisV2PoolFromConfig({- connection:- (overrides.METRICS_REDIS_HOST ?? config.METRICS_REDIS_HOST)- ? {- url: overrides.METRICS_REDIS_HOST ?? config.METRICS_REDIS_HOST,- options: {- port: overrides.METRICS_REDIS_PORT ?? config.METRICS_REDIS_PORT,- tls: (overrides.METRICS_REDIS_TLS ?? config.METRICS_REDIS_TLS) ? {} : undefined,- },- name: 'metrics-redis',- }- : { url: config.REDIS_URL, name: 'metrics-redis-fallback' },- poolMinSize: config.REDIS_POOL_MIN_SIZE,- poolMaxSize: config.REDIS_POOL_MAX_SIZE,- })- this.rateLimiter = new MetricsRateLimiterService(- { ...config, ...overrides } as MetricsIngestionConsumerConfig,- this.redis- )+ this.redis = createMetricsRateLimiterRedis({ ...config, ...overrides })+ this.rateLimiter = new MetricsRateLimiterService({ ...config, ...overrides }, this.redis)}public get service(): PluginServerService {diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-pipeline.test.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-pipeline.test.tsnew file mode 100644index 000000000000..eea4b50ef73d--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-pipeline.test.ts@@ -0,0 +1,220 @@+import { Message } from 'node-rdkafka'++import { KafkaProducerWrapper } from '~/common/kafka/producer'+import { APP_METRICS_OUTPUT, DLQ_OUTPUT } from '~/common/outputs'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'+import { MessageSizeTooLarge } from '~/common/utils/db/error'+import { parseJSON } from '~/common/utils/json-parse'+import { PromiseScheduler } from '~/common/utils/promise-scheduler'+import { createTestTeam } from '~/tests/helpers/team'++import {+ MetricsIngestionPipelineConfig,+ createMetricsIngestionPipeline,+ runMetricsIngestionPipeline,+} from './metrics-ingestion-pipeline'+import { emitMetricsUsage } from './metrics-usage-steps'+import { DEFAULT_METRICS_RETENTION_DAYS, METRICS_OUTPUT } from './outputs/outputs'++jest.mock('~/common/utils/logger', () => ({+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}))++const METRICS_TOPIC = 'clickhouse_metrics_test'+const DLQ_TOPIC = 'metrics_ingestion_dlq_test'+const APP_METRICS_TOPIC = 'clickhouse_app_metrics2_test'++type ProducedMessage = { topic: string; value: Buffer | null; key: unknown; headers?: Record<string, string> }++describe('MetricsIngestionPipeline', () => {+ const teamA = createTestTeam({ id: 1, api_token: 'token-a' })+ const teamB = createTestTeam({ id: 2, api_token: 'token-b' })+ const teamLimited = createTestTeam({ id: 3, api_token: 'token-limited' })+ const teamByToken = new Map([teamA, teamB, teamLimited].map((team) => [team.api_token, team]))++ let mockKafkaProducer: jest.Mocked<KafkaProducerWrapper>+ let promiseScheduler: PromiseScheduler+ let rateLimiter: { filterMessages: jest.Mock }+ let config: MetricsIngestionPipelineConfig+ let offset: number++ const createMessage = (token: string | null, recordCount: number): Message => {+ const headers: Record<string, string> = {+ bytes_uncompressed: String(recordCount * 100),+ record_count: String(recordCount),+ created_at: new Date().toISOString(),+ }+ if (token) {+ headers.token = token+ }+ const messageOffset = offset+++ return {+ value: Buffer.from(`opaque avro packet ${messageOffset}`),+ key: null,+ headers: Object.entries(headers).map(([k, v]) => ({ [k]: Buffer.from(v) })),+ topic: 'metrics_ingestion',+ partition: 0,+ offset: messageOffset,+ size: 0,+ }+ }++ const runPipeline = async (messages: Message[]): Promise<void> => {+ const pipeline = createMetricsIngestionPipeline(config)+ const usage = await runMetricsIngestionPipeline(pipeline, messages)+ await promiseScheduler.waitForAll()+ await emitMetricsUsage(config.outputs, usage)+ }++ const producedTo = (topic: string): ProducedMessage[] =>+ mockKafkaProducer.produce.mock.calls+ .map(([message]) => message as ProducedMessage)+ .filter((message) => message.topic === topic)++ const usageRows = (): [number, string, number][] =>+ mockKafkaProducer.queueMessages.mock.calls+ .map(([arg]) => arg as { topic: string; messages: { value: Buffer }[] })+ .filter((arg) => arg.topic === APP_METRICS_TOPIC)+ .flatMap((arg) => arg.messages.map((m) => parseJSON(m.value.toString())))+ .map(({ team_id, metric_name, count }) => [team_id, metric_name, count])++ beforeEach(() => {+ offset = 0+ mockKafkaProducer = {+ produce: jest.fn().mockResolvedValue(undefined),+ queueMessages: jest.fn().mockResolvedValue(undefined),+ flush: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<KafkaProducerWrapper>++ promiseScheduler = new PromiseScheduler()+ rateLimiter = {+ filterMessages: jest+ .fn()+ .mockImplementation((messages) => Promise.resolve({ allowed: messages, dropped: [] })),+ }++ config = {+ outputs: new IngestionOutputs({+ [METRICS_OUTPUT]: new SingleIngestionOutput(METRICS_OUTPUT, METRICS_TOPIC, mockKafkaProducer, 'test'),+ [DLQ_OUTPUT]: new SingleIngestionOutput(DLQ_OUTPUT, DLQ_TOPIC, mockKafkaProducer, 'test'),+ [APP_METRICS_OUTPUT]: new SingleIngestionOutput(+ APP_METRICS_OUTPUT,+ APP_METRICS_TOPIC,+ mockKafkaProducer,+ 'test'+ ),+ }),+ promiseScheduler,+ teamManager: {+ getTeam: jest.fn().mockResolvedValue(null),+ getTeamByToken: jest+ .fn()+ .mockImplementation((token: string) => Promise.resolve(teamByToken.get(token) ?? null)),+ },+ quotaLimiting: {+ isTeamTokenQuotaLimited: jest+ .fn()+ .mockImplementation((token: string) => Promise.resolve(token === teamLimited.api_token)),+ },+ rateLimiter,+ }+ })++ it('produces each surviving message unchanged and drops the rest silently', async () => {+ const kept = [createMessage(teamA.api_token, 2), createMessage(teamA.api_token, 3)]+ const rateLimited = createMessage(teamA.api_token, 1)+ rateLimiter.filterMessages.mockImplementation((messages: { message: Message }[]) => {+ const dropped = messages.filter((m) => m.message.offset === rateLimited.offset)+ return Promise.resolve({ allowed: messages.filter((m) => !dropped.includes(m)), dropped })+ })++ await runPipeline([+ kept[0],+ createMessage(null, 1),+ createMessage('unknown-token', 1),+ createMessage(teamLimited.api_token, 1),+ rateLimited,+ kept[1],+ ])++ const produced = producedTo(METRICS_TOPIC)+ expect(produced.map((m) => m.value)).toEqual(kept.map((m) => m.value))+ for (const message of produced) {+ expect(message.headers).toMatchObject({+ token: 'token-a',+ team_id: '1',+ 'retention-days': String(DEFAULT_METRICS_RETENTION_DAYS),+ })+ }+ expect(producedTo(DLQ_TOPIC)).toHaveLength(0)++ expect(rateLimiter.filterMessages).toHaveBeenCalledTimes(1)+ expect(rateLimiter.filterMessages.mock.calls[0][0]).toHaveLength(3)+ })++ it('emits one usage row per stat per team', async () => {+ await runPipeline([+ createMessage(teamA.api_token, 2),+ createMessage(teamB.api_token, 1),+ createMessage(teamA.api_token, 1),+ createMessage(teamLimited.api_token, 4),+ ])++ expect(producedTo(METRICS_TOPIC)).toHaveLength(3)+ expect(usageRows().sort()).toEqual(+ [+ [1, 'bytes_received', 300],+ [1, 'records_received', 3],+ [1, 'bytes_ingested', 300],+ [1, 'records_ingested', 3],+ [2, 'bytes_received', 100],+ [2, 'records_received', 1],+ [2, 'bytes_ingested', 100],+ [2, 'records_ingested', 1],+ [3, 'bytes_received', 400],+ [3, 'records_received', 4],+ [3, 'bytes_dropped', 400],+ [3, 'records_dropped', 4],+ ].sort()+ )+ })++ it('finishes the batch before the ClickHouse-bound produce is acked', async () => {+ let ack: () => void = () => {}+ mockKafkaProducer.produce.mockReturnValueOnce(new Promise<void>((resolve) => (ack = resolve)))+ const pipeline = createMetricsIngestionPipeline(config)++ await runMetricsIngestionPipeline(pipeline, [createMessage(teamA.api_token, 2)])++ let drained = false+ const drain = promiseScheduler.waitForAll().then(() => (drained = true))+ await new Promise((resolve) => setImmediate(resolve))+ expect(drained).toBe(false)++ ack()+ await drain+ expect(producedTo(METRICS_TOPIC)).toHaveLength(1)+ })++ it('sends a message whose produce fails permanently to the DLQ and still emits usage', async () => {+ mockKafkaProducer.produce.mockImplementation((message: { topic: string }) =>+ message.topic === METRICS_TOPIC+ ? Promise.reject(new MessageSizeTooLarge('too large', new Error('too large')))+ : Promise.resolve()+ )+ const message = createMessage(teamA.api_token, 2)++ await runPipeline([message])++ const dlq = producedTo(DLQ_TOPIC)+ expect(dlq.map((m) => m.value)).toEqual([message.value])+ expect(dlq[0].headers).toMatchObject({+ token: 'token-a',+ team_id: '1',+ dlq_reason: 'too large',+ dlq_step: 'produceMetricsStep',+ })+ expect(usageRows()).toEqual(expect.arrayContaining([[1, 'bytes_ingested', 200]]))+ })+})diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-pipeline.tsnew file mode 100644index 000000000000..6d87a0a17333--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-pipeline.ts@@ -0,0 +1,92 @@+import { Message } from 'node-rdkafka'++import { AppMetricsOutput, DlqOutput } from '~/common/outputs'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { QuotaLimiting } from '~/common/services/quota-limiting.service'+import { PromiseScheduler } from '~/common/utils/promise-scheduler'+import { TeamManager } from '~/common/utils/team-manager'+import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'+import { newBatchingPipeline } from '~/ingestion/framework/builders'+import { aggregateKafkaDebugContexts, createBatch } from '~/ingestion/framework/helpers'+import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'++import { MetricsUsageAccumulator, MetricsUsageBatchContext } from './metrics-usage'+import { createKeepMetricsUsageStep, createMetricsUsageBeforeBatchStep } from './metrics-usage-steps'+import { MetricsOutput } from './outputs/outputs'+import { createPrepareMetricsMessageStep, perMessage } from './prepare-metrics-message-step'+import { createProduceMetricsStep } from './produce-metrics-step'+import { createRateLimitMetricsStep } from './rate-limit-metrics-step'+import { MetricsRateLimiterService } from './services/metrics-rate-limiter.service'+import { MetricsMessageContext, MetricsPipelineInput } from './types'++export type MetricsIngestionOutputs = IngestionOutputs<MetricsOutput | DlqOutput | AppMetricsOutput>++export interface MetricsIngestionPipelineConfig {+ outputs: MetricsIngestionOutputs+ promiseScheduler: PromiseScheduler+ teamManager: Pick<TeamManager, 'getTeam' | 'getTeamByToken'>+ quotaLimiting: Pick<QuotaLimiting, 'isTeamTokenQuotaLimited'>+ rateLimiter: Pick<MetricsRateLimiterService, 'filterMessages'>+}++export type MetricsIngestionPipeline = BatchingPipeline<+ MetricsPipelineInput,+ void,+ MetricsMessageContext,+ MetricsUsageBatchContext,+ MetricsMessageContext & BatchingContext,+ never+>++export function createMetricsIngestionPipeline(config: MetricsIngestionPipelineConfig): MetricsIngestionPipeline {+ const { outputs, promiseScheduler, teamManager, quotaLimiting, rateLimiter } = config++ const pipelineConfig: PipelineConfig = { outputs, promiseScheduler, rejectOnDlqFailure: true }+ const sideEffects = { await: false }++ return newBatchingPipeline<+ MetricsPipelineInput,+ void,+ MetricsMessageContext,+ MetricsUsageBatchContext,+ MetricsMessageContext,+ never+ >(+ (before) => before.pipe(createMetricsUsageBeforeBatchStep()),+ (batch) =>+ batch+ .messageAware((b) =>+ b+ .pipeChunk(perMessage(createPrepareMetricsMessageStep(teamManager, quotaLimiting)))+ .pipeChunk(createRateLimitMetricsStep(rateLimiter))+ .pipeChunk(perMessage(createProduceMetricsStep(outputs)))+ )+ .handleResults(pipelineConfig)+ .handleSideEffects(promiseScheduler, sideEffects),+ (after) => after.pipe(createKeepMetricsUsageStep()),+ { concurrentBatches: 1 },+ { aggregateDebugContexts: aggregateKafkaDebugContexts }+ )+}++export async function runMetricsIngestionPipeline(+ pipeline: MetricsIngestionPipeline,+ messages: Message[]+): Promise<MetricsUsageAccumulator> {+ if (messages.length === 0) {+ return new MetricsUsageAccumulator()+ }++ const batch = createBatch(messages.map((message) => ({ message })))+ const feedResult = await pipeline.feed(batch, {})+ if (!feedResult.ok) {+ throw new Error(`metrics ingestion pipeline rejected feed: ${feedResult.kind} (${feedResult.reason})`)+ }++ let usage = new MetricsUsageAccumulator()+ let batchResult+ while ((batchResult = await pipeline.next()) !== null) {+ usage = batchResult.batchContext.usage+ }+ return usage+}diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-pipeline-consumer.test.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-pipeline-consumer.test.tsnew file mode 100644index 000000000000..e9e813c81204--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-pipeline-consumer.test.ts@@ -0,0 +1,112 @@+import { Message } from 'node-rdkafka'++import { KafkaConsumerV2 } from '~/common/kafka/consumer/consumer-v2'+import { DependencyUnavailableError, MessageSizeTooLarge } from '~/common/utils/db/error'+import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'+import { createTestTeam } from '~/tests/helpers/team'++import { getDefaultMetricsIngestionConsumerConfig } from './config'+import { MetricsPipelineConsumer, MetricsPipelineConsumerDeps } from './metrics-pipeline-consumer'++jest.mock('~/common/utils/logger', () => ({+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}))+jest.mock('~/common/kafka/consumer/consumer-v2', () => ({+ KafkaConsumerV2: jest.fn().mockImplementation(() => ({+ connect: jest.fn().mockResolvedValue(undefined),+ disconnect: jest.fn().mockResolvedValue(undefined),+ isHealthy: jest.fn().mockReturnValue({ status: 'ok' }),+ })),+}))+jest.mock('./services/metrics-redis', () => ({ createMetricsRateLimiterRedis: jest.fn(() => ({})) }))+jest.mock('./services/metrics-rate-limiter.service', () => ({+ MetricsRateLimiterService: jest.fn().mockImplementation(() => ({+ filterMessages: (messages: unknown[]) => Promise.resolve({ allowed: messages, dropped: [] }),+ })),+}))++describe('MetricsPipelineConsumer', () => {+ const team = createTestTeam({ id: 1, api_token: 'token-a' })+ let outputs: ReturnType<typeof createMockIngestionOutputs>+ let teamManager: { getTeam: jest.Mock; getTeamByToken: jest.Mock }+ let consumer: MetricsPipelineConsumer++ const message: Message = {+ value: Buffer.from('opaque avro packet'),+ key: null,+ headers: [{ token: Buffer.from(team.api_token) }, { record_count: Buffer.from('1') }],+ topic: 'metrics_ingestion',+ partition: 0,+ offset: 0,+ size: 0,+ }++ beforeEach(() => {+ outputs = createMockIngestionOutputs()+ teamManager = { getTeam: jest.fn(), getTeamByToken: jest.fn().mockResolvedValue(team) }+ consumer = new MetricsPipelineConsumer(getDefaultMetricsIngestionConsumerConfig(), {+ teamManager,+ quotaLimiting: { isTeamTokenQuotaLimited: jest.fn().mockResolvedValue(false) },+ outputs,+ } as unknown as MetricsPipelineConsumerDeps)+ })++ it('returns the batch before the produce is acked and settles the background task after it', async () => {+ let ack: () => void = () => {}+ outputs.produce.mockReturnValueOnce(new Promise<void>((resolve) => (ack = resolve)))++ const { backgroundTask } = await consumer.handleKafkaBatch([message])++ let settled = false+ void backgroundTask!.then(() => (settled = true))+ await new Promise((resolve) => setImmediate(resolve))+ expect(settled).toBe(false)++ expect(outputs.queueMessages).not.toHaveBeenCalled()++ ack()+ await backgroundTask+ expect(outputs.produce).toHaveBeenCalledTimes(1)+ expect(outputs.queueMessages).toHaveBeenCalled()+ })++ it('runs on consumer-v2, which stores no offsets when the background task rejects', () => {+ const config = getDefaultMetricsIngestionConsumerConfig()+ expect(KafkaConsumerV2).toHaveBeenCalledWith({+ groupId: config.METRICS_INGESTION_CONSUMER_GROUP_ID,+ topic: config.METRICS_INGESTION_CONSUMER_CONSUME_TOPIC,+ })+ })++ it('rejects the background task when the produce and the DLQ write both fail', async () => {+ const error = new MessageSizeTooLarge('too large', new Error('too large'))+ outputs.produce.mockRejectedValue(error)++ const { backgroundTask } = await consumer.handleKafkaBatch([message])++ await expect(backgroundTask).rejects.toBe(error)+ expect(outputs.produce).toHaveBeenCalledTimes(2)+ expect(outputs.queueMessages).not.toHaveBeenCalled()+ })++ it('rejects the background task when a permanent team lookup error and its DLQ write both fail', async () => {+ teamManager.getTeamByToken.mockRejectedValue(new Error('bad token row'))+ const dlqError = new Error('broker down')+ outputs.produce.mockRejectedValue(dlqError)++ const { backgroundTask } = await consumer.handleKafkaBatch([message])++ await expect(backgroundTask).rejects.toBe(dlqError)+ expect(outputs.produce).toHaveBeenCalledTimes(1)+ expect(outputs.queueMessages).not.toHaveBeenCalled()+ })++ it('fails the batch when the team lookup keeps failing with a retriable error', async () => {+ const error = new DependencyUnavailableError('pg down', 'Postgres', new Error('pg down'))+ teamManager.getTeamByToken.mockRejectedValue(error)++ await expect(consumer.handleKafkaBatch([message])).rejects.toBe(error)+ expect(teamManager.getTeamByToken).toHaveBeenCalledTimes(3)+ expect(outputs.produce).not.toHaveBeenCalled()+ })+})diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-pipeline-consumer.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-pipeline-consumer.tsnew file mode 100644index 000000000000..03f8611d9ac9--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-pipeline-consumer.ts@@ -0,0 +1,135 @@+import { Message } from 'node-rdkafka'++import { KafkaConsumerInterface } from '~/common/kafka/consumer'+import { KafkaConsumerV2 } from '~/common/kafka/consumer/consumer-v2'+import { QuotaLimiting } from '~/common/services/quota-limiting.service'+import { instrumentFn } from '~/common/tracing/tracing-utils'+import { logger } from '~/common/utils/logger'+import { PromiseScheduler } from '~/common/utils/promise-scheduler'+import { TeamManager } from '~/common/utils/team-manager'+import { HealthCheckResult, PluginServerService } from '~/types'++import { MetricsIngestionConsumerConfig } from './config'+import {+ MetricsIngestionOutputs,+ MetricsIngestionPipeline,+ createMetricsIngestionPipeline,+ runMetricsIngestionPipeline,+} from './metrics-ingestion-pipeline'+import { MetricsUsageAccumulator } from './metrics-usage'+import { emitMetricsUsage } from './metrics-usage-steps'+import { MetricsRateLimiterService } from './services/metrics-rate-limiter.service'+import { createMetricsRateLimiterRedis } from './services/metrics-redis'++export interface MetricsPipelineConsumerDeps {+ teamManager: TeamManager+ quotaLimiting: QuotaLimiting+ outputs: MetricsIngestionOutputs+}++/**+ * `PromiseScheduler` drops a promise when it settles. A side effect that rejects+ * before `waitForAll()` would go unnoticed and its offsets would be stored, so+ * this class keeps the first rejection.+ */+class FailureLatchingPromiseScheduler extends PromiseScheduler {+ private failure: { error: unknown } | undefined++ public override schedule(...promises: Promise<unknown>[]): Promise<any> {+ for (const promise of promises) {+ promise.catch((error: unknown) => {+ this.failure ??= { error }+ })+ }+ return super.schedule(...(promises as [Promise<unknown>]))+ }++ public async waitForAllOrFail(): Promise<void> {+ await this.waitForAll()+ if (this.failure) {+ throw this.failure.error+ }+ }+}++export class MetricsPipelineConsumer {+ // Same id as the pre-framework consumer, so health checks keep their name when the flag changes.+ protected name = 'MetricsIngestionConsumer'+ protected kafkaConsumer: KafkaConsumerInterface+ private promiseScheduler: FailureLatchingPromiseScheduler+ private pipeline: MetricsIngestionPipeline+ private outputs: MetricsIngestionOutputs++ constructor(config: MetricsIngestionConsumerConfig, deps: MetricsPipelineConsumerDeps) {+ // consumer-v1 stores a batch's offsets even when its background task rejects,+ // which loses a batch whose DLQ write failed.+ this.kafkaConsumer = new KafkaConsumerV2({+ groupId: config.METRICS_INGESTION_CONSUMER_GROUP_ID,+ topic: config.METRICS_INGESTION_CONSUMER_CONSUME_TOPIC,+ })+ this.outputs = deps.outputs+ this.promiseScheduler = new FailureLatchingPromiseScheduler()+ this.pipeline = createMetricsIngestionPipeline({+ outputs: deps.outputs,+ promiseScheduler: this.promiseScheduler,+ teamManager: deps.teamManager,+ quotaLimiting: deps.quotaLimiting,+ rateLimiter: new MetricsRateLimiterService(config, createMetricsRateLimiterRedis(config)),+ })+ }++ public get service(): PluginServerService {+ return {+ id: this.name,+ onShutdown: async () => await this.stop(),+ healthcheck: () => this.isHealthy(),+ }+ }++ public async start(): Promise<void> {+ await this.kafkaConsumer.connect(async (messages) => {+ logger.info('🔁', `${this.name} - handling batch`, {+ size: messages.length,+ })++ return await instrumentFn('metricsIngestionConsumer.handleEachBatch', async () => {+ return await this.handleKafkaBatch(messages)+ })+ })+ }++ public async handleKafkaBatch(messages: Message[]): Promise<{ backgroundTask?: Promise<unknown> }> {+ let usage: MetricsUsageAccumulator+ try {+ usage = await runMetricsIngestionPipeline(this.pipeline, messages)+ } catch (error) {+ logger.error('❌', `${this.name} - batch processing failed`, {+ error: error instanceof Error ? error.message : String(error),+ size: messages.length,+ })+ // A rejected side effect must not replace the batch error.+ await this.promiseScheduler.waitForAllSettled()+ throw error+ }++ // A failed batch replays, so usage is emitted only after all of its writes succeed.+ return {+ backgroundTask: instrumentFn('metricsIngestionConsumer.awaitScheduledWork', async () => {+ await this.promiseScheduler.waitForAllOrFail()+ await emitMetricsUsage(this.outputs, usage)+ }),+ }+ }++ public async stop(): Promise<void> {+ logger.info('💤', 'Stopping metrics consumer...')+ // A rejected side effect must not skip the disconnect.+ await this.promiseScheduler.waitForAllSettled()+ await this.kafkaConsumer.disconnect()+ logger.info('💤', 'Metrics consumer stopped!')+ }++ public isHealthy(): HealthCheckResult {+ return this.kafkaConsumer.isHealthy()+ }+}diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-retry.test.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-retry.test.tsnew file mode 100644index 000000000000..788bb5864b87--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-retry.test.ts@@ -0,0 +1,93 @@+import { DependencyUnavailableError, MessageSizeTooLarge } from '~/common/utils/db/error'+import { pipelineRetryAttemptsHistogram } from '~/ingestion/framework/metrics'++import { retryAfterFirstFailure } from './metrics-retry'++describe('retryAfterFirstFailure', () => {+ beforeEach(() => {+ jest.useFakeTimers()+ pipelineRetryAttemptsHistogram.reset()+ })+ afterEach(() => jest.useRealTimers())++ const retriable = (): Error => new DependencyUnavailableError('down', 'Kafka', new Error('down'))+ const retryCount = async (outcome: string): Promise<number> => {+ const { values } = await pipelineRetryAttemptsHistogram.get()+ const count = values.find(+ (v) => v.metricName?.endsWith('_count') && v.labels.name === 'test' && v.labels.outcome === outcome+ )+ return count?.value ?? 0+ }++ it('waits the full backoff before each retry, including the first', async () => {+ const fn = jest+ .fn()+ .mockRejectedValueOnce(retriable())+ .mockRejectedValueOnce(retriable())+ .mockResolvedValue('ok')+ const result = retryAfterFirstFailure(fn, { name: 'test', tries: 3, sleepMs: 100, jitter: 0 })++ await jest.advanceTimersByTimeAsync(99)+ expect(fn).toHaveBeenCalledTimes(1)+ await jest.advanceTimersByTimeAsync(1)+ expect(fn).toHaveBeenCalledTimes(2)+ await jest.advanceTimersByTimeAsync(199)+ expect(fn).toHaveBeenCalledTimes(2)+ await jest.advanceTimersByTimeAsync(1)+ await expect(result).resolves.toBe('ok')+ expect(fn).toHaveBeenCalledTimes(3)+ expect(await retryCount('completed')).toBe(1)+ })++ it('retries an error without an isRetriable flag, as librdkafka produce errors are', async () => {+ const fn = jest.fn().mockRejectedValueOnce(new Error('Local: Queue full')).mockResolvedValue('ok')+ const result = retryAfterFirstFailure(fn, { name: 'test', tries: 3, sleepMs: 100 })+ await jest.runAllTimersAsync()+ await expect(result).resolves.toBe('ok')+ expect(fn).toHaveBeenCalledTimes(2)+ })++ it('does not retry an error marked non-retriable', async () => {+ const error = new MessageSizeTooLarge('too large', new Error('too large'))+ const fn = jest.fn().mockRejectedValue(error)+ await expect(retryAfterFirstFailure(fn, { name: 'test', tries: 3, sleepMs: 100 })).rejects.toBe(error)+ expect(fn).toHaveBeenCalledTimes(1)+ expect(await retryCount('non_retriable')).toBe(1)+ })++ it('stops at a non-retriable error after a retriable one', async () => {+ const error = new MessageSizeTooLarge('too large', new Error('too large'))+ const fn = jest.fn().mockRejectedValueOnce(retriable()).mockRejectedValue(error)+ const settled = expect(retryAfterFirstFailure(fn, { name: 'test', tries: 5, sleepMs: 100 })).rejects.toBe(error)+ await jest.runAllTimersAsync()+ await settled+ expect(fn).toHaveBeenCalledTimes(2)+ })++ it('counts the soft deadline from the first attempt', async () => {+ const error = retriable()+ const fn = jest.fn(async () => {+ await new Promise((resolve) => setTimeout(resolve, 1_000))+ throw error+ })+ const settled = expect(+ retryAfterFirstFailure(fn, { name: 'test', tries: 5, sleepMs: 100, softDeadlineMs: 500 })+ ).rejects.toBe(error)+ await jest.runAllTimersAsync()+ await settled+ expect(fn).toHaveBeenCalledTimes(1)+ })++ it('throws the last error when the tries run out and records nothing for a first-try success', async () => {+ await retryAfterFirstFailure(() => Promise.resolve('ok'), { name: 'test', tries: 3 })+ expect(await retryCount('completed')).toBe(0)++ const error = retriable()+ const fn = jest.fn().mockRejectedValue(error)+ const settled = expect(retryAfterFirstFailure(fn, { name: 'test', tries: 3, sleepMs: 100 })).rejects.toBe(error)+ await jest.runAllTimersAsync()+ await settled+ expect(fn).toHaveBeenCalledTimes(3)+ expect(await retryCount('exhausted')).toBe(1)+ })+})diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-retry.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-retry.tsnew file mode 100644index 000000000000..b24b3d6c598a--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-retry.ts@@ -0,0 +1,51 @@+import { RetrySchedule, defaultRetryConfig, retryIfRetriable } from '~/common/utils/retries'+import { pipelineRetryAttemptsHistogram } from '~/ingestion/framework/metrics'++export interface MetricsRetryOptions extends RetrySchedule {+ /** Label in the `ingestion_pipeline_retry_attempts` metric. */+ name: string+}++/**+ * Same retry rule and schedule as `retryIfRetriable`, but the first attempt runs+ * outside the retry loop because the loop and its metric cost more than a call+ * that succeeds at once. `tries` and `softDeadlineMs` include the first attempt.+ * The metric records only calls that failed at least once.+ */+export async function retryAfterFirstFailure<T>(fn: () => Promise<T>, options: MetricsRetryOptions): Promise<T> {+ const { name, ...schedule } = options+ const startedAt = schedule.softDeadlineMs === undefined ? 0 : Date.now()+ let firstError: unknown+ try {+ return await fn()+ } catch (error) {+ firstError = error+ }++ let attempts = 1+ let replayed = false+ const attempt = (): Promise<T> => {+ if (!replayed) {+ replayed = true+ return Promise.reject(firstError)+ }+ attempts+++ return fn()+ }++ try {+ const softDeadlineMs =+ schedule.softDeadlineMs === undefined+ ? undefined+ : Math.max(0, schedule.softDeadlineMs - (Date.now() - startedAt))+ // With zero tries the replayed first error would not reach the caller.+ const tries = Math.max(1, schedule.tries ?? defaultRetryConfig.MAX_RETRIES_DEFAULT)+ const result = await retryIfRetriable(attempt, { ...schedule, tries, softDeadlineMs })+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'completed' }).observe(attempts)+ return result+ } catch (error) {+ const outcome = (error as { isRetriable?: boolean })?.isRetriable === false ? 'non_retriable' : 'exhausted'+ pipelineRetryAttemptsHistogram.labels({ name, outcome }).observe(attempts)+ throw error+ }+}diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-steps.test.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-steps.test.tsnew file mode 100644index 000000000000..3e9d44851a24--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-steps.test.ts@@ -0,0 +1,340 @@+import { Message } from 'node-rdkafka'++import { AppMetricsOutput, DLQ_OUTPUT, DlqOutput } from '~/common/outputs'+import { DependencyUnavailableError, MessageSizeTooLarge } from '~/common/utils/db/error'+import { isDevEnv } from '~/common/utils/env-utils'+import { logger } from '~/common/utils/logger'+import { PipelineResult, isDlqResult, isDropResult, isOkResult } from '~/ingestion/framework/results'+import { createTestMessage } from '~/tests/helpers/kafka-message'+import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'+import { createTestTeam } from '~/tests/helpers/team'++import { createDropQuotaLimitedStep } from './drop-quota-limited-step'+import { recordMetricsIngested } from './ingestion-otel-metrics'+import { metricMessageDlqCounter, metricMessageDroppedCounter } from './metrics'+import { MetricsUsageAccumulator } from './metrics-usage'+import { emitMetricsUsage } from './metrics-usage-steps'+import { DEFAULT_METRICS_RETENTION_DAYS, METRICS_OUTPUT, MetricsOutput } from './outputs/outputs'+import { createParseMetricsHeadersStep } from './parse-metrics-headers-step'+import { createProduceMetricsStep } from './produce-metrics-step'+import { createRateLimitMetricsStep } from './rate-limit-metrics-step'+import { createResolveMetricsTeamStep } from './resolve-metrics-team-step'++jest.mock('~/common/utils/logger', () => ({+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}))+jest.mock('~/common/utils/env-utils', () => ({+ ...jest.requireActual('~/common/utils/env-utils'),+ isDevEnv: jest.fn().mockReturnValue(false),+}))+jest.mock('./ingestion-otel-metrics', () => ({ recordMetricsIngested: jest.fn() }))++function toHeaders(headers: Record<string, string>): Message['headers'] {+ return Object.entries(headers).map(([key, value]) => ({ [key]: Buffer.from(value) }))+}++async function counterValue(+ counter: typeof metricMessageDroppedCounter,+ labels: { reason: string; team_id: string }+): Promise<number> {+ const { values } = await counter.get()+ const match = values.find((v) => v.labels.reason === labels.reason && v.labels.team_id === labels.team_id)+ return match?.value ?? 0+}++function expectDrop(result: PipelineResult<unknown>, reason: string): void {+ expect(isDropResult(result)).toBe(true)+ if (isDropResult(result)) {+ expect(result.reason).toBe(reason)+ }+}++describe('metrics ingestion steps', () => {+ let usage: MetricsUsageAccumulator++ beforeEach(() => {+ jest.clearAllMocks()+ metricMessageDroppedCounter.reset()+ metricMessageDlqCounter.reset()+ usage = new MetricsUsageAccumulator()+ })++ describe('parseMetricsHeadersStep', () => {+ const step = createParseMetricsHeadersStep()++ it('reads token and size headers, defaulting missing sizes to 0', async () => {+ const message = createTestMessage({+ headers: toHeaders({ token: 'tok', bytes_uncompressed: '120', record_count: '3' }),+ })+ const result = await step({ message })+ expect(isOkResult(result)).toBe(true)+ if (isOkResult(result)) {+ expect(result.value).toMatchObject({+ kafkaHeaders: { token: 'tok', bytes_uncompressed: '120', record_count: '3' },+ token: 'tok',+ bytesUncompressed: 120,+ bytesCompressed: 0,+ recordCount: 3,+ })+ }+ })++ it.each([+ ['missing_token', toHeaders({ bytes_uncompressed: '10' })],+ ['parse_error', [{ token: null as unknown as Buffer }]],+ ])('drops with %s and counts it against team "unknown"', async (reason, headers) => {+ const result = await step({ message: createTestMessage({ headers }) })+ expectDrop(result, reason)+ expect(await counterValue(metricMessageDroppedCounter, { reason, team_id: 'unknown' })).toBe(1)+ })++ it.each([['abc'], ['12abc'], ['-5'], ['1.5'], ['']])(+ 'drops a message with size header %p instead of poisoning the usage counters',+ async (value) => {+ const result = await step({+ message: createTestMessage({ headers: toHeaders({ token: 'tok', record_count: value }) }),+ })+ expectDrop(result, 'invalid_size_header')+ expect(+ await counterValue(metricMessageDroppedCounter, {+ reason: 'invalid_size_header',+ team_id: 'unknown',+ })+ ).toBe(1)+ }+ )+ })++ describe('resolveMetricsTeamStep', () => {+ const teamManager = { getTeam: jest.fn(), getTeamByToken: jest.fn() }+ const step = createResolveMetricsTeamStep(teamManager)++ it('drops an unknown token', async () => {+ teamManager.getTeamByToken.mockResolvedValueOnce(null)+ const result = await step({ token: 'tok' })+ expectDrop(result, 'team_not_found')+ expect(+ await counterValue(metricMessageDroppedCounter, { reason: 'team_not_found', team_id: 'unknown' })+ ).toBe(1)+ })++ it('sends a failed lookup to the DLQ so the message stays replayable', async () => {+ teamManager.getTeamByToken.mockRejectedValueOnce(new Error('pg down'))+ const result = await step({ token: 'tok' })+ expect(isDlqResult(result) && result.reason).toBe('team_lookup_error')+ expect(+ await counterValue(metricMessageDlqCounter, { reason: 'team_lookup_error', team_id: 'unknown' })+ ).toBe(1)+ })++ it('rethrows a retriable lookup error so the pipeline retries it and the batch replays', async () => {+ const error = new DependencyUnavailableError('pg down', 'Postgres', new Error('pg down'))+ teamManager.getTeamByToken.mockRejectedValueOnce(error)+ await expect(step({ token: 'tok' })).rejects.toBe(error)+ expect(+ await counterValue(metricMessageDlqCounter, { reason: 'team_lookup_error', team_id: 'unknown' })+ ).toBe(0)+ })++ it('maps phc_local to team 1 only in dev', async () => {+ jest.mocked(isDevEnv).mockReturnValueOnce(true)+ teamManager.getTeam.mockResolvedValueOnce(createTestTeam({ id: 1 }))+ const result = await step({ token: 'phc_local' })+ expect(isOkResult(result) && result.value.teamId).toBe(1)+ expect(teamManager.getTeam).toHaveBeenCalledWith(1)+ expect(teamManager.getTeamByToken).not.toHaveBeenCalled()+ })+ })++ describe('dropQuotaLimitedStep', () => {+ const quotaLimiting = { isTeamTokenQuotaLimited: jest.fn() }+ const step = createDropQuotaLimitedStep(quotaLimiting)+ const input = { token: 'tok', teamId: 7, bytesUncompressed: 500, recordCount: 4 }++ it('drops a quota-limited team and records the drop as usage', async () => {+ quotaLimiting.isTeamTokenQuotaLimited.mockResolvedValueOnce(true)+ const result = await step({ ...input, usage })+ expectDrop(result, 'quota_limited')+ expect(quotaLimiting.isTeamTokenQuotaLimited).toHaveBeenCalledWith('tok', 'metrics_mb_ingested')+ expect([...usage.entries()]).toEqual([+ [7, expect.objectContaining({ bytesDropped: 500, recordsDropped: 4 })],+ ])+ expect(await counterValue(metricMessageDroppedCounter, { reason: 'quota_limited', team_id: '7' })).toBe(1)+ })+ })++ describe('rateLimitMetricsStep', () => {+ const makeValue = (teamId: number, bytesUncompressed: number) => ({+ token: `tok-${teamId}`,+ teamId,+ message: createTestMessage(),+ bytesUncompressed,+ bytesCompressed: 0,+ recordCount: 1,+ usage,+ })++ it('returns one result per input in input order, dropping what the limiter dropped', async () => {+ const values = [makeValue(1, 100), makeValue(1, 200), makeValue(2, 300)]+ const rateLimiter = {+ filterMessages: jest.fn().mockResolvedValue({ allowed: [values[0], values[2]], dropped: [values[1]] }),+ }+ const results = await createRateLimitMetricsStep(rateLimiter)(values)++ expect(results).toHaveLength(3)+ expect(isOkResult(results[0]) && results[0].value).toBe(values[0])+ expectDrop(results[1], 'rate_limited')+ expect(isOkResult(results[2]) && results[2].value).toBe(values[2])+ expect(rateLimiter.filterMessages).toHaveBeenCalledTimes(1)+ expect(new Map(usage.entries())).toEqual(+ new Map([+ [+ 1,+ expect.objectContaining({+ bytesAllowed: 100,+ recordsAllowed: 1,+ bytesDropped: 200,+ recordsDropped: 1,+ }),+ ],+ [2, expect.objectContaining({ bytesAllowed: 300, recordsAllowed: 1 })],+ ])+ )+ expect(await counterValue(metricMessageDroppedCounter, { reason: 'rate_limited', team_id: '1' })).toBe(1)+ })+ })++ describe('produceMetricsStep', () => {+ let outputs: jest.Mocked<ReturnType<typeof createMockIngestionOutputs<MetricsOutput | DlqOutput>>>+ const value = Buffer.from('opaque avro packet')+ const kafkaHeaders = { token: 'tok', record_count: '3', 'retention-days': '7', batch_uuid: 'b1' }+ const input = {+ message: createTestMessage({ value, headers: toHeaders(kafkaHeaders) }),+ kafkaHeaders,+ token: 'tok',+ teamId: 7,+ bytesUncompressed: 300,+ recordCount: 3,+ }++ const runStep = async (): Promise<{ result: PipelineResult<void>; sideEffect: Promise<unknown> }> => {+ const result = await createProduceMetricsStep(outputs)(input)+ expect(isOkResult(result)).toBe(true)+ expect(result.sideEffects).toHaveLength(1)+ return { result, sideEffect: result.sideEffects[0] }+ }++ beforeEach(() => {+ outputs = createMockIngestionOutputs<MetricsOutput | DlqOutput>()+ })++ it('produces the packet unchanged with the ClickHouse headers as a side effect', async () => {+ const { sideEffect } = await runStep()+ await sideEffect++ expect(outputs.produce).toHaveBeenCalledWith(METRICS_OUTPUT, {+ value,+ key: null,+ headers: {+ token: 'tok',+ team_id: '7',+ record_count: '3',+ 'retention-days': String(DEFAULT_METRICS_RETENTION_DAYS),+ batch_uuid: 'b1',+ },+ })+ expect(recordMetricsIngested).toHaveBeenCalledWith(7, 300, 3)+ })++ it('returns before the ack and credits the message only after it', async () => {+ let ack: () => void = () => {}+ outputs.produce.mockReturnValueOnce(new Promise<void>((resolve) => (ack = resolve)))++ const { sideEffect } = await runStep()+ expect(recordMetricsIngested).not.toHaveBeenCalled()++ ack()+ await sideEffect+ expect(recordMetricsIngested).toHaveBeenCalledWith(7, 300, 3)+ })++ it('sends a non-retriable failure to the DLQ with the team headers and does not credit it', async () => {+ outputs.produce.mockImplementation((output) =>+ output === METRICS_OUTPUT+ ? Promise.reject(new MessageSizeTooLarge('too large', new Error('too large')))+ : Promise.resolve()+ )+ const { sideEffect } = await runStep()+ await sideEffect++ expect(outputs.produce).toHaveBeenCalledTimes(2)+ expect(outputs.produce).toHaveBeenLastCalledWith(+ DLQ_OUTPUT,+ expect.objectContaining({+ value,+ headers: expect.objectContaining({+ token: 'tok',+ team_id: '7',+ dlq_reason: 'too large',+ dlq_step: 'produceMetricsStep',+ }),+ })+ )+ expect(recordMetricsIngested).not.toHaveBeenCalled()+ expect(await counterValue(metricMessageDlqCounter, { reason: 'MessageSizeTooLarge', team_id: '7' })).toBe(1)+ })++ it('retries a retriable failure and sends the message to the DLQ when the retries run out', async () => {+ jest.useFakeTimers()+ try {+ const error = new DependencyUnavailableError('broker down', 'Kafka', new Error('broker down'))+ outputs.produce.mockImplementation((output) =>+ output === METRICS_OUTPUT ? Promise.reject(error) : Promise.resolve()+ )++ const { sideEffect } = await runStep()+ await jest.runAllTimersAsync()+ await expect(sideEffect).resolves.toBeUndefined()++ const metricsProduces = outputs.produce.mock.calls.filter(([output]) => output === METRICS_OUTPUT)+ expect(metricsProduces).toHaveLength(5)+ expect(outputs.produce).toHaveBeenLastCalledWith(+ DLQ_OUTPUT,+ expect.objectContaining({ headers: expect.objectContaining({ team_id: '7' }) })+ )+ expect(recordMetricsIngested).not.toHaveBeenCalled()+ } finally {+ jest.useRealTimers()+ }+ })++ it('drops a message with no value', async () => {+ const result = await createProduceMetricsStep(outputs)({+ ...input,+ message: createTestMessage({ value: null }),+ })+ expectDrop(result, 'null_value')+ expect(outputs.produce).not.toHaveBeenCalled()+ })+ })++ describe('emitMetricsUsage', () => {+ let outputs: jest.Mocked<ReturnType<typeof createMockIngestionOutputs<AppMetricsOutput>>>++ beforeEach(() => {+ outputs = createMockIngestionOutputs<AppMetricsOutput>()+ })++ it('logs and resolves when the usage produce fails', async () => {+ usage.recordReceived(1, 100, 2)+ outputs.queueMessages.mockRejectedValueOnce(new Error('broker down'))++ await expect(emitMetricsUsage(outputs, usage)).resolves.toBeUndefined()+ expect(logger.error).toHaveBeenCalledWith(+ '🔴',+ 'Failed to emit usage metrics - billing data may be lost',+ expect.anything()+ )+ })+ })+})diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-usage-steps.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-usage-steps.tsnew file mode 100644index 000000000000..52ba8db1e188--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-usage-steps.ts@@ -0,0 +1,128 @@+import { AppMetricsOutput } from '~/common/outputs'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'+import { logger } from '~/common/utils/logger'+import { BeforeBatchStep } from '~/ingestion/framework/batching-pipeline'+import { ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import {+ metricsBytesAllowedCounter,+ metricsBytesDroppedCounter,+ metricsBytesReceivedCounter,+ metricsRecordsAllowedCounter,+ metricsRecordsDroppedCounter,+ metricsRecordsReceivedCounter,+} from './metrics'+import { MetricsUsageAccumulator, MetricsUsageBatchContext, UsageStats } from './metrics-usage'++export function createMetricsUsageBeforeBatchStep<TInput, CInput, CBatch>(): BeforeBatchStep<+ TInput,+ CInput,+ CBatch,+ CBatch & MetricsUsageBatchContext+> {+ return function metricsUsageBeforeBatchStep(input) {+ return Promise.resolve(+ ok({+ elements: input.elements,+ batchContext: { ...input.batchContext, usage: new MetricsUsageAccumulator() },+ })+ )+ }+}++export interface RecordMetricsReceivedInput {+ teamId: number+ bytesUncompressed: number+ recordCount: number+ usage: MetricsUsageAccumulator+}++export function createRecordMetricsReceivedStep<T extends RecordMetricsReceivedInput>(): ProcessingStep<T, T> {+ return function recordMetricsReceivedStep(input) {+ input.usage.recordReceived(input.teamId, input.bytesUncompressed, input.recordCount)+ return Promise.resolve(ok(input))+ }+}++const USAGE_METRIC_NAMES: [keyof UsageStats, string][] = [+ ['bytesReceived', 'bytes_received'],+ ['recordsReceived', 'records_received'],+ ['bytesAllowed', 'bytes_ingested'],+ ['recordsAllowed', 'records_ingested'],+ ['bytesDropped', 'bytes_dropped'],+ ['recordsDropped', 'records_dropped'],+]++function incrementUsageCounters(usage: MetricsUsageAccumulator): void {+ let bytesReceived = 0+ let recordsReceived = 0+ let bytesAllowed = 0+ let recordsAllowed = 0+ for (const [teamId, stats] of usage.entries()) {+ bytesReceived += stats.bytesReceived+ recordsReceived += stats.recordsReceived+ bytesAllowed += stats.bytesAllowed+ recordsAllowed += stats.recordsAllowed+ const teamIdLabel = teamId.toString()+ if (stats.bytesDropped > 0) {+ metricsBytesDroppedCounter.inc({ team_id: teamIdLabel }, stats.bytesDropped)+ }+ if (stats.recordsDropped > 0) {+ metricsRecordsDroppedCounter.inc({ team_id: teamIdLabel }, stats.recordsDropped)+ }+ }+ metricsBytesReceivedCounter.inc(bytesReceived)+ metricsRecordsReceivedCounter.inc(recordsReceived)+ metricsBytesAllowedCounter.inc(bytesAllowed)+ metricsRecordsAllowedCounter.inc(recordsAllowed)+}++async function emitUsageRows(+ outputs: IngestionOutputs<AppMetricsOutput>,+ usage: MetricsUsageAccumulator+): Promise<void> {+ const aggregator = new AppMetricsAggregator(outputs)+ for (const [teamId, stats] of usage.entries()) {+ for (const [statKey, metricName] of USAGE_METRIC_NAMES) {+ const count = stats[statKey]+ if (count === 0) {+ continue+ }+ aggregator.queue({+ team_id: teamId,+ app_source: 'metrics',+ app_source_id: '',+ instance_id: '',+ metric_kind: 'usage',+ metric_name: metricName,+ count,+ })+ }+ }++ try {+ await aggregator.flush()+ } catch (error) {+ logger.error('🔴', 'Failed to emit usage metrics - billing data may be lost', { error })+ }+}++/** Never rejects. A failed write of the billing rows is logged. */+export async function emitMetricsUsage(+ outputs: IngestionOutputs<AppMetricsOutput>,+ usage: MetricsUsageAccumulator+): Promise<void> {+ incrementUsageCounters(usage)+ await emitUsageRows(outputs, usage)+}++export function createKeepMetricsUsageStep<T extends { batchContext: MetricsUsageBatchContext }>(): ProcessingStep<+ T,+ T+> {+ return function keepMetricsUsageStep(input) {+ return Promise.resolve(ok(input))+ }+}diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-usage.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-usage.tsnew file mode 100644index 000000000000..1c173da4bdad--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-usage.ts@@ -0,0 +1,58 @@+export type UsageStats = {+ bytesReceived: number+ recordsReceived: number+ bytesAllowed: number+ recordsAllowed: number+ bytesDropped: number+ recordsDropped: number+}++export const DEFAULT_USAGE_STATS: UsageStats = {+ bytesReceived: 0,+ recordsReceived: 0,+ bytesAllowed: 0,+ recordsAllowed: 0,+ bytesDropped: 0,+ recordsDropped: 0,+}++export type UsageStatsByTeam = Map<number, UsageStats>++export class MetricsUsageAccumulator {+ private readonly stats: UsageStatsByTeam = new Map()++ recordReceived(teamId: number, bytes: number, records: number): void {+ const stats = this.statsFor(teamId)+ stats.bytesReceived += bytes+ stats.recordsReceived += records+ }++ recordAllowed(teamId: number, bytes: number, records: number): void {+ const stats = this.statsFor(teamId)+ stats.bytesAllowed += bytes+ stats.recordsAllowed += records+ }++ recordDropped(teamId: number, bytes: number, records: number): void {+ const stats = this.statsFor(teamId)+ stats.bytesDropped += bytes+ stats.recordsDropped += records+ }++ entries(): IterableIterator<[number, UsageStats]> {+ return this.stats.entries()+ }++ private statsFor(teamId: number): UsageStats {+ let stats = this.stats.get(teamId)+ if (!stats) {+ stats = { ...DEFAULT_USAGE_STATS }+ this.stats.set(teamId, stats)+ }+ return stats+ }+}++export interface MetricsUsageBatchContext {+ usage: MetricsUsageAccumulator+}diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics.ts b/nodejs/src/ingestion/pipelines/metrics/metrics.tsnew file mode 100644index 000000000000..3aca7e199fc2--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/metrics.ts@@ -0,0 +1,45 @@+import { Counter } from 'prom-client'++export const metricMessageDroppedCounter = new Counter({+ name: 'metrics_ingestion_message_dropped_count',+ help: 'The number of metrics ingestion messages dropped',+ labelNames: ['reason', 'team_id'],+})++export const metricMessageDlqCounter = new Counter({+ name: 'metrics_ingestion_message_dlq_count',+ help: 'The number of metrics ingestion messages sent to DLQ',+ labelNames: ['reason', 'team_id'],+})++export const metricsBytesReceivedCounter = new Counter({+ name: 'metrics_ingestion_bytes_received_total',+ help: 'Total uncompressed bytes received for metrics ingestion',+})++export const metricsBytesAllowedCounter = new Counter({+ name: 'metrics_ingestion_bytes_allowed_total',+ help: 'Total uncompressed bytes allowed through quota and rate limiting',+})++export const metricsBytesDroppedCounter = new Counter({+ name: 'metrics_ingestion_bytes_dropped_total',+ help: 'Total uncompressed bytes dropped due to quota or rate limiting',+ labelNames: ['team_id'],+})++export const metricsRecordsReceivedCounter = new Counter({+ name: 'metrics_ingestion_records_received_total',+ help: 'Total metric records received',+})++export const metricsRecordsAllowedCounter = new Counter({+ name: 'metrics_ingestion_records_allowed_total',+ help: 'Total metric records allowed through quota and rate limiting',+})++export const metricsRecordsDroppedCounter = new Counter({+ name: 'metrics_ingestion_records_dropped_total',+ help: 'Total metric records dropped due to quota or rate limiting',+ labelNames: ['team_id'],+})diff --git a/nodejs/src/ingestion/pipelines/metrics/outputs/outputs.ts b/nodejs/src/ingestion/pipelines/metrics/outputs/outputs.tsindex 300c18e4c641..a09c3d0a14fa 100644--- a/nodejs/src/ingestion/pipelines/metrics/outputs/outputs.ts+++ b/nodejs/src/ingestion/pipelines/metrics/outputs/outputs.ts@@ -5,5 +5,9 @@export const METRICS_OUTPUT = 'metrics' as constexport type MetricsOutput = typeof METRICS_OUTPUT+/** Used only by the pre-framework consumer. */export const METRICS_DLQ_OUTPUT = 'metrics_dlq' as constexport type MetricsDlqOutput = typeof METRICS_DLQ_OUTPUT++/** Metrics has no per-team retention setting. ClickHouse applies its own default only when the `retention-days` header is missing. */+export const DEFAULT_METRICS_RETENTION_DAYS = 30diff --git a/nodejs/src/ingestion/pipelines/metrics/outputs/registry.ts b/nodejs/src/ingestion/pipelines/metrics/outputs/registry.tsindex 5dd44522adb0..5fb62c1f761f 100644--- a/nodejs/src/ingestion/pipelines/metrics/outputs/registry.ts+++ b/nodejs/src/ingestion/pipelines/metrics/outputs/registry.ts@@ -1,4 +1,4 @@-import { APP_METRICS_OUTPUT } from '~/common/outputs'+import { APP_METRICS_OUTPUT, DLQ_OUTPUT } from '~/common/outputs'import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'import { METRICS_DLQ_OUTPUT, METRICS_OUTPUT } from './outputs'@@ -7,7 +7,8 @@ import { METRICS_DLQ_OUTPUT, METRICS_OUTPUT } from './outputs'* Outputs for the metrics ingestion deployment.** - `METRICS_OUTPUT` — main metrics data path → topic from `METRICS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC`.- * - `METRICS_DLQ_OUTPUT` — DLQ for failed messages → topic from `METRICS_INGESTION_CONSUMER_DLQ_TOPIC`.+ * - `DLQ_OUTPUT` — DLQ for failed messages → topic from `METRICS_INGESTION_CONSUMER_DLQ_TOPIC`.+ * - `METRICS_DLQ_OUTPUT` — the same topic, for the pre-framework consumer.* - `APP_METRICS_OUTPUT` — usage metrics → topic from `METRICS_INGESTION_OUTPUT_APP_METRICS_TOPIC`.** Per-output producer is env-controlled (`*_PRODUCER` keys) so the route can be@@ -23,6 +24,10 @@ export function createMetricsOutputsRegistry() {topicKey: 'METRICS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC',producerKey: 'METRICS_INGESTION_OUTPUT_METRICS_PRODUCER',})+ .register(DLQ_OUTPUT, {+ topicKey: 'METRICS_INGESTION_CONSUMER_DLQ_TOPIC',+ producerKey: 'METRICS_INGESTION_OUTPUT_DLQ_PRODUCER',+ }).register(METRICS_DLQ_OUTPUT, {topicKey: 'METRICS_INGESTION_CONSUMER_DLQ_TOPIC',producerKey: 'METRICS_INGESTION_OUTPUT_DLQ_PRODUCER',diff --git a/nodejs/src/ingestion/pipelines/metrics/parse-metrics-headers-step.ts b/nodejs/src/ingestion/pipelines/metrics/parse-metrics-headers-step.tsnew file mode 100644index 000000000000..1be329a97fba--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/parse-metrics-headers-step.ts@@ -0,0 +1,60 @@+import { Message } from 'node-rdkafka'++import { parseKafkaHeaders } from '~/common/kafka/consumer'+import { logger } from '~/common/utils/logger'+import { drop, ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import { metricMessageDroppedCounter } from './metrics'++export interface MetricsHeaders {+ kafkaHeaders: Record<string, string>+ token: string+ bytesUncompressed: number+ bytesCompressed: number+ recordCount: number+}++const SIZE_HEADERS = ['bytes_uncompressed', 'bytes_compressed', 'record_count'] as const++/** A missing header counts as 0. A negative value makes the Prometheus counters throw, so only non-negative safe integers are valid. */+function parseSizeHeader(value: string | undefined): number | null {+ if (value === undefined) {+ return 0+ }+ if (!/^\d+$/.test(value)) {+ return null+ }+ const parsed = Number(value)+ return Number.isSafeInteger(parsed) ? parsed : null+}++export function createParseMetricsHeadersStep<T extends { message: Message }>(): ProcessingStep<T, T & MetricsHeaders> {+ return function parseMetricsHeadersStep(input) {+ try {+ const headers = parseKafkaHeaders(input.message.headers)+ const token = headers.token+ if (!token) {+ logger.error('missing_token')+ metricMessageDroppedCounter.inc({ reason: 'missing_token', team_id: 'unknown' })+ return Promise.resolve(drop('missing_token'))+ }+ const [bytesUncompressed, bytesCompressed, recordCount] = SIZE_HEADERS.map((name) =>+ parseSizeHeader(headers[name])+ )+ if (bytesUncompressed === null || bytesCompressed === null || recordCount === null) {+ const invalid = SIZE_HEADERS.filter((name) => parseSizeHeader(headers[name]) === null)+ logger.error('invalid_size_header', { headers: invalid })+ metricMessageDroppedCounter.inc({ reason: 'invalid_size_header', team_id: 'unknown' })+ return Promise.resolve(drop('invalid_size_header'))+ }+ return Promise.resolve(+ ok({ ...input, kafkaHeaders: headers, token, bytesUncompressed, bytesCompressed, recordCount })+ )+ } catch (e) {+ logger.error('Error parsing message', e)+ metricMessageDroppedCounter.inc({ reason: 'parse_error', team_id: 'unknown' })+ return Promise.resolve(drop('parse_error'))+ }+ }+}diff --git a/nodejs/src/ingestion/pipelines/metrics/prepare-metrics-message-step.ts b/nodejs/src/ingestion/pipelines/metrics/prepare-metrics-message-step.tsnew file mode 100644index 000000000000..8a5d6571841a--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/prepare-metrics-message-step.ts@@ -0,0 +1,51 @@+import { Message } from 'node-rdkafka'++import { QuotaLimiting } from '~/common/services/quota-limiting.service'+import { TeamManager } from '~/common/utils/team-manager'+import { ChunkProcessingStep } from '~/ingestion/framework/builders'+import { isOkResult } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import { createDropQuotaLimitedStep } from './drop-quota-limited-step'+import { retryAfterFirstFailure } from './metrics-retry'+import { MetricsUsageAccumulator } from './metrics-usage'+import { createRecordMetricsReceivedStep } from './metrics-usage-steps'+import { MetricsHeaders, createParseMetricsHeadersStep } from './parse-metrics-headers-step'+import { createResolveMetricsTeamStep } from './resolve-metrics-team-step'++const RESOLVE_TEAM_RETRY = { tries: 3, sleepMs: 100, name: 'resolve_metrics_team' }++/** The framework instruments a chunk step once per chunk, and per-message instrumentation costs more than reading the headers. */+export function perMessage<T, U, R extends string = never>(+ step: ProcessingStep<T, U, R>+): ChunkProcessingStep<T, U, R> {+ const chunkStep: ChunkProcessingStep<T, U, R> = (values) => Promise.all(values.map((value) => step(value)))+ Object.defineProperty(chunkStep, 'name', { value: step.name })+ return chunkStep+}++export function createPrepareMetricsMessageStep<T extends { message: Message; usage: MetricsUsageAccumulator }>(+ teamManager: Pick<TeamManager, 'getTeam' | 'getTeamByToken'>,+ quotaLimiting: Pick<QuotaLimiting, 'isTeamTokenQuotaLimited'>+): ProcessingStep<T, T & MetricsHeaders & { teamId: number }> {+ const parseHeaders = createParseMetricsHeadersStep<T>()+ const resolveTeam = createResolveMetricsTeamStep<T & MetricsHeaders>(teamManager)+ const recordReceived = createRecordMetricsReceivedStep<T & MetricsHeaders & { teamId: number }>()+ const dropQuotaLimited = createDropQuotaLimitedStep<T & MetricsHeaders & { teamId: number }>(quotaLimiting)++ return async function prepareMetricsMessageStep(input) {+ const parsed = await parseHeaders(input)+ if (!isOkResult(parsed)) {+ return parsed+ }+ const resolved = await retryAfterFirstFailure(() => resolveTeam(parsed.value), RESOLVE_TEAM_RETRY)+ if (!isOkResult(resolved)) {+ return resolved+ }+ const received = await recordReceived(resolved.value)+ if (!isOkResult(received)) {+ return received+ }+ return await dropQuotaLimited(received.value)+ }+}diff --git a/nodejs/src/ingestion/pipelines/metrics/produce-metrics-step.ts b/nodejs/src/ingestion/pipelines/metrics/produce-metrics-step.tsnew file mode 100644index 000000000000..b36a61fd7669--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/produce-metrics-step.ts@@ -0,0 +1,75 @@+import { Message } from 'node-rdkafka'++import { DlqOutput } from '~/common/outputs'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { produceMessageToDLQ } from '~/ingestion/framework/result-handling-helpers'+import { drop, ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import { recordMetricsIngested } from './ingestion-otel-metrics'+import { metricMessageDlqCounter, metricMessageDroppedCounter } from './metrics'+import { retryAfterFirstFailure } from './metrics-retry'+import { DEFAULT_METRICS_RETENTION_DAYS, METRICS_OUTPUT, MetricsOutput } from './outputs/outputs'++export interface ProduceMetricsInput {+ message: Message+ kafkaHeaders: Record<string, string>+ token: string+ teamId: number+ bytesUncompressed: number+ recordCount: number+}++// A delivery timeout already includes librdkafka's retries. The deadline stops more attempts after a slow failure.+const PRODUCE_RETRY = { tries: 5, sleepMs: 100, softDeadlineMs: 10_000, name: 'produce_metrics' }++/**+ * A message that still fails after the retries goes to the DLQ. If the DLQ+ * write also fails, the side effect rejects and `MetricsPipelineConsumer`+ * replays the batch.+ */+export function createProduceMetricsStep<T extends ProduceMetricsInput>(+ outputs: IngestionOutputs<MetricsOutput | DlqOutput>+): ProcessingStep<T, void> {+ return function produceMetricsStep(input) {+ const value = input.message.value+ const teamIdLabel = input.teamId.toString()+ if (value === null) {+ metricMessageDroppedCounter.inc({ reason: 'null_value', team_id: teamIdLabel })+ return Promise.resolve(drop('null_value'))+ }++ const headers = { token: input.token, team_id: teamIdLabel }+ const produced = retryAfterFirstFailure(+ () =>+ outputs.produce(METRICS_OUTPUT, {+ value,+ key: null,+ headers: {+ ...input.kafkaHeaders,+ ...headers,+ 'retention-days': DEFAULT_METRICS_RETENTION_DAYS.toString(),+ },+ }),+ PRODUCE_RETRY+ ).then(+ () => recordMetricsIngested(input.teamId, input.bytesUncompressed, input.recordCount),+ async (error) => {+ const errorName = error instanceof Error ? error.name : 'UnknownError'+ metricMessageDlqCounter.inc({ reason: errorName, team_id: teamIdLabel })+ const dlqMessage = {+ ...input.message,+ headers: [+ ...(input.message.headers ?? []),+ ...Object.entries(headers).map(([k, v]) => ({ [k]: v })),+ ],+ }+ await produceMessageToDLQ(outputs, dlqMessage, error, 'produceMetricsStep', {+ rethrowOnFailure: true,+ })+ }+ )++ return Promise.resolve(ok(undefined, [produced]))+ }+}diff --git a/nodejs/src/ingestion/pipelines/metrics/rate-limit-metrics-step.ts b/nodejs/src/ingestion/pipelines/metrics/rate-limit-metrics-step.tsnew file mode 100644index 000000000000..8acf2f654654--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/rate-limit-metrics-step.ts@@ -0,0 +1,27 @@+import { ChunkProcessingStep } from '~/ingestion/framework/builders'+import { drop, ok } from '~/ingestion/framework/results'++import { metricMessageDroppedCounter } from './metrics'+import { MetricsUsageAccumulator } from './metrics-usage'+import { MetricsRateLimiterService } from './services/metrics-rate-limiter.service'+import { MetricsIngestionMessage } from './types'++/** Allowed usage is recorded here, before the produce, so a message that later goes to the DLQ is still billed. */+export function createRateLimitMetricsStep<T extends MetricsIngestionMessage & { usage: MetricsUsageAccumulator }>(+ rateLimiter: Pick<MetricsRateLimiterService, 'filterMessages'>+): ChunkProcessingStep<T, T> {+ return async function rateLimitMetricsStep(values) {+ const { dropped } = await rateLimiter.filterMessages(values)+ const droppedSet = new Set<T>(dropped)++ return values.map((value) => {+ if (droppedSet.has(value)) {+ value.usage.recordDropped(value.teamId, value.bytesUncompressed, value.recordCount)+ metricMessageDroppedCounter.inc({ reason: 'rate_limited', team_id: value.teamId.toString() })+ return drop<T>('rate_limited')+ }+ value.usage.recordAllowed(value.teamId, value.bytesUncompressed, value.recordCount)+ return ok(value)+ })+ }+}diff --git a/nodejs/src/ingestion/pipelines/metrics/resolve-metrics-team-step.ts b/nodejs/src/ingestion/pipelines/metrics/resolve-metrics-team-step.tsnew file mode 100644index 000000000000..ae8d14a507ae--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/resolve-metrics-team-step.ts@@ -0,0 +1,38 @@+import { isDevEnv } from '~/common/utils/env-utils'+import { logger } from '~/common/utils/logger'+import { TeamManager } from '~/common/utils/team-manager'+import { dlq, drop, ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import { metricMessageDlqCounter, metricMessageDroppedCounter } from './metrics'++export function createResolveMetricsTeamStep<T extends { token: string }>(+ teamManager: Pick<TeamManager, 'getTeam' | 'getTeamByToken'>+): ProcessingStep<T, T & { teamId: number }> {+ return async function resolveMetricsTeamStep(input) {+ let team+ try {+ if (input.token === 'phc_local' && isDevEnv()) {+ team = await teamManager.getTeam(1)+ } else {+ team = await teamManager.getTeamByToken(input.token)+ }+ } catch (e) {+ // Throw so the step retry runs. If the retries fail, the batch fails and replays.+ if ((e as { isRetriable?: boolean })?.isRetriable === true) {+ throw e+ }+ logger.error('team_lookup_error', { error: e })+ metricMessageDlqCounter.inc({ reason: 'team_lookup_error', team_id: 'unknown' })+ return dlq('team_lookup_error', e)+ }++ if (!team) {+ logger.error('team_not_found', { token_with_no_team: input.token })+ metricMessageDroppedCounter.inc({ reason: 'team_not_found', team_id: 'unknown' })+ return drop('team_not_found')+ }++ return ok({ ...input, teamId: team.id })+ }+}diff --git a/nodejs/src/ingestion/pipelines/metrics/services/metrics-rate-limiter.service.ts b/nodejs/src/ingestion/pipelines/metrics/services/metrics-rate-limiter.service.tsindex 3a1cd1d792e9..b2a2a3362e9a 100644--- a/nodejs/src/ingestion/pipelines/metrics/services/metrics-rate-limiter.service.ts+++ b/nodejs/src/ingestion/pipelines/metrics/services/metrics-rate-limiter.service.ts@@ -34,9 +34,9 @@ export type MetricsRateLimit = {isRateLimited: boolean}-export type FilteredMessages = {- allowed: MetricsIngestionMessage[]- dropped: MetricsIngestionMessage[]+export type FilteredMessages<T extends MetricsIngestionMessage = MetricsIngestionMessage> = {+ allowed: T[]+ dropped: T[]}export class MetricsRateLimiterService {@@ -173,7 +173,8 @@ export class MetricsRateLimiterService {return this.enabledTeamIds.has(teamId)}- public async filterMessages(messages: MetricsIngestionMessage[]): Promise<FilteredMessages> {+ /** `allowed` and `dropped` hold the input objects, so callers can match the results by reference. */+ public async filterMessages<T extends MetricsIngestionMessage>(messages: T[]): Promise<FilteredMessages<T>> {const teamCosts = new Map<number, number>()const teamOldestTimestamps = new Map<number, number>()const teamNewestTimestamps = new Map<number, number>()@@ -220,8 +221,8 @@ export class MetricsRateLimiterService {teamLimits.set(parseInt(teamIdStr, 10), result)}- const allowed: MetricsIngestionMessage[] = []- const dropped: MetricsIngestionMessage[] = []+ const allowed: T[] = []+ const dropped: T[] = []const teamKbUsed = new Map<number, number>()for (const message of messages) {diff --git a/nodejs/src/ingestion/pipelines/metrics/services/metrics-redis.ts b/nodejs/src/ingestion/pipelines/metrics/services/metrics-redis.tsnew file mode 100644index 000000000000..be822b97f00f--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/services/metrics-redis.ts@@ -0,0 +1,29 @@+import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'+import { MetricsIngestionConsumerConfig } from '~/ingestion/pipelines/metrics/config'++export type MetricsRedisConfig = Pick<+ MetricsIngestionConsumerConfig,+ | 'METRICS_REDIS_HOST'+ | 'METRICS_REDIS_PORT'+ | 'METRICS_REDIS_TLS'+ | 'REDIS_URL'+ | 'REDIS_POOL_MIN_SIZE'+ | 'REDIS_POOL_MAX_SIZE'+>++export function createMetricsRateLimiterRedis(config: MetricsRedisConfig): RedisV2 {+ return createRedisV2PoolFromConfig({+ connection: config.METRICS_REDIS_HOST+ ? {+ url: config.METRICS_REDIS_HOST,+ options: {+ port: config.METRICS_REDIS_PORT,+ tls: config.METRICS_REDIS_TLS ? {} : undefined,+ },+ name: 'metrics-redis',+ }+ : { url: config.REDIS_URL, name: 'metrics-redis-fallback' },+ poolMinSize: config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: config.REDIS_POOL_MAX_SIZE,+ })+}diff --git a/nodejs/src/ingestion/pipelines/metrics/types.ts b/nodejs/src/ingestion/pipelines/metrics/types.tsindex bb16e96028b9..c9b8f99ad246 100644--- a/nodejs/src/ingestion/pipelines/metrics/types.ts+++ b/nodejs/src/ingestion/pipelines/metrics/types.ts@@ -1,5 +1,7 @@import { Message } from 'node-rdkafka'+import { KafkaDebugContext } from '~/ingestion/framework/helpers'+export type MetricsIngestionMessage = {token: stringteamId: number@@ -8,3 +10,7 @@ export type MetricsIngestionMessage = {bytesCompressed: numberrecordCount: number}++export type MetricsPipelineInput = { message: Message }++export type MetricsMessageContext = { message: Message; debugContext?: KafkaDebugContext }diff --git a/nodejs/src/servers/ingestion-metrics-server.ts b/nodejs/src/servers/ingestion-metrics-server.tsindex 55757d48e0ea..7b1b2fe913c0 100644--- a/nodejs/src/servers/ingestion-metrics-server.ts+++ b/nodejs/src/servers/ingestion-metrics-server.ts@@ -13,6 +13,7 @@ import {getDefaultMetricsIngestionOutputsConfig,} from '~/ingestion/pipelines/metrics/config'import { MetricsIngestionConsumer } from '~/ingestion/pipelines/metrics/metrics-ingestion-consumer'+import { MetricsPipelineConsumer } from '~/ingestion/pipelines/metrics/metrics-pipeline-consumer'import { createProducerRegistry } from '~/ingestion/pipelines/metrics/outputs/producer-registry'import {KafkaWarpstreamIngestionProducerEnvConfig,@@ -109,11 +110,10 @@ export class IngestionMetricsServer implements NodeServer {const serviceLoaders: (() => Promise<PluginServerService>)[] = []serviceLoaders.push(async () => {- const consumer = new MetricsIngestionConsumer(this.config, {- teamManager,- quotaLimiting,- outputs,- })+ const deps = { teamManager, quotaLimiting, outputs }+ const consumer = this.config.METRICS_INGESTION_USE_PIPELINE_FRAMEWORK+ ? new MetricsPipelineConsumer(this.config, deps)+ : new MetricsIngestionConsumer(this.config, deps)await consumer.start()return consumer.service})