Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(ingestion): remove the HTTP transport between consumer and workers (#90790)

José Sequeira2237eaafc58f
diff --git a/nodejs/src/ingestion/api/batch-metrics.test.ts b/nodejs/src/ingestion/api/batch-metrics.test.ts
new file mode 100644
index 000000000000..0615ffd24e3c
--- /dev/null
+++ b/nodejs/src/ingestion/api/batch-metrics.test.ts
@@ -0,0 +1,63 @@
+import { Counter, Gauge, register } from 'prom-client'
+
+import { batchAccepted, batchReleased } from './batch-metrics'
+
+describe('batch metrics', () => {
+ let clock: jest.SpyInstance
+
+ async function eventsInFlight(): Promise<number> {
+ const gauge = register.getSingleMetric('ingestion_api_events_in_flight') as Gauge<string>
+ const { values } = await gauge.get()
+ return values[0]?.value ?? 0
+ }
+
+ async function eventSecondsInFlight(): Promise<number> {
+ const counter = register.getSingleMetric('ingestion_api_event_seconds_in_flight_total') as Counter<string>
+ const { values } = await counter.get()
+ return values[0]?.value ?? 0
+ }
+
+ beforeEach(() => {
+ clock = jest.spyOn(Date, 'now').mockReturnValue(0)
+ register.getSingleMetric('ingestion_api_events_in_flight')?.reset()
+ register.getSingleMetric('ingestion_api_event_seconds_in_flight_total')?.reset()
+ })
+
+ afterEach(() => {
+ clock.mockRestore()
+ })
+
+ // The processor autoscaler reads events in flight: a count keyed to the
+ // wrong batch, or a leaked increment, scales the fleet on phantom load.
+ it('sums events across concurrent batches and releases exactly the finished batch', async () => {
+ const first = batchAccepted(100)
+ const second = batchAccepted(5)
+ const third = batchAccepted(20)
+ expect(await eventsInFlight()).toBe(125)
+
+ batchReleased(second)
+ expect(await eventsInFlight()).toBe(120)
+ batchReleased(third)
+ expect(await eventsInFlight()).toBe(100)
+ batchReleased(first)
+ expect(await eventsInFlight()).toBe(0)
+ })
+
+ // rate() over the counter must recover the time-weighted mean events in
+ // flight, so each batch has to be credited its own events * duration.
+ it('credits each batch its own event-seconds', async () => {
+ const long = batchAccepted(100)
+ clock.mockReturnValue(1_000)
+ const short = batchAccepted(4)
+
+ // short: accepted at 1s, released at 3s -> 4 * 2 = 8
+ clock.mockReturnValue(3_000)
+ batchReleased(short)
+ expect(await eventSecondsInFlight()).toBe(8)
+
+ // long: accepted at 0s, released at 4s -> 100 * 4 = 400
+ clock.mockReturnValue(4_000)
+ batchReleased(long)
+ expect(await eventSecondsInFlight()).toBe(408)
+ })
+})
diff --git a/nodejs/src/ingestion/api/batch-metrics.ts b/nodejs/src/ingestion/api/batch-metrics.ts
index a3b163888bab..6fe725453f47 100644
--- a/nodejs/src/ingestion/api/batch-metrics.ts
+++ b/nodejs/src/ingestion/api/batch-metrics.ts
@@ -1,9 +1,9 @@
import { Counter, Gauge, Histogram } from 'prom-client'
/**
- * Batch accounting shared by the HTTP and gRPC ingest transports. The
- * processor autoscaler reads these series, so a transport that skips them
- * makes its pods look idle to KEDA however much work they hold.
+ * Batch accounting for the ingest stream. The processor autoscaler reads
+ * these series, so a path that skips them makes its pods look idle to KEDA
+ * however much work they hold.
*/
const batchesProcessed = new Counter({
@@ -27,11 +27,6 @@ const batchErrors = new Counter({
help: 'Total number of batch processing errors',
})
-const batchCapacityRejections = new Counter({
- name: 'ingestion_api_batch_capacity_rejections_total',
- help: 'Total number of batches rejected because the pipeline was at concurrent batch capacity',
-})
-
const batchesInFlight = new Gauge({
name: 'ingestion_api_batches_in_flight',
help: 'Number of accepted batches currently being processed by the ingestion API (concurrent batches)',
@@ -84,10 +79,6 @@ export function batchFailed(): void {
batchErrors.inc()
}
-export function batchRejectedAtCapacity(): void {
- batchCapacityRejections.inc()
-}
-
/** The batch left the pipeline, acked or failed: free its slot and credit its event-seconds. */
export function batchReleased(batch: AcceptedBatch): void {
batchesInFlight.dec()
diff --git a/nodejs/src/ingestion/api/feed-order-sentinel.ts b/nodejs/src/ingestion/api/feed-order-sentinel.ts
index a9a6b4c918b0..0ced1fadc837 100644
--- a/nodejs/src/ingestion/api/feed-order-sentinel.ts
+++ b/nodejs/src/ingestion/api/feed-order-sentinel.ts
@@ -40,10 +40,10 @@ interface KeyEntry {
* in feed order, so "fed in Kafka offset order per key" is exactly "processed
* in order per key". Call `check` synchronously immediately before
* `pipeline.feed()` — the shared event loop then makes check order identical
- * to feed order even with concurrent /ingest requests.
+ * to feed order even with concurrent streams.
*
* The Rust consumer stamps each request with its process incarnation
- * (`consumer_id`) and a `replay` flag (HTTP retry or deferred-flush re-route).
+ * (`consumer_id`) and a `replay` flag (a deferred-flush re-route).
* An offset regression within one incarnation is an ordering violation unless
* the request is a replay (at-least-once redelivery of un-ACKed messages). A
* changed incarnation (consumer restart or partition handoff) legitimately
diff --git a/nodejs/src/ingestion/api/types.ts b/nodejs/src/ingestion/api/types.ts
index cd40157fc700..b9475f0a3803 100644
--- a/nodejs/src/ingestion/api/types.ts
+++ b/nodejs/src/ingestion/api/types.ts
@@ -1,9 +1,6 @@
/**
- * Wire types for the ingestion worker HTTP API.
- *
- * These types define the contract between the Rust Kafka consumer
- * and Node.js worker processes. Values are passed as raw UTF-8 strings
- * since PostHog Kafka messages are always JSON-encoded text.
+ * A Kafka message as the Rust consumer hands it to the worker. Values are raw
+ * UTF-8 strings since PostHog Kafka messages are always JSON-encoded text.
*/
export interface SerializedKafkaMessage {
@@ -15,19 +12,3 @@ export interface SerializedKafkaMessage {
value: string | null
headers: Record<string, string>
}
-
-export interface IngestBatchRequest {
- batch_id: string
- messages: SerializedKafkaMessage[]
- /** Consumer process incarnation; the feed-order sentinel rebaselines a key when it changes. Optional for older consumers. */
- consumer_id?: string
- /** True when the request may repeat previously sent messages (HTTP retry or deferred-flush re-route). */
- replay?: boolean
-}
-
-export interface IngestBatchResponse {
- batch_id: string
- status: 'ok' | 'error'
- accepted: number
- error?: string
-}
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index e1d26ec4554a..272faa1f2405 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -118,7 +118,7 @@ export type IngestionConsumerConfig = {
// Maximum in-flight batches per worker (BatchingPipeline.concurrentBatches).
// Mirrors INGESTION_WORKER_CONCURRENT_BATCHES on the Rust consumer side —
// both values MUST agree, otherwise either the Rust consumer over-limits
- // (idle worker capacity) or the worker rejects with HTTP 503.
+ // (idle worker capacity) or the worker stalls stream reads at capacity.
INGESTION_WORKER_CONCURRENT_BATCHES: number
// Feed-order sentinel (ingestion API server only): checks that each
@@ -130,11 +130,9 @@ export type IngestionConsumerConfig = {
// least-recently-seen key is dropped and rebaselines unchecked.
INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS: number
- // Streaming ingest (ingestion API server only): serve
- // ingestion.worker.v1.WorkerIngest over gRPC alongside HTTP /ingest.
- // The stream delivers each consumer's sub-batches in order, closing the
- // wire-reordering window concurrent HTTP requests leave open.
- INGESTION_API_GRPC_ENABLED: boolean
+ // Streaming ingest (ingestion API server only): the port serving
+ // ingestion.worker.v1.WorkerIngest. The stream delivers each consumer's
+ // sub-batches in order.
INGESTION_API_GRPC_PORT: number
// Concurrency caps for the gRPC listener. Legitimate load is roughly one
// stream per connected consumer, so these are generous ceilings that bound
@@ -324,7 +322,6 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
INGESTION_WORKER_CONCURRENT_BATCHES: 1,
INGESTION_API_FEED_ORDER_SENTINEL_ENABLED: true,
INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS: 200_000,
- INGESTION_API_GRPC_ENABLED: false,
INGESTION_API_GRPC_PORT: 6739,
INGESTION_API_GRPC_MAX_STREAMS: 256,
INGESTION_API_GRPC_MAX_SESSIONS: 256,
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index eb2d53e847f3..e724d2ea8a03 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -78,9 +78,8 @@ export interface JoinedIngestionPipelineConfig {
/**
* Maximum number of batches the BatchingPipeline will accept concurrently.
* Sourced from `INGESTION_WORKER_CONCURRENT_BATCHES` and MUST match the
- * Rust consumer's per-worker `Semaphore` capacity — divergence causes
- * either idle capacity (consumer under-limits) or HTTP 503s
- * (`ingestion_api_batch_capacity_rejections_total`).
+ * Rust consumer's per-worker stream cap — divergence causes either idle
+ * capacity (consumer under-limits) or stalled stream reads at capacity.
*/
concurrentBatches: number
createEventUsageBatch?: () => UsageRecordBatch
@@ -191,9 +190,8 @@ export function createJoinedIngestionPipeline<
// Batch stores are singleton persistent caches, but each batch receives a
// batch-bound view so entries can be reference-counted and released after
// that batch's flush lifecycle completes. The Rust consumer's per-worker
- // Semaphore caps in-flight batches at the same value
- // (INGESTION_WORKER_CONCURRENT_BATCHES); divergence shows up as HTTP 503s
- // in `ingestion_api_batch_capacity_rejections_total`.
+ // stream caps un-acked batches at the same value
+ // (INGESTION_WORKER_CONCURRENT_BATCHES).
concurrentBatches,
})
.beforeBatch((beforeBatch) =>
diff --git a/nodejs/src/servers/ingestion-api-server.test.ts b/nodejs/src/servers/ingestion-api-server.test.ts
index 6338dedfc002..cc08d3be505a 100644
--- a/nodejs/src/servers/ingestion-api-server.test.ts
+++ b/nodejs/src/servers/ingestion-api-server.test.ts
@@ -1,375 +1,18 @@
-import { Counter, Gauge, register } from 'prom-client'
-
import { GROUPS_OUTPUT } from '~/common/outputs'
import { GroupFlushResult } from '~/ingestion/common/groups/group-store.interface'
-import { IngestBatchResponse, SerializedKafkaMessage } from '../ingestion/api/types'
import { CleanupResources } from './base-server'
import { IngestionApiServer } from './ingestion-api-server'
describe('IngestionApiServer', () => {
let server: IngestionApiServer
- let pipeline: { feed: jest.Mock; next: jest.Mock }
- let stopSpy: jest.SpyInstance
-
- function makeMessage(): SerializedKafkaMessage {
- return { topic: 't', partition: 0, offset: 0, timestamp: 0, key: null, value: '{}', headers: {} }
- }
-
- function makeRes(): {
- status: (code: number) => { json: (body: IngestBatchResponse) => void }
- statusCode: () => number
- body: () => IngestBatchResponse
- } {
- const json = jest.fn()
- const status = jest.fn().mockReturnValue({ json })
- return {
- status,
- statusCode: () => status.mock.calls[0][0],
- body: () => json.mock.calls[0][0],
- }
- }
-
- function handle(res: ReturnType<typeof makeRes>, messageCount = 1): Promise<void> {
- const messages = Array.from({ length: messageCount }, makeMessage)
- const req = { body: { batch_id: 'b1', messages } }
- return (server as any).handleIngestRequest(req, res)
- }
-
- async function eventSecondsInFlight(): Promise<number> {
- const counter = register.getSingleMetric('ingestion_api_event_seconds_in_flight_total') as Counter<string>
- const { values } = await counter.get()
- return values[0]?.value ?? 0
- }
-
- async function eventsInFlight(): Promise<number> {
- const gauge = register.getSingleMetric('ingestion_api_events_in_flight') as Gauge<string>
- const { values } = await gauge.get()
- return values[0]?.value ?? 0
- }
-
- function isHealthy(): { status: string } {
- return (server as any).isHealthy()
- }
beforeEach(() => {
server = new IngestionApiServer()
- pipeline = { feed: jest.fn(), next: jest.fn() }
- ;(server as any).httpPipeline = pipeline
- ;(server as any).promiseScheduler = { schedule: jest.fn(), waitForAll: jest.fn().mockResolvedValue(undefined) }
- ;(server as any).hogTransformer = { processInvocationResults: jest.fn().mockResolvedValue(undefined) }
- // stop() would call process.exit; stub it so the test only observes that it was invoked.
- stopSpy = jest.spyOn(server, 'stop').mockResolvedValue(undefined)
- // The gauge is a module-level singleton shared across tests in this file.
- register.getSingleMetric('ingestion_api_events_in_flight')?.reset()
- register.getSingleMetric('ingestion_api_event_seconds_in_flight_total')?.reset()
})
it('reports healthy before any failure', () => {
- expect(isHealthy().status).toBe('ok')
- })
-
- it('crashes and rebuilds on an unexpected pipeline error', async () => {
- pipeline.feed.mockResolvedValue({ ok: true })
- pipeline.next.mockRejectedValue(new Error('pipeline poisoned'))
-
- const res = makeRes()
- await handle(res)
-
- // Retriable 500 so the Rust consumer redelivers the batch.
- expect(res.statusCode()).toBe(500)
- expect(res.body()).toMatchObject({ status: 'error' })
- // Latched unhealthy and shut down so the supervisor rebuilds the pipeline.
- expect(isHealthy().status).toBe('error')
- expect(stopSpy).toHaveBeenCalledTimes(1)
- })
-
- it('returns 503 backpressure at capacity without crashing', async () => {
- pipeline.feed.mockResolvedValue({ ok: false, kind: 'at_capacity', reason: 'at concurrent batch capacity (1)' })
-
- const res = makeRes()
- await handle(res)
-
- expect(res.statusCode()).toBe(503)
- expect(isHealthy().status).toBe('ok')
- expect(stopSpy).not.toHaveBeenCalled()
- expect(pipeline.next).not.toHaveBeenCalled()
- })
-
- it('processes a successful batch and stays healthy', async () => {
- pipeline.feed.mockResolvedValue({ ok: true })
- pipeline.next.mockResolvedValue(null)
-
- const res = makeRes()
- await handle(res)
-
- expect(res.statusCode()).toBe(200)
- expect(res.body()).toMatchObject({ status: 'ok', accepted: 1 })
- expect(isHealthy().status).toBe('ok')
- expect(stopSpy).not.toHaveBeenCalled()
- })
-
- type Gate = { resolve: () => void; reject: (error: Error) => void }
-
- describe('events in flight gauge', () => {
- // One gate per in-flight batch. The handler calls next() exactly once
- // (the mock resolves to null, ending its drain loop), so holding that
- // promise open holds the batch in flight and lets a test decide the
- // order batches finish in.
- let gates: Gate[]
-
- beforeEach(() => {
- gates = []
- })
-
- function gateBatches(): void {
- pipeline.feed.mockResolvedValue({ ok: true })
- pipeline.next.mockImplementation(
- () =>
- new Promise<null>((resolve, reject) => {
- gates.push({ resolve: () => resolve(null), reject })
- })
- )
- }
-
- // Let pending callbacks run so a started request reaches next() before
- // the test reads the gauge.
- function flush(): Promise<void> {
- return new Promise((resolve) => setImmediate(resolve))
- }
-
- // Starts a batch and returns its completion promise. Deliberately not
- // async: an async wrapper's promise would adopt this one, so awaiting
- // the helper would wait for the batch to finish instead of starting it.
- // Callers `await flush()` once the batches they want in flight are up.
- function start(messageCount: number): Promise<void> {
- return handle(makeRes(), messageCount)
- }
-
- it('sums events across concurrent batches of different sizes', async () => {
- gateBatches()
-
- const small = start(5)
- const medium = start(100)
- const large = start(1000)
- await flush()
-
- // 3 if it counted batches; the sum is the point of the metric.
- expect(await eventsInFlight()).toBe(1105)
-
- gates.forEach((gate) => gate.resolve())
- await Promise.all([small, medium, large])
- expect(await eventsInFlight()).toBe(0)
- })
-
- it('releases exactly the finished batch, leaving the others in flight', async () => {
- gateBatches()
-
- const first = start(100)
- const second = start(5)
- const third = start(20)
- await flush()
- expect(await eventsInFlight()).toBe(125)
-
- // Finish out of order: a decrement keyed to the wrong request would
- // subtract someone else's count and drift the gauge.
- gates[1].resolve()
- await second
- expect(await eventsInFlight()).toBe(120)
-
- gates[2].resolve()
- await third
- expect(await eventsInFlight()).toBe(100)
-
- gates[0].resolve()
- await first
- expect(await eventsInFlight()).toBe(0)
- })
-
- it('leaves in-flight batches untouched when another is rejected at capacity', async () => {
- gateBatches()
- const accepted = start(100)
- await flush()
-
- pipeline.feed.mockResolvedValueOnce({ ok: false, kind: 'at_capacity', reason: 'at capacity' })
- const rejectedRes = makeRes()
- await handle(rejectedRes, 50)
-
- expect(rejectedRes.statusCode()).toBe(503)
- expect(await eventsInFlight()).toBe(100)
-
- gates[0].resolve()
- await accepted
- expect(await eventsInFlight()).toBe(0)
- })
-
- it('releases a crashed batch while a concurrent batch stays in flight', async () => {
- gateBatches()
- const crashing = start(100)
- const surviving = start(7)
- await flush()
-
- gates[0].reject(new Error('pipeline poisoned'))
- await crashing
- expect(await eventsInFlight()).toBe(7)
-
- gates[1].resolve()
- await surviving
- expect(await eventsInFlight()).toBe(0)
- })
-
- it('does not count a batch rejected as empty', async () => {
- const res = makeRes()
- await handle(res, 0)
-
- expect(res.statusCode()).toBe(400)
- expect(await eventsInFlight()).toBe(0)
- })
-
- // A leaked increment would make the gauge climb forever and, since this
- // drives processor autoscaling, scale the fleet out on phantom load.
- it.each([
- {
- outcome: 'success',
- arrange: () => {
- pipeline.feed.mockResolvedValue({ ok: true })
- pipeline.next.mockResolvedValue(null)
- },
- },
- {
- outcome: 'capacity rejection',
- arrange: () => {
- pipeline.feed.mockResolvedValue({ ok: false, kind: 'at_capacity', reason: 'at capacity' })
- },
- },
- {
- outcome: 'pipeline crash',
- arrange: () => {
- pipeline.feed.mockResolvedValue({ ok: true })
- pipeline.next.mockRejectedValue(new Error('pipeline poisoned'))
- },
- },
- ])('returns to zero after a $outcome', async ({ arrange }) => {
- arrange()
-
- await handle(makeRes(), 5)
-
- expect(await eventsInFlight()).toBe(0)
- })
- })
-
- describe('event-seconds counter', () => {
- // The counter is the integral of the gauge, so its whole value is that
- // rate() over it recovers mean events in flight without depending on
- // when a scrape lands. Driving Date.now directly keeps that arithmetic
- // exact and avoids faking the timers the request path runs on.
- let clock: jest.SpyInstance
-
- beforeEach(() => {
- clock = jest.spyOn(Date, 'now')
- })
-
- afterEach(() => {
- clock.mockRestore()
- })
-
- function gateBatches(): Gate[] {
- const gates: Gate[] = []
- pipeline.feed.mockResolvedValue({ ok: true })
- pipeline.next.mockImplementation(
- () =>
- new Promise<null>((resolve, reject) => {
- gates.push({ resolve: () => resolve(null), reject })
- })
- )
- return gates
- }
-
- function flush(): Promise<void> {
- return new Promise((resolve) => setImmediate(resolve))
- }
-
- it('accumulates events multiplied by seconds in flight', async () => {
- const gates = gateBatches()
- clock.mockReturnValue(1_000)
-
- const batch = handle(makeRes(), 10)
- await flush()
-
- clock.mockReturnValue(3_500)
- gates[0].resolve()
- await batch
-
- // 10 events held for 2.5s.
- expect(await eventSecondsInFlight()).toBe(25)
- })
-
- it('credits each concurrent batch its own duration', async () => {
- const gates = gateBatches()
- clock.mockReturnValue(0)
-
- const long = handle(makeRes(), 100)
- await flush()
- clock.mockReturnValue(1_000)
- const short = handle(makeRes(), 4)
- await flush()
-
- // short: accepted at 1s, ends at 3s -> 4 * 2 = 8
- clock.mockReturnValue(3_000)
- gates[1].resolve()
- await short
- expect(await eventSecondsInFlight()).toBe(8)
-
- // long: accepted at 0s, ends at 4s -> 100 * 4 = 400
- clock.mockReturnValue(4_000)
- gates[0].resolve()
- await long
- expect(await eventSecondsInFlight()).toBe(408)
- })
-
- it('recovers mean events in flight, which is the point of the counter', async () => {
- // One event held for 60s and 60 events each held for 1s both mean
- // "1 event in flight on average over a minute". A gauge scraped
- // once would report 1 or 60 depending on timing; the counter says
- // 60 event-seconds either way.
- const gates = gateBatches()
-
- clock.mockReturnValue(0)
- const steady = handle(makeRes(), 1)
- await flush()
- clock.mockReturnValue(60_000)
- gates[0].resolve()
- await steady
- const heldLong = await eventSecondsInFlight()
-
- register.getSingleMetric('ingestion_api_event_seconds_in_flight_total')?.reset()
-
- for (let i = 0; i < 60; i++) {
- clock.mockReturnValue(i * 1_000)
- const burst = handle(makeRes(), 60)
- await flush()
- clock.mockReturnValue(i * 1_000 + 1_000)
- gates[gates.length - 1].resolve()
- await burst
- }
- const burstsShort = await eventSecondsInFlight()
-
- expect(heldLong).toBe(60)
- expect(burstsShort).toBe(3_600)
- // Same mean over their own window: 60/60s = 1, 3600/60s = 60.
- expect(heldLong / 60).toBe(1)
- expect(burstsShort / 60).toBe(60)
- })
-
- it('does not credit a batch rejected at capacity', async () => {
- clock.mockReturnValue(0)
- pipeline.feed.mockResolvedValue({ ok: false, kind: 'at_capacity', reason: 'at capacity' })
-
- clock.mockReturnValue(5_000)
- await handle(makeRes(), 10)
-
- expect(await eventSecondsInFlight()).toBe(0)
- })
+ expect((server as any).isHealthy().status).toBe('ok')
})
describe('cleanup', () => {
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index b6169e954fda..31e4e9fdd90f 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -1,5 +1,3 @@
-import { Message } from 'node-rdkafka'
-
import { IntegrationManagerService } from '~/cdp/services/managers/integration-manager.service'
import { initializePrometheusLabels } from '~/common/api/router'
import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'
@@ -50,7 +48,6 @@ import {
FlushBatchStoresOutputs,
createGroupProducePromises,
} from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'
-import { createKafkaDebugContext, createOkContext } from '~/ingestion/framework/helpers'
import { TopHog } from '~/ingestion/framework/tophog'
import {
JoinedIngestionPipelineConfig,
@@ -69,18 +66,8 @@ import {
} from '../cdp/hog-transformations/hog-transformer.service'
import { EncryptedFields } from '../cdp/utils/encryption-utils'
import { CommonConfig } from '../common/config'
-import {
- AcceptedBatch,
- batchAccepted,
- batchFailed,
- batchProcessed,
- batchRejectedAtCapacity,
- batchReleased,
-} from '../ingestion/api/batch-metrics'
import { FeedOrderSentinel } from '../ingestion/api/feed-order-sentinel'
import { WorkerIngestServer } from '../ingestion/api/grpc-server'
-import { deserializeKafkaMessage } from '../ingestion/api/kafka-message-converter'
-import { IngestBatchRequest, IngestBatchResponse } from '../ingestion/api/types'
import { EventFilterManagerComponent } from '../ingestion/common/event-filters'
import { createFeatureFlagCalledDedupService } from '../ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service'
import { createFlagEvaluationsService } from '../ingestion/common/flag-evaluations/flag-evaluations-service'
@@ -138,14 +125,15 @@ export type IngestionApiServerConfig = BaseServerConfig &
>
/**
- * Ingestion API server that exposes the ingestion pipeline as an HTTP endpoint.
+ * Ingestion API server that exposes the ingestion pipeline over the
+ * `WorkerIngest` gRPC stream.
*
- * Used as a sidecar alongside a Rust Kafka consumer — the consumer reads from
- * Kafka, routes messages by distinct_id, and dispatches sub-batches to this
- * server via POST /ingest.
+ * Paired with the Rust Kafka consumer: the consumer reads from Kafka, routes
+ * messages by key, and sends each worker's sub-batches on one ordered stream.
+ * The HTTP server only serves health and metrics.
*
* Infrastructure setup mirrors IngestionGeneralServer. The difference is that
- * instead of subscribing to Kafka, this server accepts batches over HTTP.
+ * instead of subscribing to Kafka, this server accepts batches over the stream.
*/
export class IngestionApiServer implements NodeServer {
readonly lifecycle: ServerLifecycle
@@ -167,9 +155,6 @@ export class IngestionApiServer implements NodeServer {
// (moved to caller-side production so create and flush share one path).
private ingestionOutputs?: FlushBatchStoresOutputs
- private httpPipeline!: ReturnType<
- typeof createJoinedIngestionPipeline<JoinedIngestionPipelineInput, JoinedIngestionPipelineContext>
- >
private grpcServer?: WorkerIngestServer
private promiseScheduler = new PromiseScheduler()
private hogTransformer!: HogTransformerService
@@ -178,7 +163,7 @@ export class IngestionApiServer implements NodeServer {
private feedOrderSentinel?: FeedOrderSentinel
// Latched on the first unexpected pipeline error. The pipeline is a single
- // long-lived instance shared across all requests; a throw can leave it
+ // long-lived instance shared across all streams; a throw can leave it
// permanently poisoned (e.g. a group exhausted retries), so we mirror the
// Kafka consumer's contract of crashing and rebuilding rather than serving
// a wedged pipeline forever.
@@ -462,49 +447,41 @@ export class IngestionApiServer implements NodeServer {
groupTypeManager,
topHog: this.topHog,
}
- // 8. Register the ingest transports. HTTP always serves; gRPC is
- // additive behind its flag, so consumers can migrate gradually.
+ // 8. Serve the WorkerIngest stream.
if (this.config.INGESTION_API_FEED_ORDER_SENTINEL_ENABLED) {
this.feedOrderSentinel = new FeedOrderSentinel(this.config.INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS)
}
- this.httpPipeline = createJoinedIngestionPipeline(joinedPipelineConfig, joinedPipelineDeps)
- this.lifecycle.expressApp.post('/ingest', async (req, res) => {
- await this.handleIngestRequest(req, res)
- })
- if (this.config.INGESTION_API_GRPC_ENABLED) {
- // Own pipeline instance: sharing httpPipeline would let an HTTP
- // handler's next() consume a gRPC batch's completion (and its ack).
- const grpcPipeline = createJoinedIngestionPipeline<
- JoinedIngestionPipelineInput,
- JoinedIngestionPipelineContext,
- GrpcBatchContext
- >(joinedPipelineConfig, joinedPipelineDeps)
- this.grpcServer = new WorkerIngestServer(
- {
- port: this.config.INGESTION_API_GRPC_PORT,
- maxConcurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,
- maxStreams: this.config.INGESTION_API_GRPC_MAX_STREAMS,
- maxSessions: this.config.INGESTION_API_GRPC_MAX_SESSIONS,
- maxStreamsPerSession: this.config.INGESTION_API_GRPC_MAX_STREAMS_PER_SESSION,
- sessionMemoryMb: this.config.INGESTION_API_GRPC_SESSION_MEMORY_MB,
- sessionIdleTimeoutMs: this.config.INGESTION_API_GRPC_SESSION_IDLE_TIMEOUT_MS,
- readMaxBytes: this.config.INGESTION_API_GRPC_READ_MAX_BYTES,
- drainTimeoutMs: this.config.INGESTION_API_GRPC_DRAIN_TIMEOUT_MS,
+ const grpcPipeline = createJoinedIngestionPipeline<
+ JoinedIngestionPipelineInput,
+ JoinedIngestionPipelineContext,
+ GrpcBatchContext
+ >(joinedPipelineConfig, joinedPipelineDeps)
+ this.grpcServer = new WorkerIngestServer(
+ {
+ port: this.config.INGESTION_API_GRPC_PORT,
+ maxConcurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,
+ maxStreams: this.config.INGESTION_API_GRPC_MAX_STREAMS,
+ maxSessions: this.config.INGESTION_API_GRPC_MAX_SESSIONS,
+ maxStreamsPerSession: this.config.INGESTION_API_GRPC_MAX_STREAMS_PER_SESSION,
+ sessionMemoryMb: this.config.INGESTION_API_GRPC_SESSION_MEMORY_MB,
+ sessionIdleTimeoutMs: this.config.INGESTION_API_GRPC_SESSION_IDLE_TIMEOUT_MS,
+ readMaxBytes: this.config.INGESTION_API_GRPC_READ_MAX_BYTES,
+ drainTimeoutMs: this.config.INGESTION_API_GRPC_DRAIN_TIMEOUT_MS,
+ },
+ {
+ driver: new GrpcStreamIngestDriver(grpcPipeline, this.promiseScheduler),
+ feedOrderSentinel: this.feedOrderSentinel,
+ onFatal: (error) => {
+ // A poisoned pipeline is rebuilt by the supervisor, not
+ // served: latch unhealthy and shut down once.
+ if (!this.fatalError) {
+ this.fatalError = error
+ void this.stop(error)
+ }
},
- {
- driver: new GrpcStreamIngestDriver(grpcPipeline, this.promiseScheduler),
- feedOrderSentinel: this.feedOrderSentinel,
- onFatal: (error) => {
- // Same crash-and-rebuild contract as the HTTP path.
- if (!this.fatalError) {
- this.fatalError = error
- void this.stop(error)
- }
- },
- }
- )
- await this.grpcServer.start()
- }
+ }
+ )
+ await this.grpcServer.start()
const service: PluginServerService = {
id: 'ingestion-api',
@@ -519,106 +496,6 @@ export class IngestionApiServer implements NodeServer {
this.lifecycle.services.push(service)
}
- private async handleIngestRequest(
- req: { body: IngestBatchRequest },
- res: {
- status: (code: number) => { json: (body: IngestBatchResponse) => void }
- }
- ): Promise<void> {
- const { batch_id, messages: serializedMessages, consumer_id, replay } = req.body
-
- if (!serializedMessages || serializedMessages.length === 0) {
- res.status(400).json({ batch_id: batch_id ?? '', status: 'error', accepted: 0, error: 'Empty batch' })
- return
- }
-
- // Set once the pipeline accepts the batch, so the `finally` releases
- // exactly what was counted.
- let inFlight: AcceptedBatch | null = null
-
- try {
- const messages: Message[] = serializedMessages.map(deserializeKafkaMessage)
-
- const batch = messages.map((message) =>
- createOkContext({ message }, { message, debugContext: createKafkaDebugContext(message) })
- )
- // Per-key order check, synchronously adjacent to feed() so check
- // order equals feed order across concurrent requests. The grouping
- // stage processes each key in feed order, so this measures the
- // "processed in order per distinct_id" invariant.
- this.feedOrderSentinel?.check(serializedMessages, consumer_id ?? 'unknown', replay ?? false)
- const feedResult = await this.httpPipeline.feed(batch, {})
- if (!feedResult.ok) {
- // Capacity rejection should not happen under correct consumer
- // behavior — the Rust consumer holds a per-worker Semaphore
- // sized to INGESTION_WORKER_CONCURRENT_BATCHES and is supposed
- // to wait (natural backpressure) before sending a batch that
- // would exceed the worker's capacity. If we land here, the
- // consumer's tracking is wrong or its env-var value disagrees
- // with ours. Respond 503 so the consumer surfaces it as a
- // distinct error (TransportError::WorkerBusy) and the alarm is
- // visible in `ingestion_api_batch_capacity_rejections_total`.
- // Use the typed `kind` discriminator (not the human-readable
- // `reason` string) so a future BatchingPipeline message tweak
- // can't silently downgrade us to a fall-through 500 — which
- // the Rust transport treats as retriable.
- if (feedResult.kind === 'at_capacity') {
- batchRejectedAtCapacity()
- res.status(503).json({
- batch_id: batch_id ?? '',
- status: 'error',
- accepted: 0,
- error: feedResult.reason,
- })
- return
- }
- throw new Error(`Pipeline rejected batch: ${feedResult.reason}`)
- }
-
- // Batch accepted into the pipeline — it now occupies a concurrent
- // slot until processing completes below.
- inFlight = batchAccepted(messages.length)
-
- // The pipeline handles its own side effects (scheduling them on
- // the promise scheduler), so draining results is all that's left
- // to do.
- let result = await this.httpPipeline.next()
- while (result !== null) {
- result = await this.httpPipeline.next()
- }
-
- // Wait for all side effects — the HTTP response is the ACK to the
- // Rust consumer, so all work must finish before responding. The hog
- // transformer drain is scheduled as a side effect by the pipeline's
- // afterBatch flush step, so it's covered by waitForAll().
- await this.promiseScheduler.waitForAll()
-
- batchProcessed(inFlight)
-
- res.status(200).json({ batch_id, status: 'ok', accepted: messages.length })
- } catch (err) {
- batchFailed()
- const error = err instanceof Error ? err : new Error(String(err))
- logger.error('💥', 'Ingestion API batch processing failed', { batch_id, error: error.message })
- // A throw here can leave the shared pipeline permanently poisoned, so
- // mirror the Kafka consumer's crash-and-rebuild contract. Respond 500
- // (the Rust transport treats it as retriable and redelivers), mark the
- // server unhealthy, and shut down so the supervisor rebuilds a fresh
- // pipeline instead of serving a wedged one. Trigger the shutdown once:
- // concurrent in-flight requests can all fail on the same poisoned
- // pipeline, but only the first should start teardown.
- if (!this.fatalError) {
- this.fatalError = error
- void this.stop(error)
- }
- res.status(500).json({ batch_id, status: 'error', accepted: 0, error: error.message })
- } finally {
- if (inFlight !== null) {
- batchReleased(inFlight)
- }
- }
- }
-
private isHealthy(): HealthCheckResult {
// TODO: add output producer health checks
if (this.fatalError) {
diff --git a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
index 4ab756891230..a156d4cf8d70 100644
--- a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
+++ b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
@@ -68,7 +68,7 @@ import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outpu
* model. Creates multiple in-flight batches WITHOUT concurrent next() calls,
* isolating pure ordering semantics deterministically.
* - Concurrent drivers: N "handlers" each doing feed → drain-until-null →
- * waitForAll (a copy of ingestion-api-server's handleIngestRequest), guarded
+ * waitForAll (a copy of the ingestion API server's stream driver), guarded
* by a Semaphore(concurrentBatches) playing the Rust consumer's per-worker
* semaphore. This is the INGESTION_WORKER_CONCURRENT_BATCHES > 1 rollout model.
*
@@ -420,7 +420,7 @@ class Harness {
}
}
- /** Mirrors ingestion-api-server's handleIngestRequest: feed a batch, then drain. */
+ /** Mirrors the ingestion API server's stream driver: feed a batch, then drain. */
async run(events: EventSpec[]): Promise<void> {
const feedResult = await this.feed(events)
if (!feedResult.ok) {
diff --git a/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts b/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts
index d9fc8a280e04..b25783845814 100644
--- a/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts
+++ b/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts
@@ -1,4 +1,4 @@
-import http, { IncomingMessage, ServerResponse } from 'http'
+import net from 'net'
import {
ConsumerGlobalConfig,
KafkaConsumer,
@@ -41,7 +41,9 @@ const RUST_ROOT = path.join(REPO_ROOT, 'rust')
const TEST_TEAM_ID = 2
const TEST_TEAM_TOKEN = `THIS IS NOT A TOKEN FOR TEAM ${TEST_TEAM_ID}`
-const INTERNAL_API_SECRET = 'rust-node-ingestion-e2e-secret'
+// Each worker serves its WorkerIngest stream on its HTTP port plus this offset;
+// the Rust consumer derives the stream address the same way.
+const GRPC_PORT_OFFSET = 1
const POSTGRES_URL = 'postgres://posthog:posthog@localhost:5432'
const NODE_WORKER_COUNT = 2
const RUST_BATCH_SIZE = 10
@@ -79,7 +81,6 @@ let outputTopicStartWatermarks = new Map<string, TopicWatermarks>()
describe('Rust ingestion consumer with Node ingestion API workers', () => {
let clickhouse: Clickhouse
let services: ServiceProcess[] = []
- let proxies: IngestionApiProxy[] = []
beforeAll(() => {
configureParentTestEnv()
@@ -99,12 +100,8 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {
})
afterEach(async () => {
- await Promise.allSettled([
- ...services.map((service) => service.stop()),
- ...proxies.map((proxy) => proxy.stop()),
- ])
+ await Promise.allSettled(services.map((service) => service.stop()))
services = []
- proxies = []
outputTopicStartWatermarks = new Map()
})
@@ -114,26 +111,6 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {
clickhouse.close()
})
- test('Node ingestion API requires internal auth and validates batches', async () => {
- const worker = await startNodeIngestionApiWorker('node-worker-contract')
- services.push(worker.service)
-
- const authResponse = await worker.service.request(`${worker.url}/ingest`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ batch_id: 'auth-check', messages: [] }),
- })
- expect(authResponse.statusCode).toBe(401)
-
- const emptyBatchResponse = await worker.service.request(`${worker.url}/ingest`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', 'X-Internal-Api-Secret': INTERNAL_API_SECRET },
- body: JSON.stringify({ batch_id: 'empty-batch-check', messages: [] }),
- })
- expect(emptyBatchResponse.statusCode).toBe(400)
- await waitForTopicMessageCount(KAFKA_EVENTS_JSON, 0)
- })
-
test('Rust consumer ingests Kafka events through multiple real Node ingestion API workers', async () => {
const workers = await startNodeWorkerSet(services)
const producer = await KafkaProducerWrapper.create(undefined)
@@ -180,49 +157,6 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {
}
})
- test('Rust consumer retries a transient Node ingestion API failure without duplicate output', async () => {
- const workers = await startNodeWorkerSet(services)
- const proxy = await IngestionApiProxy.start('node-worker-transient-failure-proxy', workers[0].url, {
- failNextIngestRequests: 1,
- })
- proxies.push(proxy)
-
- const proxiedWorkers = [{ service: workers[0].service, url: proxy.url }, workers[1]]
- const producer = await KafkaProducerWrapper.create(undefined)
- const team = { ...DEFAULT_TEAM, id: TEST_TEAM_ID, api_token: TEST_TEAM_TOKEN }
- const events = buildBatchBoundaryEvents(team, 'rust node e2e transient failure event', 'transient')
-
- try {
- await produceEvents(producer, events)
- const { rustConsumer, rustMetricsPort, groupId } = await startRustConsumerForWorkers(
- services,
- proxiedWorkers
- )
- await waitForEvents(clickhouse, events)
- await assertKafkaIngestionState(groupId, events)
-
- await waitForExpect(async () => {
- const metrics = await fetchMetrics(rustConsumer, rustMetricsPort)
- expect(
- getPrometheusSample(metrics, {
- name: 'ingestion_consumer_transport_requests_total',
- labels: { worker: proxy.url, status: 'error' },
- })
- ).toBeGreaterThanOrEqual(1)
- expect(
- getPrometheusSample(metrics, {
- name: 'ingestion_consumer_transport_retries_total',
- labels: { worker: proxy.url },
- })
- ).toBeGreaterThanOrEqual(1)
- }, 30_000)
- expect(proxy.failedIngestRequests).toBe(1)
- expect(proxy.forwardedIngestRequests).toBeGreaterThanOrEqual(1)
- } finally {
- await producer.disconnect()
- }
- })
-
test('Rust consumer commits a mixed batch after Node DLQs an invalid event', async () => {
const workers = await startNodeWorkerSet(services)
const producer = await KafkaProducerWrapper.create(undefined)
@@ -469,7 +403,7 @@ async function startRustNodeStack(
}
async function startNodeIngestionApiWorker(name: string, port?: number): Promise<NodeWorker> {
- const workerPort = port ?? (await getFreePort())
+ const workerPort = port ?? (await getFreeWorkerPort())
const service = new ServiceProcess(name, 'pnpm', ['exec', 'tsx', 'src/index.ts'], {
cwd: NODEJS_ROOT,
env: {
@@ -479,7 +413,7 @@ async function startNodeIngestionApiWorker(name: string, port?: number): Promise
NODE_ENV: 'dev',
PLUGIN_SERVER_MODE: 'ingestion-api',
HTTP_SERVER_PORT: workerPort.toString(),
- INTERNAL_API_SECRET,
+ INGESTION_API_GRPC_PORT: (workerPort + GRPC_PORT_OFFSET).toString(),
OTEL_SDK_DISABLED: 'true',
DISABLE_OPENTELEMETRY_TRACING: 'true',
LOG_LEVEL: 'warn',
@@ -494,6 +428,25 @@ async function startNodeIngestionApiWorker(name: string, port?: number): Promise
return { service, url }
}
+// A worker needs two adjacent free ports: HTTP, and HTTP + GRPC_PORT_OFFSET for the stream.
+async function getFreeWorkerPort(): Promise<number> {
+ for (let attempt = 0; attempt < 20; attempt++) {
+ const port = await getFreePort()
+ if (await isPortFree(port + GRPC_PORT_OFFSET)) {
+ return port
+ }
+ }
+ throw new Error('could not find adjacent free ports for a worker')
+}
+
+function isPortFree(port: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ const server = net.createServer()
+ server.once('error', () => resolve(false))
+ server.listen(port, '127.0.0.1', () => server.close(() => resolve(true)))
+ })
+}
+
async function restartNodeIngestionApiWorker(
services: ServiceProcess[],
worker: NodeWorker,
@@ -528,9 +481,7 @@ function startRustIngestionConsumer(
CONSUMER_MAX_BACKGROUND_TASKS: '1',
INGESTION_WORKER_CONCURRENT_BATCHES: '1',
WORKER_ADDRESSES: workers.join(','),
- INTERNAL_API_SECRET,
- HTTP_TIMEOUT_MS: '10000',
- MAX_RETRIES: '1',
+ INGESTION_WORKER_GRPC_PORT_OFFSET: GRPC_PORT_OFFSET.toString(),
WORKER_PROBE_INTERVAL_MS: '250',
WORKER_DEAD_DECLARATION_MS: '750',
WORKER_MIN_STATE_DURATION_MS: '100',
@@ -1088,122 +1039,3 @@ function kafkaHeadersToRecord(headers: Message['headers']): Record<string, strin
)
)
}
-
-class IngestionApiProxy {
- failedIngestRequests = 0
- forwardedIngestRequests = 0
-
- private constructor(
- private readonly name: string,
- private readonly targetUrl: string,
- readonly url: string,
- private readonly server: http.Server,
- private failNextIngestRequests: number
- ) {}
-
- static async start(
- name: string,
- targetUrl: string,
- { failNextIngestRequests }: { failNextIngestRequests: number }
- ): Promise<IngestionApiProxy> {
- const port = await getFreePort()
- const server = http.createServer()
- const proxy = new IngestionApiProxy(name, targetUrl, `http://127.0.0.1:${port}`, server, failNextIngestRequests)
- server.on('request', (req, res) => {
- void proxy.handle(req, res)
- })
-
- await new Promise<void>((resolve, reject) => {
- server.once('error', reject)
- server.listen(port, '127.0.0.1', () => resolve())
- })
-
- return proxy
- }
-
- async stop(): Promise<void> {
- if (!this.server.listening) {
- return
- }
-
- await new Promise<void>((resolve, reject) => {
- this.server.close((error) => {
- if (error) {
- reject(error)
- } else {
- resolve()
- }
- })
- })
- }
-
- private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
- try {
- const path = req.url ?? '/'
- if (req.method === 'POST' && path.startsWith('/ingest') && this.failNextIngestRequests > 0) {
- this.failNextIngestRequests--
- this.failedIngestRequests++
- res.writeHead(500, { 'Content-Type': 'application/json' })
- res.end(JSON.stringify({ status: 'error', accepted: 0, error: `${this.name} injected failure` }))
- return
- }
-
- if (req.method === 'POST' && path.startsWith('/ingest')) {
- this.forwardedIngestRequests++
- }
-
- await this.forward(req, res)
- } catch (error) {
- if (res.headersSent) {
- res.destroy(error instanceof Error ? error : new Error(String(error)))
- return
- }
-
- res.writeHead(502, { 'Content-Type': 'application/json' })
- res.end(
- JSON.stringify({
- status: 'error',
- accepted: 0,
- error: error instanceof Error ? error.message : String(error),
- })
- )
- }
- }
-
- private async forward(req: IncomingMessage, res: ServerResponse): Promise<void> {
- const body = await readRequestBody(req)
- const target = new URL(req.url ?? '/', this.targetUrl)
- const headers = { ...req.headers, host: target.host }
-
- await new Promise<void>((resolve, reject) => {
- const proxiedReq = http.request(
- target,
- {
- method: req.method,
- headers,
- },
- (proxiedRes) => {
- res.writeHead(proxiedRes.statusCode ?? 502, proxiedRes.headers)
- proxiedRes.pipe(res)
- proxiedRes.on('error', reject)
- res.on('error', reject)
- proxiedRes.on('end', resolve)
- }
- )
-
- proxiedReq.on('error', reject)
- if (body.length > 0) {
- proxiedReq.write(body)
- }
- proxiedReq.end()
- })
- }
-}
-
-async function readRequestBody(req: IncomingMessage): Promise<Buffer> {
- const chunks: Buffer[] = []
- for await (const chunk of req) {
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
- }
- return Buffer.concat(chunks)
-}
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index f631f3da7611..fec1691b1321 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -6008,7 +6008,6 @@ dependencies = [
"common-continuous-profiling",
"dashmap 6.1.0",
"envconfig",
- "flate2",
"futures",
"ingestion-worker-proto",
"k8s-awareness",
@@ -6028,7 +6027,6 @@ dependencies = [
"tokio-stream",
"tokio-util",
"tonic 0.12.3",
- "tower-http 0.5.2",
"tracing",
"tracing-subscriber",
"uuid",
diff --git a/rust/ingestion-consumer/Cargo.toml b/rust/ingestion-consumer/Cargo.toml
index 9792e7246f70..640067a89274 100644
--- a/rust/ingestion-consumer/Cargo.toml
+++ b/rust/ingestion-consumer/Cargo.toml
@@ -11,7 +11,6 @@ common-alloc = { path = "../common/alloc" }
common-continuous-profiling = { path = "../common/continuous_profiling" }
dashmap = { workspace = true }
envconfig = { workspace = true }
-flate2 = { workspace = true }
futures = { workspace = true }
ingestion-worker-proto = { path = "../ingestion-worker-proto" }
k8s-awareness = { path = "../common/k8s-awareness" }
@@ -38,5 +37,4 @@ tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
[dev-dependencies]
-tower-http = { workspace = true }
uuid = { workspace = true }
diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.md
index 28269cf8ad01..e9887580c5d0 100644
--- a/rust/ingestion-consumer/README.md
+++ b/rust/ingestion-consumer/README.md
@@ -1,7 +1,7 @@
# ingestion-consumer
-Rust Kafka consumer that routes analytics events to Node.js ingestion workers over HTTP with sticky per-key assignment.
-It reads batches from Kafka, groups messages by Kafka message key, pins each key to a worker (preserving per-key ordering; unkeyed messages can go to any worker), scatters sub-batches over HTTP, and commits offsets only after every message in the batch is accepted.
+Rust Kafka consumer that routes analytics events to Node.js ingestion workers over ordered gRPC streams with sticky per-key assignment.
+It reads batches from Kafka, groups messages by Kafka message key, pins each key to a worker (preserving per-key ordering; unkeyed messages can go to any worker), sends each worker's sub-batches on its `WorkerIngest` stream, and commits offsets only after every message in the batch is accepted.
Worker health combines active `/_ready` probes with passive send outcomes; workers that leave the pool drain gracefully — in-flight work finishes, new work for their keys defers and re-routes to survivors in order.
## Ordering sentinels
@@ -22,7 +22,7 @@ Alerts should gate on `ingestion_consumer_offset_commits_total > 0` — an idle
Both sides default to enabled and have kill switches: `CONSUMER_ORDER_SENTINEL_ENABLED` here, `INGESTION_API_FEED_ORDER_SENTINEL_ENABLED` (plus `INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS`) on the worker.
The rebalance metrics from the consumer context stay on regardless, and the `consumer_id`/`replay` request fields are always stamped so either side can be toggled independently.
-The worker-side check lives in `nodejs/src/ingestion/api/feed-order-sentinel.ts`, fed by the `consumer_id` (process incarnation) and `replay` fields the transport stamps on every `/ingest` request.
+The worker-side check lives in `nodejs/src/ingestion/api/feed-order-sentinel.ts`, fed by the `consumer_id` (process incarnation) and `replay` fields the transport stamps on every sub-batch.
It measures the invariant at its end point: the worker's grouping stage processes each key strictly in feed order, so "fed in offset order per key" is "processed in order per key".
Rebalances reset all baselines (`ingestion_consumer_rebalances_total{event}` counts them), so partition handoffs don't fire false positives.
Null-key messages (e.g. overflow rerouting) are excluded from both checks: the producer deliberately forfeits per-key order for them, and the consumer routes each one individually rather than pinning it, so there is no invariant to check on either side.
@@ -33,7 +33,7 @@ Set `DEBUG_API_ENABLED=true` **and** `DEBUG_API_SECRET` to mount a real-time deb
Every request must present the secret as `X-Debug-Api-Secret`; enabling without a secret fails closed (nothing is mounted).
The secret is dedicated to this control-plane→consumer hop — deliberately not `INTERNAL_API_SECRET` (see `.agents/security.md`).
The ingestion control plane UI consumes these endpoints to render the consumer's live state.
-`debug_recorder.rs` keeps a bounded in-memory buffer of structured lifecycle events — batch dispatch/assignment/commit, deferrals and flushes, send retries/exhaustion, worker health and membership — recorded at the same points that emit metrics, and it never influences routing.
+`debug_recorder.rs` keeps a bounded in-memory buffer of structured lifecycle events — batch dispatch/assignment/commit, deferrals and flushes, worker health and membership — recorded at the same points that emit metrics, and it never influences routing.
- `/debug/load` — cheap JSON snapshot (worker health + dispatcher in-flight/pins/stash), safe to poll fast.
- `/debug/state` — the same plus the retained event backlog.
@@ -49,11 +49,9 @@ The ingestion control plane UI consumes these endpoints to render the consumer's
Known gaps in priority order.
The details below are grounded in the current code — re-verify limits and paths before building on them.
-### 1. Sub-batch size cap and 413 handling (incident-class)
+### 1. Sub-batch size cap — done
-Sub-batches have no size bound: a batch (default 500 messages, each up to ~1 MB of Kafka payload) can merge onto one worker as a single HTTP request, while the worker's express app rejects bodies over 20 MB (`nodejs/src/common/api/router.ts`) with a 413.
-The transport treats 4xx as non-retriable, so the same oversized sub-batch re-sends until the deferred-flush timeout, the process exits, Kafka redelivers, and it crash-loops deterministically — a stalled partition triggered by an ordinary burst of large events.
-Fix: cap sub-batch payload size at build time (chunks sent sequentially per worker to preserve per-key order), plus a defensive split-in-half retry on 413.
+Sub-batches are split at `INGESTION_TRANSPORT_MAX_BODY_BYTES` (default 10 MiB) into consecutive frames on the worker stream, under the worker's `INGESTION_API_GRPC_READ_MAX_BYTES` (32 MiB).
### 2. Commit-error observability — done
@@ -63,7 +61,7 @@ Remaining: alert rules on the new metrics.
### 3. DLQ for poison messages
-A message a worker permanently rejects (4xx, or persistent `status:"error"`) has no dead-letter path: after the flush timeout the batch fails and the process crash-loops on redelivery.
+A message a worker permanently rejects (a nack on every delivery) has no dead-letter path: after the flush timeout the batch fails and the process crash-loops on redelivery.
`poison_batch_fails_safely_without_committing` pins the safe half of the trade-off (never commit past unaccepted messages).
Needs a design pass: DLQ topic, retry budget before giving up, the per-key ordering caveat (DLQ-ing one message then delivering later ones for the same person), and replay ownership.
Non-UTF-8 payloads — currently nulled in `collect_batch` with no metric — should route to the same DLQ as malformed input; a bytes-preserving wire format is not worth it while the producer (capture) guarantees UTF-8 JSON.
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rs
index 677175605238..d8f0b17919c4 100644
--- a/rust/ingestion-consumer/src/config.rs
+++ b/rust/ingestion-consumer/src/config.rs
@@ -6,7 +6,6 @@ use tracing::info;
use crate::discovery::DiscoveryMode;
use crate::kafka_config::ConsumerConfigBuilder;
use crate::routing::RoutingStrategy;
-use crate::transports::TransportMode;
/// Configuration for the ingestion consumer.
///
@@ -206,57 +205,26 @@ pub struct Config {
pub consumer_order_sentinel_enabled: bool,
// ---- Worker transport ----
- /// Comma-separated list of worker HTTP URLs
+ /// Comma-separated list of worker HTTP URLs. Readiness probes hit these
+ /// directly; each worker's gRPC stream address is derived from its URL's
+ /// host plus the gRPC port settings below.
#[envconfig(default = "http://localhost:9001")]
pub worker_addresses: String,
- /// HTTP request timeout for worker calls (milliseconds)
- #[envconfig(default = "30000")]
- pub http_timeout_ms: u64,
-
- /// Maximum number of retries for a failed worker call
- #[envconfig(default = "3")]
- pub max_retries: u32,
-
- /// Soft cap on in-flight batches per worker, enforced by a per-worker
- /// `Semaphore`. Ideally aligned with the worker's
- /// `BatchingPipeline.concurrentBatches` (`INGESTION_WORKER_CONCURRENT_BATCHES`
- /// on the Node.js side) so the happy path backpressures by waiting for a
- /// permit before the worker fills up. It need not match exactly: if the
- /// worker still responds 503, the transport treats it as retriable
- /// backpressure and retries with a longer, jittered backoff. Divergence
- /// remains observable via `ingestion_api_batch_capacity_rejections_total`.
- /// (A future adaptive-concurrency controller will replace this static cap.)
+ /// Cap on un-acked sub-batches per worker stream. Ideally aligned with the
+ /// worker's `BatchingPipeline.concurrentBatches`
+ /// (`INGESTION_WORKER_CONCURRENT_BATCHES` on the Node.js side) so the
+ /// stream backpressures before the worker stalls its reads.
#[envconfig(from = "INGESTION_WORKER_CONCURRENT_BATCHES", default = "1")]
pub ingestion_worker_concurrent_batches: usize,
- /// Gzip-compress /ingest request bodies (`Content-Encoding: gzip`). Batch
- /// bodies are JSON wrapping JSON-text Kafka messages, so they compress
- /// several-fold; the worker's Express body parser inflates transparently.
- /// Kill switch in case compression CPU cost is ever implicated.
- #[envconfig(from = "INGESTION_TRANSPORT_COMPRESSION_ENABLED", default = "true")]
- pub transport_compression_enabled: bool,
-
- /// Cap on the serialized JSON size of one /ingest request body (bytes).
- /// Sub-batches above it are split into multiple sequential requests. Must
- /// stay under the worker's HTTP body limit (20 MB) with headroom for the
- /// size estimate; a request the worker still rejects with 413 is halved
- /// and resent. Default 10 MiB.
+ /// Cap on the estimated serialized size of one sub-batch frame (bytes).
+ /// Sub-batches above it ride the worker stream as consecutive chunks. Must
+ /// stay under the worker's gRPC message limit with headroom for the size
+ /// estimate. Default 10 MiB.
#[envconfig(from = "INGESTION_TRANSPORT_MAX_BODY_BYTES", default = "10485760")]
pub transport_max_body_bytes: usize,
- /// Shared secret for authenticating with Node.js workers (X-Internal-Api-Secret header)
- #[envconfig(default = "")]
- pub internal_api_secret: String,
-
- /// How sub-batches reach the workers: `http` (concurrent POST /ingest
- /// requests) or `grpc` (one ordered WorkerIngest stream per worker, which
- /// closes the wire-reordering window concurrent HTTP requests leave open).
- /// The worker must serve the stream (`INGESTION_API_GRPC_ENABLED`) before
- /// a consumer switches to `grpc`.
- #[envconfig(from = "INGESTION_TRANSPORT", default = "http")]
- pub ingestion_transport: TransportMode,
-
/// The worker pods' gRPC port (`INGESTION_API_GRPC_PORT` on the Node.js
/// side). Worker streams derive each worker's stream address from its HTTP URL's
/// host plus this port.
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index 9cf9536041ab..cec689f7843d 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -17,9 +17,9 @@ use crate::config::Config;
use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionOffset};
use crate::discovery::DiscoveryMode;
use crate::dispatcher::{Dispatcher, EagerFlush, KeyOffset, SubBatch};
+use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};
use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};
use crate::transport::SendError;
-use crate::transports::{PendingSend, Transport};
use crate::types::SerializedKafkaMessage;
use crate::worker_registry::WorkerId;
@@ -71,13 +71,13 @@ struct InFlightBatch {
}
/// A sub-batch whose send order is already established on its worker's stream
-/// (`Transport::begin_send`), plus the metadata the resolve protocol needs.
+/// (`GrpcTransport::begin_send`), plus the metadata the resolve protocol needs.
struct PendingSubBatch {
worker: WorkerId,
routing_keys: Vec<String>,
key_offsets: Vec<KeyOffset>,
message_count: usize,
- pending: PendingSend,
+ pending: PendingWorkerStreamSend,
}
/// Options for constructing an [`IngestionConsumer`] from pre-built parts.
@@ -104,11 +104,11 @@ pub struct IngestionConsumerOptions {
/// The main consumer loop: reads from Kafka, routes messages by Kafka key
/// via the health-aware Dispatcher, dispatches sub-batches to workers over
-/// HTTP, and commits offsets only after all workers ACK.
+/// ordered gRPC streams, and commits offsets only after all workers ACK.
pub struct IngestionConsumer {
consumer: Arc<StreamConsumer<SentinelContext>>,
dispatcher: Arc<Dispatcher>,
- transport: Arc<Transport>,
+ transport: Arc<GrpcTransport>,
worker_urls: Vec<String>,
batch_size: usize,
batch_size_bytes: usize,
@@ -132,7 +132,7 @@ impl IngestionConsumer {
pub fn from_parts(
consumer: StreamConsumer<SentinelContext>,
dispatcher: Arc<Dispatcher>,
- transport: Arc<Transport>,
+ transport: Arc<GrpcTransport>,
worker_urls: Vec<String>,
options: IngestionConsumerOptions,
handle: Handle,
@@ -161,7 +161,7 @@ impl IngestionConsumer {
pub fn new(
config: &Config,
dispatcher: Arc<Dispatcher>,
- transport: Arc<Transport>,
+ transport: Arc<GrpcTransport>,
handle: Handle,
debug_recorder: Option<Arc<DebugRecorder>>,
) -> anyhow::Result<Self> {
@@ -189,9 +189,7 @@ impl IngestionConsumer {
let key_sentinel = dispatcher.key_order_sentinel();
key_sentinel.set_enabled(config.consumer_order_sentinel_enabled);
let mut context = SentinelContext::new(Arc::clone(&commit_sentinel), key_sentinel);
- if let Transport::Grpc(grpc) = &*transport {
- context.set_assignment_epoch(grpc.assignment_epoch());
- }
+ context.set_assignment_epoch(transport.assignment_epoch());
let consumer: StreamConsumer<SentinelContext> =
client_config.create_with_context(context)?;
consumer.subscribe(&[&config.ingestion_consumer_consume_topic])?;
@@ -532,7 +530,7 @@ impl IngestionConsumer {
/// channel-receive order, before the awaiting task spawns.
async fn run_eager_flush_loop(
dispatcher: Arc<Dispatcher>,
- transport: Arc<Transport>,
+ transport: Arc<GrpcTransport>,
mut rx: mpsc::UnboundedReceiver<EagerFlush>,
) {
while let Some(flush) = rx.recv().await {
@@ -623,7 +621,7 @@ impl IngestionConsumer {
/// lock on the consumer loop, and in the eager flush loop), so a key's
/// sub-batches enter its worker's stream in exactly that order.
fn begin_send(
- transport: &Transport,
+ transport: &GrpcTransport,
batch_id: &str,
sub_batch: SubBatch,
replay: bool,
diff --git a/rust/ingestion-consumer/src/debug_recorder.rs b/rust/ingestion-consumer/src/debug_recorder.rs
index 473e84f2c7c4..32b4d99ab764 100644
--- a/rust/ingestion-consumer/src/debug_recorder.rs
+++ b/rust/ingestion-consumer/src/debug_recorder.rs
@@ -93,30 +93,6 @@ pub enum DebugEventKind {
batch_id: Option<String>,
error: String,
},
- /// A send to a worker was retried (`reason`: busy/error).
- SendRetry {
- worker: String,
- batch_id: String,
- attempt: u32,
- reason: &'static str,
- },
- /// A sub-batch was split into size-bounded chunks before sending
- /// (`reason`: size_estimate — the pre-send estimate exceeded the body cap —
- /// or http_413 — the worker rejected a chunk and it was halved).
- SendSplit {
- worker: String,
- batch_id: String,
- reason: &'static str,
- chunks: usize,
- messages: usize,
- },
- /// A send exhausted its retries; the messages are deferred for replay.
- SendExhausted {
- worker: String,
- batch_id: String,
- messages: usize,
- error: String,
- },
/// A worker moved between health states.
WorkerStateChanged {
worker: String,
diff --git a/rust/ingestion-consumer/src/grpc_transport.rs b/rust/ingestion-consumer/src/grpc_transport.rs
index 02d148714fbb..8f396c242560 100644
--- a/rust/ingestion-consumer/src/grpc_transport.rs
+++ b/rust/ingestion-consumer/src/grpc_transport.rs
@@ -74,7 +74,7 @@ pub struct PendingWorkerStreamSend {
}
impl PendingWorkerStreamSend {
- /// All-or-nothing, like `HttpTransport::send_batch`: `Ok` only when every
+ /// All-or-nothing: `Ok` only when every
/// chunk was accepted; on any failure the `SendError` carries back the
/// full original message set, in order, so the caller defers all of it.
/// Already-accepted chunks then replay, which is ordinary at-least-once.
@@ -155,7 +155,7 @@ pub struct GrpcTransport {
/// How each worker's stream address is derived from its HTTP URL.
grpc_port: GrpcPort,
/// Max un-acked sub-batches per worker stream (aligned with the worker's
- /// `concurrentBatches`, like the HTTP semaphore it replaces).
+ /// `concurrentBatches`).
max_unacked: usize,
/// Fence the worker stream when un-acked work sees no ack for this long.
ack_timeout: Duration,
@@ -166,7 +166,7 @@ pub struct GrpcTransport {
probe_client: reqwest::Client,
/// Cap on one frame's estimated size. A sub-batch over it is sent as
/// consecutive chunks (see `begin_send`), so no frame crosses the worker's
- /// message limit — the HTTP body cap, applied per frame.
+ /// message limit.
max_body_bytes: usize,
}
@@ -576,8 +576,7 @@ impl WorkerStreamRunner {
/// sub-batch may sit unacked. Each entry carries its own deadline, armed
/// when it was sent, so the watchdog keys on the oldest (front) entry,
/// which is never acked (acked prefixes pop at once): a stuck sub-batch
- /// fences even while its siblings keep acking — the per-send bound the
- /// HTTP timeout it replaces gave. A worker that stops acking (saturated
+ /// fences even while its siblings keep acking. A worker that stops acking (saturated
/// by other consumers, wedged, half-dead network) becomes a fence — and
/// so a defer-and-reroute — rather than a silent forever-wait.
async fn await_next_ack(
@@ -878,7 +877,8 @@ fn jittered(base: Duration) -> Duration {
base.mul_f64(jitter)
}
-/// Process-unique sender id, matching the HTTP transport's semantics.
+/// Process-unique sender id: workers scope feed-order baselines to one
+/// consumer incarnation.
fn make_consumer_id() -> String {
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rs
index 75de663af429..1b29911adcfc 100644
--- a/rust/ingestion-consumer/src/lib.rs
+++ b/rust/ingestion-consumer/src/lib.rs
@@ -12,6 +12,5 @@ pub mod readiness;
pub mod routing;
pub mod stash;
pub mod transport;
-pub mod transports;
pub mod types;
pub mod worker_registry;
diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rs
index 7d8e03718f44..32b0f384ddaa 100644
--- a/rust/ingestion-consumer/src/main.rs
+++ b/rust/ingestion-consumer/src/main.rs
@@ -27,8 +27,6 @@ use ingestion_consumer::discovery::{
use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
use ingestion_consumer::routing::RoutingStrategy;
-use ingestion_consumer::transport::HttpTransport;
-use ingestion_consumer::transports::{Transport, TransportMode};
use ingestion_consumer::worker_registry::{WorkerId, WorkerRegistry, WorkerRegistryConfig};
common_alloc::used!();
@@ -236,47 +234,17 @@ async fn async_main(config: Config) -> Result<()> {
}
let dispatcher = Arc::new(dispatcher);
- let api_secret = if config.internal_api_secret.is_empty() {
- None
+ let grpc_port = if config.ingestion_worker_grpc_port_offset > 0 {
+ GrpcPort::OffsetFromHttp(config.ingestion_worker_grpc_port_offset)
} else {
- Some(config.internal_api_secret.clone())
- };
- let transport = match config.ingestion_transport {
- TransportMode::Http => {
- // Transport semaphores are created lazily per worker, so it starts empty.
- let mut transport = HttpTransport::new(
- Duration::from_millis(config.http_timeout_ms),
- config.max_retries,
- api_secret,
- &[],
- config.ingestion_worker_concurrent_batches,
- config.transport_compression_enabled,
- );
- transport.set_max_body_bytes(config.transport_max_body_bytes);
- if let Some(recorder) = &debug_recorder {
- transport.set_debug_recorder(Arc::clone(recorder));
- }
- Transport::Http(Arc::new(transport))
- }
- TransportMode::Grpc => {
- let grpc_port = if config.ingestion_worker_grpc_port_offset > 0 {
- GrpcPort::OffsetFromHttp(config.ingestion_worker_grpc_port_offset)
- } else {
- GrpcPort::Fixed(config.ingestion_worker_grpc_port)
- };
- let mut transport = GrpcTransport::new(
- grpc_port,
- config.ingestion_worker_concurrent_batches,
- Duration::from_millis(config.ingestion_worker_stream_ack_timeout_ms),
- );
- transport.set_max_body_bytes(config.transport_max_body_bytes);
- Transport::Grpc(Arc::new(transport))
- }
+ GrpcPort::Fixed(config.ingestion_worker_grpc_port)
};
- info!(
- transport = config.ingestion_transport.as_str(),
- "Worker transport selected"
+ let mut transport = GrpcTransport::new(
+ grpc_port,
+ config.ingestion_worker_concurrent_batches,
+ Duration::from_millis(config.ingestion_worker_stream_ack_timeout_ms),
);
+ transport.set_max_body_bytes(config.transport_max_body_bytes);
let transport = Arc::new(transport);
// Select the worker discovery provider and start it (static applies the
diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rs
index 8afd1cfa1b07..efa039f11dfa 100644
--- a/rust/ingestion-consumer/src/order_sentinel.rs
+++ b/rust/ingestion-consumer/src/order_sentinel.rs
@@ -565,7 +565,7 @@ pub struct SentinelContext {
key_sentinel: Arc<KeyOrderSentinel>,
/// Bumped on every partition assignment; the gRPC transport stamps it on
/// sub-batches so the worker's feed-order sentinel rebaselines across
- /// rebalances. `None` on the HTTP transport.
+ /// rebalances.
assignment_epoch: Option<Arc<AtomicU64>>,
}
diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rs
index 04ad0c9fca57..c9c414254918 100644
--- a/rust/ingestion-consumer/src/transport.rs
+++ b/rust/ingestion-consumer/src/transport.rs
@@ -1,525 +1,17 @@
-use std::collections::VecDeque;
-use std::io::Write;
-use std::sync::Arc;
-use std::time::Duration;
+//! Types shared by the worker transport: the send failure contract, the fence
+//! guard, and the size-bounded chunking that keeps one frame under the
+//! worker's message limit.
-use dashmap::DashMap;
-use flate2::write::GzEncoder;
-use flate2::Compression;
-use metrics::{counter, gauge, histogram};
-use rand::Rng;
-use tokio::sync::Semaphore;
-use tracing::{error, warn};
+use crate::types::SerializedKafkaMessage;
-use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder};
-use crate::readiness;
-use crate::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};
-
-/// Default cap on the serialized JSON size of one /ingest request body. The
-/// worker's HTTP body limit is 20 MB; half that leaves headroom for the
-/// per-message size estimate (which ignores JSON string escaping).
+/// Default cap on the estimated serialized size of one frame sent to a
+/// worker. The worker's message limit is well above this; the headroom absorbs
+/// the per-message size estimate (which ignores JSON string escaping).
pub const DEFAULT_MAX_BODY_BYTES: usize = 10 * 1024 * 1024;
-/// RAII guard that tracks the number of batches currently in flight to a
-/// worker. Increments the gauge on creation and decrements on drop, so every
-/// `send_batch` return path (success, error, retries exhausted, panic unwind)
-/// is covered — mirroring the lifetime of the worker's `Semaphore` permit.
-struct InFlightGuard {
- worker_url: String,
-}
-
-impl InFlightGuard {
- fn new(worker_url: &str) -> Self {
- gauge!("ingestion_consumer_transport_concurrent_batches", "worker" => worker_url.to_string())
- .increment(1.0);
- Self {
- worker_url: worker_url.to_string(),
- }
- }
-}
-
-impl Drop for InFlightGuard {
- fn drop(&mut self) {
- gauge!("ingestion_consumer_transport_concurrent_batches", "worker" => self.worker_url.clone())
- .decrement(1.0);
- }
-}
-
-/// Sends batches to Node.js worker processes over HTTP.
-///
-/// Uses reqwest with connection pooling (one pool per worker URL).
-/// Retries on 5xx/timeout/503 with exponential backoff.
-///
-/// Per-worker `Semaphore`s are a soft cap on how many concurrent batches we
-/// keep in flight to each worker URL — ideally aligned with the worker's
-/// `BatchingPipeline.concurrentBatches` (`INGESTION_WORKER_CONCURRENT_BATCHES`)
-/// so the happy path proactively backpressures (waits for a permit) before the
-/// worker fills up. The cap need not match the worker exactly: if the worker
-/// rejects a batch with 503, the transport treats it as transient backpressure
-/// and retries with a longer, jittered backoff. This keeps the consumer correct
-/// when a worker is shared by other callers and its true capacity isn't a
-/// number this consumer can reserve in advance.
-///
-/// Semaphores are created lazily on first send to a worker and pruned via
-/// [`remove_worker`](HttpTransport::remove_worker), so the worker pool can
-/// change at runtime (workers joining/leaving via discovery).
-pub struct HttpTransport {
- client: reqwest::Client,
- max_retries: u32,
- api_secret: Option<String>,
- worker_semaphores: DashMap<String, Arc<Semaphore>>,
- worker_concurrent_batches: usize,
- /// Gzip request bodies (`Content-Encoding: gzip`). Batch bodies are JSON
- /// wrapping JSON-text Kafka messages, so they compress several-fold; the
- /// worker's Express body parser inflates transparently.
- compression_enabled: bool,
- /// Process-unique sender id stamped on every request, so the worker-side
- /// feed-order sentinel can rebaseline when the consumer restarts.
- consumer_id: String,
- /// Cap on the serialized JSON size of one request body. Sub-batches whose
- /// estimated size exceeds it are split into multiple sequential requests;
- /// a request the worker still rejects with 413 is halved and resent.
- max_body_bytes: usize,
- /// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.
- debug_recorder: Option<Arc<DebugRecorder>>,
-}
-
-impl HttpTransport {
- pub fn new(
- timeout: Duration,
- max_retries: u32,
- api_secret: Option<String>,
- worker_urls: &[String],
- worker_concurrent_batches: usize,
- compression_enabled: bool,
- ) -> Self {
- assert!(
- worker_concurrent_batches > 0,
- "worker_concurrent_batches must be > 0"
- );
-
- let client = reqwest::Client::builder()
- .timeout(timeout)
- .pool_max_idle_per_host(4)
- .build()
- .expect("failed to create HTTP client");
-
- // Pre-seed semaphores for the initial worker set; new workers get one
- // lazily on first send (see `semaphore_for`).
- let worker_semaphores = DashMap::new();
- for url in worker_urls {
- worker_semaphores.insert(
- url.clone(),
- Arc::new(Semaphore::new(worker_concurrent_batches)),
- );
- }
-
- Self {
- client,
- max_retries,
- api_secret,
- worker_semaphores,
- worker_concurrent_batches,
- compression_enabled,
- consumer_id: make_consumer_id(),
- max_body_bytes: DEFAULT_MAX_BODY_BYTES,
- debug_recorder: None,
- }
- }
-
- /// Inject the debug UI recorder. Call before the transport is shared.
- pub fn set_debug_recorder(&mut self, recorder: Arc<DebugRecorder>) {
- self.debug_recorder = Some(recorder);
- }
-
- /// Override the request body size cap. Call before the transport is shared.
- pub fn set_max_body_bytes(&mut self, bytes: usize) {
- assert!(bytes > 0, "max_body_bytes must be > 0");
- self.max_body_bytes = bytes;
- }
-
- /// Get the worker's concurrency semaphore, creating it on first use so the
- /// transport serves workers added at runtime without explicit registration.
- fn semaphore_for(&self, worker_url: &str) -> Arc<Semaphore> {
- if let Some(sem) = self.worker_semaphores.get(worker_url) {
- return sem.clone();
- }
- self.worker_semaphores
- .entry(worker_url.to_string())
- .or_insert_with(|| Arc::new(Semaphore::new(self.worker_concurrent_batches)))
- .clone()
- }
-
- /// Drop a worker's semaphore after it leaves the pool, so departed workers
- /// don't accumulate. In-flight sends already hold a cloned `Arc`, so their
- /// permits remain valid until they complete.
- pub fn remove_worker(&self, worker_url: &str) {
- self.worker_semaphores.remove(worker_url);
- }
-
- /// Check if a worker is ready by probing its health endpoint.
- pub async fn check_ready(&self, worker_url: &str) -> bool {
- readiness::check_ready(&self.client, worker_url).await
- }
-
- /// Wait until all workers are ready, polling with backoff.
- /// Returns an error if shutdown is signalled before all workers are ready.
- pub async fn wait_for_workers_ready(
- &self,
- worker_urls: &[String],
- shutdown: &lifecycle::Handle,
- ) -> anyhow::Result<()> {
- readiness::wait_for_workers_ready(&self.client, worker_urls, shutdown).await
- }
-
- /// Send a sub-batch to a worker. Returns the number of accepted messages.
- ///
- /// Acquires a permit from the worker's `Semaphore` before sending. If
- /// `worker_concurrent_batches` permits are already held, the call waits
- /// here — that's the natural backpressure. The permit is released on
- /// drop, covering all return paths (success, retriable error, retries
- /// exhausted, non-retriable error).
- ///
- /// A sub-batch whose estimated body size exceeds `max_body_bytes` is split
- /// into multiple sequential requests (order-preserving, under the same
- /// permit). A request the worker still rejects with 413 is halved and
- /// resent; a single message the worker rejects with 413 is a non-retriable
- /// failure. The result stays all-or-nothing: `Ok` only when every chunk was
- /// accepted, and on any failure the `SendError` carries back the full
- /// original message set — already-accepted chunks may then be re-sent
- /// later, which is ordinary at-least-once replay.
- ///
- /// `replay` marks a request that may repeat previously sent messages (a
- /// deferred-flush re-route); HTTP retries within this call are marked as
- /// replays automatically.
- pub async fn send_batch(
- &self,
- worker_url: &str,
- batch_id: &str,
- messages: Vec<SerializedKafkaMessage>,
- replay: bool,
- ) -> Result<u32, SendError> {
- let semaphore = self.semaphore_for(worker_url);
-
- // Atomic "did we actually have to wait?" check. `available_permits`
- // followed by `acquire_owned` would race — a permit could be released
- // between the two (false positive) or stolen (false negative). Using
- // `try_acquire_owned` first gives an accurate backpressure counter.
- let _permit = match semaphore.clone().try_acquire_owned() {
- Ok(permit) => permit,
- Err(_) => {
- counter!(
- "ingestion_consumer_transport_backpressure_waits_total",
- "worker" => worker_url.to_string()
- )
- .increment(1);
- semaphore
- .acquire_owned()
- .await
- .expect("worker semaphore must not be closed")
- }
- };
-
- // Now that the permit is held, this batch is genuinely in flight to the
- // worker. The guard decrements the gauge on every return path.
- let _in_flight = InFlightGuard::new(worker_url);
-
- let message_total = messages.len();
- let mut queue: VecDeque<Vec<SerializedKafkaMessage>> =
- split_by_size(messages, self.max_body_bytes).into();
- if queue.len() > 1 {
- counter!(
- "ingestion_consumer_transport_batch_splits_total",
- "reason" => "size_estimate"
- )
- .increment((queue.len() - 1) as u64);
- record_if(&self.debug_recorder, || DebugEventKind::SendSplit {
- worker: worker_url.to_string(),
- batch_id: batch_id.to_string(),
- reason: "size_estimate",
- chunks: queue.len(),
- messages: message_total,
- });
- }
-
- let mut sent: Vec<SerializedKafkaMessage> = Vec::new();
- let mut accepted_total = 0u32;
- while let Some(chunk) = queue.pop_front() {
- match self.send_chunk(worker_url, batch_id, chunk, replay).await {
- ChunkOutcome::Accepted { accepted, messages } => {
- accepted_total += accepted;
- sent.extend(messages);
- }
- ChunkOutcome::TooLarge { messages } if messages.len() > 1 => {
- // The estimate undershot the worker's body limit — halve
- // the chunk and resend both parts, front of the queue so
- // message order is preserved.
- counter!(
- "ingestion_consumer_transport_batch_splits_total",
- "reason" => "http_413"
- )
- .increment(1);
- record_if(&self.debug_recorder, || DebugEventKind::SendSplit {
- worker: worker_url.to_string(),
- batch_id: batch_id.to_string(),
- reason: "http_413",
- chunks: 2,
- messages: messages.len(),
- });
- let mut left = messages;
- let right = left.split_off(left.len() / 2);
- queue.push_front(right);
- queue.push_front(left);
- }
- ChunkOutcome::TooLarge { messages } => {
- // A single message the worker refuses can never succeed by
- // splitting or retrying.
- error!(
- worker = %worker_url,
- batch_id = %batch_id,
- "Worker rejected a single message as too large"
- );
- return Err(SendError {
- error: TransportError::PayloadTooLarge(String::new()),
- messages: reassemble(sent, messages, queue),
- fence_guard: None,
- });
- }
- ChunkOutcome::Failed { error, messages } => {
- return Err(SendError {
- error,
- messages: reassemble(sent, messages, queue),
- fence_guard: None,
- });
- }
- }
- }
-
- Ok(accepted_total)
- }
-
- /// Send one already-size-bounded chunk with the retry loop. Ownership of
- /// the messages travels through the outcome so the caller can split or
- /// re-defer them.
- async fn send_chunk(
- &self,
- worker_url: &str,
- batch_id: &str,
- messages: Vec<SerializedKafkaMessage>,
- replay: bool,
- ) -> ChunkOutcome {
- let message_count = messages.len();
- let mut request = IngestBatchRequest {
- batch_id: batch_id.to_string(),
- messages,
- consumer_id: self.consumer_id.clone(),
- replay,
- };
-
- let url = format!("{worker_url}/ingest");
-
- let mut last_err = None;
- // Whether the previous attempt failed with a 503. A busy worker gets a
- // longer, jittered backoff so callers don't retry it in lockstep.
- let mut last_was_busy = false;
- for attempt in 0..=self.max_retries {
- if attempt > 0 {
- // A retried request may repeat messages the worker already
- // processed (e.g. a timeout after the worker finished) — mark it
- // so the worker-side sentinel counts repeats as replays.
- request.replay = true;
- tokio::time::sleep(retry_backoff(attempt, last_was_busy)).await;
- counter!(
- "ingestion_consumer_transport_retries_total",
- "worker" => worker_url.to_string(),
- "reason" => if last_was_busy { "busy" } else { "error" },
- )
- .increment(1);
- record_if(&self.debug_recorder, || DebugEventKind::SendRetry {
- worker: worker_url.to_string(),
- batch_id: batch_id.to_string(),
- attempt,
- reason: if last_was_busy { "busy" } else { "error" },
- });
- }
-
- let start = std::time::Instant::now();
- match self.do_send(&url, &request).await {
- Ok(response) => {
- let elapsed = start.elapsed();
- histogram!("ingestion_consumer_transport_duration_seconds", "worker" => worker_url.to_string())
- .record(elapsed.as_secs_f64());
- counter!("ingestion_consumer_transport_requests_total", "worker" => worker_url.to_string(), "status" => "ok")
- .increment(1);
-
- if response.status == "ok" {
- return ChunkOutcome::Accepted {
- accepted: response.accepted,
- messages: request.messages,
- };
- }
-
- last_was_busy = false;
- let err_msg = response.error.unwrap_or_default();
- warn!(
- worker = %worker_url,
- batch_id = %batch_id,
- attempt = attempt + 1,
- error = %err_msg,
- "Worker returned error status"
- );
- last_err = Some(TransportError::WorkerError(err_msg));
- }
- Err(err) => {
- let elapsed = start.elapsed();
- histogram!("ingestion_consumer_transport_duration_seconds", "worker" => worker_url.to_string())
- .record(elapsed.as_secs_f64());
- last_was_busy = matches!(err, TransportError::WorkerBusy(_));
- let status_label = if last_was_busy { "busy" } else { "error" };
- counter!("ingestion_consumer_transport_requests_total", "worker" => worker_url.to_string(), "status" => status_label)
- .increment(1);
-
- warn!(
- worker = %worker_url,
- batch_id = %batch_id,
- attempt = attempt + 1,
- messages = message_count,
- error = %err,
- "Failed to send batch to worker"
- );
- // 413 is deterministic for this chunk on every worker —
- // hand it back for splitting instead of retrying verbatim.
- if matches!(err, TransportError::PayloadTooLarge(_)) {
- return ChunkOutcome::TooLarge {
- messages: request.messages,
- };
- }
- if !err.is_retriable() {
- return ChunkOutcome::Failed {
- error: err,
- messages: request.messages,
- };
- }
- last_err = Some(err);
- }
- }
- }
-
- let err = last_err.unwrap_or(TransportError::RetriesExhausted);
- error!(
- worker = %worker_url,
- batch_id = %batch_id,
- messages = message_count,
- max_retries = self.max_retries,
- "All retries exhausted"
- );
- counter!("ingestion_consumer_transport_exhausted_total", "worker" => worker_url.to_string())
- .increment(1);
- record_if(&self.debug_recorder, || DebugEventKind::SendExhausted {
- worker: worker_url.to_string(),
- batch_id: batch_id.to_string(),
- messages: message_count,
- error: err.to_string(),
- });
- ChunkOutcome::Failed {
- error: err,
- messages: request.messages,
- }
- }
-
- async fn do_send(
- &self,
- url: &str,
- request: &IngestBatchRequest,
- ) -> Result<IngestBatchResponse, TransportError> {
- // Serialized per attempt: the retry loop flips `request.replay`
- // between attempts, so the body can't be built once up front.
- let json = serde_json::to_vec(request)?;
- counter!("ingestion_consumer_transport_body_bytes_total", "encoding" => "raw")
- .increment(json.len() as u64);
-
- let mut req_builder = self
- .client
- .post(url)
- .header(reqwest::header::CONTENT_TYPE, "application/json");
- if self.compression_enabled {
- let body = gzip(&json);
- counter!("ingestion_consumer_transport_body_bytes_total", "encoding" => "gzip")
- .increment(body.len() as u64);
- req_builder = req_builder
- .header(reqwest::header::CONTENT_ENCODING, "gzip")
- .body(body);
- } else {
- req_builder = req_builder.body(json);
- }
- if let Some(secret) = &self.api_secret {
- req_builder = req_builder.header("X-Internal-Api-Secret", secret);
- }
- let response = req_builder.send().await?;
- let status = response.status();
-
- // 503 means the worker is at concurrent batch capacity. Surface it as a
- // distinct error so the retry loop applies the longer, jittered busy
- // backoff (rather than hammering with the short 5xx backoff).
- if status == reqwest::StatusCode::SERVICE_UNAVAILABLE {
- let body = response.text().await.unwrap_or_default();
- return Err(TransportError::WorkerBusy(body));
- }
-
- // 413 means the body exceeded the worker's HTTP body limit. Every
- // worker enforces the same limit, so retrying elsewhere can't succeed;
- // the caller splits the chunk instead.
- if status == reqwest::StatusCode::PAYLOAD_TOO_LARGE {
- let body = response.text().await.unwrap_or_default();
- return Err(TransportError::PayloadTooLarge(body));
- }
-
- if status.is_client_error() || status.is_server_error() {
- let body = response.text().await.unwrap_or_default();
- return Err(TransportError::HttpStatus(status.as_u16(), body));
- }
-
- let parsed: IngestBatchResponse = response.json().await?;
- Ok(parsed)
- }
-}
-
-/// Outcome of sending one size-bounded chunk of a sub-batch.
-enum ChunkOutcome {
- Accepted {
- accepted: u32,
- messages: Vec<SerializedKafkaMessage>,
- },
- /// The worker rejected the body with 413 — split and resend, don't retry.
- TooLarge {
- messages: Vec<SerializedKafkaMessage>,
- },
- Failed {
- error: TransportError,
- messages: Vec<SerializedKafkaMessage>,
- },
-}
-
-/// Rebuild the sub-batch's full message list, in original order, from the
-/// already-sent chunks, the failing chunk, and the not-yet-sent remainder —
-/// `send_batch`'s failure contract hands the whole sub-batch back to the
-/// caller for deferral.
-fn reassemble(
- mut sent: Vec<SerializedKafkaMessage>,
- failed: Vec<SerializedKafkaMessage>,
- queue: VecDeque<Vec<SerializedKafkaMessage>>,
-) -> Vec<SerializedKafkaMessage> {
- sent.extend(failed);
- for chunk in queue {
- sent.extend(chunk);
- }
- sent
-}
-
-/// Approximate serialized JSON size of one message within the batch body.
-/// Field names and punctuation are a small constant; escaping of the embedded
-/// JSON text is absorbed by the headroom between the split cap and the
-/// worker's hard body limit (and by the 413 halving fallback).
+/// Approximate serialized size of one message within a frame. Field names and
+/// punctuation are a small constant; escaping of the embedded JSON text is
+/// absorbed by the headroom between the split cap and the worker's hard limit.
fn approx_message_size(msg: &SerializedKafkaMessage) -> usize {
const PER_MESSAGE_OVERHEAD: usize = 96;
msg.topic.len()
@@ -558,9 +50,9 @@ pub(crate) fn split_by_size(
chunks
}
-/// Failure from [`HttpTransport::send_batch`], carrying back the batch's
-/// messages so the caller can defer/replay them (the worker may have died
-/// mid-send and the messages were never accepted).
+/// Failure from a worker stream send, carrying back the sub-batch's messages
+/// so the caller can defer/replay them (the worker may have died mid-send and
+/// the messages were never accepted).
#[derive(Debug)]
pub struct SendError {
pub error: TransportError,
@@ -608,27 +100,6 @@ impl std::fmt::Debug for FenceGuard {
#[derive(Debug, thiserror::Error)]
pub enum TransportError {
- #[error("HTTP request failed: {0}")]
- Http(#[from] reqwest::Error),
-
- #[error("Failed to serialize request: {0}")]
- Serialize(#[from] serde_json::Error),
-
- #[error("Worker busy (HTTP 503): {0}")]
- WorkerBusy(String),
-
- #[error("Request body too large (HTTP 413): {0}")]
- PayloadTooLarge(String),
-
- #[error("Worker returned HTTP {0}: {1}")]
- HttpStatus(u16, String),
-
- #[error("Worker returned error: {0}")]
- WorkerError(String),
-
- #[error("All retries exhausted")]
- RetriesExhausted,
-
#[error("Worker stream failed: {0}")]
WorkerStreamFailed(&'static str),
@@ -640,77 +111,17 @@ pub enum TransportError {
}
impl TransportError {
- /// 4xx errors are non-transient and should not be retried.
- /// `WorkerBusy` (HTTP 503) is retriable backpressure: a worker shared by
- /// other callers can be momentarily at capacity even when this consumer's
- /// soft semaphore cap would allow more, so we retry with a longer, jittered
- /// backoff instead of failing.
+ /// Worker stream failures resolve through the deferral path and are never
+ /// retried in place. A busy worker stream is transient backpressure, so the
+ /// fenced work re-routes as retriable rather than as a worker fault.
pub fn is_retriable(&self) -> bool {
- match self {
- TransportError::HttpStatus(status, _) => *status >= 500,
- TransportError::Http(_) => true,
- TransportError::Serialize(_) => false,
- TransportError::WorkerBusy(_) => true,
- TransportError::PayloadTooLarge(_) => false,
- TransportError::WorkerError(_) => true,
- TransportError::RetriesExhausted => false,
- // Worker stream failures resolve through the deferral path, not the HTTP
- // retry loop — never retried in place.
- TransportError::WorkerStreamFailed(_) => false,
- // A busy worker stream is transient backpressure (like WorkerBusy), so the
- // fenced work re-routes as retriable rather than a worker fault.
- TransportError::WorkerStreamBusy(_) => true,
- TransportError::WorkerStreamClosed => false,
- }
+ matches!(self, TransportError::WorkerStreamBusy(_))
}
- /// Backpressure the worker signalled deliberately (503 or a busy worker stream).
- /// Distinct from `is_retriable`: connection errors and 5xx are retriable
- /// too, but they are worker faults and must count against passive health.
+ /// Backpressure the worker signalled deliberately. Distinct from a worker
+ /// fault, which must count against passive health.
pub fn is_backpressure(&self) -> bool {
- matches!(
- self,
- TransportError::WorkerBusy(_) | TransportError::WorkerStreamBusy(_)
- )
- }
-}
-
-/// Backoff before a retry. A busy worker (503) gets a longer base plus jitter so
-/// that callers backing off the same worker don't retry in lockstep; other
-/// retriable errors use a short exponential backoff. `attempt` is 1-based (the
-/// first retry passes 1).
-/// Process-unique sender id: workers use it to scope feed-order baselines to
-/// one consumer incarnation.
-fn make_consumer_id() -> String {
- let ts = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_millis();
- let rand: u32 = rand::random();
- format!("{ts:x}-{rand:08x}")
-}
-
-/// Gzip a serialized body. Level `fast` (1): the payload is JSON text that
-/// already compresses several-fold at the lowest level, and this sits on the
-/// per-batch send path where CPU spent compressing delays the batch.
-fn gzip(bytes: &[u8]) -> Vec<u8> {
- let mut encoder = GzEncoder::new(Vec::with_capacity(bytes.len() / 4), Compression::fast());
- encoder
- .write_all(bytes)
- .expect("writing to a Vec cannot fail");
- encoder
- .finish()
- .expect("finishing a Vec-backed gzip stream cannot fail")
-}
-
-fn retry_backoff(attempt: u32, busy: bool) -> Duration {
- let exp = 2u64.saturating_pow(attempt.saturating_sub(1));
- if busy {
- let base = (250 * exp).min(5_000);
- let jitter = rand::thread_rng().gen_range(0..=base / 2);
- Duration::from_millis(base + jitter)
- } else {
- Duration::from_millis(100 * exp)
+ matches!(self, TransportError::WorkerStreamBusy(_))
}
}
@@ -719,25 +130,13 @@ mod tests {
use super::*;
#[test]
- fn test_worker_busy_is_retriable() {
- assert!(TransportError::WorkerBusy("at capacity".into()).is_retriable());
- }
-
- #[test]
- fn test_only_busy_errors_are_backpressure() {
- assert!(TransportError::WorkerBusy("at capacity".into()).is_backpressure());
+ fn test_only_busy_errors_are_backpressure_and_retriable() {
assert!(TransportError::WorkerStreamBusy("busy").is_backpressure());
- assert!(!TransportError::HttpStatus(500, "boom".into()).is_backpressure());
- assert!(!TransportError::WorkerError("boom".into()).is_backpressure());
+ assert!(TransportError::WorkerStreamBusy("busy").is_retriable());
assert!(!TransportError::WorkerStreamFailed("nack").is_backpressure());
- assert!(!TransportError::RetriesExhausted.is_backpressure());
- }
-
- #[test]
- fn test_client_errors_are_not_retriable() {
- assert!(!TransportError::HttpStatus(400, "bad".into()).is_retriable());
- assert!(!TransportError::PayloadTooLarge("too big".into()).is_retriable());
- assert!(!TransportError::RetriesExhausted.is_retriable());
+ assert!(!TransportError::WorkerStreamFailed("nack").is_retriable());
+ assert!(!TransportError::WorkerStreamClosed.is_backpressure());
+ assert!(!TransportError::WorkerStreamClosed.is_retriable());
}
fn message_with_value(offset: i64, value_len: usize) -> SerializedKafkaMessage {
@@ -792,34 +191,4 @@ mod tests {
assert_eq!(chunks.len(), 1);
assert_eq!(chunks[0].len(), 3);
}
-
- #[test]
- fn test_server_errors_are_retriable() {
- assert!(TransportError::HttpStatus(500, "boom".into()).is_retriable());
- }
-
- #[test]
- fn test_busy_backoff_is_longer_than_error_backoff() {
- // Across attempts the busy backoff floor (base, no jitter) must exceed
- // the error backoff for the same attempt.
- for attempt in 1..=4 {
- let busy_min = 250 * 2u64.saturating_pow(attempt - 1);
- let err = retry_backoff(attempt, false);
- assert!(
- retry_backoff(attempt, true) >= Duration::from_millis(busy_min.min(5_000)),
- "busy backoff below floor at attempt {attempt}"
- );
- assert!(
- err < Duration::from_millis(busy_min.min(5_000)),
- "error backoff not shorter than busy at attempt {attempt}"
- );
- }
- }
-
- #[test]
- fn test_busy_backoff_is_capped() {
- // Even at a high attempt the busy base is capped at 5s; jitter adds up to
- // half the base, so the total stays at most 7.5s.
- assert!(retry_backoff(20, true) <= Duration::from_millis(7_500));
- }
}
diff --git a/rust/ingestion-consumer/src/transports.rs b/rust/ingestion-consumer/src/transports.rs
deleted file mode 100644
index 6b413c805714..000000000000
--- a/rust/ingestion-consumer/src/transports.rs
+++ /dev/null
@@ -1,151 +0,0 @@
-//! Transport selection: HTTP request/response vs ordered gRPC worker streams.
-//!
-//! The consumer talks to workers through one [`Transport`], picked by
-//! `INGESTION_TRANSPORT`. Sends are two-phase everywhere: [`Transport::begin_send`]
-//! establishes send order and must be called where that order is decided (the
-//! consumer loop right after assignment, or the serialized flush paths);
-//! [`PendingSend::wait`] resolves like an HTTP response. The HTTP transport
-//! implements `begin_send` lazily (nothing happens until `wait`), which keeps
-//! its behavior identical to the direct `send_batch` call it replaces; the
-//! gRPC transport enqueues synchronously onto the worker's ordered stream.
-
-use std::str::FromStr;
-use std::sync::Arc;
-
-use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};
-use crate::transport::{HttpTransport, SendError};
-use crate::types::SerializedKafkaMessage;
-
-/// Which transport carries sub-batches to the workers.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
-pub enum TransportMode {
- #[default]
- Http,
- Grpc,
-}
-
-impl FromStr for TransportMode {
- type Err = String;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match s.trim().to_lowercase().as_str() {
- "http" => Ok(TransportMode::Http),
- "grpc" => Ok(TransportMode::Grpc),
- other => Err(format!(
- "unknown ingestion transport '{other}' (expected 'http' or 'grpc')"
- )),
- }
- }
-}
-
-impl TransportMode {
- pub fn as_str(&self) -> &'static str {
- match self {
- TransportMode::Http => "http",
- TransportMode::Grpc => "grpc",
- }
- }
-}
-
-/// The consumer's worker transport.
-pub enum Transport {
- Http(Arc<HttpTransport>),
- Grpc(Arc<GrpcTransport>),
-}
-
-/// A sub-batch whose send order is established; await it for the outcome.
-pub enum PendingSend {
- Http {
- transport: Arc<HttpTransport>,
- worker_url: String,
- batch_id: String,
- messages: Vec<SerializedKafkaMessage>,
- replay: bool,
- },
- Grpc(PendingWorkerStreamSend),
-}
-
-impl PendingSend {
- pub async fn wait(self) -> Result<u32, SendError> {
- match self {
- PendingSend::Http {
- transport,
- worker_url,
- batch_id,
- messages,
- replay,
- } => {
- transport
- .send_batch(&worker_url, &batch_id, messages, replay)
- .await
- }
- PendingSend::Grpc(pending) => pending.wait().await,
- }
- }
-}
-
-impl Transport {
- /// Establish send order for a sub-batch. Synchronous — call it in the
- /// order sends must reach the worker; the per-key ordering guarantee on
- /// the gRPC path is exactly "begin_send order per worker".
- pub fn begin_send(
- &self,
- worker_url: &str,
- batch_id: &str,
- messages: Vec<SerializedKafkaMessage>,
- replay: bool,
- ) -> PendingSend {
- match self {
- Transport::Http(transport) => PendingSend::Http {
- transport: Arc::clone(transport),
- worker_url: worker_url.to_string(),
- batch_id: batch_id.to_string(),
- messages,
- replay,
- },
- Transport::Grpc(transport) => {
- PendingSend::Grpc(transport.begin_send(worker_url, batch_id, messages, replay))
- }
- }
- }
-
- pub async fn wait_for_workers_ready(
- &self,
- worker_urls: &[String],
- shutdown: &lifecycle::Handle,
- ) -> anyhow::Result<()> {
- match self {
- Transport::Http(transport) => {
- transport
- .wait_for_workers_ready(worker_urls, shutdown)
- .await
- }
- Transport::Grpc(transport) => {
- transport
- .wait_for_workers_ready(worker_urls, shutdown)
- .await
- }
- }
- }
-
- /// Drop a departed worker's transport state (semaphore or worker stream).
- pub fn remove_worker(&self, worker_url: &str) {
- match self {
- Transport::Http(transport) => transport.remove_worker(worker_url),
- Transport::Grpc(transport) => transport.remove_worker(worker_url),
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_transport_mode_parses_known_values() {
- assert_eq!("http".parse(), Ok(TransportMode::Http));
- assert_eq!(" gRPC ".parse(), Ok(TransportMode::Grpc));
- assert!("carrier-pigeon".parse::<TransportMode>().is_err());
- assert_eq!(TransportMode::default(), TransportMode::Http);
- }
-}
diff --git a/rust/ingestion-consumer/src/types.rs b/rust/ingestion-consumer/src/types.rs
index 30fe25c76f26..102f90e48794 100644
--- a/rust/ingestion-consumer/src/types.rs
+++ b/rust/ingestion-consumer/src/types.rs
@@ -14,28 +14,3 @@ pub struct SerializedKafkaMessage {
pub value: Option<String>,
pub headers: HashMap<String, String>,
}
-
-/// Matches `IngestBatchRequest` in `nodejs/src/ingestion/api/types.ts`.
-#[derive(Debug, Serialize, Deserialize)]
-pub struct IngestBatchRequest {
- pub batch_id: String,
- pub messages: Vec<SerializedKafkaMessage>,
- /// Identifies this consumer process incarnation. The worker's feed-order
- /// sentinel rebaselines a key when the sender changes (restart/rebalance
- /// legitimately replays uncommitted offsets).
- pub consumer_id: String,
- /// True when this request may repeat previously sent messages (an HTTP
- /// retry, or a deferred-flush re-route after a send failure). The worker's
- /// sentinel counts repeats on replay requests as at-least-once replays
- /// rather than order violations.
- pub replay: bool,
-}
-
-/// Matches `IngestBatchResponse` in `nodejs/src/ingestion/api/types.ts`.
-#[derive(Debug, Serialize, Deserialize)]
-pub struct IngestBatchResponse {
- pub batch_id: String,
- pub status: String,
- pub accepted: u32,
- pub error: Option<String>,
-}
diff --git a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
index beef9015bc3f..182a87b6ed61 100644
--- a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
+++ b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
@@ -3,15 +3,15 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
-use axum::extract::{Json, State};
+use axum::extract::State;
use axum::response::IntoResponse;
-use axum::routing::{get, post};
+use axum::routing::get;
use axum::Router;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
use ingestion_consumer::dispatcher::Dispatcher;
-use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};
+use ingestion_consumer::types::SerializedKafkaMessage;
use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig, WorkerState};
// ---- FakeWorker ----
@@ -29,19 +29,6 @@ async fn ready_handler(State(ctrl): State<WorkerCtrl>) -> impl IntoResponse {
}
}
-async fn ingest_handler(
- State(_ctrl): State<WorkerCtrl>,
- Json(req): Json<IngestBatchRequest>,
-) -> Json<IngestBatchResponse> {
- let accepted = req.messages.len() as u32;
- Json(IngestBatchResponse {
- batch_id: req.batch_id,
- status: "ok".to_string(),
- accepted,
- error: None,
- })
-}
-
struct FakeWorker {
pub url: String,
is_healthy: Arc<AtomicBool>,
@@ -60,7 +47,6 @@ impl FakeWorker {
let app = Router::new()
.route("/_ready", get(ready_handler))
- .route("/ingest", post(ingest_handler))
.with_state(ctrl);
let handle = tokio::spawn(async move {
diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
index 95a84255307f..bfed88659f5c 100644
--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -8,8 +8,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
-use axum::extract::Json as AxumJson;
-use axum::routing::{get, post};
+use axum::routing::get;
use axum::Router;
use futures::StreamExt;
use lifecycle::{ComponentOptions, Manager};
@@ -29,9 +28,7 @@ use ingestion_consumer::discovery::reconcile_membership;
use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
use ingestion_consumer::order_sentinel::SentinelContext;
-use ingestion_consumer::transport::HttpTransport;
-use ingestion_consumer::transports::Transport;
-use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};
+use ingestion_consumer::types::SerializedKafkaMessage;
use ingestion_consumer::worker_registry::{
WorkerId, WorkerRegistry, WorkerRegistryConfig, WorkerState,
};
@@ -133,30 +130,30 @@ struct FakeWorker {
pub url: String,
/// (distinct_id, seq) pairs in arrival order.
pub received: Arc<Mutex<Vec<(String, usize)>>>,
- /// Message count of each accepted /ingest request, in arrival order. With a
+ /// Message count of each accepted sub-batch, in arrival order. With a
/// single worker and partition a sub-batch is the whole Kafka batch, which
/// is what lets the batching-bound tests read batch sizes from here.
pub batch_sizes: Arc<Mutex<Vec<usize>>>,
/// Gates /_ready (pool membership). When false the worker leaves the pool.
pub healthy: Arc<AtomicBool>,
- /// Gates /ingest only. When false the worker stays ready (in the pool) but
+ /// Gates ingest only. When false the worker stays ready (in the pool) but
/// fails every send — a "flapping" worker, used to exercise the flush loop's
/// re-defer path and its timeout bound.
pub ingest_ok: Arc<AtomicBool>,
- /// When set, the next /ingest request is processed and recorded but answered
- /// with an error — a "lost ACK". Models the ambiguous outcome where the
+ /// When set, the next sub-batch is processed and recorded but answered
+ /// with a nack — a "lost ACK". Models the ambiguous outcome where the
/// worker did the work but the consumer never learns it, so it replays.
pub ack_lost_once: Arc<AtomicBool>,
- /// When true, every /ingest request is rejected with HTTP 400 without
+ /// When true, every sub-batch is nacked without
/// ingesting anything — a poison batch this worker will never accept.
pub reject_4xx: Arc<AtomicBool>,
- /// When set, the next /ingest request is ingested in full but reports one
+ /// When set, the next sub-batch is ingested in full but reports one
/// message fewer than sent — a partial-acceptance contract violation.
pub underreport_once: Arc<AtomicBool>,
- /// Number of /ingest requests that have reached the handler. Counted before
+ /// Number of sub-batches that have reached the handler. Counted before
/// the gate, so a test can observe a batch is in-flight even while held.
arrived: Arc<AtomicUsize>,
- /// Held by the handler for the duration of each /ingest request. A test can
+ /// Held by the handler for the duration of each sub-batch. A test can
/// acquire it via `block()` to freeze a request in flight (simulating a slow
/// worker), then drop the guard to let it complete.
gate: Arc<tokio::sync::Mutex<()>>,
@@ -191,140 +188,22 @@ impl FakeWorker {
let arrived = Arc::new(AtomicUsize::new(0));
let gate = Arc::new(tokio::sync::Mutex::new(()));
- let app = Router::new()
- .route(
- "/_ready",
- get({
- let h = Arc::clone(&healthy);
- move || {
- let h = h.clone();
- async move {
- if h.load(Ordering::Relaxed) {
- axum::http::StatusCode::OK
- } else {
- axum::http::StatusCode::SERVICE_UNAVAILABLE
- }
+ let app = Router::new().route(
+ "/_ready",
+ get({
+ let h = Arc::clone(&healthy);
+ move || {
+ let h = h.clone();
+ async move {
+ if h.load(Ordering::Relaxed) {
+ axum::http::StatusCode::OK
+ } else {
+ axum::http::StatusCode::SERVICE_UNAVAILABLE
}
}
- }),
- )
- .route(
- "/ingest",
- post({
- let recv = Arc::clone(&received);
- let sizes = Arc::clone(&batch_sizes);
- let h = Arc::clone(&healthy);
- let ingest_ok = Arc::clone(&ingest_ok);
- let ack_lost_once = Arc::clone(&ack_lost_once);
- let reject_4xx = Arc::clone(&reject_4xx);
- let underreport_once = Arc::clone(&underreport_once);
- let arrived = Arc::clone(&arrived);
- let gate = Arc::clone(&gate);
- let delivery_log = delivery_log.clone();
- move |AxumJson(req): AxumJson<IngestBatchRequest>| {
- let recv = recv.clone();
- let sizes = sizes.clone();
- let h = h.clone();
- let ingest_ok = ingest_ok.clone();
- let ack_lost_once = ack_lost_once.clone();
- let reject_4xx = reject_4xx.clone();
- let underreport_once = underreport_once.clone();
- let arrived = arrived.clone();
- let gate = gate.clone();
- let delivery_log = delivery_log.clone();
- async move {
- arrived.fetch_add(1, Ordering::SeqCst);
- // Block here while a test holds the gate (slow worker).
- let _hold = gate.lock().await;
- // Health is checked after the gate so a test can flip a
- // held request to a failure before releasing it. A
- // worker that is ready but has ingest_ok=false fails
- // sends while staying in the pool (a flapping worker).
- if !h.load(Ordering::Relaxed) || !ingest_ok.load(Ordering::Relaxed) {
- return (
- axum::http::StatusCode::INTERNAL_SERVER_ERROR,
- AxumJson(IngestBatchResponse {
- batch_id: req.batch_id,
- status: "error".to_string(),
- accepted: 0,
- error: Some("worker unhealthy".to_string()),
- }),
- );
- }
- // A poison batch: permanently rejected with a client
- // error, nothing ingested.
- if reject_4xx.load(Ordering::SeqCst) {
- return (
- axum::http::StatusCode::BAD_REQUEST,
- AxumJson(IngestBatchResponse {
- batch_id: req.batch_id,
- status: "error".to_string(),
- accepted: 0,
- error: Some("poison batch".to_string()),
- }),
- );
- }
- let accepted = req.messages.len() as u32;
- let entries: Vec<(String, usize)> = req
- .messages
- .iter()
- .map(|msg| {
- let did =
- msg.headers.get("distinct_id").cloned().unwrap_or_default();
- let seq = msg
- .value
- .as_deref()
- .and_then(|v| {
- serde_json::from_str::<serde_json::Value>(v).ok()
- })
- .and_then(|v| v["seq"].as_u64())
- .unwrap_or(0)
- as usize;
- (did, seq)
- })
- .collect();
- recv.lock().unwrap().extend(entries.iter().cloned());
- sizes.lock().unwrap().push(req.messages.len());
- // Record the whole batch as one contiguous slot in the
- // shared total order (it was accepted as a unit).
- if let Some(log) = &delivery_log {
- log.lock().unwrap().extend(entries);
- }
- // The work is done and recorded, but the ACK is lost:
- // answer with an error so the consumer must replay.
- if ack_lost_once.swap(false, Ordering::SeqCst) {
- return (
- axum::http::StatusCode::INTERNAL_SERVER_ERROR,
- AxumJson(IngestBatchResponse {
- batch_id: req.batch_id,
- status: "error".to_string(),
- accepted: 0,
- error: Some("ack lost".to_string()),
- }),
- );
- }
- // Partial acceptance: everything was ingested, but the
- // response claims one message fewer than sent.
- let reported = if underreport_once.swap(false, Ordering::SeqCst) {
- accepted.saturating_sub(1)
- } else {
- accepted
- };
- (
- axum::http::StatusCode::OK,
- AxumJson(IngestBatchResponse {
- batch_id: req.batch_id,
- status: "ok".to_string(),
- accepted: reported,
- error: None,
- }),
- )
- }
- }
- }),
- )
- // Like the real Express worker, inflate gzipped request bodies.
- .layer(tower_http::decompression::RequestDecompressionLayer::new());
+ }
+ }),
+ );
// Bind HTTP on an ephemeral port and gRPC on that port + 1, so the
// gRPC transport's OffsetFromHttp mode can address each worker.
@@ -345,6 +224,7 @@ impl FakeWorker {
let grpc_service = FakeWorkerGrpc {
received: Arc::clone(&received),
+ batch_sizes: Arc::clone(&batch_sizes),
healthy: Arc::clone(&healthy),
ingest_ok: Arc::clone(&ingest_ok),
ack_lost_once: Arc::clone(&ack_lost_once),
@@ -387,17 +267,17 @@ impl FakeWorker {
self.received.lock().unwrap().len()
}
- /// Message count of each accepted /ingest request, in arrival order.
+ /// Message count of each accepted sub-batch, in arrival order.
fn batch_sizes(&self) -> Vec<usize> {
self.batch_sizes.lock().unwrap().clone()
}
- /// /ingest requests that have reached this worker (including any held by the gate).
+ /// Sub-batches that have reached this worker (including any held by the gate).
fn arrived_count(&self) -> usize {
self.arrived.load(Ordering::SeqCst)
}
- /// Freeze this worker's /ingest handling: requests arrive but block until the
+ /// Freeze this worker's ingest handling: sub-batches arrive but block until the
/// returned guard is dropped. Acquire before producing so the batch is caught.
async fn block(&self) -> tokio::sync::OwnedMutexGuard<()> {
Arc::clone(&self.gate).lock_owned().await
@@ -414,11 +294,11 @@ impl FakeWorker {
}
}
-/// The FakeWorker's WorkerIngest implementation, sharing the HTTP handler's
-/// state and knobs so gRPC scenarios drive the same failure modes. Per the
-/// protocol, any failure ends the stream (a nack means the worker stream is dead).
+/// The FakeWorker's WorkerIngest implementation. Per the protocol, any
+/// failure ends the stream (a nack means the worker stream is dead).
struct FakeWorkerGrpc {
received: Arc<Mutex<Vec<(String, usize)>>>,
+ batch_sizes: Arc<Mutex<Vec<usize>>>,
healthy: Arc<AtomicBool>,
ingest_ok: Arc<AtomicBool>,
ack_lost_once: Arc<AtomicBool>,
@@ -442,6 +322,7 @@ impl WorkerIngestService for FakeWorkerGrpc {
let mut inbound = request.into_inner();
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let received = Arc::clone(&self.received);
+ let batch_sizes = Arc::clone(&self.batch_sizes);
let healthy = Arc::clone(&self.healthy);
let ingest_ok = Arc::clone(&self.ingest_ok);
let ack_lost_once = Arc::clone(&self.ack_lost_once);
@@ -501,6 +382,7 @@ impl WorkerIngestService for FakeWorkerGrpc {
})
.collect();
received.lock().unwrap().extend(entries.iter().cloned());
+ batch_sizes.lock().unwrap().push(sub_batch.messages.len());
if let Some(log) = &delivery_log {
log.lock().unwrap().extend(entries);
}
@@ -579,13 +461,21 @@ fn make_kafka_consumer(
kafka_consumer
}
+/// The consumer's worker transport, addressed at each FakeWorker's gRPC port
+/// (`GrpcPort::OffsetFromHttp(1)` — HTTP port + 1). One un-acked sub-batch per
+/// worker, and a short ack timeout so a stalled scenario fences within a
+/// test's patience rather than production's 60s.
+fn test_transport() -> GrpcTransport {
+ GrpcTransport::new(GrpcPort::OffsetFromHttp(1), 1, Duration::from_secs(10))
+}
+
/// Reap drained workers exactly as `main.rs` does in production: complete the
/// drain of an idle drainer, then remove reaped workers from the registry and
/// transport. Runs until `token` is cancelled. (A faster tick than production's
/// 1s keeps test scenarios responsive.)
fn spawn_reaper(
registry: Arc<WorkerRegistry>,
- transport: Arc<Transport>,
+ transport: Arc<GrpcTransport>,
dispatcher: Arc<Dispatcher>,
token: CancellationToken,
) {
@@ -625,7 +515,6 @@ impl Harness {
deferred_flush_timeout,
registry_config,
0,
- false,
ComponentOptions::new(),
)
.await
@@ -646,7 +535,6 @@ impl Harness {
deferred_flush_timeout,
fast_registry_config(),
0,
- false,
ComponentOptions::new()
.with_liveness_deadline(liveness_deadline)
.with_stall_threshold(stall_threshold),
@@ -656,7 +544,7 @@ impl Harness {
/// Like `start`, but bounds batch collection by payload bytes as well as
/// count (`CONSUMER_BATCH_SIZE_KB`). Single worker and partition, so each
- /// /ingest request is one whole Kafka batch.
+ /// sub-batch is one whole Kafka batch.
async fn start_byte_capped(topic: &str, batch_size_bytes: usize) -> Self {
Self::start_inner(
topic,
@@ -666,32 +554,6 @@ impl Harness {
Duration::from_secs(60),
fast_registry_config(),
batch_size_bytes,
- false,
- ComponentOptions::new(),
- )
- .await
- }
-
- /// Like `start`, but the consumer sends over WorkerIngest gRPC worker streams
- /// (`GrpcPort::OffsetFromHttp(1)` — each FakeWorker serves gRPC on its
- /// HTTP port + 1).
- async fn start_grpc(
- topic: &str,
- partitions: i32,
- worker_count: usize,
- max_in_flight: usize,
- deferred_flush_timeout: Duration,
- registry_config: WorkerRegistryConfig,
- ) -> Self {
- Self::start_inner(
- topic,
- partitions,
- worker_count,
- max_in_flight,
- deferred_flush_timeout,
- registry_config,
- 0,
- true,
ComponentOptions::new(),
)
.await
@@ -706,7 +568,6 @@ impl Harness {
deferred_flush_timeout: Duration,
registry_config: WorkerRegistryConfig,
batch_size_bytes: usize,
- grpc: bool,
component_options: ComponentOptions,
) -> Self {
create_topic(topic, partitions).await;
@@ -725,24 +586,7 @@ impl Harness {
let dispatcher = Arc::new(Dispatcher::new(Arc::clone(&registry)));
let registry_for_test = Arc::clone(&registry);
let dispatcher_for_test = Arc::clone(&dispatcher);
- let transport = Arc::new(if grpc {
- // Short ack timeout so a stalled scenario fences within a test's
- // patience rather than production's 60s.
- Transport::Grpc(Arc::new(GrpcTransport::new(
- GrpcPort::OffsetFromHttp(1),
- 1,
- Duration::from_secs(10),
- )))
- } else {
- Transport::Http(Arc::new(HttpTransport::new(
- Duration::from_secs(5),
- 0, // no retries — errors surface immediately for health tracking
- None,
- &worker_urls,
- 1,
- true,
- )))
- });
+ let transport = Arc::new(test_transport());
spawn_reaper(
Arc::clone(&registry),
Arc::clone(&transport),
@@ -817,14 +661,7 @@ impl Harness {
let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config));
Arc::clone(&registry).start_probing(self._probe_token.clone());
let dispatcher = Arc::new(Dispatcher::new(Arc::clone(&registry)));
- let transport = Arc::new(Transport::Http(Arc::new(HttpTransport::new(
- Duration::from_secs(5),
- 0,
- None,
- &worker_urls,
- 1,
- true,
- ))));
+ let transport = Arc::new(test_transport());
spawn_reaper(
Arc::clone(&registry),
Arc::clone(&transport),
@@ -923,7 +760,7 @@ async fn wait_until(timeout: Duration, msg: &str, mut cond: impl FnMut() -> bool
}
}
-/// Index of the single worker that has received an /ingest request so far.
+/// Index of the single worker that has received a sub-batch so far.
/// Panics if zero or more than one have — callers rely on a unique pin.
fn sole_arrived_worker(harness: &Harness) -> usize {
let arrived: Vec<usize> = harness
@@ -1817,10 +1654,15 @@ async fn flush_target_failure_re_defers_then_replays_in_order() {
},
)
.await;
- assert!(
- harness.dispatcher.stashed_messages() > 0,
- "re-deferred work must be held after the replay target also fails"
- );
+ // The failed replay may still be parked on its worker stream (reconnect
+ // backoff) when the pool empties; it lands in the stash once that send
+ // fails too, and stays there with nowhere to route.
+ wait_until(
+ Duration::from_secs(10),
+ "re-deferred work to be held after the replay target also fails",
+ || harness.dispatcher.stashed_messages() > 0,
+ )
+ .await;
// Recover the second worker → the replay finally lands, in order.
harness.workers[second]
@@ -1842,15 +1684,15 @@ async fn flush_target_failure_re_defers_then_replays_in_order() {
harness.stop().await;
}
-/// Drain-triggered defer through the dispatcher + real HTTP transport — the path
-/// the consumer drives. The Kafka poll loop can't inject a drain between two
+/// Drain-triggered defer through the dispatcher + real worker stream transport
+/// — the path the consumer drives. The Kafka poll loop can't inject a drain between two
/// overlapping batch assigns deterministically (it assigns available batches
/// back-to-back and parks in `complete_oldest_batch` the moment data dries up),
/// so this models the consumer's exact sequence — assign, drain, assign (defer),
-/// resolve, flush — and delivers over real HTTP, asserting the deferred key lands
-/// on the survivor in order.
+/// resolve, flush — and delivers over a real stream, asserting the deferred key
+/// lands on the survivor in order.
#[tokio::test]
-async fn drain_defer_flush_delivers_to_survivor_over_http() {
+async fn drain_defer_flush_delivers_to_survivor_over_stream() {
let w0 = FakeWorker::start().await;
let w1 = FakeWorker::start().await;
let urls = vec![w0.url.clone(), w1.url.clone()];
@@ -1860,7 +1702,7 @@ async fn drain_defer_flush_delivers_to_survivor_over_http() {
let probe_token = CancellationToken::new();
Arc::clone(&registry).start_probing(probe_token.clone());
let dispatcher = Dispatcher::new(Arc::clone(&registry));
- let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1, true);
+ let transport = test_transport();
// batch-1: user-1 pins to a worker. Send it for real but DON'T resolve, so it
// is genuinely in flight on that worker.
@@ -1870,7 +1712,8 @@ async fn drain_defer_flush_delivers_to_survivor_over_http() {
let pinned_idx = workers.iter().position(|w| w.url == pinned_url).unwrap();
let survivor_idx = 1 - pinned_idx;
transport
- .send_batch(&pinned_url, "batch-1", b1[0].messages.clone(), false)
+ .begin_send(&pinned_url, "batch-1", b1[0].messages.clone(), false)
+ .wait()
.await
.expect("batch-1 send");
@@ -1898,17 +1741,18 @@ async fn drain_defer_flush_delivers_to_survivor_over_http() {
"deferred group flushes to the survivor, not the drainer"
);
transport
- .send_batch(
+ .begin_send(
f2[0].worker.as_ref(),
"batch-2",
f2[0].messages.clone(),
false,
)
+ .wait()
.await
.expect("batch-2 flush send");
// The drainer kept its in-flight seq 0; the deferred seq 1 landed on the
- // survivor — delivered over real HTTP, in order, with nothing lost.
+ // survivor — delivered over a real stream, in order, with nothing lost.
assert_eq!(workers[pinned_idx].seqs_for("user-1"), vec![0]);
assert_eq!(workers[survivor_idx].seqs_for("user-1"), vec![1]);
assert!(
@@ -2124,7 +1968,7 @@ async fn lost_ack_after_processing_replays_without_loss() {
.await;
let producer = make_producer();
- // Arm both workers (the batch could land on either): the first /ingest each
+ // Arm both workers (the batch could land on either): the first sub-batch each
// receives is processed and recorded, but answered with an error.
for w in &harness.workers {
w.ack_lost_once.store(true, Ordering::SeqCst);
@@ -2609,14 +2453,7 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {
let probe2 = CancellationToken::new();
Arc::clone(&registry2).start_probing(probe2.clone());
let dispatcher2 = Arc::new(Dispatcher::new(Arc::clone(&registry2)));
- let transport2 = Arc::new(Transport::Http(Arc::new(HttpTransport::new(
- Duration::from_secs(5),
- 0,
- None,
- &worker_urls,
- 1,
- true,
- ))));
+ let transport2 = Arc::new(test_transport());
let mut manager2 = Manager::builder("e2e-c2").with_trap_signals(false).build();
let handle2 = manager2.register("consumer", ComponentOptions::new());
let shutdown2 = handle2.shutdown_token();
@@ -2685,14 +2522,7 @@ async fn fenced_static_member_exits_on_fatal_error() {
let probe = CancellationToken::new();
Arc::clone(&registry).start_probing(probe.clone());
let dispatcher = Arc::new(Dispatcher::new(Arc::clone(&registry)));
- let transport = Arc::new(Transport::Http(Arc::new(HttpTransport::new(
- Duration::from_secs(5),
- 0,
- None,
- &urls,
- 1,
- true,
- ))));
+ let transport = Arc::new(test_transport());
let mut manager = Manager::builder("e2e-fenced")
.with_trap_signals(false)
.build();
@@ -2995,57 +2825,15 @@ async fn flapping_worker_does_not_pin_batch_past_flush_timeout() {
);
}
-// ── gRPC transport (WorkerIngest worker streams) ────────────────────────────────────
-
-/// The full Kafka → assign → worker stream → stream → ack → commit loop over the gRPC
-/// transport: every message arrives exactly once, and each distinct_id's
-/// messages arrive in order on whichever worker its worker stream delivered them to.
-#[tokio::test]
-async fn grpc_messages_per_distinct_id_arrive_in_order() {
- let topic = format!("e2e-grpc-ordering-{}", Uuid::new_v4());
- let harness = Harness::start_grpc(
- &topic,
- 3,
- 2,
- 1,
- Duration::from_secs(60),
- fast_registry_config(),
- )
- .await;
-
- let producer = make_producer();
- for seq in 0..8usize {
- produce(&producer, &topic, 0, "tok", "user-1", seq).await;
- produce(&producer, &topic, 1, "tok", "user-2", seq).await;
- produce(&producer, &topic, 2, "tok", "user-3", seq).await;
- }
-
- harness.wait_for(24, Duration::from_secs(15)).await;
-
- let total: usize = harness.workers.iter().map(|w| w.count()).sum();
- assert_eq!(total, 24, "expected 24 messages total, got {total}");
-
- for worker in &harness.workers {
- for user in ["user-1", "user-2", "user-3"] {
- let seqs = worker.seqs_for(user);
- assert!(
- seqs.windows(2).all(|w| w[0] < w[1]),
- "{user} arrived out of order on a worker: {seqs:?}"
- );
- }
- }
-
- harness.stop().await;
-}
+// ── Worker stream fencing ──────────────────────────────────────────────────
/// A worker that nacks fences its worker stream: the fenced messages fail back into
/// the deferral path with nothing lost, and once the worker leaves the pool
-/// the keys re-route to the survivor in order — the same recovery contract
-/// the HTTP transport gets from its request errors.
+/// the keys re-route to the survivor in order.
#[tokio::test]
-async fn grpc_nacking_worker_fences_worker_stream_and_reroutes_in_order() {
- let topic = format!("e2e-grpc-fence-{}", Uuid::new_v4());
- let harness = Harness::start_grpc(
+async fn nacking_worker_fences_worker_stream_and_reroutes_in_order() {
+ let topic = format!("e2e-fence-{}", Uuid::new_v4());
+ let harness = Harness::start(
&topic,
2,
2,
diff --git a/rust/ingestion-consumer/tests/transport_integration_test.rs b/rust/ingestion-consumer/tests/transport_integration_test.rs
deleted file mode 100644
index 441f34d432c0..000000000000
--- a/rust/ingestion-consumer/tests/transport_integration_test.rs
+++ /dev/null
@@ -1,793 +0,0 @@
-use std::collections::HashMap;
-use std::sync::atomic::{AtomicUsize, Ordering};
-use std::sync::{Arc, Mutex};
-use std::time::Duration;
-
-use axum::extract::Json;
-use axum::response::IntoResponse;
-use axum::routing::post;
-use axum::Router;
-use tokio::net::TcpListener;
-use tokio::time::sleep;
-use tower_http::decompression::RequestDecompressionLayer;
-
-use ingestion_consumer::dispatcher::Dispatcher;
-use ingestion_consumer::transport::{HttpTransport, TransportError};
-use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};
-use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
-
-fn make_message(
- token: &str,
- distinct_id: &str,
- offset: i64,
- value: &str,
-) -> SerializedKafkaMessage {
- let mut headers = HashMap::new();
- headers.insert("token".to_string(), token.to_string());
- headers.insert("distinct_id".to_string(), distinct_id.to_string());
- SerializedKafkaMessage {
- topic: "events_plugin_ingestion".to_string(),
- partition: 0,
- offset,
- timestamp: 1700000000000,
- key: Some(format!("{token}:{distinct_id}")),
- value: Some(value.to_string()),
- headers,
- }
-}
-
-/// Bind a mock worker app on an ephemeral port. Like the real Express worker,
-/// mock workers inflate request bodies, so the transport's gzipped requests
-/// round-trip in every test.
-async fn serve_worker(app: Router) -> (String, tokio::task::JoinHandle<()>) {
- let app = app.layer(RequestDecompressionLayer::new());
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- let url = format!("http://127.0.0.1:{}", addr.port());
-
- let handle = tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- (url, handle)
-}
-
-/// Spin up a mock worker that records received batches and returns OK.
-async fn start_mock_worker(
- received: Arc<Mutex<Vec<IngestBatchRequest>>>,
-) -> (String, tokio::task::JoinHandle<()>) {
- let app = Router::new().route(
- "/ingest",
- post({
- let received = received.clone();
- move |Json(req): Json<IngestBatchRequest>| {
- let received = received.clone();
- async move {
- let accepted = req.messages.len() as u32;
- received.lock().unwrap().push(req);
- Json(IngestBatchResponse {
- batch_id: "test".to_string(),
- status: "ok".to_string(),
- accepted,
- error: None,
- })
- }
- }
- }),
- );
-
- serve_worker(app).await
-}
-
-/// Spin up a mock worker that returns errors.
-async fn start_failing_worker() -> (String, tokio::task::JoinHandle<()>) {
- let app = Router::new().route(
- "/ingest",
- post(|| async {
- (
- axum::http::StatusCode::INTERNAL_SERVER_ERROR,
- "internal error",
- )
- }),
- );
-
- serve_worker(app).await
-}
-
-/// Spin up a mock worker that always returns 503 (worker-busy contract violation).
-async fn start_always_busy_worker() -> (String, tokio::task::JoinHandle<()>) {
- let app = Router::new().route(
- "/ingest",
- post(|Json(req): Json<IngestBatchRequest>| async move {
- (
- axum::http::StatusCode::SERVICE_UNAVAILABLE,
- axum::Json(IngestBatchResponse {
- batch_id: req.batch_id,
- status: "error".to_string(),
- accepted: 0,
- error: Some("at concurrent batch capacity (1)".to_string()),
- }),
- )
- .into_response()
- }),
- );
-
- serve_worker(app).await
-}
-
-/// Spin up a mock worker that returns 503 for its first `busy_times` requests,
-/// then 200 OK thereafter — simulating a worker that is momentarily at capacity.
-async fn start_busy_then_ok_worker(busy_times: usize) -> (String, tokio::task::JoinHandle<()>) {
- let calls = Arc::new(AtomicUsize::new(0));
- let app = Router::new().route(
- "/ingest",
- post(move |Json(req): Json<IngestBatchRequest>| {
- let calls = calls.clone();
- async move {
- let n = calls.fetch_add(1, Ordering::SeqCst);
- if n < busy_times {
- return (
- axum::http::StatusCode::SERVICE_UNAVAILABLE,
- axum::Json(IngestBatchResponse {
- batch_id: req.batch_id,
- status: "error".to_string(),
- accepted: 0,
- error: Some("at concurrent batch capacity (1)".to_string()),
- }),
- )
- .into_response();
- }
- axum::Json(IngestBatchResponse {
- batch_id: req.batch_id,
- status: "ok".to_string(),
- accepted: req.messages.len() as u32,
- error: None,
- })
- .into_response()
- }
- }),
- );
-
- serve_worker(app).await
-}
-
-/// Spin up a mock worker that sleeps `delay` before responding ok. Records
-/// the max number of overlapping in-flight requests it ever observed.
-async fn start_slow_worker(
- delay: Duration,
- max_concurrent: Arc<AtomicUsize>,
-) -> (String, tokio::task::JoinHandle<()>) {
- let in_flight = Arc::new(AtomicUsize::new(0));
- let app = Router::new().route(
- "/ingest",
- post({
- let in_flight = in_flight.clone();
- let max_concurrent = max_concurrent.clone();
- move |Json(req): Json<IngestBatchRequest>| {
- let in_flight = in_flight.clone();
- let max_concurrent = max_concurrent.clone();
- async move {
- let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
- max_concurrent.fetch_max(now, Ordering::SeqCst);
- sleep(delay).await;
- in_flight.fetch_sub(1, Ordering::SeqCst);
- Json(IngestBatchResponse {
- batch_id: req.batch_id,
- status: "ok".to_string(),
- accepted: req.messages.len() as u32,
- error: None,
- })
- }
- }
- }),
- );
-
- serve_worker(app).await
-}
-
-/// Spin up a mock worker that rejects bodies larger than `limit` bytes with
-/// 413 (like the real worker's JSON body limit) and otherwise records the
-/// batch and returns OK.
-async fn start_size_limited_worker(
- limit: usize,
- received: Arc<Mutex<Vec<IngestBatchRequest>>>,
-) -> (String, tokio::task::JoinHandle<()>) {
- let app = Router::new().route(
- "/ingest",
- post({
- let received = received.clone();
- move |body: axum::body::Bytes| {
- let received = received.clone();
- async move {
- if body.len() > limit {
- return (
- axum::http::StatusCode::PAYLOAD_TOO_LARGE,
- "Request entity too large".to_string(),
- )
- .into_response();
- }
- let req: IngestBatchRequest = serde_json::from_slice(&body).unwrap();
- let accepted = req.messages.len() as u32;
- let batch_id = req.batch_id.clone();
- received.lock().unwrap().push(req);
- Json(IngestBatchResponse {
- batch_id,
- status: "ok".to_string(),
- accepted,
- error: None,
- })
- .into_response()
- }
- }
- }),
- );
-
- serve_worker(app).await
-}
-
-#[tokio::test]
-async fn transport_sends_batch_and_receives_ack() {
- let received = Arc::new(Mutex::new(Vec::new()));
- let (url, _handle) = start_mock_worker(received.clone()).await;
-
- let urls = vec![url.clone()];
- let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1, true);
-
- let messages = vec![
- make_message("tok1", "user-a", 0, r#"{"event":"$pageview"}"#),
- make_message("tok1", "user-a", 1, r#"{"event":"$identify"}"#),
- ];
-
- let accepted = transport
- .send_batch(&url, "batch-1", messages, false)
- .await
- .unwrap();
-
- assert_eq!(accepted, 2);
-
- let batches = received.lock().unwrap();
- assert_eq!(batches.len(), 1);
- assert_eq!(batches[0].messages.len(), 2);
- assert_eq!(batches[0].messages[0].offset, 0);
- assert_eq!(batches[0].messages[1].offset, 1);
-
- // Verify headers survived the round-trip
- assert_eq!(batches[0].messages[0].headers.get("token").unwrap(), "tok1");
- assert_eq!(
- batches[0].messages[0].headers.get("distinct_id").unwrap(),
- "user-a"
- );
-}
-
-#[tokio::test]
-async fn transport_retries_on_server_error() {
- let (url, _handle) = start_failing_worker().await;
-
- let urls = vec![url.clone()];
- let transport = HttpTransport::new(Duration::from_secs(1), 2, None, &urls, 1, true);
-
- let messages = vec![make_message("tok", "user", 0, "{}")];
-
- let result = transport
- .send_batch(&url, "batch-retry", messages, false)
- .await;
- assert!(result.is_err());
-}
-
-#[tokio::test]
-async fn transport_retries_on_worker_busy() {
- // 503 is transient backpressure (a shared worker can be momentarily full),
- // so the transport retries with the longer, jittered busy backoff rather
- // than failing fast. An always-busy worker exhausts retries and returns the
- // last WorkerBusy error — but only after backing off at least once.
- let (url, _handle) = start_always_busy_worker().await;
-
- let urls = vec![url.clone()];
- let transport = HttpTransport::new(Duration::from_secs(5), 1, None, &urls, 1, true);
-
- let messages = vec![make_message("tok", "user", 0, "{}")];
-
- let start = std::time::Instant::now();
- let err = transport
- .send_batch(&url, "batch-busy", messages, false)
- .await
- .unwrap_err();
- let elapsed = start.elapsed();
-
- assert!(
- matches!(err.error, TransportError::WorkerBusy(_)),
- "expected WorkerBusy, got {err:?}"
- );
- // One retry means one busy backoff (base 250ms + jitter), so the call must
- // take noticeably longer than the old fail-fast path (<200ms).
- assert!(
- elapsed >= Duration::from_millis(240),
- "expected a busy backoff before exhausting (≥240ms), got {elapsed:?}"
- );
-}
-
-#[tokio::test]
-async fn transport_recovers_after_worker_busy() {
- // A worker that is busy once and then ready should succeed after a retry.
- let (url, _handle) = start_busy_then_ok_worker(1).await;
-
- let urls = vec![url.clone()];
- let transport = HttpTransport::new(Duration::from_secs(5), 3, None, &urls, 1, true);
-
- let messages = vec![make_message("tok", "user", 0, "{}")];
-
- let accepted = transport
- .send_batch(&url, "batch-recover", messages, false)
- .await
- .expect("should succeed after the worker stops being busy");
- assert_eq!(accepted, 1);
-}
-
-#[tokio::test]
-async fn transport_fails_on_unreachable_worker() {
- let url = "http://127.0.0.1:1".to_string();
- let urls = vec![url.clone()];
- let transport = HttpTransport::new(Duration::from_secs(1), 0, None, &urls, 1, true);
- let messages = vec![make_message("tok", "user", 0, "{}")];
-
- let result = transport
- .send_batch(&url, "batch-fail", messages, false)
- .await;
- assert!(result.is_err());
-}
-
-#[tokio::test]
-async fn transport_splits_oversized_batch_by_estimate() {
- // A sub-batch whose estimated body size exceeds the cap is split into
- // multiple sequential requests, preserving message order, and the result
- // still reports every message accepted.
- let received = Arc::new(Mutex::new(Vec::new()));
- let (url, _handle) = start_mock_worker(received.clone()).await;
-
- let urls = vec![url.clone()];
- let mut transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1, true);
- transport.set_max_body_bytes(3000);
-
- let value = "x".repeat(1000);
- let messages: Vec<_> = (0..10)
- .map(|i| make_message("tok", "user", i, &value))
- .collect();
-
- let accepted = transport
- .send_batch(&url, "batch-split", messages, false)
- .await
- .expect("split batch should be fully accepted");
- assert_eq!(accepted, 10);
-
- let batches = received.lock().unwrap();
- assert!(
- batches.len() > 1,
- "expected multiple requests, got {}",
- batches.len()
- );
- let offsets: Vec<i64> = batches
- .iter()
- .flat_map(|b| &b.messages)
- .map(|m| m.offset)
- .collect();
- assert_eq!(offsets, (0..10).collect::<Vec<_>>());
-}
-
-#[tokio::test]
-async fn transport_halves_chunk_on_413() {
- // The size estimate can undershoot the worker's body limit. A 413 response
- // must split the chunk in half and resend rather than retrying verbatim
- // (which would loop forever) or giving up (which would poison the batch).
- let received = Arc::new(Mutex::new(Vec::new()));
- let (url, _handle) = start_size_limited_worker(2000, received.clone()).await;
-
- let urls = vec![url.clone()];
- // Compression off so the mock's body-length check sees raw JSON sizes.
- let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1, false);
-
- let value = "x".repeat(700);
- let messages: Vec<_> = (0..4)
- .map(|i| make_message("tok", "user", i, &value))
- .collect();
-
- let accepted = transport
- .send_batch(&url, "batch-413", messages, false)
- .await
- .expect("batch should succeed after halving on 413");
- assert_eq!(accepted, 4);
-
- let batches = received.lock().unwrap();
- assert!(
- batches.len() >= 2,
- "expected the batch to be split after 413, got {} request(s)",
- batches.len()
- );
- let offsets: Vec<i64> = batches
- .iter()
- .flat_map(|b| &b.messages)
- .map(|m| m.offset)
- .collect();
- assert_eq!(offsets, (0..4).collect::<Vec<_>>());
-}
-
-#[tokio::test]
-async fn transport_single_oversize_message_fails_without_splitting() {
- // A single message the worker rejects with 413 can't be split further —
- // the send fails with a non-retriable error carrying the message back.
- let received = Arc::new(Mutex::new(Vec::new()));
- let (url, _handle) = start_size_limited_worker(500, received.clone()).await;
-
- let urls = vec![url.clone()];
- let transport = HttpTransport::new(Duration::from_secs(5), 3, None, &urls, 1, false);
-
- let value = "x".repeat(1000);
- let messages = vec![make_message("tok", "user", 0, &value)];
-
- let err = transport
- .send_batch(&url, "batch-giant", messages, false)
- .await
- .unwrap_err();
-
- assert!(
- matches!(err.error, TransportError::PayloadTooLarge(_)),
- "expected PayloadTooLarge, got {:?}",
- err.error
- );
- assert_eq!(err.messages.len(), 1);
- assert!(!err.error.is_retriable());
-}
-
-#[tokio::test]
-async fn transport_lazily_creates_semaphore_for_unseeded_worker() {
- // Dynamic membership: a worker not seeded at construction (discovered at
- // runtime) gets a semaphore created on first send and is served normally.
- let received = Arc::new(Mutex::new(Vec::new()));
- let (url, _handle) = start_mock_worker(received.clone()).await;
-
- // Construct with an empty worker set — the target is "unknown" at build time.
- let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &[], 1, true);
-
- let messages = vec![make_message("tok", "user", 0, "{}")];
- let accepted = transport
- .send_batch(&url, "batch-lazy", messages, false)
- .await
- .expect("send to an unseeded worker should succeed via lazy semaphore creation");
-
- assert_eq!(accepted, 1);
-}
-
-#[tokio::test]
-async fn transport_serializes_concurrent_sends_to_same_worker() {
- // With concurrency=1 and a 500ms-slow worker, two parallel send_batch
- // calls must serialize: total elapsed ≈ 1s (not 500ms), and the worker
- // never sees more than 1 concurrent request.
- let max_concurrent = Arc::new(AtomicUsize::new(0));
- let (url, _h) = start_slow_worker(Duration::from_millis(500), max_concurrent.clone()).await;
-
- let urls = vec![url.clone()];
- let transport = Arc::new(HttpTransport::new(
- Duration::from_secs(5),
- 0,
- None,
- &urls,
- 1,
- true,
- ));
-
- let start = std::time::Instant::now();
- let mut handles = Vec::new();
- for i in 0..2 {
- let t = transport.clone();
- let u = url.clone();
- handles.push(tokio::spawn(async move {
- t.send_batch(
- &u,
- &format!("batch-{i}"),
- vec![make_message("tok", "u", 0, "{}")],
- false,
- )
- .await
- .unwrap()
- }));
- }
- for h in handles {
- h.await.unwrap();
- }
- let elapsed = start.elapsed();
-
- assert_eq!(
- max_concurrent.load(Ordering::SeqCst),
- 1,
- "semaphore must serialize calls to the same worker"
- );
- assert!(
- elapsed >= Duration::from_millis(900),
- "expected ≥900ms for serialized 500ms calls, got {elapsed:?}"
- );
-}
-
-#[tokio::test]
-async fn transport_parallelizes_across_different_workers() {
- // Semaphores are per-URL: two different workers must run in parallel.
- let max_a = Arc::new(AtomicUsize::new(0));
- let max_b = Arc::new(AtomicUsize::new(0));
- let (url_a, _h_a) = start_slow_worker(Duration::from_millis(500), max_a.clone()).await;
- let (url_b, _h_b) = start_slow_worker(Duration::from_millis(500), max_b.clone()).await;
-
- let urls = vec![url_a.clone(), url_b.clone()];
- let transport = Arc::new(HttpTransport::new(
- Duration::from_secs(5),
- 0,
- None,
- &urls,
- 1,
- true,
- ));
-
- let start = std::time::Instant::now();
- let t1 = {
- let t = transport.clone();
- let u = url_a.clone();
- tokio::spawn(async move {
- t.send_batch(
- &u,
- "batch-a",
- vec![make_message("tok", "u", 0, "{}")],
- false,
- )
- .await
- .unwrap()
- })
- };
- let t2 = {
- let t = transport.clone();
- let u = url_b.clone();
- tokio::spawn(async move {
- t.send_batch(
- &u,
- "batch-b",
- vec![make_message("tok", "u", 0, "{}")],
- false,
- )
- .await
- .unwrap()
- })
- };
- t1.await.unwrap();
- t2.await.unwrap();
- let elapsed = start.elapsed();
-
- // ≈ 500ms (parallel), well under 1s (which would mean serialized).
- assert!(
- elapsed < Duration::from_millis(900),
- "expected ≈500ms for parallel workers, got {elapsed:?}"
- );
-}
-
-#[tokio::test]
-async fn dispatcher_and_transport_end_to_end() {
- // Start 2 mock workers
- let received_1 = Arc::new(Mutex::new(Vec::new()));
- let received_2 = Arc::new(Mutex::new(Vec::new()));
- let (url_1, _h1) = start_mock_worker(received_1.clone()).await;
- let (url_2, _h2) = start_mock_worker(received_2.clone()).await;
-
- let worker_urls = [url_1.clone(), url_2.clone()];
- let registry = Arc::new(WorkerRegistry::new(
- &worker_urls,
- WorkerRegistryConfig {
- probe_interval: Duration::from_secs(60),
- dead_declaration: Duration::from_secs(60),
- passive_window: Duration::from_secs(30),
- passive_error_threshold: 0.5,
- passive_min_samples: 1000,
- degraded_hold: Duration::from_secs(10),
- min_state_duration: Duration::ZERO,
- probe_failure_threshold: 2,
- drain_timeout: Duration::from_secs(5),
- },
- ));
- let dispatcher = Arc::new(Dispatcher::new(Arc::clone(&registry)));
- let transport = Arc::new(HttpTransport::new(
- Duration::from_secs(5),
- 0,
- None,
- &worker_urls,
- 1,
- true,
- ));
-
- // Create messages for multiple distinct_ids — user-1 appears twice
- let messages = vec![
- make_message("tok", "user-1", 0, r#"{"event":"a"}"#),
- make_message("tok", "user-2", 1, r#"{"event":"b"}"#),
- make_message("tok", "user-1", 2, r#"{"event":"c"}"#),
- make_message("tok", "user-3", 3, r#"{"event":"d"}"#),
- ];
-
- let sub_batches = dispatcher.assign("b", messages);
-
- // Scatter to workers
- let mut handles = Vec::new();
- for sub_batch in sub_batches {
- let t = transport.clone();
- let worker = sub_batch.worker.clone();
- let routing_keys = sub_batch.routing_keys.clone();
- let message_count = sub_batch.messages.len();
- let d = Arc::clone(&dispatcher);
- handles.push(tokio::spawn(async move {
- let result = t
- .send_batch(&worker, "batch-e2e", sub_batch.messages, false)
- .await
- .unwrap();
- d.on_sub_batch_resolved(&worker, message_count, &routing_keys, false, false);
- result
- }));
- }
-
- // Gather
- let mut total_accepted = 0u32;
- for h in handles {
- total_accepted += h.await.unwrap();
- }
- assert_eq!(total_accepted, 4);
-
- // user-1 messages (offsets 0 and 2) must have landed on the same worker
- let batches_1 = received_1.lock().unwrap();
- let batches_2 = received_2.lock().unwrap();
-
- let all_messages: Vec<&SerializedKafkaMessage> = batches_1
- .iter()
- .chain(batches_2.iter())
- .flat_map(|b| &b.messages)
- .collect();
- assert_eq!(all_messages.len(), 4);
-
- let user1_workers: Vec<usize> = all_messages
- .iter()
- .filter(|m| m.headers.get("distinct_id").map(|s| s.as_str()) == Some("user-1"))
- .map(|m| {
- if batches_1
- .iter()
- .any(|b| b.messages.iter().any(|bm| bm.offset == m.offset))
- {
- 0
- } else {
- 1
- }
- })
- .collect();
- assert!(
- user1_workers.iter().all(|&w| w == user1_workers[0]),
- "user-1 messages should all be on the same worker"
- );
-}
-
-#[tokio::test]
-async fn wire_format_preserves_unicode_and_null_fields() {
- let received = Arc::new(Mutex::new(Vec::new()));
- let (url, _handle) = start_mock_worker(received.clone()).await;
-
- let urls = vec![url.clone()];
- let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1, true);
-
- let messages = vec![SerializedKafkaMessage {
- topic: "test".to_string(),
- partition: 0,
- offset: 42,
- timestamp: 0,
- key: None,
- value: Some(r#"{"name":"José 日本語 🎉"}"#.to_string()),
- headers: HashMap::new(),
- }];
-
- transport
- .send_batch(&url, "batch-unicode", messages, false)
- .await
- .unwrap();
-
- let batches = received.lock().unwrap();
- let msg = &batches[0].messages[0];
- assert!(msg.key.is_none());
- assert_eq!(msg.value.as_deref(), Some(r#"{"name":"José 日本語 🎉"}"#));
- assert!(msg.headers.is_empty());
-}
-
-/// The request's Content-Encoding header (if any) and raw body bytes.
-type CapturedRequest = (Option<String>, Vec<u8>);
-
-/// Spin up a worker that captures the request's Content-Encoding header and
-/// raw body bytes without any decompression — asserting what's actually on
-/// the wire, which the layered mocks can't distinguish.
-async fn start_raw_capture_worker(
- captured: Arc<Mutex<Option<CapturedRequest>>>,
-) -> (String, tokio::task::JoinHandle<()>) {
- let app = Router::new().route(
- "/ingest",
- post({
- let captured = captured.clone();
- move |headers: axum::http::HeaderMap, body: axum::body::Bytes| {
- let captured = captured.clone();
- async move {
- let encoding = headers
- .get(axum::http::header::CONTENT_ENCODING)
- .and_then(|v| v.to_str().ok())
- .map(str::to_string);
- *captured.lock().unwrap() = Some((encoding, body.to_vec()));
- Json(IngestBatchResponse {
- batch_id: "test".to_string(),
- status: "ok".to_string(),
- accepted: 1,
- error: None,
- })
- }
- }
- }),
- );
-
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- let url = format!("http://127.0.0.1:{}", addr.port());
-
- let handle = tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- (url, handle)
-}
-
-#[tokio::test]
-async fn transport_gzips_request_body_on_the_wire() {
- use std::io::Read;
-
- let captured = Arc::new(Mutex::new(None));
- let (url, _handle) = start_raw_capture_worker(captured.clone()).await;
-
- let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &[], 1, true);
- transport
- .send_batch(
- &url,
- "batch-gz",
- vec![make_message("tok", "user", 0, r#"{"event":"$pageview"}"#)],
- false,
- )
- .await
- .unwrap();
-
- let (encoding, body) = captured.lock().unwrap().take().unwrap();
- assert_eq!(encoding.as_deref(), Some("gzip"));
-
- let mut json = String::new();
- flate2::read::GzDecoder::new(&body[..])
- .read_to_string(&mut json)
- .expect("body must be valid gzip");
- let request: IngestBatchRequest = serde_json::from_str(&json).unwrap();
- assert_eq!(request.batch_id, "batch-gz");
- assert_eq!(request.messages.len(), 1);
- assert_eq!(
- request.messages[0].value.as_deref(),
- Some(r#"{"event":"$pageview"}"#)
- );
-}
-
-#[tokio::test]
-async fn transport_sends_plain_json_when_compression_disabled() {
- let captured = Arc::new(Mutex::new(None));
- let (url, _handle) = start_raw_capture_worker(captured.clone()).await;
-
- let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &[], 1, false);
- transport
- .send_batch(
- &url,
- "batch-plain",
- vec![make_message("tok", "user", 0, "{}")],
- false,
- )
- .await
- .unwrap();
-
- let (encoding, body) = captured.lock().unwrap().take().unwrap();
- assert_eq!(encoding, None);
- let request: IngestBatchRequest = serde_json::from_slice(&body).unwrap();
- assert_eq!(request.batch_id, "batch-plain");
-}