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.

feat(capture): each output reads its own topic and producer (#106535)

Paweł Ledwoń1ee75d82b946
diff --git a/bin/start-rust-service b/bin/start-rust-service
index 5f1bddfbbf57..1a27a71273bd 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -58,7 +58,7 @@ case "$RS_SVC" in
export CAPTURE_MODE=events
export LOG_LEVEL=debug
export DEBUG=1
- export KAFKA_ERROR_TRACKING_TOPIC=${KAFKA_ERROR_TRACKING_TOPIC:-ingestion-errortracking-main}
+ export CAPTURE_OUTPUT_ERROR_TRACKING_TOPIC=${CAPTURE_OUTPUT_ERROR_TRACKING_TOPIC:-ingestion-errortracking-main}
# v1 capture sink (MSK, writes to same topics as v0)
export CAPTURE_V1_SINKS=${CAPTURE_V1_SINKS:-msk}
export CAPTURE_V1_SINK_MSK_KAFKA_HOSTS=${CAPTURE_V1_SINK_MSK_KAFKA_HOSTS:-$DEFAULT_KAFKA}
@@ -77,8 +77,8 @@ case "$RS_SVC" in
export RUST_BACKTRACE=1
export ADDRESS=0.0.0.0:3306 # avoid port conflict in local dev
export KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST="$DEFAULT_KAFKA"
- export KAFKA_TOPIC=session_recording_snapshot_item_events
- export KAFKA_OVERFLOW_TOPIC=session_recording_snapshot_item_overflow
+ export CAPTURE_OUTPUT_SESSION_REPLAY_MAIN_TOPIC=session_recording_snapshot_item_events
+ export CAPTURE_OUTPUT_SESSION_REPLAY_OVERFLOW_TOPIC=session_recording_snapshot_item_overflow
export REDIS_URL="$DEFAULT_REDIS"
export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PG}"
export CAPTURE_MODE=recordings
@@ -93,7 +93,7 @@ case "$RS_SVC" in
export RUST_BACKTRACE=1
export ADDRESS=0.0.0.0:3309 # avoid port conflict in local dev (3308 is used by llm-gateway)
export KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST="$DEFAULT_KAFKA"
- export KAFKA_TOPIC=events_plugin_ingestion_ai
+ export CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC=events_plugin_ingestion_ai
export REDIS_URL="$DEFAULT_REDIS"
export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PG}"
# `ai` mode produces to the AI lane as its main topic, matching prod capture-ai
diff --git a/docker-compose.base.yml b/docker-compose.base.yml
index 91390aa113e1..5f93048f6358 100644
--- a/docker-compose.base.yml
+++ b/docker-compose.base.yml
@@ -378,7 +378,9 @@ services:
environment:
ADDRESS: '0.0.0.0:3000'
KAFKA_TOPIC: 'events_plugin_ingestion'
+ CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC: 'events_plugin_ingestion'
KAFKA_ERROR_TRACKING_TOPIC: 'ingestion-errortracking-main'
+ CAPTURE_OUTPUT_ERROR_TRACKING_TOPIC: 'ingestion-errortracking-main'
KAFKA_HOSTS: 'kafka:9092'
KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST: 'kafka:9092'
REDIS_URL: 'redis://redis7:6379/'
@@ -404,6 +406,7 @@ services:
environment:
ADDRESS: '0.0.0.0:3000'
KAFKA_TOPIC: 'session_recording_snapshot_item_events'
+ CAPTURE_OUTPUT_SESSION_REPLAY_MAIN_TOPIC: 'session_recording_snapshot_item_events'
KAFKA_HOSTS: 'kafka:9092'
KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST: 'kafka:9092'
REDIS_URL: 'redis://redis7:6379/'
@@ -419,6 +422,7 @@ services:
environment:
ADDRESS: '0.0.0.0:3000'
KAFKA_TOPIC: 'events_plugin_ingestion_ai'
+ CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC: 'events_plugin_ingestion_ai'
KAFKA_HOSTS: 'kafka:9092'
KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST: 'kafka:9092'
REDIS_URL: 'redis://redis7:6379/'
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.md
index 92972ba0e082..2ccda094c5bf 100644
--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md
+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md
@@ -1,6 +1,6 @@
# Capture outputs refactor — implementation plan
-Working contract for implementation agents. Steps 1–8 have shipped. Each remaining step is one commit in its own PR.
+Working contract for implementation agents. Steps 1–10 have shipped. Each remaining step is one commit in its own PR.
This doc is deleted when it schedules nothing. Step 18 closes objective 1; objectives 2 and 3 are then scheduled in order. Before deletion, the parts still needed — the vocabulary rules, the ordering-vs-person-processing contract, the repartitioning note — move into module docs or `v1/sinks/DESIGN.md`, and unscheduled work becomes issues.
@@ -55,8 +55,8 @@ producers → named connections (brokers, TLS, tuning), instantiated onc
### Vocabulary rules
- **Address** = a lane of a pipeline, or an admin redirect (`Dlq`, `Custom(topic)`) outside the lane model. v0 builds it through `resolve`, v1 by mapping its `Destination`. Never reintroduce a flat enum that mixes pipeline and lane.
-- **Prepared event** = the transport-independent result of processing one event. v1's `PreparedEvent` is the shape; v0's `PreparedPayload` differs only in carrying a topic instead of an address.
-- **Output** = targets + selection policy. **OutputRegistry** = the address → output map. The Step-3 **TopicTable** is absorbed into the targets.
+- **Prepared event** = the transport-independent result of processing one event. v1's `PreparedEvent` is the shape; v0's `PreparedPayload` differs only in carrying v0's `Destination` instead of an address.
+- **Output** = targets + selection policy. **OutputRegistry** = the address → output map. The Step-3 **TopicTable** became the Step-10 **OutputTable**: one target per `Destination`.
- **Destination** = v0's `sinks::registry::Destination` and v1's `v1::sinks::types::Destination` name the same routed slots. Both map onto `Address`. Never call both a policy tree and a routed topic an `Output`.
- **Sink** = one transport. Anything that picks between sinks is an output policy.
- **Producer** config never carries topic names, and output config never carries connection config. An output moves clusters by naming a different producer.
@@ -72,7 +72,7 @@ producers → named connections (brokers, TLS, tuning), instantiated onc
## Starting point
-Steps 1–8 shipped the structure:
+Steps 1–10 shipped the structure:
- **1** — `assert_routing` goldens pin topic, partition key, headers, and reroute counters for every pipeline and lane.
- **2, 5** — routing is the pure `pipeline::resolve(&metadata, ai_events_overflow_armed) -> AddressDecision { address, ordering }`. The Kafka sink still calls it during prep.
@@ -81,32 +81,19 @@ Steps 1–8 shipped the structure:
- **6** — the `Sink` trait takes `PreparedPayload`s and returns per-event `SinkResult`s. Kafka's `prepare_batch` is an inherent method.
- **7** — `outputs.rs`: `Output` is a leaf or a `failover` over two outputs. `FallbackSink` is deleted. Accepted metric change: `capture_event_batch_size` now records on the S3 fallback path and on print/noop single sends.
- **8** — every v0 call site publishes through `OutputRegistry::publish`. `State.outputs` is a concrete `Arc<OutputRegistry>`. The v0 `Event` trait is deleted. `kafka_send` stays on the one-event path: removing it adds a task spawn per event and drops the `ack_wait_one` span, so Step 20 takes it.
+- **9** — named producers (`producers.rs`): each slot reads `KAFKA_<SLOT>_PRODUCER_<RDKAFKA_KEY>` and is instantiated once. `INGESTION` is the one slot. ([#105335](https://github.com/PostHog/posthog/pull/105335))
+- **10** — each v0 `Destination` is an output with a topic and a producer, read from `CAPTURE_OUTPUT_<OUTPUT>_TOPIC` and `CAPTURE_OUTPUT_<OUTPUT>_PRODUCER` as in Node.js ingestion. `OutputTable` replaces `TopicTable`. `PreparedPayload` carries the `Destination`. Setup maps each target's producer name to its handle once and hands the Kafka sink the resolved table; at enqueue the sink publishes through the target's own producer. Custom redirects publish through `CAPTURE_OUTPUT_CUSTOM_PRODUCER`. The table sits inside the sink only because v0 resolves the lane during Kafka prep; it serves the v0 event route and is deleted in Step 20.
Today the registry holds one deployment-wide `Output`: a Kafka leaf, or Kafka→S3 failover. v1 (`CAPTURE_V1_SINKS`) serializes its own `PreparedEvent`s and publishes them through its own `Router` to one default sink, the first name in `CAPTURE_V1_SINKS`.
## Objective 1 — manual fallback for all capture traffic
-Steps 9–10 move configuration onto named producers and outputs. Steps 11–12 bring v1 onto the outputs layer. Steps 13–14 make the set of reachable outputs a type. Steps 15–16 are the checks that type allows. Step 17 is the fallback. Step 18 deletes the S3 fallback it replaces.
-
-### Step 9 · Named producers, instantiated once
-
-- **Goal.** Producer slots are declared in code, and each holds only connection config (brokers, TLS, client tuning) and is instantiated once at startup. The v0 Kafka output publishes through the `INGESTION` slot, which replaces the connection half of `KafkaConfig`. Behavior is byte-identical.
-- **Why.** Two outputs on one cluster must share one connection, and moving one output to another cluster must not move the others. Sharing by name makes both structural.
-- **Same model as Node.js ingestion.** A slot is a role, not a cluster; charts wire it to a cluster per deployment. Its settings are `KAFKA_<SLOT>_PRODUCER_<RDKAFKA_KEY>`, for example `KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST`. Slot names are single words, so no slot's prefix is a prefix of another's.
-- **Migration.** Explicit: capture stops reading `KAFKA_HOSTS`, `KAFKA_TLS`, and the `KAFKA_PRODUCER_*` tuning; charts set the new variables first. The broker list defaults to `kafka:9092`, the local dev and hobby broker, so those setups need no change. capture-logs keeps its own `KafkaConfig`.
-- **Parity proof.** Goldens and integration suites unmodified. A test pins the rdkafka settings of the default slot config to capture's current ones.
-- **Size.** M.
-
-### Step 10 · An output owns its topics and names its producer
-
-- **Goal.** Each leaf output is built from its own config block: its topic names and a producer name. It no longer reads `KafkaConfig`. Two outputs can name different producers (different clusters) or the same one (one connection).
-- **Why.** The policy tree composes any two outputs; the only pair today is Kafka→S3 because `setup` builds it that way. After this step, a second cluster is one more producer and one more output block: a `setup` change and a values file.
-- **Topic defaults stay** until Step 15.
-- **Size.** M.
+Steps 11–12 bring v1 onto the outputs layer. Steps 13–14 make the set of reachable outputs a type. Steps 15–16 are the checks that type allows. Step 17 is the fallback. Step 18 deletes the S3 fallback it replaces.
### Step 11 · Outputs accept prepared events
- **Goal.** A second route into the outputs layer: `publish_prepared(Vec<PreparedEvent>) -> Vec<SinkResult>`, one result per event. Each target maps the event's address to its own topic, and its sink does the transport encoding: the Kafka sink builds the record, and the S3 sink writes the JSON body as a line. Every policy works on this route. v0's event route is unchanged.
+- **Targets live in the outputs layer.** A target is a topic plus a sink. There is one Kafka sink per named producer, built once in setup; it takes a topic and a prepared event and makes no routing decision. This route never reads the Step-10 in-sink `OutputTable`.
- **Why.** v1 already produces prepared events with per-event results. Joining at this level leaves v1's lane decision, JSON body, and response model untouched, so there is no second pass through `resolve` and no parity mapping of v1 decisions onto v0 metadata.
- **Parity proof.** New tests drive prepared events through each leaf and each policy. Goldens unmodified.
- **Size.** M.
@@ -156,7 +143,7 @@ Example of what this catches: until [charts#14941](https://github.com/PostHog/ch
### Step 17 · capture-analytics emergency fallback
-- **Shape.** The capture-analytics output tree holds two Kafka outputs, primary and fallback. Each names its own producer (own brokers, own TLS) and its own topic names. The fallback cluster does not have to copy the primary's topic names. v0 and v1 traffic both publish through this tree.
+- **Shape.** Each capture-analytics output gets a secondary target beside its primary, as in Node.js ingestion's dual-write outputs: `CAPTURE_OUTPUT_<OUTPUT>_SECONDARY_TOPIC` and `CAPTURE_OUTPUT_<OUTPUT>_SECONDARY_PRODUCER`. The secondary producer has its own brokers and TLS, and its topics do not have to copy the primary's names. v0 and v1 traffic both publish through these outputs.
- **Arming.** One environment variable, matched exactly against a sentinel value. `"1"`, `"true"`, or `"yes"` does not arm it; any value other than the sentinel refuses to boot. Unset is normal operation.
- **Static at boot.** A new `select` policy holds both targets and publishes to one, picked by the arming variable. It does not react to health: switching means setting the variable and rolling the pods, because a person decides to move off a degraded MSK. Automatic switching is objective 3. The health-gated `failover` policy is not used here; it serves only S3.
- **A retryable error stays on the live target.** It returns to the caller like any other publish error and never sends the batch to the other target.
@@ -191,7 +178,7 @@ v0 and v1 producer tuning is reconciled into one set per cluster, and capture-an
### Step 20 · v0 builds prepared events
-v0 resolves the lane, builds the JSON body and header values, and hands prepared events to `publish_prepared`, as v1 does. The lz4 envelope moves into the Kafka sink as target config. `PublishEvents`, `kafka_send`, and v0's event route into the outputs layer are deleted. v0 call sites fold per-event results into the whole-request `CaptureError`.
+v0 resolves the lane, builds the JSON body and header values, and hands prepared events to `publish_prepared`, as v1 does. The lz4 envelope moves into the Kafka sink as target config. `PublishEvents`, `kafka_send`, and v0's event route into the outputs layer are deleted, and with them the in-sink `OutputTable`, its `resolve`, and `map_producers`. v0 call sites fold per-event results into the whole-request `CaptureError`.
- **Tests.** Capturing mocks see prepared events, not `ProcessedEvent`s, so about 60 metadata assertions become wire-level (topic, key, headers, payload). The `ExpectedEvent` checkers rebuild the expected record, so test bodies stay the same. This also pins that replay events redirected to dlq/custom partition on the event key, not the session id.
- **Accepted differences.** print/noop run the real prep path, so they can now fail prep (e.g. `MissingSessionId`). Prep histograms keep their `capture_kafka_*` names.
@@ -293,8 +280,8 @@ One step = one commit, subject from the tracker. No `--no-verify`.
| 7 · Outputs layer with policies; composites retired | done | `feat(capture): outputs layer owns the failover policy` |
| 8a · Call sites on the table | done | `refactor(capture): call sites publish through outputs` |
| 8b · `Event` retired | done | `refactor(capture): retire v0 Event trait` |
-| 9 · Named producers, instantiated once | pending | `refactor(capture): named producers own their connection config` |
-| 10 · An output owns its topics and names its producer | pending | `refactor(capture): outputs carry their own topics and name their producer` |
+| 9 · Named producers, instantiated once | done | `refactor(capture): named producers own their connection config` |
+| 10 · An output owns its topics and names its producer | done | `feat(capture): each output reads its own topic and producer` |
| 11 · Outputs accept prepared events | pending | `feat(capture): outputs publish prepared events with per-event results` |
| 12 · v1 publishes through the outputs layer | pending | `refactor(capture): v1 publishes through outputs; v1 sink stack deleted` |
| 13 · Typed per-pipeline lanes | pending | `refactor(capture): typed per-pipeline lanes` |
@@ -315,7 +302,7 @@ One step = one commit, subject from the tracker. No `--no-verify`.
| 28 · Sinks realize namespaces | superseded | — (targets map addresses to topics from Step 11) |
| 29 · Handlers bound by publish capabilities | deferred | `feat(capture): handlers bound by publish capabilities over per-mode state` |
| 30 · AI ingress family | deferred | `feat(capture): ai ingress is its own router family with its own capability` |
-| 31 · Topic tables injected into sinks | superseded | — (each target owns its topics from Step 10) |
+| 31 · Topic tables injected into sinks | superseded | — (targets move to the outputs layer in Step 11; the in-sink table goes in Step 20) |
| 32 · Per-pipeline output overrides; boot topic verification | superseded | — (boot verification became Step 16; retargeting is configuration after Steps 10 and 14) |
| 33 · Naming and import hygiene | deferred | `refactor(capture): replace remaining nested paths with imports` + `refactor(capture): name the session replay pipeline consistently` |
| 34 · Outputs as an open trait | deferred | `refactor(capture): Outputs becomes an open trait` |
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 3feefb258e4c..9c1b01187d6b 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -4,6 +4,7 @@ use common_continuous_profiling::ContinuousProfilingConfig;
use envconfig::Envconfig;
use tracing::Level;
+use crate::producers::ProducerName;
use crate::v0_request::AiLanePredicate;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
@@ -280,7 +281,7 @@ pub struct Config {
pub historical_rerouting_threshold_days: i64,
#[envconfig(nested = true)]
- pub kafka_topics: KafkaTopicsConfig,
+ pub outputs: OutputsConfig,
/// Application-level compression of session replay payloads, independent of
/// broker-level compression. Consumers detect and decompress it.
@@ -288,7 +289,7 @@ pub struct Config {
pub replay_envelope_compression: EnvelopeCompression,
/// Refuse to boot when a registered output has an empty topic name (see
- /// `TopicTable::check_complete`). Off by default so that a deployment which
+ /// `OutputTable::check_complete`). Off by default so that a deployment which
/// blanks a topic it never produces to still boots.
#[envconfig(from = "CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED", default = "false")]
pub outputs_completeness_check_enabled: bool,
@@ -449,7 +450,7 @@ pub struct Config {
// The warnings emitter's own destination. It serves every pipeline that
// emits (v1 and legacy analytics, both AI endpoints, and replay) but reads
// only these three vars, never the ingestion producer's settings or
- // `KAFKA_CLIENT_INGESTION_WARNING_TOPIC`. charts sets all three per env,
+ // `CAPTURE_OUTPUT_CLIENT_WARNINGS_TOPIC`. charts sets all three per env,
// pointed at the MSK cluster the clientwarnings consumer reads from.
//
// Defaults are inert on purpose: empty hosts or topic makes
@@ -496,52 +497,108 @@ pub struct Config {
pub ai_byte_limit_local_cache_max_entries: u64,
}
-/// The topic each capture destination produces to. Connection settings live
-/// with the named producers in [`crate::producers`].
+/// Mirrors Node.js ingestion's `INGESTION_OUTPUT_<OUTPUT>_{TOPIC,PRODUCER}`.
+///
+/// Topic defaults are the local dev and hobby topics. Those stacks pull
+/// `capture:master` with compose files that can predate these variables.
#[derive(Envconfig, Clone)]
-pub struct KafkaTopicsConfig {
- #[envconfig(from = "KAFKA_TOPIC", default = "events_plugin_ingestion")]
- pub main: String,
+pub struct OutputsConfig {
#[envconfig(
- from = "KAFKA_OVERFLOW_TOPIC",
+ from = "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ default = "events_plugin_ingestion"
+ )]
+ pub analytics_main_topic: String,
+ #[envconfig(from = "CAPTURE_OUTPUT_ANALYTICS_MAIN_PRODUCER", default = "INGESTION")]
+ pub analytics_main_producer: ProducerName,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_ANALYTICS_OVERFLOW_TOPIC",
default = "events_plugin_ingestion_overflow"
)]
- pub overflow: String,
+ pub analytics_overflow_topic: String,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_ANALYTICS_OVERFLOW_PRODUCER",
+ default = "INGESTION"
+ )]
+ pub analytics_overflow_producer: ProducerName,
#[envconfig(
- from = "KAFKA_HISTORICAL_TOPIC",
+ from = "CAPTURE_OUTPUT_ANALYTICS_HISTORICAL_TOPIC",
default = "events_plugin_ingestion_historical"
)]
- pub historical: String,
+ pub analytics_historical_topic: String,
#[envconfig(
- from = "KAFKA_CLIENT_INGESTION_WARNING_TOPIC",
- default = "ingestion-clientwarnings-main-1"
+ from = "CAPTURE_OUTPUT_ANALYTICS_HISTORICAL_PRODUCER",
+ default = "INGESTION"
)]
- pub client_ingestion_warning: String,
- #[envconfig(from = "KAFKA_ERROR_TRACKING_TOPIC", default = "error_tracking_events")]
- pub error_tracking: String,
- #[envconfig(from = "KAFKA_HEATMAPS_TOPIC", default = "heatmaps_ingestion")]
- pub heatmaps: String,
+ pub analytics_historical_producer: ProducerName,
#[envconfig(
- from = "KAFKA_REPLAY_OVERFLOW_TOPIC",
+ from = "CAPTURE_OUTPUT_SESSION_REPLAY_MAIN_TOPIC",
+ default = "session_recording_snapshot_item_events"
+ )]
+ pub session_replay_main_topic: String,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_SESSION_REPLAY_MAIN_PRODUCER",
+ default = "INGESTION"
+ )]
+ pub session_replay_main_producer: ProducerName,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_SESSION_REPLAY_OVERFLOW_TOPIC",
default = "session_recording_snapshot_item_overflow"
)]
- pub replay_overflow: String,
- #[envconfig(from = "KAFKA_DLQ_TOPIC", default = "events_plugin_ingestion_dlq")]
- pub dlq: String,
+ pub session_replay_overflow_topic: String,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_SESSION_REPLAY_OVERFLOW_PRODUCER",
+ default = "INGESTION"
+ )]
+ pub session_replay_overflow_producer: ProducerName,
+ #[envconfig(from = "CAPTURE_OUTPUT_HEATMAPS_TOPIC", default = "heatmaps_ingestion")]
+ pub heatmaps_topic: String,
+ #[envconfig(from = "CAPTURE_OUTPUT_HEATMAPS_PRODUCER", default = "INGESTION")]
+ pub heatmaps_producer: ProducerName,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_CLIENT_WARNINGS_TOPIC",
+ default = "ingestion-clientwarnings-main-1"
+ )]
+ pub client_warnings_topic: String,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_CLIENT_WARNINGS_PRODUCER",
+ default = "INGESTION"
+ )]
+ pub client_warnings_producer: ProducerName,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_ERROR_TRACKING_TOPIC",
+ default = "ingestion-errortracking-main"
+ )]
+ pub error_tracking_topic: String,
+ #[envconfig(from = "CAPTURE_OUTPUT_ERROR_TRACKING_PRODUCER", default = "INGESTION")]
+ pub error_tracking_producer: ProducerName,
+ #[envconfig(
+ from = "CAPTURE_OUTPUT_DLQ_TOPIC",
+ default = "events_plugin_ingestion_dlq"
+ )]
+ pub dlq_topic: String,
+ #[envconfig(from = "CAPTURE_OUTPUT_DLQ_PRODUCER", default = "INGESTION")]
+ pub dlq_producer: ProducerName,
/// The v0 (`DataType::AiEvents`) and v1 (`Destination::AiEvents`) pipelines
/// divert AI events here instead of the main topic on every deployment,
/// capture-ai included. Setup also injects it into every v1 sink config.
#[envconfig(
- from = "CAPTURE_ANALYTICS_AI_EVENTS_TOPIC",
+ from = "CAPTURE_OUTPUT_AI_MAIN_TOPIC",
default = "events_plugin_ingestion_ai"
)]
- pub ai_events: String,
+ pub ai_main_topic: String,
+ #[envconfig(from = "CAPTURE_OUTPUT_AI_MAIN_PRODUCER", default = "INGESTION")]
+ pub ai_main_producer: ProducerName,
/// Unset means AI events never overflow. When set, the AI lane uses the
/// analytics main lane's overflow limiter and restriction-driven
/// force_overflow, and reroutes here. Import mode refuses it at boot
/// because imports must never overflow.
- #[envconfig(from = "CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC")]
- pub ai_events_overflow: Option<String>,
+ #[envconfig(from = "CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC")]
+ pub ai_overflow_topic: Option<String>,
+ #[envconfig(from = "CAPTURE_OUTPUT_AI_OVERFLOW_PRODUCER", default = "INGESTION")]
+ pub ai_overflow_producer: ProducerName,
+ /// Carries event-restriction redirects to an admin-supplied topic.
+ #[envconfig(from = "CAPTURE_OUTPUT_CUSTOM_PRODUCER", default = "INGESTION")]
+ pub custom_producer: ProducerName,
}
#[derive(Envconfig, Clone)]
@@ -612,6 +669,7 @@ pub struct KafkaConfig {
#[cfg(test)]
mod tests {
use super::{CaptureMode, Config};
+ use crate::producers::ProducerName;
use crate::v0_request::AiLanePredicate;
use std::collections::HashMap;
use std::str::FromStr;
@@ -624,24 +682,33 @@ mod tests {
}
#[test]
- fn capture_analytics_ai_events_topic_defaults() {
+ fn output_topic_defaults_match_the_local_stack() {
let config: Config =
envconfig::Envconfig::init_from_hashmap(&required_config_env()).unwrap();
- assert_eq!(config.kafka_topics.ai_events, "events_plugin_ingestion_ai");
- assert_eq!(config.kafka_topics.ai_events_overflow, None);
+ assert_eq!(config.outputs.ai_main_topic, "events_plugin_ingestion_ai");
+ assert_eq!(config.outputs.ai_overflow_topic, None);
+ assert_eq!(
+ config.outputs.session_replay_main_topic,
+ "session_recording_snapshot_item_events"
+ );
+ assert_eq!(
+ config.outputs.error_tracking_topic,
+ "ingestion-errortracking-main"
+ );
}
#[rstest::rstest]
- #[case("KAFKA_TOPIC", |c: &Config| c.kafka_topics.main.clone())]
- #[case("KAFKA_OVERFLOW_TOPIC", |c: &Config| c.kafka_topics.overflow.clone())]
- #[case("KAFKA_HISTORICAL_TOPIC", |c: &Config| c.kafka_topics.historical.clone())]
- #[case("KAFKA_CLIENT_INGESTION_WARNING_TOPIC", |c: &Config| c.kafka_topics.client_ingestion_warning.clone())]
- #[case("KAFKA_ERROR_TRACKING_TOPIC", |c: &Config| c.kafka_topics.error_tracking.clone())]
- #[case("KAFKA_HEATMAPS_TOPIC", |c: &Config| c.kafka_topics.heatmaps.clone())]
- #[case("KAFKA_REPLAY_OVERFLOW_TOPIC", |c: &Config| c.kafka_topics.replay_overflow.clone())]
- #[case("KAFKA_DLQ_TOPIC", |c: &Config| c.kafka_topics.dlq.clone())]
- #[case("CAPTURE_ANALYTICS_AI_EVENTS_TOPIC", |c: &Config| c.kafka_topics.ai_events.clone())]
- #[case("CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC", |c: &Config| c.kafka_topics.ai_events_overflow.clone().unwrap_or_default())]
+ #[case("CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC", |c: &Config| c.outputs.analytics_main_topic.clone())]
+ #[case("CAPTURE_OUTPUT_ANALYTICS_OVERFLOW_TOPIC", |c: &Config| c.outputs.analytics_overflow_topic.clone())]
+ #[case("CAPTURE_OUTPUT_ANALYTICS_HISTORICAL_TOPIC", |c: &Config| c.outputs.analytics_historical_topic.clone())]
+ #[case("CAPTURE_OUTPUT_SESSION_REPLAY_MAIN_TOPIC", |c: &Config| c.outputs.session_replay_main_topic.clone())]
+ #[case("CAPTURE_OUTPUT_SESSION_REPLAY_OVERFLOW_TOPIC", |c: &Config| c.outputs.session_replay_overflow_topic.clone())]
+ #[case("CAPTURE_OUTPUT_HEATMAPS_TOPIC", |c: &Config| c.outputs.heatmaps_topic.clone())]
+ #[case("CAPTURE_OUTPUT_CLIENT_WARNINGS_TOPIC", |c: &Config| c.outputs.client_warnings_topic.clone())]
+ #[case("CAPTURE_OUTPUT_ERROR_TRACKING_TOPIC", |c: &Config| c.outputs.error_tracking_topic.clone())]
+ #[case("CAPTURE_OUTPUT_DLQ_TOPIC", |c: &Config| c.outputs.dlq_topic.clone())]
+ #[case("CAPTURE_OUTPUT_AI_MAIN_TOPIC", |c: &Config| c.outputs.ai_main_topic.clone())]
+ #[case("CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC", |c: &Config| c.outputs.ai_overflow_topic.clone().unwrap_or_default())]
fn topic_env_var_binds_to_its_field(
#[case] env_var: &str,
#[case] field: fn(&Config) -> String,
@@ -652,6 +719,57 @@ mod tests {
assert_eq!(field(&config), "configured_topic");
}
+ #[rstest::rstest]
+ #[case("KAFKA_TOPIC")]
+ #[case("KAFKA_OVERFLOW_TOPIC")]
+ #[case("KAFKA_HISTORICAL_TOPIC")]
+ #[case("KAFKA_CLIENT_INGESTION_WARNING_TOPIC")]
+ #[case("KAFKA_ERROR_TRACKING_TOPIC")]
+ #[case("KAFKA_HEATMAPS_TOPIC")]
+ #[case("KAFKA_REPLAY_OVERFLOW_TOPIC")]
+ #[case("KAFKA_DLQ_TOPIC")]
+ #[case("CAPTURE_ANALYTICS_AI_EVENTS_TOPIC")]
+ #[case("CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC")]
+ fn legacy_topic_env_var_is_not_read(#[case] env_var: &str) {
+ let mut env = required_config_env();
+ env.insert(env_var.into(), "legacy_topic".into());
+ let config: Config = envconfig::Envconfig::init_from_hashmap(&env).unwrap();
+ let outputs = &config.outputs;
+ let topics = [
+ outputs.analytics_main_topic.as_str(),
+ outputs.analytics_overflow_topic.as_str(),
+ outputs.analytics_historical_topic.as_str(),
+ outputs.session_replay_main_topic.as_str(),
+ outputs.session_replay_overflow_topic.as_str(),
+ outputs.heatmaps_topic.as_str(),
+ outputs.client_warnings_topic.as_str(),
+ outputs.error_tracking_topic.as_str(),
+ outputs.dlq_topic.as_str(),
+ outputs.ai_main_topic.as_str(),
+ outputs.ai_overflow_topic.as_deref().unwrap_or_default(),
+ ];
+ assert!(!topics.contains(&"legacy_topic"), "{env_var} is still read");
+ }
+
+ #[test]
+ fn output_producers_default_to_ingestion_and_parse_their_env_var() {
+ let config: Config =
+ envconfig::Envconfig::init_from_hashmap(&required_config_env()).unwrap();
+ assert_eq!(
+ config.outputs.analytics_main_producer,
+ ProducerName::Ingestion
+ );
+ assert_eq!(config.outputs.custom_producer, ProducerName::Ingestion);
+
+ let mut env = required_config_env();
+ env.insert(
+ "CAPTURE_OUTPUT_HEATMAPS_PRODUCER".into(),
+ "WARPSTREAM".into(),
+ );
+ let bad: Result<Config, _> = envconfig::Envconfig::init_from_hashmap(&env);
+ assert!(bad.is_err(), "an undeclared producer must fail startup");
+ }
+
#[test]
fn moved_output_settings_keep_their_env_vars() {
let mut env = required_config_env();
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 1931c6d4c1a5..da5a297ce788 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -1436,7 +1436,7 @@ mod tests {
/// End-to-end: `process_events` drops the over-budget `$ai_generation` and keeps the small one.
#[tokio::test]
async fn ai_events_over_byte_budget_are_dropped_end_to_end() {
- use crate::sinks::kafka::{test_topics, KafkaSinkBase};
+ use crate::sinks::kafka::{test_outputs, KafkaSinkBase};
use crate::sinks::producer::MockKafkaProducer;
// 800-byte budget: the enveloped small event (~672 B) fits, and the
@@ -1446,7 +1446,7 @@ mod tests {
let producer = MockKafkaProducer::new();
let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(
producer.clone(),
- test_topics(),
+ test_outputs(),
)));
let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
@@ -1492,10 +1492,10 @@ mod tests {
1,
"only the under-budget AI event must reach the sink"
);
- let topics = test_topics();
+ let topics = test_outputs();
let ai_topic = topics.topic_for(&crate::sinks::registry::Destination::AiMain);
assert_eq!(
- records[0].topic, ai_topic,
+ &*records[0].topic, ai_topic,
"the surviving record must be on the AI lane"
);
}
@@ -1794,7 +1794,7 @@ mod tests {
/// it diverts to `AiEvents` and the AI topic, exactly as under `Events`.
#[tokio::test]
async fn ai_mode_routes_ai_events_to_the_ai_lane_end_to_end() {
- use crate::sinks::kafka::{test_topics, KafkaSinkBase};
+ use crate::sinks::kafka::{test_outputs, KafkaSinkBase};
use crate::sinks::producer::MockKafkaProducer;
// 800-byte budget: the small event fits, the large one takes the
@@ -1804,7 +1804,7 @@ mod tests {
let producer = MockKafkaProducer::new();
let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(
producer.clone(),
- test_topics(),
+ test_outputs(),
)));
let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
@@ -1851,10 +1851,10 @@ mod tests {
1,
"only the under-budget event must reach the sink under Ai mode"
);
- let topics = test_topics();
+ let topics = test_outputs();
let ai_topic = topics.topic_for(&crate::sinks::registry::Destination::AiMain);
assert_eq!(
- records[0].topic, ai_topic,
+ &*records[0].topic, ai_topic,
"an allowlisted AI event diverts to the AI lane under Ai mode too"
);
}
@@ -2450,7 +2450,7 @@ mod tests {
/// End-to-end gate for the AI overflow valve: a diverted AI event
/// is overflow-stamped only when the AI limiter is wired (setup builds
- /// it exactly when `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` is
+ /// it exactly when `CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC` is
/// configured), and keeps its AI lane either way.
#[rstest]
#[case::limiter_present(AiValveCase {
@@ -3241,7 +3241,7 @@ mod tests {
// tests alone cover: stamp metadata in pipeline, ensure the real sink
// reads the metadata and produces the expected topic, key, and headers.
- use crate::sinks::kafka::{test_topics, KafkaSinkBase};
+ use crate::sinks::kafka::{test_outputs, KafkaSinkBase};
use crate::sinks::producer::MockKafkaProducer;
#[tokio::test]
@@ -3259,7 +3259,7 @@ mod tests {
let producer = MockKafkaProducer::new();
let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(
producer.clone(),
- test_topics(),
+ test_outputs(),
)));
// test_token in reroute list -> ForceLimited stamped in pipeline.
let limiter = build_limiter(10, 10, Some("test_token".to_string()), false);
@@ -3279,7 +3279,7 @@ mod tests {
let records = producer.get_records();
assert_eq!(records.len(), 1);
assert_eq!(
- records[0].topic, "events_plugin_ingestion_overflow",
+ &*records[0].topic, "events_plugin_ingestion_overflow",
"ForceLimited must route to overflow topic"
);
assert_eq!(
@@ -3315,7 +3315,7 @@ mod tests {
let producer = MockKafkaProducer::new();
let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(
producer.clone(),
- test_topics(),
+ test_outputs(),
)));
// burst=1 => event[1] stamped RateLimited { preserve_locality }.
let limiter = build_limiter(1, 1, None, preserve_locality);
@@ -3335,11 +3335,11 @@ mod tests {
let records = producer.get_records();
assert_eq!(records.len(), 2);
assert_eq!(
- records[0].topic, "events_plugin_ingestion",
+ &*records[0].topic, "events_plugin_ingestion",
"event[0]: within burst -> main topic"
);
assert_eq!(
- records[1].topic, "events_plugin_ingestion_overflow",
+ &*records[1].topic, "events_plugin_ingestion_overflow",
"event[1]: over burst -> overflow topic"
);
assert!(
@@ -3703,7 +3703,7 @@ mod tests {
let producer = MockKafkaProducer::new();
let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(
producer.clone(),
- test_topics(),
+ test_outputs(),
)));
run_pipeline(outputs, events, &context, PipelineOptions::default())
@@ -3719,11 +3719,11 @@ mod tests {
let original = records
.iter()
- .find(|r| r.topic == "events_plugin_ingestion")
+ .find(|r| &*r.topic == "events_plugin_ingestion")
.expect("original event should land on the main events topic");
let redirect = records
.iter()
- .find(|r| r.topic == "heatmaps")
+ .find(|r| &*r.topic == "heatmaps")
.expect("redirect should land on the heatmaps topic");
// ---- original on events topic ----
diff --git a/rust/capture/src/events/overflow_stamping.rs b/rust/capture/src/events/overflow_stamping.rs
index bd12f7f457f9..c5d22c6f6dd3 100644
--- a/rust/capture/src/events/overflow_stamping.rs
+++ b/rust/capture/src/events/overflow_stamping.rs
@@ -32,7 +32,7 @@ use crate::v0_request::{DataType, OverflowReason, ProcessedEvent};
///
/// Two lanes can overflow: `AnalyticsMain` always, and `AiEvents` only when
/// its limiter is present — setup builds `ai_limiter` exactly when the AI
-/// overflow valve (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`) is armed and
+/// overflow valve (`CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC`) is armed and
/// overflow is enabled, so limiter presence IS the valve here; the kafka sink
/// independently ignores overflow stamps on the AI lane when the topic is
/// unset. Each lane consults its own limiter instance — `analytics_limiter`
diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rs
index 303e0c7cfe75..63685963d2a1 100644
--- a/rust/capture/src/events/recordings.rs
+++ b/rust/capture/src/events/recordings.rs
@@ -1502,7 +1502,7 @@ mod tests {
// metadata and produces to `replay_overflow_topic` with the session_id
// as partition key.
- use crate::sinks::kafka::{test_topics, KafkaSinkBase};
+ use crate::sinks::kafka::{test_outputs, KafkaSinkBase};
use crate::sinks::producer::MockKafkaProducer;
#[tokio::test]
@@ -1510,7 +1510,7 @@ mod tests {
let producer = MockKafkaProducer::new();
let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(
producer.clone(),
- test_topics(),
+ test_outputs(),
)));
let limiter = build_replay_limiter(vec!["test-session-123".to_string()]).await;
@@ -1531,7 +1531,7 @@ mod tests {
let records = producer.get_records();
assert_eq!(records.len(), 1);
assert_eq!(
- records[0].topic, "replay_overflow",
+ &*records[0].topic, "replay_overflow",
"ReplayLimited must route to replay_overflow topic"
);
assert_eq!(
diff --git a/rust/capture/src/outputs.rs b/rust/capture/src/outputs.rs
index f77d9b7e96ef..3e0c6297f05c 100644
--- a/rust/capture/src/outputs.rs
+++ b/rust/capture/src/outputs.rs
@@ -26,10 +26,6 @@ pub trait PublishEvents: Send + Sync {
/// One method for any batch size: a backend that serves a one-event
/// batch more cheaply specializes inside its own impl.
async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError>;
-
- fn flush(&self) -> Result<(), anyhow::Error> {
- Ok(())
- }
}
pub struct Output {
@@ -83,13 +79,6 @@ impl PublishEvents for Output {
Inner::Failover(failover) => failover.publish_events(events).await,
}
}
-
- fn flush(&self) -> Result<(), anyhow::Error> {
- match &self.inner {
- Inner::Single(leaf) => leaf.flush(),
- Inner::Failover(failover) => failover.flush(),
- }
- }
}
struct Failover {
@@ -126,17 +115,13 @@ impl Failover {
self.fallback.publish_events(events).await
}
}
-
- fn flush(&self) -> Result<(), anyhow::Error> {
- self.primary.flush()
- }
}
-/// The (pipeline, lane) → output map the deployment state holds.
-/// Degenerate today: one deployment-wide output serves every address, and
-/// per-lane topics resolve during prep via the [`TopicTable`].
+/// The (pipeline, lane) → output map the deployment state holds. One
+/// deployment-wide output serves every address; the Kafka sink resolves
+/// per-lane topics through its [`OutputTable`] at enqueue.
///
-/// [`TopicTable`]: crate::sinks::registry::TopicTable
+/// [`OutputTable`]: crate::sinks::registry::OutputTable
pub struct OutputRegistry {
output: Output,
}
@@ -157,10 +142,6 @@ impl OutputRegistry {
pub async fn publish(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {
self.output.publish_events(events).await
}
-
- pub fn flush(&self) -> Result<(), anyhow::Error> {
- self.output.flush()
- }
}
#[cfg(test)]
@@ -338,6 +319,5 @@ mod tests {
.unwrap();
assert_eq!(leaf.get_events().len(), 3);
- registry.flush().unwrap();
}
}
diff --git a/rust/capture/src/overflow_parity.rs b/rust/capture/src/overflow_parity.rs
index f15bf410f855..58da53979913 100644
--- a/rust/capture/src/overflow_parity.rs
+++ b/rust/capture/src/overflow_parity.rs
@@ -22,7 +22,7 @@ use std::num::NonZeroU32;
use crate::global_rate_limiter::GlobalRateLimiter;
use crate::outputs::OutputRegistry;
use crate::router::HistoricalConfig;
-use crate::sinks::kafka::{test_topics, KafkaSinkBase};
+use crate::sinks::kafka::{test_outputs, KafkaSinkBase};
use crate::sinks::producer::MockKafkaProducer;
use crate::v0_request::ProcessingContext;
use crate::v1::analytics::process::process_batch;
@@ -126,7 +126,7 @@ async fn run_v0(limits: Limits, batch_size: usize, observe: usize) -> Observed {
let producer = MockKafkaProducer::new();
let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(
producer.clone(),
- test_topics(),
+ test_outputs(),
)));
let global = limits.globally_limited.then(|| {
Arc::new(GlobalRateLimiter::mock_limiting(&[&format!(
@@ -157,14 +157,14 @@ async fn run_v0(limits: Limits, batch_size: usize, observe: usize) -> Observed {
let records = producer.get_records();
assert_eq!(records.len(), batch_size, "v0 must produce every event");
let record = &records[observe];
- let topics = test_topics();
+ let topics = test_outputs();
Observed {
- lane: if record.topic == topics.main {
+ lane: if *record.topic == *topics.analytics_main.topic {
Lane::Main
- } else if record.topic == topics.overflow {
+ } else if *record.topic == *topics.analytics_overflow.topic {
Lane::Overflow
} else {
- Lane::Other(record.topic.clone())
+ Lane::Other(record.topic.to_string())
},
has_key: record.key.is_some(),
person_processing_disabled: record
diff --git a/rust/capture/src/producers.rs b/rust/capture/src/producers.rs
index 418eed353b77..907cdfb14e44 100644
--- a/rust/capture/src/producers.rs
+++ b/rust/capture/src/producers.rs
@@ -7,6 +7,7 @@
//! publishes through a slot shares its one producer.
use std::collections::HashMap;
+use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
@@ -17,7 +18,7 @@ use rdkafka::ClientConfig;
use tracing::log::{debug, info};
use crate::sinks::kafka::KafkaContext;
-use crate::sinks::producer::RdKafkaProducer;
+use crate::sinks::producer::{KafkaProducer, RdKafkaProducer};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProducerName {
@@ -40,6 +41,20 @@ impl ProducerName {
}
}
+impl FromStr for ProducerName {
+ type Err = anyhow::Error;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ Self::ALL
+ .into_iter()
+ .find(|name| name.as_str() == s)
+ .ok_or_else(|| {
+ let known: Vec<&str> = Self::ALL.iter().map(|name| name.as_str()).collect();
+ anyhow::anyhow!("unknown producer {s:?}, expected one of {known:?}")
+ })
+ }
+}
+
/// One producer's connection and tuning. Each field maps to the rdkafka key of
/// the same name.
#[derive(Envconfig, Clone, Debug)]
@@ -214,6 +229,14 @@ impl ProducerRegistry {
pub fn get(&self, name: ProducerName) -> ProducerHandle {
Arc::clone(&self.producers[&name])
}
+
+ /// Blocks until every producer's queue drains or times out.
+ pub fn flush(&self) -> anyhow::Result<()> {
+ for producer in self.producers.values() {
+ producer.flush()?;
+ }
+ Ok(())
+ }
}
pub fn load_all(
@@ -345,4 +368,16 @@ mod tests {
assert!(err.to_string().contains("INGESTION"), "{err}");
}
+
+ #[test]
+ fn producer_name_parses_only_declared_slots() {
+ assert_eq!(
+ "INGESTION".parse::<ProducerName>().unwrap(),
+ ProducerName::Ingestion
+ );
+ for unknown in ["ingestion", "WARPSTREAM", ""] {
+ let err = unknown.parse::<ProducerName>().unwrap_err();
+ assert!(err.to_string().contains("INGESTION"), "{err}");
+ }
+ }
}
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rs
index e8c48e8ea018..3093585b021b 100644
--- a/rust/capture/src/router.rs
+++ b/rust/capture/src/router.rs
@@ -114,7 +114,7 @@ pub struct State {
/// V1 sink router for the new capture analytics pipeline.
/// When present, the v1 analytics handler publishes events through this.
pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,
- /// Whether the AI overflow valve is armed (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` is
+ /// Whether the AI overflow valve is armed (`CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC` is
/// set). Gates overflow stamping for the AI lane in both pipelines: when
/// false, AI events never overflow (pre-overflow behavior).
pub ai_events_overflow_enabled: bool,
diff --git a/rust/capture/src/server.rs b/rust/capture/src/server.rs
index cf02150a08ec..4c6b2cf0188a 100644
--- a/rust/capture/src/server.rs
+++ b/rust/capture/src/server.rs
@@ -1,6 +1,5 @@
use std::io;
use std::net::SocketAddr;
-use std::sync::Arc;
use std::time::Duration;
use axum::extract::ConnectInfo;
@@ -93,7 +92,7 @@ pub async fn serve(listener: TcpListener, components: CaptureComponents) {
let CaptureComponents {
app,
server_handle,
- outputs,
+ producers,
v1_sink_router,
event_restriction_service: _,
http1_header_read_timeout_ms,
@@ -230,19 +229,19 @@ pub async fn serve(listener: TcpListener, components: CaptureComponents) {
graceful.shutdown().await;
info!("Hyper accept loop (shutdown): graceful shutdown completed");
- // Flush both produce layers concurrently. The v0 outputs flush is
- // synchronous (rdkafka), so it runs on the blocking thread pool. V1
- // sinks already use spawn_blocking internally (see KafkaSink::flush).
+ // The v0 producers flush is synchronous (rdkafka), so it runs on the
+ // blocking thread pool. V1 sinks already use spawn_blocking internally
+ // (see KafkaSink::flush).
info!("Flushing sinks...");
- let legacy_flush = {
- let outputs = Arc::clone(&outputs);
- async move {
- let result = tokio::task::spawn_blocking(move || outputs.flush()).await;
- match result {
- Ok(Err(e)) => error!("Output flush failed: {e:#}"),
- Err(e) => error!("Output flush task panicked: {e}"),
- Ok(Ok(())) => {}
- }
+ let legacy_flush = async move {
+ let Some(producers) = producers else {
+ return;
+ };
+ let result = tokio::task::spawn_blocking(move || producers.flush()).await;
+ match result {
+ Ok(Err(e)) => error!("Producer flush failed: {e:#}"),
+ Err(e) => error!("Producer flush task panicked: {e}"),
+ Ok(Ok(())) => {}
}
};
let v1_flush = async {
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index 597df18d41f4..b98608e91a03 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -29,7 +29,7 @@ use crate::router::BATCH_BODY_SIZE;
use crate::sinks::kafka::KafkaSink;
use crate::sinks::noop::NoOpSink;
use crate::sinks::print::PrintSink;
-use crate::sinks::registry::TopicTable;
+use crate::sinks::registry::OutputTable;
use crate::sinks::s3::S3Sink;
use limiters::overflow::OverflowLimiter;
use limiters::redis::{QuotaResource, RedisLimiter, ServiceName, OVERFLOW_LIMITER_CACHE_KEY};
@@ -129,7 +129,8 @@ pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) ->
pub struct CaptureComponents {
pub app: Router,
pub server_handle: lifecycle::Handle,
- pub outputs: Arc<OutputRegistry>,
+ /// `None` with the print or noop sink, which produce to no Kafka.
+ pub producers: Option<Arc<ProducerRegistry>>,
pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,
pub event_restriction_service: Option<EventRestrictionService>,
pub http1_header_read_timeout_ms: Option<u64>,
@@ -292,12 +293,11 @@ pub async fn build_components(
_ => None,
};
- let outputs = Arc::new(
+ let (outputs, producers) =
create_output_registry(&config, &producer_configs, sink_handle, advisory_handle)
.await
- .expect("failed to create the output registry"),
- );
- let outputs_for_flush = outputs.clone();
+ .expect("failed to create the output registry");
+ let outputs = Arc::new(outputs);
let event_restriction_service = if let Some(handle) = event_restrictions_handle {
create_event_restriction_service(
@@ -310,13 +310,13 @@ pub async fn build_components(
};
assert!(
- !config.kafka_topics.ai_events.is_empty(),
- "invalid configuration: CAPTURE_ANALYTICS_AI_EVENTS_TOPIC must not be empty",
+ !config.outputs.ai_main_topic.is_empty(),
+ "invalid configuration: CAPTURE_OUTPUT_AI_MAIN_TOPIC must not be empty",
);
let ai_events_overflow_enabled = ai_events_overflow_valve(&config);
info!(
- capture_analytics_ai_events_topic = %config.kafka_topics.ai_events,
- capture_analytics_ai_events_overflow_topic = ?config.kafka_topics.ai_events_overflow,
+ ai_main_topic = %config.outputs.ai_main_topic,
+ ai_overflow_topic = ?config.outputs.ai_overflow_topic,
ai_events_overflow_enabled,
"AI events topic routing"
);
@@ -429,7 +429,7 @@ pub async fn build_components(
CaptureComponents {
app,
server_handle: server,
- outputs: outputs_for_flush,
+ producers: producers.map(Arc::new),
v1_sink_router,
event_restriction_service,
http1_header_read_timeout_ms: config.http1_header_read_timeout_ms,
@@ -437,7 +437,7 @@ pub async fn build_components(
}
/// The AI overflow valve: an unset or empty
-/// `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` means AI events never
+/// `CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC` means AI events never
/// overflow. Import mode refuses an armed valve at boot: non-AI import events
/// can't overflow because historical rerouting takes precedence no matter how
/// the deployment is configured, but nothing structural protects AI
@@ -445,13 +445,13 @@ pub async fn build_components(
/// guarantee.
fn ai_events_overflow_valve(config: &Config) -> bool {
let armed = config
- .kafka_topics
- .ai_events_overflow
+ .outputs
+ .ai_overflow_topic
.as_deref()
.is_some_and(|topic| !topic.is_empty());
assert!(
!(armed && matches!(config.capture_mode, CaptureMode::Import)),
- "invalid configuration: CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC must be unset in import mode; imports must never overflow"
+ "invalid configuration: CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC must be unset in import mode; imports must never overflow"
);
armed
}
@@ -556,7 +556,7 @@ fn warn_if_ai_byte_budget_below_max_event(config: &Config) {
}
/// Builds the v1 sink router. The dedicated AI topics are
-/// deployment-level config (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` and `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`),
+/// deployment-level config (`CAPTURE_OUTPUT_AI_MAIN_TOPIC` and `CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC`),
/// so they are injected into every sink config here; the overwrite is
/// unconditional so a stray per-sink `TOPIC_AI`/`TOPIC_AI_OVERFLOW` env var
/// cannot diverge from the shared policy.
@@ -572,8 +572,8 @@ fn create_v1_sink_router(
.context("v1 sink config validation failed")?;
for cfg in sinks_cfg.configs.values_mut() {
- cfg.kafka.topic_ai = config.kafka_topics.ai_events.clone();
- cfg.kafka.topic_ai_overflow = config.kafka_topics.ai_events_overflow.clone();
+ cfg.kafka.topic_ai = config.outputs.ai_main_topic.clone();
+ cfg.kafka.topic_ai_overflow = config.outputs.ai_overflow_topic.clone();
}
warn_if_ai_ceiling_exceeds_v1_sink_caps(config, &sinks_cfg);
@@ -618,9 +618,10 @@ async fn create_output_registry(
producer_configs: &HashMap<ProducerName, ProducerConfig>,
sink_handle: Option<lifecycle::Handle>,
advisory_handle: Option<lifecycle::Handle>,
-) -> anyhow::Result<OutputRegistry> {
- let output = create_output(config, producer_configs, sink_handle, advisory_handle).await?;
- Ok(OutputRegistry::new(output))
+) -> anyhow::Result<(OutputRegistry, Option<ProducerRegistry>)> {
+ let (output, producers) =
+ create_output(config, producer_configs, sink_handle, advisory_handle).await?;
+ Ok((OutputRegistry::new(output), producers))
}
async fn create_output(
@@ -628,20 +629,20 @@ async fn create_output(
producer_configs: &HashMap<ProducerName, ProducerConfig>,
sink_handle: Option<lifecycle::Handle>,
advisory_handle: Option<lifecycle::Handle>,
-) -> anyhow::Result<Output> {
+) -> anyhow::Result<(Output, Option<ProducerRegistry>)> {
if config.print_sink {
- return Ok(Output::single(PrintSink {}));
+ return Ok((Output::single(PrintSink {}), None));
}
if config.noop_sink {
info!("NoOpSink enabled, events will be silently dropped");
- return Ok(Output::single(NoOpSink::new()));
+ return Ok((Output::single(NoOpSink::new()), None));
}
// Runs before any producer connects, so a blank topic refuses boot
// immediately instead of after a broker connect attempt.
- let topics = TopicTable::from(&config.kafka_topics);
+ let outputs = OutputTable::from(&config.outputs);
if config.outputs_completeness_check_enabled {
- topics.check_complete()?;
+ outputs.check_complete()?;
} else {
info!("outputs completeness check disabled; a blank output topic will fail at first produce instead of at boot");
}
@@ -663,13 +664,12 @@ async fn create_output(
)
.context("failed to start Kafka producers")?;
let kafka_sink = KafkaSink::new(
- producers.get(ProducerName::Ingestion),
- topics,
+ outputs.map_producers(|name| producers.get(*name)),
config.replay_envelope_compression,
);
if !config.s3_fallback_enabled {
- return Ok(Output::single(kafka_sink));
+ return Ok((Output::single(kafka_sink), Some(producers)));
}
let s3_handle = sink_handle.expect("sink lifecycle handle required for S3 fallback");
@@ -685,11 +685,12 @@ async fn create_output(
.await
.expect("failed to create S3 sink");
- Ok(Output::failover(
+ let output = Output::failover(
Output::single(kafka_sink),
Output::single(s3_sink),
kafka_handle,
- ))
+ );
+ Ok((output, Some(producers)))
}
// Fixed fire-and-forget tuning for the warnings producer. These are
@@ -946,7 +947,10 @@ mod tests {
let cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", "events"),
- ("KAFKA_TOPIC", "events_plugin_ingestion"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion",
+ ),
(
"CAPTURE_INGESTION_WARNINGS_ENABLED",
if enabled { "true" } else { "false" },
@@ -1006,14 +1010,17 @@ mod tests {
let mut cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", input.capture_mode),
- ("KAFKA_TOPIC", "events_plugin_ingestion"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion",
+ ),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
if let Some(topic) = input.overflow_topic {
cfg_env.insert(
- "CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC".to_string(),
+ "CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC".to_string(),
topic.to_string(),
);
}
@@ -1075,7 +1082,10 @@ mod tests {
let cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", "events"),
- ("KAFKA_TOPIC", "events_plugin_ingestion"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion",
+ ),
("GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS", "0"),
]
.into_iter()
@@ -1104,7 +1114,10 @@ mod tests {
let cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", "events"),
- ("KAFKA_TOPIC", "events_plugin_ingestion"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion",
+ ),
("GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS", "180"),
("AI_BYTE_LIMIT_WINDOW_INTERVAL_SECS", "0"),
]
@@ -1146,7 +1159,10 @@ mod tests {
let cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", "events"),
- ("KAFKA_TOPIC", "events_plugin_ingestion"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion",
+ ),
("CAPTURE_V1_SINKS", "msk"),
]
.into_iter()
@@ -1228,13 +1244,16 @@ mod tests {
async fn ingestion_warnings_emitter_does_not_consult_v0_kafka_block() {
// Regression guard for the v0 fallback removal: with warnings enabled but
// no dedicated hosts, the emitter must stay disabled rather than reuse the
- // v0 KAFKA_HOSTS / KAFKA_CLIENT_INGESTION_WARNING_TOPIC block. If the
+ // v0 KAFKA_HOSTS / CAPTURE_OUTPUT_CLIENT_WARNINGS_TOPIC block. If the
// fallback were still live, it would build a producer against v0-broker.
let cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", "events"),
- ("KAFKA_TOPIC", "events_plugin_ingestion"),
- ("KAFKA_CLIENT_INGESTION_WARNING_TOPIC", "v0-warnings-topic"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion",
+ ),
+ ("CAPTURE_OUTPUT_CLIENT_WARNINGS_TOPIC", "v0-warnings-topic"),
("CAPTURE_INGESTION_WARNINGS_ENABLED", "true"),
// CAPTURE_INGESTION_WARNINGS_KAFKA_HOSTS deliberately left unset.
]
@@ -1264,7 +1283,10 @@ mod tests {
let cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", "events"),
- ("KAFKA_TOPIC", "events_plugin_ingestion"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion",
+ ),
("CAPTURE_INGESTION_WARNINGS_ENABLED", "true"),
]
.into_iter()
@@ -1301,9 +1323,6 @@ mod tests {
assert!(!server.is_shutting_down(), "capture must still be serving");
}
- /// A blank output topic makes `create_sink` refuse to boot in every capture
- /// mode — the misconfig fails fast at startup (via the `TopicTable`
- /// completeness check inside `KafkaSink::new`) rather than at first produce.
#[rstest::rstest]
#[case(CaptureMode::Events)]
#[case(CaptureMode::Recordings)]
@@ -1321,7 +1340,7 @@ mod tests {
let mut config: Config =
envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");
config.outputs_completeness_check_enabled = true;
- config.kafka_topics.dlq = String::new();
+ config.outputs.dlq_topic = String::new();
let default_producers = producers::load_all(&HashMap::new()).expect("default producers");
let err = create_output_registry(&config, &default_producers, None, None)
@@ -1358,7 +1377,10 @@ mod tests {
let cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", "ai"),
- ("KAFKA_TOPIC", "events_plugin_ingestion_ai"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion_ai",
+ ),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
@@ -1391,7 +1413,10 @@ mod tests {
let cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", "ai"),
- ("KAFKA_TOPIC", "events_plugin_ingestion_ai"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion_ai",
+ ),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rs
index f0889ed0d741..8226166552a9 100644
--- a/rust/capture/src/sinks/kafka.rs
+++ b/rust/capture/src/sinks/kafka.rs
@@ -5,7 +5,8 @@
//! redirects, custom-topic redirects, force-disable-person-processing headers) is
//! decided *upstream* in the pipeline and stamped onto
//! `ProcessedEventMetadata`. `KafkaSinkBase::prepare_record` reads that metadata
-//! and maps it to a concrete topic + partition key.
+//! and maps it to a [`Destination`] and partition key; enqueue resolves the
+//! destination to a topic and producer.
//!
//! The `overflow_reason` stamping specifically runs at four call sites, all via
//! the shared `events::overflow_stamping::stamp_overflow_reason` helper:
@@ -15,8 +16,8 @@
//! * `otel::otel_handler` (`/i/v0/ai/otel`, multi-span batch)
//!
//! Keeping routing policy out of the sink keeps the clone-per-spawned-task
-//! cost in the scatter-gather batch path at two `Arc::clone` calls (producer
-//! + topics) rather than deep copies of limiter state.
+//! cost in the scatter-gather batch path at one `Arc::clone` call (the output
+//! table) rather than deep copies of limiter state.
use crate::api::CaptureError;
use crate::config::EnvelopeCompression;
use crate::ordering::OrderingGuarantee;
@@ -25,7 +26,7 @@ use crate::pipeline::{self, Address, Lane, Pipeline};
use crate::producers::ProducerHandle;
use crate::serialization::Serializer;
use crate::sinks::producer::{KafkaProducer, ProduceRecord};
-use crate::sinks::registry::{Destination, TopicTable};
+use crate::sinks::registry::{Destination, OutputTable};
use crate::sinks::sink::{fold_results, Outcome, PreparedPayload, Sink, SinkResult};
use crate::v0_request::{DataType, ProcessedEvent};
use async_trait::async_trait;
@@ -178,25 +179,15 @@ impl rdkafka::ClientContext for KafkaContext {
}
/// Generic Kafka sink that can use any producer implementation.
-///
-/// Holds only the producer handle, the topic config, and the replay envelope
-/// compression setting. No limiter state — overflow and replay-overflow routing
-/// decisions are stamped upstream in the pipeline onto
-/// `ProcessedEventMetadata::overflow_reason` and read here.
-/// Both Arc fields are cheap to clone (two atomic ref-count increments),
-/// which matters under the scatter-gather batch produce path where the sink
-/// is cloned once per spawned prep task.
pub struct KafkaSinkBase<P: KafkaProducer> {
- producer: Arc<P>,
- topics: Arc<TopicTable>,
+ outputs: Arc<OutputTable<Arc<P>>>,
replay_envelope_compression: EnvelopeCompression,
}
impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {
fn clone(&self) -> Self {
Self {
- producer: Arc::clone(&self.producer),
- topics: Arc::clone(&self.topics),
+ outputs: Arc::clone(&self.outputs),
replay_envelope_compression: self.replay_envelope_compression,
}
}
@@ -243,13 +234,11 @@ pub type KafkaSink = KafkaSinkBase<RdKafkaProducer<KafkaContext>>;
impl KafkaSink {
pub fn new(
- producer: ProducerHandle,
- topics: TopicTable,
+ outputs: OutputTable<ProducerHandle>,
replay_envelope_compression: EnvelopeCompression,
) -> KafkaSink {
KafkaSinkBase {
- producer,
- topics: Arc::new(topics),
+ outputs: Arc::new(outputs),
replay_envelope_compression,
}
}
@@ -259,23 +248,19 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
/// Create a new KafkaSinkBase with a custom producer (useful for testing).
/// No limiters — the sink is a mechanism layer; overflow stamping happens
/// upstream in the pipeline. See the module header for details.
- pub fn with_producer(producer: P, topics: TopicTable) -> Self {
- Self {
- producer: Arc::new(producer),
- topics: Arc::new(topics),
- replay_envelope_compression: EnvelopeCompression::None,
- }
+ pub fn with_producer(producer: P, outputs: OutputTable) -> Self {
+ Self::with_producer_and_compression(producer, outputs, EnvelopeCompression::None)
}
/// Same as `with_producer` but with envelope compression enabled. Used in tests.
pub fn with_producer_and_compression(
producer: P,
- topics: TopicTable,
+ outputs: OutputTable,
replay_envelope_compression: EnvelopeCompression,
) -> Self {
+ let producer = Arc::new(producer);
Self {
- producer: Arc::new(producer),
- topics: Arc::new(topics),
+ outputs: Arc::new(outputs.map_producers(|_| Arc::clone(&producer))),
replay_envelope_compression,
}
}
@@ -333,13 +318,11 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
headers.set_skip_heatmap_processing(true);
}
- // The address decision is pure metadata policy, owned by the pipeline
- // layer; the sink bridges it to an output, resolves that against its
- // topic config, realizes the key policy against the values it owns,
- // and applies the address-implied side effects in the same match —
- // the dlq output's contract includes the dlq header set, and both
- // admin redirects count their reroutes.
- let decision = pipeline::resolve(&metadata, self.topics.ai_events_overflow_armed())?;
+ // The pipeline layer owns the address decision. Each address's side
+ // effects live in the same match that maps it to an output, so a new
+ // address cannot skip them: dlq sets the dlq headers, and both admin
+ // redirects count their reroutes.
+ let decision = pipeline::resolve(&metadata, self.outputs.ai_events_overflow_armed())?;
let target = match decision.address {
Address::Dlq => {
dlq_reroute_effects(&mut headers, "event_restriction");
@@ -369,8 +352,6 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
},
};
- let destination = self.topics.topic_for(&target).to_string();
-
let partition_key = match decision.ordering {
// resolve() rejects replay events without a session id, so the id
// is present whenever PerSession is decided.
@@ -386,7 +367,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
Ok(PreparedPayload {
uuid,
- destination,
+ destination: target,
partition_key,
ordering: decision.ordering,
payload,
@@ -394,15 +375,13 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
})
}
- /// Serial, ordering-preserving enqueue into librdkafka. The one place the
- /// backend-agnostic payload becomes Kafka-shaped: `destination` is the
- /// topic, and `ordering` decides whether the record is keyed. Emits the
- /// per-topic bytes counter and returns the ack future for the caller to
- /// await. librdkafka preserves on-wire partition order by `send_result`
- /// call order, so this MUST be called in the original event order within
- /// a batch.
+ /// librdkafka preserves on-wire partition order by `send_result` call
+ /// order, so this MUST be called in the original event order within a
+ /// batch.
fn enqueue_record(&self, payload: PreparedPayload) -> Result<P::AckFuture, CaptureError> {
- counter!("capture_kafka_produce_bytes_total", "topic" => payload.destination.clone())
+ let (topic, producer) = self.outputs.resolve(&payload.destination);
+
+ counter!("capture_kafka_produce_bytes_total", "topic" => Arc::clone(&topic))
.increment(payload.payload.len() as u64);
// No key reaches rdkafka as round-robin; `Some("")` would murmur2-hash
@@ -412,8 +391,8 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
_ => Some(payload.partition_key),
};
- self.producer.send(ProduceRecord {
- topic: payload.destination,
+ producer.send(ProduceRecord {
+ topic,
key,
payload: payload.payload,
headers: payload.headers,
@@ -602,10 +581,6 @@ impl<P: KafkaProducer + 'static> Sink for KafkaSinkBase<P> {
}
}
}
-
- fn flush(&self) -> Result<(), anyhow::Error> {
- self.producer.flush().map_err(|e| anyhow::anyhow!(e))
- }
}
#[async_trait]
@@ -625,10 +600,6 @@ impl<P: KafkaProducer + 'static> PublishEvents for KafkaSinkBase<P> {
let payloads = self.prepare_batch(events).await?;
fold_results(Sink::publish(self, payloads).await)
}
-
- fn flush(&self) -> Result<(), anyhow::Error> {
- Sink::flush(self)
- }
}
/// Concurrent ack drain for `Sink::publish`, fail-fast on first ack error.
@@ -658,7 +629,7 @@ async fn drain_acks(mut ack_set: JoinSet<Result<(), CaptureError>>) -> Result<()
}
#[cfg(test)]
-pub(crate) use crate::sinks::registry::test_topics;
+pub(crate) use crate::sinks::registry::test_outputs;
#[cfg(test)]
mod tests {
@@ -666,7 +637,7 @@ mod tests {
use crate::config::EnvelopeCompression;
use crate::outputs::PublishEvents;
use crate::producers::{self, ProducerName, ProducerRegistry};
- use crate::sinks::kafka::{test_topics, KafkaSink};
+ use crate::sinks::kafka::{test_outputs, KafkaSink};
use crate::utils::uuid_v7_from_datetime;
use crate::v0_request::{DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata};
use common_types::CapturedEvent;
@@ -711,8 +682,7 @@ mod tests {
)
.expect("failed to create producer");
let sink = KafkaSink::new(
- producers.get(ProducerName::Ingestion),
- test_topics(),
+ test_outputs().map_producers(|name| producers.get(*name)),
EnvelopeCompression::None,
);
(cluster, sink)
@@ -1015,7 +985,7 @@ mod tests {
#[cfg(test)]
mod topic_routing {
use super::*;
- use crate::sinks::kafka::{test_topics, KafkaSinkBase, SCATTER_GATHER_MIN_BATCH};
+ use crate::sinks::kafka::{test_outputs, KafkaSinkBase, SCATTER_GATHER_MIN_BATCH};
use crate::sinks::producer::MockKafkaProducer;
use crate::sinks::sink::{Outcome, Sink};
use rstest::rstest;
@@ -1143,7 +1113,7 @@ mod tests {
let producer = MockKafkaProducer::new();
let sink = KafkaSinkBase::with_producer_and_compression(
producer.clone(),
- test_topics(),
+ test_outputs(),
input.compression,
);
@@ -1166,7 +1136,7 @@ mod tests {
input.overflow_reason,
);
- assert_eq!(record.topic, expected.topic, "wrong topic for {ctx}");
+ assert_eq!(&*record.topic, expected.topic, "wrong topic for {ctx}");
assert_eq!(
record.key.is_some(),
expected.has_key,
@@ -2093,8 +2063,8 @@ mod tests {
// ==================== AiEvents ====================
// The dedicated $ai_* lane routes to its own topic, keyed on the
- // event key. test_topics() arms the AI overflow valve
- // (CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC), so overflow handling mirrors the
+ // event key. test_outputs() arms the AI overflow valve
+ // (CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC), so overflow handling mirrors the
// AnalyticsMain arm onto the AI topics; the unarmed tests below
// override the valve off.
@@ -2217,12 +2187,12 @@ mod tests {
#[tokio::test]
async fn ai_events_unarmed_never_overflows() {
- // Without CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC the lane keeps today's
- // behavior: force_overflow and any stamped reason (which the
+ // Without CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC the lane never
+ // overflows: force_overflow and any stamped reason (which the
// gated pipeline would not produce anyway) are ignored.
let producer = MockKafkaProducer::new();
- let mut topics = test_topics();
- topics.ai_events_overflow = None;
+ let mut topics = test_outputs();
+ topics.ai_overflow = None;
let sink = KafkaSinkBase::with_producer(producer.clone(), topics);
let mut event = create_test_event(&EventInput {
@@ -2239,7 +2209,7 @@ mod tests {
let records = producer.get_records();
assert_eq!(records.len(), 1);
- assert_eq!(records[0].topic, AI_EVENTS_TOPIC);
+ assert_eq!(&*records[0].topic, AI_EVENTS_TOPIC);
assert_eq!(records[0].key.as_deref(), Some("test_token:test_user"));
}
@@ -2322,7 +2292,7 @@ mod tests {
// record key is the event key (token:distinct_id) and the headers
// are identical to what another dedicated lane produces.
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
let base = create_test_event(&EventInput::default());
let mut ai_event = base.clone();
@@ -2335,8 +2305,8 @@ mod tests {
let records = producer.get_records();
assert_eq!(records.len(), 2);
- assert_eq!(records[0].topic, AI_EVENTS_TOPIC);
- assert_eq!(records[1].topic, ERROR_TRACKING_TOPIC);
+ assert_eq!(&*records[0].topic, AI_EVENTS_TOPIC);
+ assert_eq!(&*records[1].topic, ERROR_TRACKING_TOPIC);
assert_eq!(records[0].key.as_deref(), Some("test_token:test_user"));
assert_eq!(records[0].key, records[1].key);
assert_eq!(records[0].payload, records[1].payload);
@@ -2685,7 +2655,7 @@ mod tests {
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn publish_events_preserves_order_same_key() {
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
// 20 events, all sharing the same distinct_id (so they hash to the
// same partition via murmur2), each with a unique UUID so we can
@@ -2749,7 +2719,7 @@ mod tests {
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn publish_events_prep_error_aborts_batch() {
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
// Build a batch where event #3 is a SnapshotMain with session_id=None,
// which causes prepare_record to return MissingSessionId. The other
@@ -2823,7 +2793,7 @@ mod tests {
const BATCH: usize = 10;
const FAIL_IDX: usize = 3;
let producer = MockKafkaProducer::new_failing_at(FAIL_IDX);
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
let events = build_batch(BATCH);
let input_distinct_ids: Vec<String> =
@@ -2869,7 +2839,7 @@ mod tests {
// One event short-circuits to kafka_send: no prepare_batch, no
// JoinSet. This is the live path for the single-event endpoints.
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
let events = build_batch(1);
sink.publish_events(events)
@@ -2878,7 +2848,7 @@ mod tests {
let records = producer.get_records();
assert_eq!(records.len(), 1, "expected exactly one record");
- assert_eq!(records[0].topic, MAIN_TOPIC);
+ assert_eq!(&*records[0].topic, MAIN_TOPIC);
}
#[tokio::test]
@@ -2887,7 +2857,7 @@ mod tests {
// prepare_batch. A one-event guard that grew an off-by-one would
// swallow the second event here and nowhere else.
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
sink.publish_events(build_batch(2))
.await
@@ -2938,7 +2908,7 @@ mod tests {
] {
let samples = histogram_sample_count(name, || {
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer, test_topics());
+ let sink = KafkaSinkBase::with_producer(producer, test_outputs());
runtime
.block_on(sink.publish_events(build_batch(1)))
.expect("publish_events failed");
@@ -2953,7 +2923,7 @@ mod tests {
// path. We can't observe "which path ran" directly, so we assert
// behavioral equivalence: N records, correct topic, input order.
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
let size = SCATTER_GATHER_MIN_BATCH - 1;
let events = build_batch(size);
@@ -2986,7 +2956,7 @@ mod tests {
// path. Behavioral equivalence with the serial path must hold:
// same N records, same order, same topics.
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
let size = SCATTER_GATHER_MIN_BATCH;
let events = build_batch(size);
@@ -3022,7 +2992,7 @@ mod tests {
#[tokio::test]
async fn publish_reports_uuid_aligned_results() {
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
let payloads = sink
.prepare_batch(build_batch(3))
@@ -3043,7 +3013,7 @@ mod tests {
async fn publish_enqueue_failure_is_batch_uniform() {
const FAIL_IDX: usize = 1;
let producer = MockKafkaProducer::new_failing_at(FAIL_IDX);
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
let payloads = sink
.prepare_batch(build_batch(3))
@@ -3071,7 +3041,7 @@ mod tests {
async fn publish_ack_failure_is_batch_uniform() {
const FAIL_IDX: usize = 1;
let producer = MockKafkaProducer::new_failing_ack_at(FAIL_IDX);
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
let payloads = sink
.prepare_batch(build_batch(3))
@@ -3102,7 +3072,7 @@ mod tests {
/// and the scatter-gather path (10 events).
async fn mixed_datatypes_routing_for_batch(pad_to: usize) {
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
// Core 5-event diverse batch.
let mut events: Vec<ProcessedEvent> = vec![
@@ -3145,18 +3115,18 @@ mod tests {
// Per-index topic assertions (order-preserving: phase-2 is serial
// in input order on both paths).
- assert_eq!(records[0].topic, MAIN_TOPIC, "event[0]: AnalyticsMain");
- assert_eq!(records[1].topic, HEATMAPS_TOPIC, "event[1]: HeatmapMain");
+ assert_eq!(&*records[0].topic, MAIN_TOPIC, "event[0]: AnalyticsMain");
+ assert_eq!(&*records[1].topic, HEATMAPS_TOPIC, "event[1]: HeatmapMain");
assert_eq!(
- records[2].topic, ERROR_TRACKING_TOPIC,
+ &*records[2].topic, ERROR_TRACKING_TOPIC,
"event[2]: ExceptionErrorTracking"
);
assert_eq!(
- records[3].topic, CLIENT_INGESTION_WARNING_TOPIC,
+ &*records[3].topic, CLIENT_INGESTION_WARNING_TOPIC,
"event[3]: ClientIngestionWarning"
);
assert_eq!(
- records[4].topic, OVERFLOW_TOPIC,
+ &*records[4].topic, OVERFLOW_TOPIC,
"event[4]: AnalyticsMain + force_overflow"
);
}
@@ -3178,7 +3148,7 @@ mod tests {
#[tokio::test]
async fn snapshot_payload_uncompressed_by_default() {
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());
+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
let event = create_test_event(&EventInput {
data_type: DataType::SnapshotMain,
@@ -3199,7 +3169,7 @@ mod tests {
let producer = MockKafkaProducer::new();
let sink = KafkaSinkBase::with_producer_and_compression(
producer.clone(),
- test_topics(),
+ test_outputs(),
EnvelopeCompression::Lz4,
);
@@ -3232,7 +3202,7 @@ mod tests {
let producer = MockKafkaProducer::new();
let sink = KafkaSinkBase::with_producer_and_compression(
producer.clone(),
- test_topics(),
+ test_outputs(),
EnvelopeCompression::Lz4,
);
diff --git a/rust/capture/src/sinks/producer.rs b/rust/capture/src/sinks/producer.rs
index eb2d7c9df73f..15102a642ff2 100644
--- a/rust/capture/src/sinks/producer.rs
+++ b/rust/capture/src/sinks/producer.rs
@@ -4,6 +4,7 @@ use rdkafka::error::{KafkaError, RDKafkaErrorCode};
use rdkafka::producer::{DeliveryFuture, FutureProducer, FutureRecord, Producer};
use std::future::Future;
use std::pin::Pin;
+use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use tracing::error;
@@ -14,7 +15,7 @@ use crate::prometheus::report_dropped_events;
/// A record to be produced to Kafka
#[derive(Debug, Clone)]
pub struct ProduceRecord {
- pub topic: String,
+ pub topic: Arc<str>,
pub key: Option<String>,
pub payload: Vec<u8>,
pub headers: CapturedEventHeaders,
@@ -45,7 +46,7 @@ pub trait KafkaProducer: Send + Sync {
pub struct DeliveryAckFuture {
inner: DeliveryFuture,
started: Instant,
- topic: String,
+ topic: Arc<str>,
recorded: bool,
}
@@ -133,7 +134,7 @@ impl<C: rdkafka::ClientContext + Send + Sync + 'static> KafkaProducer for RdKafk
fn send(&self, record: ProduceRecord) -> Result<Self::AckFuture, CaptureError> {
let headers: rdkafka::message::OwnedHeaders = record.headers.into();
- let topic = record.topic.clone();
+ let topic = Arc::clone(&record.topic);
match self.producer.send_result(FutureRecord {
topic: &record.topic,
diff --git a/rust/capture/src/sinks/registry.rs b/rust/capture/src/sinks/registry.rs
index 73b50af11714..b291482ee38d 100644
--- a/rust/capture/src/sinks/registry.rs
+++ b/rust/capture/src/sinks/registry.rs
@@ -1,29 +1,17 @@
-//! Destination registry — the topic-completeness surface.
-//!
-//! Binds every fixed routing [`Destination`] variant to its configured Kafka topic
-//! and provides a startup completeness check ([`TopicTable::check_complete`])
-//! that refuses to boot when any fixed output resolves to an empty topic. This
-//! is the single place the output→topic wiring lives, so adding an output is a
-//! one-place change: the `topic_for` and `is_required` matches are
-//! compiler-forced exhaustive, a test pins `REGISTERED` to the required set,
-//! and `check_complete` catches an unwired output at boot rather than at
-//! first produce.
-//!
-//! Two outputs sit outside the completeness check: `Custom` topics are
-//! admin-supplied inline on the event's metadata (they carry their own topic),
-//! and `AiOverflow` is the opt-in overflow valve — unset means routing never
-//! selects it.
+//! Binds every fixed routing [`Destination`] to its output: a Kafka topic and
+//! the named producer that carries it. Adding an output is a one-place change:
+//! the `target_for` and `is_required` matches are compiler-forced exhaustive,
+//! a test pins `REGISTERED` to the required set, and
+//! [`OutputTable::check_complete`] catches an unwired output at boot instead
+//! of at first produce.
-use crate::config::KafkaTopicsConfig;
+use std::sync::Arc;
-/// Which configured output a routing decision selects, named **pipeline +
-/// lane** — the vocabulary the refactor converges on (typed per-pipeline
-/// lanes; see the plan doc). The sink resolves each output to a concrete
-/// topic string against the [`TopicTable`]; distinct outputs may share a
-/// topic (analytics main and session-replay main both resolve the
-/// deployment's main topic today). Mirrors v1's `Destination` split — the
-/// convergence target when the v1 stack folds onto this registry (see the
-/// plan doc).
+use crate::config::OutputsConfig;
+use crate::producers::ProducerName;
+
+/// Which configured output a routing decision selects, named by pipeline and
+/// lane. Distinct outputs may share a topic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Destination {
AnalyticsMain,
@@ -33,18 +21,13 @@ pub enum Destination {
HeatmapsMain,
SessionReplayMain,
SessionReplayOverflow,
- /// Every pipeline's dlq lane; one shared output until the typed-address
- /// step gives each pipeline its own dlq row.
+ /// Every pipeline's dlq lane, one shared output.
Dlq,
ErrorTrackingMain,
- /// The AI pipeline's main lane — the dedicated `$ai_*` topic
- /// (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`).
AiMain,
- /// The AI pipeline's overflow lane; only routed to when the AI overflow
- /// valve (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`) is armed.
+ /// Only routed to when the AI overflow valve is armed.
AiOverflow,
- /// Admin-configured custom topic copied from `redirect_to_topic`. Resolved
- /// inline by the sink; never registered (it carries its own topic).
+ /// Admin-configured topic copied from `redirect_to_topic`.
Custom(String),
}
@@ -109,63 +92,103 @@ impl Destination {
}
}
-/// The one place output→topic wiring lives. Holds the configured topic for every
-/// fixed [`Destination`] variant. Cheap to clone; the sink holds it behind an `Arc`.
+/// `R` is how the target names its producer: a [`ProducerName`] in config,
+/// the producer handle once setup resolves it.
#[derive(Clone, Debug)]
-pub struct TopicTable {
- pub(crate) main: String,
- pub(crate) overflow: String,
- pub(crate) historical: String,
- pub(crate) client_ingestion_warning: String,
- pub(crate) heatmaps: String,
- pub(crate) replay_overflow: String,
- pub(crate) dlq: String,
- pub(crate) error_tracking: String,
- /// Dedicated topic for `Destination::AiMain` (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`,
- /// required with a default).
- pub(crate) ai_events: String,
- /// Overflow topic for the AI lane. Unset means the AI overflow valve is
- /// unarmed and routing never selects `Destination::AiOverflow`.
- pub(crate) ai_events_overflow: Option<String>,
+pub struct OutputTarget<R = ProducerName> {
+ // `Arc<str>` so the per-record lookup, metric labels and produce record never allocate.
+ pub(crate) topic: Arc<str>,
+ pub(crate) producer: R,
}
-impl TopicTable {
- /// Resolve an output to its topic. Fixed outputs read the registered topic;
- /// `Custom` returns its inline, admin-supplied topic.
- pub fn topic_for<'a>(&'a self, output: &'a Destination) -> &'a str {
+#[derive(Clone, Debug)]
+pub struct OutputTable<R = ProducerName> {
+ pub(crate) analytics_main: OutputTarget<R>,
+ pub(crate) analytics_overflow: OutputTarget<R>,
+ pub(crate) analytics_historical: OutputTarget<R>,
+ pub(crate) session_replay_main: OutputTarget<R>,
+ pub(crate) session_replay_overflow: OutputTarget<R>,
+ pub(crate) client_warnings: OutputTarget<R>,
+ pub(crate) heatmaps: OutputTarget<R>,
+ pub(crate) dlq: OutputTarget<R>,
+ pub(crate) error_tracking: OutputTarget<R>,
+ pub(crate) ai_main: OutputTarget<R>,
+ pub(crate) ai_overflow: Option<OutputTarget<R>>,
+ pub(crate) custom_producer: R,
+}
+
+impl<R> OutputTable<R> {
+ fn target_for(&self, output: &Destination) -> Option<&OutputTarget<R>> {
match output {
- Destination::AnalyticsMain | Destination::SessionReplayMain => &self.main,
- Destination::AnalyticsOverflow => &self.overflow,
- Destination::AnalyticsHistorical => &self.historical,
- Destination::ClientWarningsMain => &self.client_ingestion_warning,
- Destination::HeatmapsMain => &self.heatmaps,
- Destination::SessionReplayOverflow => &self.replay_overflow,
- Destination::Dlq => &self.dlq,
- Destination::ErrorTrackingMain => &self.error_tracking,
- Destination::AiMain => &self.ai_events,
- Destination::AiOverflow => match self.ai_events_overflow.as_deref() {
- Some(topic) if !topic.is_empty() => topic,
+ Destination::AnalyticsMain => Some(&self.analytics_main),
+ Destination::AnalyticsOverflow => Some(&self.analytics_overflow),
+ Destination::AnalyticsHistorical => Some(&self.analytics_historical),
+ Destination::ClientWarningsMain => Some(&self.client_warnings),
+ Destination::HeatmapsMain => Some(&self.heatmaps),
+ Destination::SessionReplayMain => Some(&self.session_replay_main),
+ Destination::SessionReplayOverflow => Some(&self.session_replay_overflow),
+ Destination::Dlq => Some(&self.dlq),
+ Destination::ErrorTrackingMain => Some(&self.error_tracking),
+ Destination::AiMain => Some(&self.ai_main),
+ Destination::AiOverflow => match &self.ai_overflow {
+ Some(target) if !target.topic.is_empty() => Some(target),
// Unreachable: routing only selects this output when the
// valve is armed, i.e. exactly when the topic is set.
- _ => &self.ai_events,
+ _ => Some(&self.ai_main),
},
- Destination::Custom(topic) => topic,
+ Destination::Custom(_) => None,
+ }
+ }
+
+ pub fn topic_for<'a>(&'a self, output: &'a Destination) -> &'a str {
+ match (output, self.target_for(output)) {
+ (Destination::Custom(topic), _) => topic,
+ (_, Some(target)) => &target.topic,
+ (_, None) => unreachable!("every fixed output has a target"),
+ }
+ }
+
+ pub(crate) fn resolve(&self, output: &Destination) -> (Arc<str>, &R) {
+ match (output, self.target_for(output)) {
+ (_, Some(target)) => (Arc::clone(&target.topic), &target.producer),
+ (Destination::Custom(topic), None) => {
+ (Arc::from(topic.as_str()), &self.custom_producer)
+ }
+ (_, None) => unreachable!("every fixed output has a target"),
+ }
+ }
+
+ pub(crate) fn map_producers<T>(&self, mut f: impl FnMut(&R) -> T) -> OutputTable<T> {
+ let custom_producer = f(&self.custom_producer);
+ let mut target = |t: &OutputTarget<R>| OutputTarget {
+ topic: Arc::clone(&t.topic),
+ producer: f(&t.producer),
+ };
+ OutputTable {
+ analytics_main: target(&self.analytics_main),
+ analytics_overflow: target(&self.analytics_overflow),
+ analytics_historical: target(&self.analytics_historical),
+ session_replay_main: target(&self.session_replay_main),
+ session_replay_overflow: target(&self.session_replay_overflow),
+ client_warnings: target(&self.client_warnings),
+ heatmaps: target(&self.heatmaps),
+ dlq: target(&self.dlq),
+ error_tracking: target(&self.error_tracking),
+ ai_main: target(&self.ai_main),
+ ai_overflow: self.ai_overflow.as_ref().map(&mut target),
+ custom_producer,
}
}
- /// Whether the AI overflow valve is armed: the AI overflow topic is wired,
- /// so routing may select `Destination::AiOverflow`.
pub fn ai_events_overflow_armed(&self) -> bool {
- self.ai_events_overflow
- .as_deref()
- .is_some_and(|t| !t.is_empty())
+ self.ai_overflow
+ .as_ref()
+ .is_some_and(|target| !target.topic.is_empty())
}
- /// Startup completeness check: every registered output must resolve to a
- /// non-empty topic, so a misconfigured or newly-added-but-unwired output
- /// fails fast at boot instead of at first produce. `Custom` is excluded
- /// (it carries its own topic per event), as is the opt-in `AiOverflow`
- /// valve (unset means routing never selects it).
+ /// Every registered output must resolve to a non-empty topic. `Custom` is
+ /// excluded because it carries its own topic per event, and the opt-in
+ /// `AiOverflow` valve because unset means routing never selects it.
pub fn check_complete(&self) -> anyhow::Result<()> {
for output in &Destination::REGISTERED {
anyhow::ensure!(
@@ -179,39 +202,66 @@ impl TopicTable {
}
}
-impl From<&KafkaTopicsConfig> for TopicTable {
- fn from(config: &KafkaTopicsConfig) -> Self {
+impl From<&OutputsConfig> for OutputTable {
+ fn from(config: &OutputsConfig) -> Self {
+ let target = |topic: &String, producer: ProducerName| OutputTarget {
+ topic: Arc::from(topic.as_str()),
+ producer,
+ };
Self {
- main: config.main.clone(),
- overflow: config.overflow.clone(),
- historical: config.historical.clone(),
- client_ingestion_warning: config.client_ingestion_warning.clone(),
- heatmaps: config.heatmaps.clone(),
- replay_overflow: config.replay_overflow.clone(),
- dlq: config.dlq.clone(),
- error_tracking: config.error_tracking.clone(),
- ai_events: config.ai_events.clone(),
- ai_events_overflow: config.ai_events_overflow.clone(),
+ analytics_main: target(&config.analytics_main_topic, config.analytics_main_producer),
+ analytics_overflow: target(
+ &config.analytics_overflow_topic,
+ config.analytics_overflow_producer,
+ ),
+ analytics_historical: target(
+ &config.analytics_historical_topic,
+ config.analytics_historical_producer,
+ ),
+ session_replay_main: target(
+ &config.session_replay_main_topic,
+ config.session_replay_main_producer,
+ ),
+ session_replay_overflow: target(
+ &config.session_replay_overflow_topic,
+ config.session_replay_overflow_producer,
+ ),
+ client_warnings: target(
+ &config.client_warnings_topic,
+ config.client_warnings_producer,
+ ),
+ heatmaps: target(&config.heatmaps_topic, config.heatmaps_producer),
+ dlq: target(&config.dlq_topic, config.dlq_producer),
+ error_tracking: target(&config.error_tracking_topic, config.error_tracking_producer),
+ ai_main: target(&config.ai_main_topic, config.ai_main_producer),
+ ai_overflow: config
+ .ai_overflow_topic
+ .as_ref()
+ .map(|topic| target(topic, config.ai_overflow_producer)),
+ custom_producer: config.custom_producer,
}
}
}
-/// Shared `TopicTable` fixture for tests across the capture crate. Used by
-/// sink-side routing tests and pipeline-to-sink E2E tests so every test site
-/// asserts against the same canonical topic names.
#[cfg(test)]
-pub(crate) fn test_topics() -> TopicTable {
- TopicTable {
- main: "events_plugin_ingestion".to_string(),
- overflow: "events_plugin_ingestion_overflow".to_string(),
- historical: "events_plugin_ingestion_historical".to_string(),
- client_ingestion_warning: "client_ingestion_warning".to_string(),
- heatmaps: "heatmaps".to_string(),
- replay_overflow: "replay_overflow".to_string(),
- dlq: "events_plugin_ingestion_dlq".to_string(),
- error_tracking: "error_tracking_events".to_string(),
- ai_events: "ai_events".to_string(),
- ai_events_overflow: Some("ai_events_overflow".to_string()),
+pub(crate) fn test_outputs() -> OutputTable {
+ let target = |topic: &str| OutputTarget {
+ topic: Arc::from(topic),
+ producer: ProducerName::Ingestion,
+ };
+ OutputTable {
+ analytics_main: target("events_plugin_ingestion"),
+ analytics_overflow: target("events_plugin_ingestion_overflow"),
+ analytics_historical: target("events_plugin_ingestion_historical"),
+ session_replay_main: target("events_plugin_ingestion"),
+ session_replay_overflow: target("replay_overflow"),
+ client_warnings: target("client_ingestion_warning"),
+ heatmaps: target("heatmaps"),
+ dlq: target("events_plugin_ingestion_dlq"),
+ error_tracking: target("error_tracking_events"),
+ ai_main: target("ai_events"),
+ ai_overflow: Some(target("ai_events_overflow")),
+ custom_producer: ProducerName::Ingestion,
}
}
@@ -233,12 +283,12 @@ mod tests {
#[case(Destination::AiMain, "ai_events")]
#[case(Destination::AiOverflow, "ai_events_overflow")]
fn topic_for_resolves_registered_outputs(#[case] output: Destination, #[case] expected: &str) {
- assert_eq!(test_topics().topic_for(&output), expected);
+ assert_eq!(test_outputs().topic_for(&output), expected);
}
#[test]
fn topic_for_custom_returns_inline_topic() {
- let registry = test_topics();
+ let registry = test_outputs();
assert_eq!(
registry.topic_for(&Destination::Custom("admin_topic".to_string())),
"admin_topic"
@@ -249,16 +299,49 @@ mod tests {
/// disarms the AI main lane.
#[test]
fn unset_ai_overflow_valve_is_unarmed() {
- let mut registry = test_topics();
- registry.ai_events_overflow = None;
+ let mut registry = test_outputs();
+ registry.ai_overflow = None;
assert!(registry.check_complete().is_ok());
assert!(!registry.ai_events_overflow_armed());
assert_eq!(registry.topic_for(&Destination::AiMain), "ai_events");
}
+ #[test]
+ fn session_replay_main_does_not_share_analytics_main() {
+ let mut registry = test_outputs();
+ registry.session_replay_main.topic = Arc::from("replay_main");
+ assert_eq!(
+ registry.topic_for(&Destination::SessionReplayMain),
+ "replay_main"
+ );
+ assert_eq!(
+ registry.topic_for(&Destination::AnalyticsMain),
+ "events_plugin_ingestion"
+ );
+ }
+
+ #[test]
+ fn each_output_resolves_to_its_own_producer() {
+ let mut next = 0;
+ let table = test_outputs().map_producers(|_| {
+ next += 1;
+ next
+ });
+ let custom = Destination::Custom("admin_topic".to_string());
+ let (topic, _) = table.resolve(&custom);
+ assert_eq!(&*topic, "admin_topic");
+
+ let producers: std::collections::HashSet<i32> = Destination::REGISTERED
+ .iter()
+ .chain([&custom])
+ .map(|output| *table.resolve(output).1)
+ .collect();
+ assert_eq!(producers.len(), Destination::REGISTERED.len() + 1);
+ }
+
#[test]
fn check_complete_accepts_full_registry() {
- assert!(test_topics().check_complete().is_ok());
+ assert!(test_outputs().check_complete().is_ok());
}
/// `REGISTERED` is a hand-maintained array while `is_required` is
@@ -295,20 +378,21 @@ mod tests {
/// Every registered output, blanked one at a time, must fail the check and
/// the error must name the offending output.
#[rstest]
- #[case("analytics-main", |r: &mut TopicTable| r.main.clear())]
- #[case("analytics-overflow", |r: &mut TopicTable| r.overflow.clear())]
- #[case("analytics-historical", |r: &mut TopicTable| r.historical.clear())]
- #[case("clientwarnings-main", |r: &mut TopicTable| r.client_ingestion_warning.clear())]
- #[case("heatmaps-main", |r: &mut TopicTable| r.heatmaps.clear())]
- #[case("sessionreplay-overflow", |r: &mut TopicTable| r.replay_overflow.clear())]
- #[case("dlq", |r: &mut TopicTable| r.dlq.clear())]
- #[case("errortracking-main", |r: &mut TopicTable| r.error_tracking.clear())]
- #[case("ai-main", |r: &mut TopicTable| r.ai_events.clear())]
+ #[case("analytics-main", |r: &mut OutputTable| r.analytics_main.topic = Arc::from(""))]
+ #[case("analytics-overflow", |r: &mut OutputTable| r.analytics_overflow.topic = Arc::from(""))]
+ #[case("analytics-historical", |r: &mut OutputTable| r.analytics_historical.topic = Arc::from(""))]
+ #[case("clientwarnings-main", |r: &mut OutputTable| r.client_warnings.topic = Arc::from(""))]
+ #[case("heatmaps-main", |r: &mut OutputTable| r.heatmaps.topic = Arc::from(""))]
+ #[case("sessionreplay-main", |r: &mut OutputTable| r.session_replay_main.topic = Arc::from(""))]
+ #[case("sessionreplay-overflow", |r: &mut OutputTable| r.session_replay_overflow.topic = Arc::from(""))]
+ #[case("dlq", |r: &mut OutputTable| r.dlq.topic = Arc::from(""))]
+ #[case("errortracking-main", |r: &mut OutputTable| r.error_tracking.topic = Arc::from(""))]
+ #[case("ai-main", |r: &mut OutputTable| r.ai_main.topic = Arc::from(""))]
fn check_complete_rejects_empty_topic(
#[case] output_name: &str,
- #[case] blank: fn(&mut TopicTable),
+ #[case] blank: fn(&mut OutputTable),
) {
- let mut registry = test_topics();
+ let mut registry = test_outputs();
blank(&mut registry);
let err = registry
.check_complete()
diff --git a/rust/capture/src/sinks/sink.rs b/rust/capture/src/sinks/sink.rs
index 3beb4dc42dbc..1eac0304175e 100644
--- a/rust/capture/src/sinks/sink.rs
+++ b/rust/capture/src/sinks/sink.rs
@@ -17,6 +17,7 @@ use uuid::Uuid;
use crate::api::CaptureError;
use crate::ordering::OrderingGuarantee;
+use crate::sinks::registry::Destination;
/// A serialized, addressed record ready for a backend: the sink input.
/// The uuid identifies the source event so per-event results can be
@@ -29,9 +30,9 @@ use crate::ordering::OrderingGuarantee;
#[derive(Debug, Clone)]
pub(crate) struct PreparedPayload {
pub uuid: Uuid,
- /// Realized namespace within the backend: a Kafka topic, an S3 prefix.
- /// Namespace realization happens above the sink.
- pub destination: String,
+ /// The output this record is addressed to. Each sink resolves it to its
+ /// own target, as v1's sinks resolve their `Destination`.
+ pub destination: Destination,
/// Raw key; whether the sink uses it is decided by `ordering`.
pub partition_key: String,
/// The guarantee `partition_key` exists to preserve.
@@ -89,9 +90,6 @@ impl SinkResult {
#[async_trait]
pub(crate) trait Sink {
async fn publish(&self, payloads: Vec<PreparedPayload>) -> Vec<SinkResult>;
-
- /// Flush any buffered/pending data before shutdown.
- fn flush(&self) -> Result<(), anyhow::Error>;
}
/// Collapse per-event results into the v0 whole-request response:
diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rs
index 50baa35ca257..081323130664 100644
--- a/rust/capture/src/v0_request.rs
+++ b/rust/capture/src/v0_request.rs
@@ -185,7 +185,7 @@ pub enum DataType {
ExceptionErrorTracking,
SnapshotMain,
/// Dedicated AI lane, mirroring v1's `Destination::AiEvents`. The
- /// kafka sink maps it to `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`, so every
+ /// kafka sink maps it to `CAPTURE_OUTPUT_AI_MAIN_TOPIC`, so every
/// deployment that accepts AI traffic must configure that topic. Like
/// heatmaps and exceptions, AI events never reroute historical.
AiEvents,
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index 7fb74c6e58a2..de03304e3ee9 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -818,7 +818,7 @@ fn apply_overflow_stamping(
// overflow (never analytics overflow) and the per-key budgets are
// isolated between the lanes. The AI lane only participates when its
// limiter exists — setup builds it exactly when the AI overflow valve
- // (CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC) is armed, so limiter
+ // (CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC) is armed, so limiter
// presence encodes the valve here.
let (overflow_destination, lane_limiter) = match event.destination {
Destination::AnalyticsMain => (Destination::Overflow, analytics_limiter),
diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index 317f2d7ef75f..a3ff3b8bf70a 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -112,7 +112,8 @@ mod tests {
use crate::config::EnvelopeCompression;
- use crate::config::{CaptureMode, Config, KafkaTopicsConfig};
+ use crate::config::{CaptureMode, Config, OutputsConfig};
+ use crate::producers::ProducerName;
use crate::v1::analytics::types::{Event, Options, RawOptions};
fn test_config() -> Config {
@@ -166,17 +167,31 @@ mod tests {
is_mirror_deploy: false,
log_level: Level::INFO,
verbose_sample_percent: 0.0,
- kafka_topics: KafkaTopicsConfig {
- main: "events_plugin_ingestion".to_string(),
- overflow: "events_plugin_ingestion_overflow".to_string(),
- historical: "events_plugin_ingestion_historical".to_string(),
- client_ingestion_warning: "events_plugin_ingestion".to_string(),
- error_tracking: "error_tracking_events".to_string(),
- heatmaps: "events_plugin_ingestion".to_string(),
- replay_overflow: "session_recording_snapshot_item_overflow".to_string(),
- dlq: "events_plugin_ingestion_dlq".to_string(),
- ai_events: "events_plugin_ingestion_ai".to_string(),
- ai_events_overflow: None,
+ outputs: OutputsConfig {
+ analytics_main_topic: "events_plugin_ingestion".to_string(),
+ analytics_main_producer: ProducerName::Ingestion,
+ analytics_overflow_topic: "events_plugin_ingestion_overflow".to_string(),
+ analytics_overflow_producer: ProducerName::Ingestion,
+ analytics_historical_topic: "events_plugin_ingestion_historical".to_string(),
+ analytics_historical_producer: ProducerName::Ingestion,
+ session_replay_main_topic: "events_plugin_ingestion".to_string(),
+ session_replay_main_producer: ProducerName::Ingestion,
+ session_replay_overflow_topic: "session_recording_snapshot_item_overflow"
+ .to_string(),
+ session_replay_overflow_producer: ProducerName::Ingestion,
+ heatmaps_topic: "events_plugin_ingestion".to_string(),
+ heatmaps_producer: ProducerName::Ingestion,
+ client_warnings_topic: "events_plugin_ingestion".to_string(),
+ client_warnings_producer: ProducerName::Ingestion,
+ error_tracking_topic: "error_tracking_events".to_string(),
+ error_tracking_producer: ProducerName::Ingestion,
+ dlq_topic: "events_plugin_ingestion_dlq".to_string(),
+ dlq_producer: ProducerName::Ingestion,
+ ai_main_topic: "events_plugin_ingestion_ai".to_string(),
+ ai_main_producer: ProducerName::Ingestion,
+ ai_overflow_topic: None,
+ ai_overflow_producer: ProducerName::Ingestion,
+ custom_producer: ProducerName::Ingestion,
},
replay_envelope_compression: EnvelopeCompression::None,
outputs_completeness_check_enabled: true,
diff --git a/rust/capture/src/v1/sinks/kafka/config.rs b/rust/capture/src/v1/sinks/kafka/config.rs
index 7ddadd025063..47ee7782fd3f 100644
--- a/rust/capture/src/v1/sinks/kafka/config.rs
+++ b/rust/capture/src/v1/sinks/kafka/config.rs
@@ -106,13 +106,13 @@ pub struct Config {
pub topic_client_ingestion_warning: String,
/// Dedicated topic for `$ai_*` events. Not meant to be set via per-sink
- /// env: setup injects the deployment-level `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` into
+ /// env: setup injects the deployment-level `CAPTURE_OUTPUT_AI_MAIN_TOPIC` into
/// every sink config, overwriting whatever the env parse produced.
#[envconfig(default = "events_plugin_ingestion_ai")]
pub topic_ai: String,
/// Optional overflow topic for the AI lane. Like `topic_ai`, injected at
- /// setup from the deployment-level `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`; unset
+ /// setup from the deployment-level `CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC`; unset
/// means the pipeline never produces `Destination::AiEventsOverflow`.
pub topic_ai_overflow: Option<String>,
}
@@ -416,7 +416,7 @@ mod tests {
#[test]
fn topic_ai_overflow_present_resolves_destination() {
// Set the field directly, mirroring how setup injects
- // CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC into sink configs after env loading.
+ // CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC into sink configs after env loading.
let mut cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();
cfg.topic_ai_overflow = Some("ai_events_overflow".to_string());
assert_eq!(
@@ -427,7 +427,7 @@ mod tests {
#[test]
fn topic_ai_present_resolves_destination() {
- // Set the field directly, mirroring how setup injects CAPTURE_ANALYTICS_AI_EVENTS_TOPIC
+ // Set the field directly, mirroring how setup injects CAPTURE_OUTPUT_AI_MAIN_TOPIC
// into sink configs after env loading.
let mut cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();
cfg.topic_ai = "ai_events".to_string();
diff --git a/rust/capture/src/v1/sinks/types.rs b/rust/capture/src/v1/sinks/types.rs
index 34776a053090..4920e6e8998c 100644
--- a/rust/capture/src/v1/sinks/types.rs
+++ b/rust/capture/src/v1/sinks/types.rs
@@ -24,7 +24,7 @@ pub enum Destination {
ClientIngestionWarning,
AiEvents,
/// Overflow lane for `AiEvents`. Only produced when the AI overflow
- /// valve (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`) is armed; overflow on the AI lane
+ /// valve (`CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC`) is armed; overflow on the AI lane
/// lands here, never on the analytics `Overflow` destination.
AiEventsOverflow,
}
diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rs
index b9a7c213d188..e08dcfb748d8 100644
--- a/rust/capture/src/v1/test_utils.rs
+++ b/rust/capture/src/v1/test_utils.rs
@@ -184,7 +184,7 @@ pub fn test_kafka_config() -> crate::v1::sinks::kafka::config::Config {
let mut cfg: crate::v1::sinks::kafka::config::Config =
envconfig::Envconfig::init_from_hashmap(&env).unwrap();
// Mirrors production, where setup injects the deployment-level
- // CAPTURE_ANALYTICS_AI_EVENTS_TOPIC and CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC into every sink config
+ // CAPTURE_OUTPUT_AI_MAIN_TOPIC and CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC into every sink config
// after env loading.
cfg.topic_ai = "ai_events".to_string();
cfg.topic_ai_overflow = Some("ai_events_overflow".to_string());
@@ -870,7 +870,10 @@ impl TestStateBuilder {
let cfg_env: HashMap<String, String> = [
("REDIS_URL", "redis://localhost:6379/"),
("CAPTURE_MODE", "events"),
- ("KAFKA_TOPIC", "events_plugin_ingestion"),
+ (
+ "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",
+ "events_plugin_ingestion",
+ ),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index 17de5453e2ac..3886a3a0dd52 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -26,7 +26,8 @@ use tokio::net::TcpListener;
use tokio::time::timeout;
use tracing::{info, warn, Level};
-use capture::config::{CaptureMode, Config, EnvelopeCompression, KafkaTopicsConfig};
+use capture::config::{CaptureMode, Config, EnvelopeCompression, OutputsConfig};
+use capture::producers::ProducerName;
use capture::server::serve;
use capture::setup;
use common_continuous_profiling::ContinuousProfilingConfig;
@@ -100,17 +101,30 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
is_mirror_deploy: false,
log_level: Level::INFO,
verbose_sample_percent: 0.0_f32,
- kafka_topics: KafkaTopicsConfig {
- main: "events_plugin_ingestion".to_string(),
- overflow: "events_plugin_ingestion_overflow".to_string(),
- historical: "events_plugin_ingestion_historical".to_string(),
- client_ingestion_warning: "events_plugin_ingestion".to_string(),
- error_tracking: "error_tracking_events".to_string(),
- heatmaps: "events_plugin_ingestion".to_string(),
- replay_overflow: "session_recording_snapshot_item_overflow".to_string(),
- dlq: "events_plugin_ingestion_dlq".to_string(),
- ai_events: "events_plugin_ingestion_ai".to_string(),
- ai_events_overflow: None,
+ outputs: OutputsConfig {
+ analytics_main_topic: "events_plugin_ingestion".to_string(),
+ analytics_main_producer: ProducerName::Ingestion,
+ analytics_overflow_topic: "events_plugin_ingestion_overflow".to_string(),
+ analytics_overflow_producer: ProducerName::Ingestion,
+ analytics_historical_topic: "events_plugin_ingestion_historical".to_string(),
+ analytics_historical_producer: ProducerName::Ingestion,
+ session_replay_main_topic: "events_plugin_ingestion".to_string(),
+ session_replay_main_producer: ProducerName::Ingestion,
+ session_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),
+ session_replay_overflow_producer: ProducerName::Ingestion,
+ heatmaps_topic: "events_plugin_ingestion".to_string(),
+ heatmaps_producer: ProducerName::Ingestion,
+ client_warnings_topic: "events_plugin_ingestion".to_string(),
+ client_warnings_producer: ProducerName::Ingestion,
+ error_tracking_topic: "error_tracking_events".to_string(),
+ error_tracking_producer: ProducerName::Ingestion,
+ dlq_topic: "events_plugin_ingestion_dlq".to_string(),
+ dlq_producer: ProducerName::Ingestion,
+ ai_main_topic: "events_plugin_ingestion_ai".to_string(),
+ ai_main_producer: ProducerName::Ingestion,
+ ai_overflow_topic: None,
+ ai_overflow_producer: ProducerName::Ingestion,
+ custom_producer: ProducerName::Ingestion,
},
replay_envelope_compression: EnvelopeCompression::None,
outputs_completeness_check_enabled: true,
@@ -191,8 +205,8 @@ pub struct ServerHandle {
impl ServerHandle {
pub async fn for_topics(main: &EphemeralTopic, historical: &EphemeralTopic) -> Self {
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main.topic_name().to_string();
- config.kafka_topics.historical = historical.topic_name().to_string();
+ config.outputs.analytics_main_topic = main.topic_name().to_string();
+ config.outputs.analytics_historical_topic = historical.topic_name().to_string();
Self::for_config(config).await
}
/// Like `for_topics`, with the synthetic ingestion warnings emitter enabled
@@ -205,8 +219,8 @@ impl ServerHandle {
warnings_topic: &EphemeralTopic,
) -> Self {
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main.topic_name().to_string();
- config.kafka_topics.historical = historical.topic_name().to_string();
+ config.outputs.analytics_main_topic = main.topic_name().to_string();
+ config.outputs.analytics_historical_topic = historical.topic_name().to_string();
config.capture_ingestion_warnings_enabled = true;
config.capture_ingestion_warnings_kafka_hosts = TEST_KAFKA_HOSTS.to_string();
config.capture_ingestion_warnings_kafka_topic = warnings_topic.topic_name().to_string();
@@ -215,7 +229,7 @@ impl ServerHandle {
pub async fn for_recordings(main: &EphemeralTopic) -> Self {
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main.topic_name().to_string();
+ config.outputs.session_replay_main_topic = main.topic_name().to_string();
config.capture_mode = CaptureMode::Recordings;
Self::for_config(config).await
}
@@ -229,7 +243,7 @@ impl ServerHandle {
warnings_topic: &EphemeralTopic,
) -> Self {
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main.topic_name().to_string();
+ config.outputs.session_replay_main_topic = main.topic_name().to_string();
config.capture_mode = CaptureMode::Recordings;
config.capture_ingestion_warnings_enabled = true;
config.capture_ingestion_warnings_kafka_hosts = TEST_KAFKA_HOSTS.to_string();
@@ -276,7 +290,7 @@ impl ServerHandle {
config.ai_gateway_signing_secret = Some(secret.to_string());
// The gateway tests send AI events, which route to the AI topic;
// point it at the same ephemeral topic so the consumer sees them.
- config.kafka_topics.ai_events = topic.topic_name().to_string();
+ config.outputs.ai_main_topic = topic.topic_name().to_string();
let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());
Self::for_config_with_sink_env(config, sink_env).await
}
diff --git a/rust/capture/tests/events.rs b/rust/capture/tests/events.rs
index af9e769dd65f..1432f88e7e8b 100644
--- a/rust/capture/tests/events.rs
+++ b/rust/capture/tests/events.rs
@@ -114,9 +114,9 @@ async fn it_drops_events_if_dropper_enabled() -> Result<()> {
let histo_topic = EphemeralTopic::new().await;
let overflow_topic = EphemeralTopic::new().await;
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main_topic.topic_name().to_string();
- config.kafka_topics.historical = histo_topic.topic_name().to_string();
- config.kafka_topics.overflow = overflow_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = main_topic.topic_name().to_string();
+ config.outputs.analytics_historical_topic = histo_topic.topic_name().to_string();
+ config.outputs.analytics_overflow_topic = overflow_topic.topic_name().to_string();
config.drop_events_by_token_distinct_id = Some(format!("{token}:{dropped_id}"));
let server = ServerHandle::for_config(config).await;
@@ -343,8 +343,8 @@ async fn it_overflows_events_on_specified_keys() -> Result<()> {
let mut config = DEFAULT_CONFIG.clone();
// this is the candidate list of tokens/event keys to reroute on sight
config.ingestion_force_overflow_by_token_distinct_id = Some(format!("{token1},{key2}"));
- config.kafka_topics.main = topic.topic_name().to_string();
- config.kafka_topics.overflow = overflow_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = topic.topic_name().to_string();
+ config.outputs.analytics_overflow_topic = overflow_topic.topic_name().to_string();
config.overflow_enabled = true;
config.overflow_burst_limit = NonZeroU32::new(10).unwrap();
config.overflow_per_second_limit = NonZeroU32::new(10).unwrap();
@@ -519,8 +519,8 @@ async fn it_overflows_events_on_specified_keys_preserving_locality() -> Result<(
let mut config = DEFAULT_CONFIG.clone();
// this is the candidate list of tokens/event keys to reroute on sight
config.ingestion_force_overflow_by_token_distinct_id = Some(format!("{token1},{key2}"));
- config.kafka_topics.main = topic.topic_name().to_string();
- config.kafka_topics.overflow = overflow_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = topic.topic_name().to_string();
+ config.outputs.analytics_overflow_topic = overflow_topic.topic_name().to_string();
config.overflow_enabled = true;
config.overflow_preserve_partition_locality = true;
config.overflow_burst_limit = NonZeroU32::new(10).unwrap();
@@ -685,8 +685,8 @@ async fn it_should_not_set_force_disable_person_processing_header_when_rate_limi
let mut config = DEFAULT_CONFIG.clone();
// NO forced overflow keys - only rate limiting
config.ingestion_force_overflow_by_token_distinct_id = None;
- config.kafka_topics.main = topic.topic_name().to_string();
- config.kafka_topics.overflow = overflow_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = topic.topic_name().to_string();
+ config.outputs.analytics_overflow_topic = overflow_topic.topic_name().to_string();
config.overflow_enabled = true;
// Very low limits to trigger rate-based overflow
config.overflow_burst_limit = NonZeroU32::new(1).unwrap();
@@ -769,8 +769,8 @@ async fn it_reroutes_to_historical_on_event_timestamp() -> Result<()> {
config.enable_historical_rerouting = true;
config.historical_rerouting_threshold_days = 1_i64;
- config.kafka_topics.main = topic.topic_name().to_string();
- config.kafka_topics.historical = historical_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = topic.topic_name().to_string();
+ config.outputs.analytics_historical_topic = historical_topic.topic_name().to_string();
config.overflow_enabled = false;
config.overflow_burst_limit = NonZeroU32::new(10).unwrap();
config.overflow_per_second_limit = NonZeroU32::new(10).unwrap();
@@ -842,8 +842,8 @@ async fn it_overflows_events_on_burst() -> Result<()> {
let overflow_topic = EphemeralTopic::new().await;
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = topic.topic_name().to_string();
- config.kafka_topics.overflow = overflow_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = topic.topic_name().to_string();
+ config.outputs.analytics_overflow_topic = overflow_topic.topic_name().to_string();
config.overflow_enabled = true;
config.overflow_burst_limit = NonZeroU32::new(2).unwrap();
config.overflow_per_second_limit = NonZeroU32::new(1).unwrap();
@@ -906,7 +906,7 @@ async fn it_does_not_overflow_team_with_different_ids() -> Result<()> {
let topic = EphemeralTopic::new().await;
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = topic.topic_name().to_string();
config.overflow_enabled = true;
config.overflow_burst_limit = NonZeroU32::new(1).unwrap();
config.overflow_per_second_limit = NonZeroU32::new(1).unwrap();
@@ -950,8 +950,8 @@ async fn it_skips_overflows_when_disabled() -> Result<()> {
let overflow_topic = EphemeralTopic::new().await;
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = topic.topic_name().to_string();
- config.kafka_topics.overflow = overflow_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = topic.topic_name().to_string();
+ config.outputs.analytics_overflow_topic = overflow_topic.topic_name().to_string();
config.overflow_enabled = false;
config.overflow_burst_limit = NonZeroU32::new(2).unwrap();
config.overflow_per_second_limit = NonZeroU32::new(1).unwrap();
@@ -1094,7 +1094,7 @@ async fn it_applies_billing_limits() -> Result<()> {
let mut config = DEFAULT_CONFIG.clone();
config.redis_key_prefix = redis.key_prefix();
- config.kafka_topics.main = topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = topic.topic_name().to_string();
let server = ServerHandle::for_config(config).await;
for payload in [
@@ -1148,10 +1148,10 @@ async fn it_routes_exceptions_and_heapmaps_to_separate_topics() -> Result<()> {
let heatmaps_topic = EphemeralTopic::new().await;
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main_topic.topic_name().to_string();
- config.kafka_topics.client_ingestion_warning = warnings_topic.topic_name().to_string();
- config.kafka_topics.error_tracking = error_tracking_topic.topic_name().to_string();
- config.kafka_topics.heatmaps = heatmaps_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = main_topic.topic_name().to_string();
+ config.outputs.client_warnings_topic = warnings_topic.topic_name().to_string();
+ config.outputs.error_tracking_topic = error_tracking_topic.topic_name().to_string();
+ config.outputs.heatmaps_topic = heatmaps_topic.topic_name().to_string();
let server = ServerHandle::for_config(config).await;
diff --git a/rust/capture/tests/integration_person_processing_matrix.rs b/rust/capture/tests/integration_person_processing_matrix.rs
index c31daf3dc817..2a9645b6e8bf 100644
--- a/rust/capture/tests/integration_person_processing_matrix.rs
+++ b/rust/capture/tests/integration_person_processing_matrix.rs
@@ -46,7 +46,7 @@ use capture::quota_limiters::CaptureQuotaLimiter;
use capture::router::router;
use capture::sinks::kafka::KafkaSinkBase;
use capture::sinks::producer::MockKafkaProducer;
-use capture::sinks::registry::TopicTable;
+use capture::sinks::registry::OutputTable;
use capture::time::TimeSource;
use capture::v0_request::AiLanePredicate;
use capture::v1::router::{router as v1_router, RouterConfig as V1RouterConfig};
@@ -228,7 +228,7 @@ async fn run_v0(inputs: Inputs, distinct_ids: &[&str]) -> Batch {
let service = build_restrictions(inputs).await;
let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), TopicTable::from(&cfg.kafka_topics));
+ let sink = KafkaSinkBase::with_producer(producer.clone(), OutputTable::from(&cfg.outputs));
let quota_limiter =
CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));
diff --git a/rust/capture/tests/recordings.rs b/rust/capture/tests/recordings.rs
index a1d969809fd7..eda380b04497 100644
--- a/rust/capture/tests/recordings.rs
+++ b/rust/capture/tests/recordings.rs
@@ -381,8 +381,8 @@ async fn it_applies_overflow_limits() -> Result<()> {
let mut config = DEFAULT_CONFIG.clone();
config.redis_key_prefix = redis.key_prefix();
- config.kafka_topics.main = topic.topic_name().to_string();
- config.kafka_topics.replay_overflow = overflow_topic.topic_name().to_string();
+ config.outputs.session_replay_main_topic = topic.topic_name().to_string();
+ config.outputs.session_replay_overflow_topic = overflow_topic.topic_name().to_string();
config.capture_mode = CaptureMode::Recordings;
let server = ServerHandle::for_config(config).await;
diff --git a/rust/capture/tests/routing_e2e.rs b/rust/capture/tests/routing_e2e.rs
index 050b16bae25a..bc346e6d6f9e 100644
--- a/rust/capture/tests/routing_e2e.rs
+++ b/rust/capture/tests/routing_e2e.rs
@@ -65,8 +65,8 @@ async fn it_routes_dlq_redirected_events_to_the_dlq_topic() -> Result<()> {
);
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main_topic.topic_name().to_string();
- config.kafka_topics.dlq = dlq_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = main_topic.topic_name().to_string();
+ config.outputs.dlq_topic = dlq_topic.topic_name().to_string();
config.event_restrictions_enabled = true;
config.event_restrictions_redis_url = Some(config.redis_url.clone());
// A failed first load (tight Redis timeout on a busy runner) retries on
@@ -130,7 +130,7 @@ async fn it_routes_custom_redirected_events_to_the_admin_topic() -> Result<()> {
);
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = main_topic.topic_name().to_string();
config.event_restrictions_enabled = true;
config.event_restrictions_redis_url = Some(config.redis_url.clone());
// A failed first load (tight Redis timeout on a busy runner) retries on
@@ -179,8 +179,8 @@ async fn it_routes_diverted_ai_events_to_the_ai_topic() -> Result<()> {
let ai_topic = EphemeralTopic::new().await;
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main_topic.topic_name().to_string();
- config.kafka_topics.ai_events = ai_topic.topic_name().to_string();
+ config.outputs.analytics_main_topic = main_topic.topic_name().to_string();
+ config.outputs.ai_main_topic = ai_topic.topic_name().to_string();
let server = ServerHandle::for_config(config).await;
let batch = json!([
@@ -234,9 +234,9 @@ async fn it_routes_forced_ai_events_to_ai_overflow_when_the_valve_is_armed() ->
let ai_overflow_topic = EphemeralTopic::new().await;
let mut config = DEFAULT_CONFIG.clone();
- config.kafka_topics.main = main_topic.topic_name().to_string();
- config.kafka_topics.ai_events = ai_topic.topic_name().to_string();
- config.kafka_topics.ai_events_overflow = Some(ai_overflow_topic.topic_name().to_string());
+ config.outputs.analytics_main_topic = main_topic.topic_name().to_string();
+ config.outputs.ai_main_topic = ai_topic.topic_name().to_string();
+ config.outputs.ai_overflow_topic = Some(ai_overflow_topic.topic_name().to_string());
config.overflow_enabled = true;
config.overflow_burst_limit = NonZeroU32::new(10).unwrap();
config.overflow_per_second_limit = NonZeroU32::new(10).unwrap();