:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(capture): named producers own their connection config (#105335)
Paweł Ledwoń0345d5e91849
diff --git a/bin/start-rust-service b/bin/start-rust-serviceindex bbf9dfb38717..5f1bddfbbf57 100755--- a/bin/start-rust-service+++ b/bin/start-rust-service@@ -52,7 +52,7 @@ case "$RS_SVC" inexport RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warnexport RUST_BACKTRACE=1export ADDRESS=0.0.0.0:3307 # avoid port conflict in local dev- export KAFKA_HOSTS="$DEFAULT_KAFKA"+ export KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST="$DEFAULT_KAFKA"export REDIS_URL="$DEFAULT_REDIS"export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PG}"export CAPTURE_MODE=events@@ -76,7 +76,7 @@ case "$RS_SVC" inexport RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warnexport RUST_BACKTRACE=1export ADDRESS=0.0.0.0:3306 # avoid port conflict in local dev- export KAFKA_HOSTS="$DEFAULT_KAFKA"+ export KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST="$DEFAULT_KAFKA"export KAFKA_TOPIC=session_recording_snapshot_item_eventsexport KAFKA_OVERFLOW_TOPIC=session_recording_snapshot_item_overflowexport REDIS_URL="$DEFAULT_REDIS"@@ -92,7 +92,7 @@ case "$RS_SVC" inexport RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warnexport RUST_BACKTRACE=1export ADDRESS=0.0.0.0:3309 # avoid port conflict in local dev (3308 is used by llm-gateway)- export KAFKA_HOSTS="$DEFAULT_KAFKA"+ export KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST="$DEFAULT_KAFKA"export KAFKA_TOPIC=events_plugin_ingestion_aiexport REDIS_URL="$DEFAULT_REDIS"export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PG}"diff --git a/docker-compose.base.yml b/docker-compose.base.ymlindex f83d6f799a0f..91390aa113e1 100644--- a/docker-compose.base.yml+++ b/docker-compose.base.yml@@ -380,6 +380,7 @@ services:KAFKA_TOPIC: 'events_plugin_ingestion'KAFKA_ERROR_TRACKING_TOPIC: 'ingestion-errortracking-main'KAFKA_HOSTS: 'kafka:9092'+ KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST: 'kafka:9092'REDIS_URL: 'redis://redis7:6379/'CAPTURE_MODE: eventsRUST_LOG: 'info,rdkafka=warn'@@ -404,6 +405,7 @@ services:ADDRESS: '0.0.0.0:3000'KAFKA_TOPIC: 'session_recording_snapshot_item_events'KAFKA_HOSTS: 'kafka:9092'+ KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST: 'kafka:9092'REDIS_URL: 'redis://redis7:6379/'CAPTURE_MODE: recordings@@ -418,6 +420,7 @@ services:ADDRESS: '0.0.0.0:3000'KAFKA_TOPIC: 'events_plugin_ingestion_ai'KAFKA_HOSTS: 'kafka:9092'+ KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST: 'kafka:9092'REDIS_URL: 'redis://redis7:6379/'# `ai` mode produces to the AI lane as its main topic (no $ai_* divert needed),# matching the production capture-ai deployment.diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex e395f48dae1a..5fe2d0e61e13 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -283,7 +283,18 @@ pub struct Config {pub historical_rerouting_threshold_days: i64,#[envconfig(nested = true)]- pub kafka: KafkaConfig,+ pub kafka_topics: KafkaTopicsConfig,++ /// Application-level compression of session replay payloads, independent of+ /// broker-level compression. Consumers detect and decompress it.+ #[envconfig(from = "KAFKA_REPLAY_ENVELOPE_COMPRESSION", default = "none")]+ 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+ /// blanks a topic it never produces to still boots.+ #[envconfig(from = "CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED", default = "false")]+ pub outputs_completeness_check_enabled: bool,#[envconfig(default = "1.0")]pub otel_sampling_rate: f64,@@ -330,7 +341,7 @@ pub struct Config {////// Set it below what the deployment's broker accepts, leaving room for the/// `CapturedEvent` envelope and the JSON-escaping of `data`:- /// `KAFKA_PRODUCER_MESSAGE_MAX_BYTES` bounds the produced message, not the+ /// `KAFKA_INGESTION_PRODUCER_MESSAGE_MAX_BYTES` bounds the produced message, not the/// event inside it. capture-analytics needs a smaller value than capture-ai/// because its AI topic is on MSK.///@@ -353,7 +364,7 @@ pub struct Config {/// event in it, not just the offender. The multipart handler counts no/// drop at all: like every other error it raises, the refusal shows up/// only on `capture_error_by_stage_and_type`.- /// Keep this under the deployment's `KAFKA_PRODUCER_MESSAGE_MAX_BYTES`.+ /// Keep this under the deployment's `KAFKA_INGESTION_PRODUCER_MESSAGE_MAX_BYTES`./// Above it the ceiling stops being a guard: capture reads the body, builds/// the event, and the producer refuses it anyway. A deployment that has not/// raised its producer cap wants a lower value than this default; the boot@@ -439,10 +450,9 @@ pub struct Config {pub capture_ingestion_warnings_kafka_message_max_bytes: u32,// The warnings emitter's own destination. It serves every pipeline that- // emits (v1 and legacy analytics, both AI endpoints, and replay) but is- // independent of the v0 `KAFKA_*` block: it reads only these three vars,- // never `kafka_hosts` / `kafka_tls` /- // `kafka_client_ingestion_warning_topic`. charts sets all three per env,+ // 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,// pointed at the MSK cluster the clientwarnings consumer reads from.//// Defaults are inert on purpose: empty hosts or topic makes@@ -493,6 +503,54 @@ 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`].+#[derive(Envconfig, Clone)]+pub struct KafkaTopicsConfig {+ #[envconfig(from = "KAFKA_TOPIC", default = "events_plugin_ingestion")]+ pub main: String,+ #[envconfig(+ from = "KAFKA_OVERFLOW_TOPIC",+ default = "events_plugin_ingestion_overflow"+ )]+ pub overflow: String,+ #[envconfig(+ from = "KAFKA_HISTORICAL_TOPIC",+ default = "events_plugin_ingestion_historical"+ )]+ pub historical: String,+ #[envconfig(+ from = "KAFKA_CLIENT_INGESTION_WARNING_TOPIC",+ default = "ingestion-clientwarnings-main-1"+ )]+ 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,+ #[envconfig(+ from = "KAFKA_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,+ /// 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",+ default = "events_plugin_ingestion_ai"+ )]+ pub ai_events: String,+ /// 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>,+}+#[derive(Envconfig, Clone)]pub struct KafkaConfig {#[envconfig(default = "20")]@@ -505,19 +563,6 @@ pub struct KafkaConfig {pub kafka_producer_message_max_bytes: u32, // message.max.bytes - max kafka message size we will produce#[envconfig(default = "none")]pub kafka_compression_codec: String, // none, gzip, snappy, lz4, zstd- /// Application-level compression for session replay (snapshot) Kafka payloads.- /// Independent of broker-level compression; consumers must detect and decompress.- /// Set to "lz4" to enable. Default "none" for safe rollout and rollback.- #[envconfig(default = "none")]- pub kafka_replay_envelope_compression: EnvelopeCompression,- /// Refuse to boot when a registered output resolves to an empty topic- /// name (see `TopicTable::check_complete`). Config-only — the broker- /// is never probed, so topic autocreation on first publish is unaffected.- /// Opt-in (default off) so deployments that deliberately blank a topic- /// they never produce to keep booting; arm it per deployment once its- /// topic wiring is known-complete.- #[envconfig(from = "CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED", default = "false")]- pub outputs_completeness_check_enabled: bool,pub kafka_hosts: String,#[envconfig(default = "events_plugin_ingestion")]pub kafka_topic: String,@@ -525,35 +570,6 @@ pub struct KafkaConfig {pub kafka_traces_topic: String,#[envconfig(default = "ingestion-metrics")]pub kafka_metrics_topic: String,- #[envconfig(default = "events_plugin_ingestion_overflow")]- pub kafka_overflow_topic: String,- #[envconfig(default = "events_plugin_ingestion_historical")]- pub kafka_historical_topic: String,- #[envconfig(default = "ingestion-clientwarnings-main-1")]- pub kafka_client_ingestion_warning_topic: String,- #[envconfig(default = "error_tracking_events")]- pub kafka_error_tracking_topic: String,- #[envconfig(default = "heatmaps_ingestion")]- pub kafka_heatmaps_topic: String,- #[envconfig(default = "session_recording_snapshot_item_overflow")]- pub kafka_replay_overflow_topic: String,- #[envconfig(default = "events_plugin_ingestion_dlq")]- pub kafka_dlq_topic: String,- /// Dedicated Kafka topic for AI events (env: `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`).- /// Both the v0 pipeline (via `DataType::AiEvents`) and the v1 pipeline- /// (via `Destination::AiEvents`) divert AI events here instead of the- /// analytics main topic, on every deployment that accepts them — including- /// capture-ai, whose main topic used to double as the AI topic. Setup also- /// injects it into every v1 sink config.- #[envconfig(default = "events_plugin_ingestion_ai")]- pub capture_analytics_ai_events_topic: String,- /// Optional overflow topic for the AI lane (env: `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`).- /// Unset means AI events never overflow (the pre-overflow behavior). When- /// set, the AI lane participates in the same overflow limiter and- /// restriction-driven force_overflow as the analytics main lane, rerouting- /// here instead of the analytics overflow topic. Refused at boot in import- /// mode because imports must never overflow.- pub capture_analytics_ai_events_overflow_topic: Option<String>,#[envconfig(default = "false")]pub kafka_tls: bool,#[envconfig(default = "")]@@ -568,32 +584,6 @@ pub struct KafkaConfig {// default is 3x metadata refresh interval so we maintain that here#[envconfig(default = "60000")]pub kafka_metadata_max_age_ms: u32,- #[envconfig(default = "60000")] // lib default, can tweak in env overrides- pub kafka_socket_timeout_ms: u32,- #[envconfig(default = "10000")] // librdkafka default- pub kafka_producer_batch_num_messages: u32, // batch.num.messages - max messages per batch- #[envconfig(default = "1000000")] // librdkafka default- pub kafka_producer_batch_size: u32, // batch.size - max batch size in bytes- #[envconfig(default = "1000000")] // librdkafka default- pub kafka_producer_max_in_flight_requests: u32, // max.in.flight.requests.per.connection- #[envconfig(default = "10")] // librdkafka default- pub kafka_producer_sticky_partitioning_linger_ms: u32, // sticky.partitioning.linger.ms- #[envconfig(default = "false")] // librdkafka default- pub kafka_producer_enable_idempotence: bool, // enable.idempotence- #[envconfig(default = "murmur2_random")]- pub kafka_producer_partitioner: String, // partitioner- #[envconfig(default = "")]- pub kafka_broker_address_family: String, // broker.address.family - v4, v6, any; empty = don't set- #[envconfig(default = "true")] // librdkafka default- pub kafka_log_connection_close: bool, // log.connection.close- #[envconfig(default = "100000")] // librdkafka default- pub kafka_producer_queue_buffering_max_messages: u32, // queue.buffering.max.messages- #[envconfig(default = "1000")] // librdkafka default- pub kafka_retry_backoff_max_ms: u32, // retry.backoff.max.ms- #[envconfig(default = "0")] // librdkafka default (OS auto-tune)- pub kafka_socket_send_buffer_bytes: u32, // socket.send.buffer.bytes- #[envconfig(default = "0")] // librdkafka default (OS auto-tune)- pub kafka_socket_receive_buffer_bytes: u32, // socket.receive.buffer.bytes// Traces-cluster overrides (consumed by capture-logs). When unset, the// traces producer reuses the corresponding `kafka_*` value above.@@ -634,38 +624,55 @@ mod tests {use std::str::FromStr;fn required_config_env() -> HashMap<String, String> {- [- ("REDIS_URL", "redis://localhost:6379/"),- ("KAFKA_HOSTS", "localhost:9092"),- ]- .into_iter()- .map(|(k, v)| (k.to_string(), v.to_string()))- .collect()+ [("REDIS_URL", "redis://localhost:6379/")]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect()}#[test]fn capture_analytics_ai_events_topic_defaults() {let config: Config =envconfig::Envconfig::init_from_hashmap(&required_config_env()).unwrap();- assert_eq!(- config.kafka.capture_analytics_ai_events_topic,- "events_plugin_ingestion_ai"- );- assert_eq!(- config.kafka.capture_analytics_ai_events_overflow_topic,- None- );+ assert_eq!(config.kafka_topics.ai_events, "events_plugin_ingestion_ai");+ assert_eq!(config.kafka_topics.ai_events_overflow, None);+ }++ #[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())]+ fn topic_env_var_binds_to_its_field(+ #[case] env_var: &str,+ #[case] field: fn(&Config) -> String,+ ) {+ let mut env = required_config_env();+ env.insert(env_var.into(), "configured_topic".into());+ let config: Config = envconfig::Envconfig::init_from_hashmap(&env).unwrap();+ assert_eq!(field(&config), "configured_topic");}#[test]- fn capture_analytics_ai_events_topic_parses() {+ fn moved_output_settings_keep_their_env_vars() {let mut env = required_config_env();+ env.insert("KAFKA_REPLAY_ENVELOPE_COMPRESSION".into(), "lz4".into());env.insert(- "CAPTURE_ANALYTICS_AI_EVENTS_TOPIC".into(),- "ai_events".into(),+ "CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED".into(),+ "true".into(),);let config: Config = envconfig::Envconfig::init_from_hashmap(&env).unwrap();- assert_eq!(config.kafka.capture_analytics_ai_events_topic, "ai_events");+ assert_eq!(+ config.replay_envelope_compression,+ super::EnvelopeCompression::Lz4+ );+ assert!(config.outputs_completeness_check_enabled);}#[test]diff --git a/rust/capture/src/lib.rs b/rust/capture/src/lib.rsindex b42cf97f6972..8f692129a64d 100644--- a/rust/capture/src/lib.rs+++ b/rust/capture/src/lib.rs@@ -18,6 +18,7 @@ pub mod outputs;mod overflow_parity;pub mod payload;pub mod pipeline;+pub mod producers;pub mod prometheus;pub mod quota_limiters;pub mod router;diff --git a/rust/capture/src/producers.rs b/rust/capture/src/producers.rsnew file mode 100644index 000000000000..418eed353b77--- /dev/null+++ b/rust/capture/src/producers.rs@@ -0,0 +1,348 @@+//! Named Kafka producers, declared in code and instantiated once.+//!+//! A [`ProducerName`] is a connection slot, not a fixed cluster: charts wire+//! each slot to a cluster per deployment, the same model as Node.js+//! ingestion's `KafkaProducerRegistry`. A slot's settings are read from+//! `KAFKA_<SLOT>_PRODUCER_<RDKAFKA_KEY>` variables, and every output that+//! publishes through a slot shares its one producer.++use std::collections::HashMap;+use std::sync::Arc;+use std::time::Duration;++use envconfig::Envconfig;+use rdkafka::producer::{FutureProducer, Producer};+use rdkafka::util::Timeout;+use rdkafka::ClientConfig;+use tracing::log::{debug, info};++use crate::sinks::kafka::KafkaContext;+use crate::sinks::producer::RdKafkaProducer;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum ProducerName {+ /// The cluster the ingestion pipelines consume capture's topics from.+ Ingestion,+}++impl ProducerName {+ pub const ALL: [ProducerName; 1] = [ProducerName::Ingestion];++ pub fn as_str(&self) -> &'static str {+ match self {+ ProducerName::Ingestion => "INGESTION",+ }+ }++ // Slot names are single words, so no prefix is a prefix of another.+ fn env_prefix(&self) -> String {+ format!("KAFKA_{}_PRODUCER_", self.as_str())+ }+}++/// One producer's connection and tuning. Each field maps to the rdkafka key of+/// the same name.+#[derive(Envconfig, Clone, Debug)]+pub struct ProducerConfig {+ // `kafka:9092` is the broker in local dev and hobby. A deployment that+ // forgets to wire the slot fails its liveness check instead of producing+ // somewhere unexpected.+ #[envconfig(default = "kafka:9092")]+ pub metadata_broker_list: String,+ #[envconfig(default = "")]+ pub security_protocol: String,+ #[envconfig(default = "")]+ pub enable_ssl_certificate_verification: String,+ #[envconfig(default = "")]+ pub client_id: String,+ #[envconfig(default = "none")]+ pub compression_codec: String,+ #[envconfig(default = "20")]+ pub linger_ms: u32,+ #[envconfig(default = "1000000")]+ pub batch_size: u32,+ #[envconfig(default = "10000")]+ pub batch_num_messages: u32,+ #[envconfig(default = "100000")]+ pub queue_buffering_max_messages: u32,+ #[envconfig(default = "409600")]+ pub queue_buffering_max_kbytes: u32,+ #[envconfig(default = "1000000")]+ pub message_max_bytes: u32,+ #[envconfig(default = "20000")]+ pub message_timeout_ms: u32,+ #[envconfig(default = "10")]+ pub sticky_partitioning_linger_ms: u32,+ #[envconfig(default = "20000")]+ pub topic_metadata_refresh_interval_ms: u32,+ #[envconfig(default = "60000")]+ pub metadata_max_age_ms: u32,+ /// `message.send.max.retries`, named `RETRIES` as in Node.js ingestion.+ #[envconfig(default = "2")]+ pub retries: u32,+ #[envconfig(default = "1000000")]+ pub max_in_flight_requests_per_connection: u32,+ #[envconfig(default = "false")]+ pub enable_idempotence: bool,+ #[envconfig(default = "all")]+ pub acks: String,+ #[envconfig(default = "murmur2_random")]+ pub partitioner: String,+ #[envconfig(default = "60000")]+ pub socket_timeout_ms: u32,+ #[envconfig(default = "")]+ pub broker_address_family: String,+ #[envconfig(default = "true")]+ pub log_connection_close: bool,+ #[envconfig(default = "1000")]+ pub retry_backoff_max_ms: u32,+ #[envconfig(default = "0")]+ pub socket_send_buffer_bytes: u32,+ #[envconfig(default = "0")]+ pub socket_receive_buffer_bytes: u32,+}++impl ProducerConfig {+ pub fn load(name: ProducerName, env: &HashMap<String, String>) -> anyhow::Result<Self> {+ let prefix = name.env_prefix();+ let slot_env: HashMap<String, String> = env+ .iter()+ .filter_map(|(k, v)| {+ k.strip_prefix(&prefix)+ .map(|key| (key.to_string(), v.clone()))+ })+ .collect();+ Self::init_from_hashmap(&slot_env)+ .map_err(|e| anyhow::anyhow!("producer {}: {e}", name.as_str()))+ }++ fn client_config(&self) -> ClientConfig {+ let mut client_config = ClientConfig::new();+ client_config+ .set("bootstrap.servers", &self.metadata_broker_list)+ .set("statistics.interval.ms", "10000")+ .set("partitioner", &self.partitioner)+ .set("metadata.max.age.ms", self.metadata_max_age_ms.to_string())+ .set(+ "topic.metadata.refresh.interval.ms",+ self.topic_metadata_refresh_interval_ms.to_string(),+ )+ .set("message.send.max.retries", self.retries.to_string())+ .set("linger.ms", self.linger_ms.to_string())+ .set("message.max.bytes", self.message_max_bytes.to_string())+ .set("message.timeout.ms", self.message_timeout_ms.to_string())+ .set("socket.timeout.ms", self.socket_timeout_ms.to_string())+ .set("compression.codec", &self.compression_codec)+ .set(+ "queue.buffering.max.kbytes",+ self.queue_buffering_max_kbytes.to_string(),+ )+ .set("acks", &self.acks)+ .set("batch.num.messages", self.batch_num_messages.to_string())+ .set("batch.size", self.batch_size.to_string())+ .set(+ "max.in.flight.requests.per.connection",+ self.max_in_flight_requests_per_connection.to_string(),+ )+ .set(+ "sticky.partitioning.linger.ms",+ self.sticky_partitioning_linger_ms.to_string(),+ )+ .set("enable.idempotence", self.enable_idempotence.to_string())+ .set(+ "log.connection.close",+ self.log_connection_close.to_string(),+ )+ .set(+ "queue.buffering.max.messages",+ self.queue_buffering_max_messages.to_string(),+ )+ .set(+ "retry.backoff.max.ms",+ self.retry_backoff_max_ms.to_string(),+ )+ .set(+ "socket.send.buffer.bytes",+ self.socket_send_buffer_bytes.to_string(),+ )+ .set(+ "socket.receive.buffer.bytes",+ self.socket_receive_buffer_bytes.to_string(),+ );++ for (key, value) in [+ ("broker.address.family", &self.broker_address_family),+ ("client.id", &self.client_id),+ ("security.protocol", &self.security_protocol),+ (+ "enable.ssl.certificate.verification",+ &self.enable_ssl_certificate_verification,+ ),+ ] {+ if !value.is_empty() {+ client_config.set(key, value);+ }+ }++ client_config+ }+}++pub type ProducerHandle = Arc<RdKafkaProducer<KafkaContext>>;++/// Every declared producer, each instantiated once.+pub struct ProducerRegistry {+ producers: HashMap<ProducerName, ProducerHandle>,+}++impl ProducerRegistry {+ pub fn build(+ configs: &HashMap<ProducerName, ProducerConfig>,+ mut liveness: HashMap<ProducerName, lifecycle::Handle>,+ ) -> anyhow::Result<Self> {+ let mut producers = HashMap::new();+ for name in ProducerName::ALL {+ let config = configs+ .get(&name)+ .ok_or_else(|| anyhow::anyhow!("no config for producer {}", name.as_str()))?;+ let producer = create_producer(name, config, liveness.remove(&name))?;+ producers.insert(name, producer);+ }+ Ok(Self { producers })+ }++ pub fn get(&self, name: ProducerName) -> ProducerHandle {+ Arc::clone(&self.producers[&name])+ }+}++pub fn load_all(+ env: &HashMap<String, String>,+) -> anyhow::Result<HashMap<ProducerName, ProducerConfig>> {+ ProducerName::ALL+ .into_iter()+ .map(|name| Ok((name, ProducerConfig::load(name, env)?)))+ .collect()+}++fn create_producer(+ name: ProducerName,+ config: &ProducerConfig,+ liveness: Option<lifecycle::Handle>,+) -> anyhow::Result<ProducerHandle> {+ info!(+ "connecting producer {} to Kafka brokers at {}...",+ name.as_str(),+ config.metadata_broker_list+ );++ let client_config = config.client_config();+ debug!("rdkafka configuration: {client_config:?}");++ let producer: FutureProducer<KafkaContext> =+ client_config.create_with_context(KafkaContext::new(liveness.clone()))?;++ // A failed ping is not an error, because other sinks may still report healthy.+ if producer+ .client()+ .fetch_metadata(+ Some("__consumer_offsets"),+ Timeout::After(Duration::new(10, 0)),+ )+ .is_ok()+ {+ if let Some(liveness) = &liveness {+ liveness.report_healthy();+ }+ info!("connected to Kafka brokers");+ };++ Ok(Arc::new(RdKafkaProducer::new(producer)))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {+ pairs+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect()+ }++ #[test]+ fn default_config_sets_the_legacy_rdkafka_settings() {+ let client_config = ProducerConfig::load(ProducerName::Ingestion, &HashMap::new())+ .unwrap()+ .client_config();++ let expected = [+ ("bootstrap.servers", "kafka:9092"),+ ("statistics.interval.ms", "10000"),+ ("partitioner", "murmur2_random"),+ ("metadata.max.age.ms", "60000"),+ ("topic.metadata.refresh.interval.ms", "20000"),+ ("message.send.max.retries", "2"),+ ("linger.ms", "20"),+ ("message.max.bytes", "1000000"),+ ("message.timeout.ms", "20000"),+ ("socket.timeout.ms", "60000"),+ ("compression.codec", "none"),+ ("queue.buffering.max.kbytes", "409600"),+ ("acks", "all"),+ ("batch.num.messages", "10000"),+ ("batch.size", "1000000"),+ ("max.in.flight.requests.per.connection", "1000000"),+ ("sticky.partitioning.linger.ms", "10"),+ ("enable.idempotence", "false"),+ ("log.connection.close", "true"),+ ("queue.buffering.max.messages", "100000"),+ ("retry.backoff.max.ms", "1000"),+ ("socket.send.buffer.bytes", "0"),+ ("socket.receive.buffer.bytes", "0"),+ ];+ for (key, value) in expected {+ assert_eq!(client_config.get(key), Some(value), "{key}");+ }+ for unset in [+ "broker.address.family",+ "client.id",+ "security.protocol",+ "enable.ssl.certificate.verification",+ ] {+ assert_eq!(client_config.get(unset), None, "{unset}");+ }+ }++ #[test]+ fn load_reads_only_its_slot_prefix() {+ let config = ProducerConfig::load(+ ProducerName::Ingestion,+ &env(&[+ ("KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST", "msk:9094"),+ ("KAFKA_INGESTION_PRODUCER_SECURITY_PROTOCOL", "ssl"),+ ("KAFKA_INGESTION_PRODUCER_RETRIES", "7"),+ ("KAFKA_HOSTS", "legacy:9092"),+ ("KAFKA_PRODUCER_LINGER_MS", "99"),+ ]),+ )+ .unwrap();++ assert_eq!(config.metadata_broker_list, "msk:9094");+ assert_eq!(config.security_protocol, "ssl");+ assert_eq!(config.retries, 7);+ assert_eq!(config.linger_ms, 20);+ }++ #[test]+ fn load_rejects_an_unparseable_value() {+ let err = ProducerConfig::load(+ ProducerName::Ingestion,+ &env(&[("KAFKA_INGESTION_PRODUCER_LINGER_MS", "soon")]),+ )+ .unwrap_err();++ assert!(err.to_string().contains("INGESTION"), "{err}");+ }+}diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex 20f78a8cc175..14a5f996fcd3 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -17,6 +17,7 @@ use crate::config::{CaptureMode, Config};use crate::event_restrictions::{EventRestrictionService, Pipeline, RedisRestrictionsRepository};use crate::global_rate_limiter::{ai_byte_limit_window, GlobalRateLimiter};use crate::outputs::{Output, OutputRegistry};+use crate::producers::{self, ProducerConfig, ProducerName, ProducerRegistry};use crate::prometheus::setup_metrics_recorder;use crate::quota_limiters::{is_exception_event, is_llm_event, is_survey_event, CaptureQuotaLimiter,@@ -26,6 +27,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::s3::S3Sink;use limiters::overflow::OverflowLimiter;use limiters::redis::{QuotaResource, RedisLimiter, ServiceName, OVERFLOW_LIMITER_CACHE_KEY};@@ -133,7 +135,7 @@ pub struct CaptureComponents {pub async fn build_components(config: Config,- sink_env: HashMap<String, String>,+ env: HashMap<String, String>,handles: LifecycleHandles,) -> CaptureComponents {let LifecycleHandles {@@ -156,6 +158,10 @@ pub async fn build_components()});+ let producer_configs = producers::load_all(&env)+ .unwrap_or_else(|e| panic!("fatal: invalid producer configuration: {e:#}"));+ let ingestion_message_max_bytes = producer_configs[&ProducerName::Ingestion].message_max_bytes;+let redis_client = Arc::new(RedisClient::with_config(config.redis_url.clone(),@@ -238,7 +244,7 @@ pub async fn build_components(// body size to be unpacked. If a single event is still too big, we'll drop it at kafka send time.let event_payload_max_bytes = match config.capture_mode {CaptureMode::Events | CaptureMode::Ai | CaptureMode::Import => BATCH_BODY_SIZE * 5,- CaptureMode::Recordings => config.kafka.kafka_producer_message_max_bytes as usize,+ CaptureMode::Recordings => ingestion_message_max_bytes as usize,};// Build the overflow limiters here (not inside the sink) so routing@@ -291,7 +297,7 @@ pub async fn build_components(};let outputs = Arc::new(- create_output_registry(&config, sink_handle, advisory_handle)+ create_output_registry(&config, &producer_configs, sink_handle, advisory_handle).await.expect("failed to create the output registry"),);@@ -308,13 +314,13 @@ pub async fn build_components(};assert!(- !config.kafka.capture_analytics_ai_events_topic.is_empty(),+ !config.kafka_topics.ai_events.is_empty(),"invalid configuration: CAPTURE_ANALYTICS_AI_EVENTS_TOPIC must not be empty",);let ai_events_overflow_enabled = ai_events_overflow_valve(&config);info!(- capture_analytics_ai_events_topic = %config.kafka.capture_analytics_ai_events_topic,- capture_analytics_ai_events_overflow_topic = ?config.kafka.capture_analytics_ai_events_overflow_topic,+ capture_analytics_ai_events_topic = %config.kafka_topics.ai_events,+ capture_analytics_ai_events_overflow_topic = ?config.kafka_topics.ai_events_overflow,ai_events_overflow_enabled,"AI events topic routing");@@ -359,7 +365,7 @@ pub async fn build_components(if ai_byte_limit_enabled {warn_if_ai_byte_budget_below_max_event(&config);}- warn_if_ai_ceiling_exceeds_producer_cap(&config);+ warn_if_ai_ceiling_exceeds_producer_cap(&config, ingestion_message_max_bytes);let ai_byte_rate_limiter = ai_byte_limiter_redis.as_ref().map(|redis| {Arc::new(GlobalRateLimiter::new_ai_bytes(&config, vec![redis.clone()])@@ -369,7 +375,7 @@ pub async fn build_components(let v1_sink_router = if !config.capture_v1_sinks.is_empty() {Some(- create_v1_sink_router(&config, &sink_env, v1_sink_handles)+ create_v1_sink_router(&config, &env, v1_sink_handles).unwrap_or_else(|e| panic!("fatal: v1 sink router creation failed: {e:#}")),)} else {@@ -443,8 +449,8 @@ pub async fn build_components(/// guarantee.fn ai_events_overflow_valve(config: &Config) -> bool {let armed = config- .kafka- .capture_analytics_ai_events_overflow_topic+ .kafka_topics+ .ai_events_overflow.as_deref().is_some_and(|topic| !topic.is_empty());assert!(@@ -470,18 +476,18 @@ fn ai_byte_limit_per_second(config: &Config) -> u64 {/// body, builds the event, and the producer refuses it anyway, so the only/// thing the higher ceiling buys is a later failure. Both sides come from/// config, so the check stays correct when either knob moves.-fn ai_ceiling_exceeds_producer_cap(config: &Config) -> bool {+fn ai_ceiling_exceeds_producer_cap(config: &Config, producer_message_max_bytes: u32) -> bool {let ceiling = config.ai_max_event_bytes;// `0` disables the ceiling, so there is no ordering to be wrong about.- ceiling != 0 && ceiling >= config.kafka.kafka_producer_message_max_bytes as u64+ ceiling != 0 && ceiling >= producer_message_max_bytes as u64}-fn warn_if_ai_ceiling_exceeds_producer_cap(config: &Config) {- if ai_ceiling_exceeds_producer_cap(config) {+fn warn_if_ai_ceiling_exceeds_producer_cap(config: &Config, producer_message_max_bytes: u32) {+ if ai_ceiling_exceeds_producer_cap(config, producer_message_max_bytes) {warn!(ai_max_event_bytes = config.ai_max_event_bytes,- kafka_producer_message_max_bytes = config.kafka.kafka_producer_message_max_bytes,- "AI_MAX_EVENT_BYTES is at or above KAFKA_PRODUCER_MESSAGE_MAX_BYTES; \+ producer_message_max_bytes,+ "AI_MAX_EVENT_BYTES is at or above KAFKA_INGESTION_PRODUCER_MESSAGE_MAX_BYTES; \events between the producer cap and the ceiling are built and then \refused by the producer");@@ -511,7 +517,7 @@ fn v1_sinks_below_ai_ceiling(/// The v1-sink counterpart to [`warn_if_ai_ceiling_exceeds_producer_cap`].///-/// That check reads `KAFKA_PRODUCER_MESSAGE_MAX_BYTES`, which governs only the+/// That check reads `KAFKA_INGESTION_PRODUCER_MESSAGE_MAX_BYTES`, which governs only the/// v0 producer. Every v1 sink carries its own `message_max_bytes`/// (`CAPTURE_V1_SINK_<NAME>_KAFKA_MESSAGE_MAX_BYTES`, default 1MB), so a/// deployment whose AI traffic runs on a v1 sink can pass the v0 check with a@@ -570,11 +576,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.capture_analytics_ai_events_topic.clone();- cfg.kafka.topic_ai_overflow = config- .kafka- .capture_analytics_ai_events_overflow_topic- .clone();+ cfg.kafka.topic_ai = config.kafka_topics.ai_events.clone();+ cfg.kafka.topic_ai_overflow = config.kafka_topics.ai_events_overflow.clone();}warn_if_ai_ceiling_exceeds_v1_sink_caps(config, &sinks_cfg);@@ -616,55 +619,81 @@ fn create_v1_sink_router(async fn create_output_registry(config: &Config,+ producer_configs: &HashMap<ProducerName, ProducerConfig>,sink_handle: Option<lifecycle::Handle>,advisory_handle: Option<lifecycle::Handle>,) -> anyhow::Result<OutputRegistry> {- let output = create_output(config, sink_handle, advisory_handle).await?;+ let output = create_output(config, producer_configs, sink_handle, advisory_handle).await?;Ok(OutputRegistry::new(output))}async fn create_output(config: &Config,+ producer_configs: &HashMap<ProducerName, ProducerConfig>,sink_handle: Option<lifecycle::Handle>,advisory_handle: Option<lifecycle::Handle>,) -> anyhow::Result<Output> {if config.print_sink {- Ok(Output::single(PrintSink {}))- } else if config.noop_sink {+ return Ok(Output::single(PrintSink {}));+ }+ if config.noop_sink {info!("NoOpSink enabled, events will be silently dropped");- Ok(Output::single(NoOpSink::new()))- } else if config.s3_fallback_enabled {- let s3_handle = sink_handle.expect("sink lifecycle handle required for S3 fallback");- let kafka_handle = advisory_handle.expect("kafka advisory handle required for fallback");+ return Ok(Output::single(NoOpSink::new()));+ }- let kafka_sink = KafkaSink::new(config.kafka.clone(), Some(kafka_handle.clone()))- .await- .context("failed to start Kafka sink")?;-- let s3_sink = S3Sink::new(- config- .s3_fallback_bucket- .clone()- .expect("S3 bucket required when fallback enabled"),- config.s3_fallback_prefix.clone(),- config.s3_fallback_endpoint.clone(),- s3_handle,- )- .await- .expect("failed to create S3 sink");+ // 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);+ if config.outputs_completeness_check_enabled {+ topics.check_complete()?;+ } else {+ info!("outputs completeness check disabled; a blank output topic will fail at first produce instead of at boot");+ }- Ok(Output::failover(- Output::single(kafka_sink),- Output::single(s3_sink),- Some(kafka_handle),- ))+ // With the S3 fallback, the Kafka producer reports to the advisory handle+ // so an unhealthy primary never gates the pod.+ let kafka_handle = if config.s3_fallback_enabled {+ Some(advisory_handle.expect("kafka advisory handle required for fallback"))} else {- let kafka_sink = KafkaSink::new(config.kafka.clone(), sink_handle)- .await- .context("failed to start Kafka sink")?;+ sink_handle.clone()+ };+ let producers = ProducerRegistry::build(+ producer_configs,+ kafka_handle+ .clone()+ .map(|handle| (ProducerName::Ingestion, handle))+ .into_iter()+ .collect(),+ )+ .context("failed to start Kafka producers")?;+ let kafka_sink = KafkaSink::new(+ producers.get(ProducerName::Ingestion),+ topics,+ config.replay_envelope_compression,+ );- Ok(Output::single(kafka_sink))+ if !config.s3_fallback_enabled {+ return Ok(Output::single(kafka_sink));}++ let s3_handle = sink_handle.expect("sink lifecycle handle required for S3 fallback");+ let s3_sink = S3Sink::new(+ config+ .s3_fallback_bucket+ .clone()+ .expect("S3 bucket required when fallback enabled"),+ config.s3_fallback_prefix.clone(),+ config.s3_fallback_endpoint.clone(),+ s3_handle,+ )+ .await+ .expect("failed to create S3 sink");++ Ok(Output::failover(+ Output::single(kafka_sink),+ Output::single(s3_sink),+ kafka_handle,+ ))}// Fixed fire-and-forget tuning for the warnings producer. These are@@ -909,7 +938,6 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", "events"),- ("KAFKA_HOSTS", "v0-broker:9092"),("KAFKA_TOPIC", "events_plugin_ingestion"),("CAPTURE_INGESTION_WARNINGS_ENABLED",@@ -970,7 +998,6 @@ mod tests {let mut cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", input.capture_mode),- ("KAFKA_HOSTS", "localhost:9092"),("KAFKA_TOPIC", "events_plugin_ingestion"),].into_iter()@@ -1040,7 +1067,6 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", "events"),- ("KAFKA_HOSTS", "localhost:9092"),("KAFKA_TOPIC", "events_plugin_ingestion"),("GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS", "0"),]@@ -1070,7 +1096,6 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", "events"),- ("KAFKA_HOSTS", "localhost:9092"),("KAFKA_TOPIC", "events_plugin_ingestion"),("GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS", "180"),("AI_BYTE_LIMIT_WINDOW_INTERVAL_SECS", "0"),@@ -1113,7 +1138,6 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", "events"),- ("KAFKA_HOSTS", "localhost:9092"),("KAFKA_TOPIC", "events_plugin_ingestion"),("CAPTURE_V1_SINKS", "msk"),]@@ -1201,7 +1225,6 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", "events"),- ("KAFKA_HOSTS", "v0-broker:9092"),("KAFKA_TOPIC", "events_plugin_ingestion"),("KAFKA_CLIENT_INGESTION_WARNING_TOPIC", "v0-warnings-topic"),("CAPTURE_INGESTION_WARNINGS_ENABLED", "true"),@@ -1213,9 +1236,6 @@ mod tests {let config: Config =envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");- // The v0 block is populated, so a live fallback would have hosts to use;- // the dedicated hosts are empty, which is the only thing that should count.- assert_eq!(config.kafka.kafka_hosts, "v0-broker:9092");assert!(config.capture_ingestion_warnings_kafka_hosts.is_empty());let emitter = create_ingestion_warning_emitter(&config, None).await;@@ -1236,7 +1256,6 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", "events"),- ("KAFKA_HOSTS", "v0-broker:9092"),("KAFKA_TOPIC", "events_plugin_ingestion"),("CAPTURE_INGESTION_WARNINGS_ENABLED", "true"),]@@ -1287,17 +1306,17 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", mode.as_tag()),- ("KAFKA_HOSTS", "localhost:9092"),].into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();let mut config: Config =envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");- config.kafka.outputs_completeness_check_enabled = true;- config.kafka.kafka_dlq_topic = String::new();+ config.outputs_completeness_check_enabled = true;+ config.kafka_topics.dlq = String::new();+ let default_producers = producers::load_all(&HashMap::new()).expect("default producers");- let err = create_output_registry(&config, None, None)+ let err = create_output_registry(&config, &default_producers, None, None).await.err().expect("boot must be refused when an output topic is empty");@@ -1309,8 +1328,8 @@ mod tests {// The default: with the check off, the same blank topic boots (and// would fail at first produce instead).- config.kafka.outputs_completeness_check_enabled = false;- create_output_registry(&config, None, None)+ config.outputs_completeness_check_enabled = false;+ create_output_registry(&config, &default_producers, None, None).await.expect("boot must proceed when the completeness check is disabled");}@@ -1331,7 +1350,6 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", "ai"),- ("KAFKA_HOSTS", "localhost:9092"),("KAFKA_TOPIC", "events_plugin_ingestion_ai"),].into_iter()@@ -1340,12 +1358,14 @@ mod tests {let mut config: Config =envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");config.ai_max_event_bytes = ceiling;- config.kafka.kafka_producer_message_max_bytes = producer_cap;- assert_eq!(ai_ceiling_exceeds_producer_cap(&config), expected);+ assert_eq!(+ ai_ceiling_exceeds_producer_cap(&config, producer_cap),+ expected+ );}- /// The v0 check above reads `KAFKA_PRODUCER_MESSAGE_MAX_BYTES`, which a+ /// The v0 check above reads `KAFKA_INGESTION_PRODUCER_MESSAGE_MAX_BYTES`, which a/// v1-sink-only deployment never produces through. capture-ai is exactly/// that shape, so without this the AI ceiling is checked against a producer/// the deployment does not use while the sink that does the producing keeps@@ -1363,7 +1383,6 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", "ai"),- ("KAFKA_HOSTS", "localhost:9092"),("KAFKA_TOPIC", "events_plugin_ingestion_ai"),].into_iter()@@ -1374,7 +1393,7 @@ mod tests {config.ai_max_event_bytes = ceiling;// Raised well above the ceiling, so a v0-only check would say "clear"// and any flag below must have come from the v1 sink.- config.kafka.kafka_producer_message_max_bytes = 20_971_520;+ let v0_producer_cap = 20_971_520;let mut sink_cfg = crate::v1::sinks::Config {produce_timeout: std::time::Duration::from_secs(30),@@ -1389,7 +1408,7 @@ mod tests {};assert!(- !ai_ceiling_exceeds_producer_cap(&config),+ !ai_ceiling_exceeds_producer_cap(&config, v0_producer_cap),"v0 producer is raised, so only the v1 sink can be the offender");let offenders = v1_sinks_below_ai_ceiling(&config, &sinks_cfg);@@ -1415,7 +1434,6 @@ mod tests {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", mode.as_tag()),- ("KAFKA_HOSTS", "localhost:9092"),].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.rsindex 1205e620a28c..f0889ed0d741 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -18,10 +18,11 @@//! cost in the scatter-gather batch path at two `Arc::clone` calls (producer//! + topics) rather than deep copies of limiter state.use crate::api::CaptureError;-use crate::config::{EnvelopeCompression, KafkaConfig};+use crate::config::EnvelopeCompression;use crate::ordering::OrderingGuarantee;use crate::outputs::PublishEvents;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};@@ -29,13 +30,10 @@ use crate::sinks::sink::{fold_results, Outcome, PreparedPayload, Sink, SinkResuluse crate::v0_request::{DataType, ProcessedEvent};use async_trait::async_trait;use metrics::{counter, gauge, histogram};-use rdkafka::producer::{FutureProducer, Producer};-use rdkafka::util::Timeout;-use rdkafka::ClientConfig;use std::sync::Arc;-use std::time::{Duration, Instant};+use std::time::Instant;use tokio::task::JoinSet;-use tracing::log::{debug, error, info};+use tracing::log::error;use tracing::{info_span, instrument, Instrument};use super::producer::RdKafkaProducer;@@ -47,6 +45,12 @@ pub struct KafkaContext {liveness: Option<lifecycle::Handle>,}+impl KafkaContext {+ pub(crate) fn new(liveness: Option<lifecycle::Handle>) -> Self {+ Self { liveness }+ }+}+/// Emit min/avg/max/stddev plus p50/p90/p95/p99 for an rdkafka window stat/// (rtt, int_latency, outbuf_latency). Gauges are tagged with `quantile` and/// `broker` so existing dashboards keyed on `quantile` keep working and new@@ -238,146 +242,16 @@ fn dlq_reroute_effects(headers: &mut common_types::CapturedEventHeaders, reason:pub type KafkaSink = KafkaSinkBase<RdKafkaProducer<KafkaContext>>;impl KafkaSink {- pub async fn new(- config: KafkaConfig,- liveness: Option<lifecycle::Handle>,- ) -> anyhow::Result<KafkaSink> {- // Refuse to boot on incomplete output wiring: a blank topic fails- // here, at startup, instead of at first produce. Config-only, so it- // runs before the producer is built and the broker is pinged — the- // refusal is instant, not one connect attempt later.- let registry = TopicTable::from(&config);- if config.outputs_completeness_check_enabled {- registry.check_complete()?;- } else {- info!("outputs completeness check disabled; a blank output topic will fail at first produce instead of at boot");- }-- info!("connecting to Kafka brokers at {}...", config.kafka_hosts);-- let mut client_config = ClientConfig::new();- client_config- .set("bootstrap.servers", &config.kafka_hosts)- .set("statistics.interval.ms", "10000")- .set("partitioner", &config.kafka_producer_partitioner)- .set(- "metadata.max.age.ms",- config.kafka_metadata_max_age_ms.to_string(),- )- .set(- "topic.metadata.refresh.interval.ms",- config.kafka_topic_metadata_refresh_interval_ms.to_string(),- )- .set(- "message.send.max.retries",- config.kafka_producer_max_retries.to_string(),- )- .set("linger.ms", config.kafka_producer_linger_ms.to_string())- .set(- "message.max.bytes",- config.kafka_producer_message_max_bytes.to_string(),- )- .set(- "message.timeout.ms",- config.kafka_message_timeout_ms.to_string(),- )- .set(- "socket.timeout.ms",- config.kafka_socket_timeout_ms.to_string(),- )- .set("compression.codec", &config.kafka_compression_codec)- .set(- "queue.buffering.max.kbytes",- (config.kafka_producer_queue_mib * 1024).to_string(),- )- .set("acks", &config.kafka_producer_acks)- .set(- "batch.num.messages",- config.kafka_producer_batch_num_messages.to_string(),- )- .set("batch.size", config.kafka_producer_batch_size.to_string())- .set(- "max.in.flight.requests.per.connection",- config.kafka_producer_max_in_flight_requests.to_string(),- )- .set(- "sticky.partitioning.linger.ms",- config- .kafka_producer_sticky_partitioning_linger_ms- .to_string(),- )- .set(- "enable.idempotence",- config.kafka_producer_enable_idempotence.to_string(),- )- .set(- "log.connection.close",- config.kafka_log_connection_close.to_string(),- )- .set(- "queue.buffering.max.messages",- config- .kafka_producer_queue_buffering_max_messages- .to_string(),- )- .set(- "retry.backoff.max.ms",- config.kafka_retry_backoff_max_ms.to_string(),- )- .set(- "socket.send.buffer.bytes",- config.kafka_socket_send_buffer_bytes.to_string(),- )- .set(- "socket.receive.buffer.bytes",- config.kafka_socket_receive_buffer_bytes.to_string(),- );-- if !config.kafka_broker_address_family.is_empty() {- client_config.set("broker.address.family", &config.kafka_broker_address_family);- }-- if !&config.kafka_client_id.is_empty() {- client_config.set("client.id", &config.kafka_client_id);+ pub fn new(+ producer: ProducerHandle,+ topics: TopicTable,+ replay_envelope_compression: EnvelopeCompression,+ ) -> KafkaSink {+ KafkaSinkBase {+ producer,+ topics: Arc::new(topics),+ replay_envelope_compression,}-- if config.kafka_tls {- client_config- .set("security.protocol", "ssl")- .set("enable.ssl.certificate.verification", "false");- };-- debug!("rdkafka configuration: {client_config:?}");-- let producer: FutureProducer<KafkaContext> =- client_config.create_with_context(KafkaContext {- liveness: liveness.clone(),- })?;-- // Ping the cluster to make sure we can reach brokers, fail after 10 seconds- // Note: we don't error if we fail to connect as there may be other sinks that report healthy- if producer- .client()- .fetch_metadata(- Some("__consumer_offsets"),- Timeout::After(Duration::new(10, 0)),- )- .is_ok()- {- if let Some(liveness) = &liveness {- liveness.report_healthy();- }- info!("connected to Kafka brokers");- };-- let topics = Arc::new(registry);- let rd_producer = RdKafkaProducer::new(producer);-- Ok(KafkaSinkBase {- producer: Arc::new(rd_producer),- topics,- replay_envelope_compression: config.kafka_replay_envelope_compression,- })}}@@ -789,9 +663,10 @@ pub(crate) use crate::sinks::registry::test_topics;#[cfg(test)]mod tests {use crate::api::CaptureError;- use crate::config::{self, EnvelopeCompression};+ use crate::config::EnvelopeCompression;use crate::outputs::PublishEvents;- use crate::sinks::kafka::KafkaSink;+ use crate::producers::{self, ProducerName, ProducerRegistry};+ use crate::sinks::kafka::{test_topics, KafkaSink};use crate::utils::uuid_v7_from_datetime;use crate::v0_request::{DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata};use common_types::CapturedEvent;@@ -800,6 +675,7 @@ mod tests {use rdkafka::mocking::MockCluster;use rdkafka::producer::DefaultProducerContext;use rdkafka::types::{RDKafkaApiKey, RDKafkaRespErr};+ use std::collections::HashMap;use tokio_util::sync::CancellationToken;async fn start_on_mocked_sink(@@ -818,74 +694,27 @@ mod tests {);let _monitor = manager.monitor_background();let cluster = MockCluster::new(1).expect("failed to create mock brokers");- let config = config::KafkaConfig {- kafka_producer_linger_ms: 0,- kafka_producer_queue_mib: 50,- kafka_message_timeout_ms: 500,- kafka_topic_metadata_refresh_interval_ms: 20000,- kafka_producer_message_max_bytes: message_max_bytes.unwrap_or(1000000),- kafka_compression_codec: "none".to_string(),- kafka_hosts: cluster.bootstrap_servers(),- kafka_topic: "events_plugin_ingestion".to_string(),- kafka_overflow_topic: "events_plugin_ingestion_overflow".to_string(),- kafka_historical_topic: "events_plugin_ingestion_historical".to_string(),- kafka_client_ingestion_warning_topic: "events_plugin_ingestion".to_string(),- kafka_error_tracking_topic: "error_tracking_events".to_string(),- kafka_heatmaps_topic: "events_plugin_ingestion".to_string(),- kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),- kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),- outputs_completeness_check_enabled: true,- capture_analytics_ai_events_topic: "events_plugin_ingestion_ai".to_string(),- capture_analytics_ai_events_overflow_topic: None,- kafka_traces_topic: "traces_ingestion".to_string(),- kafka_metrics_topic: "metrics_ingestion".to_string(),- kafka_tls: false,- kafka_client_id: "".to_string(),- kafka_metadata_max_age_ms: 60000,- kafka_producer_max_retries: 2,- kafka_producer_acks: "all".to_string(),- kafka_socket_timeout_ms: 60000,- kafka_producer_batch_num_messages: 10000,- kafka_producer_batch_size: 1000000,- kafka_producer_max_in_flight_requests: 1000000,- kafka_producer_sticky_partitioning_linger_ms: 10,- kafka_producer_enable_idempotence: false,- kafka_producer_partitioner: "murmur2_random".to_string(),- kafka_broker_address_family: String::new(),- kafka_log_connection_close: true,- kafka_producer_queue_buffering_max_messages: 100000,- kafka_retry_backoff_max_ms: 1000,- kafka_socket_send_buffer_bytes: 0,- kafka_socket_receive_buffer_bytes: 0,- kafka_traces_hosts: None,- kafka_traces_tls: None,- kafka_traces_client_id: None,- kafka_traces_compression_codec: None,- kafka_traces_producer_acks: None,- kafka_traces_producer_linger_ms: None,- kafka_traces_producer_queue_mib: None,- kafka_traces_message_timeout_ms: None,- kafka_traces_producer_message_max_bytes: None,- kafka_traces_producer_max_retries: None,- kafka_traces_topic_metadata_refresh_interval_ms: None,- kafka_traces_metadata_max_age_ms: None,- kafka_metrics_hosts: None,- kafka_metrics_tls: None,- kafka_metrics_client_id: None,- kafka_metrics_compression_codec: None,- kafka_metrics_producer_acks: None,- kafka_metrics_producer_linger_ms: None,- kafka_metrics_producer_queue_mib: None,- kafka_metrics_message_timeout_ms: None,- kafka_metrics_producer_message_max_bytes: None,- kafka_metrics_producer_max_retries: None,- kafka_metrics_topic_metadata_refresh_interval_ms: None,- kafka_metrics_metadata_max_age_ms: None,- kafka_replay_envelope_compression: EnvelopeCompression::None,- };- let sink = KafkaSink::new(config, Some(handle))- .await- .expect("failed to create sink");+ let message_max_bytes = message_max_bytes.unwrap_or(1000000).to_string();+ let env: HashMap<String, String> = [+ ("METADATA_BROKER_LIST", cluster.bootstrap_servers()),+ ("LINGER_MS", "0".to_string()),+ ("QUEUE_BUFFERING_MAX_KBYTES", (50 * 1024).to_string()),+ ("MESSAGE_TIMEOUT_MS", "500".to_string()),+ ("MESSAGE_MAX_BYTES", message_max_bytes),+ ]+ .into_iter()+ .map(|(k, v)| (format!("KAFKA_INGESTION_PRODUCER_{k}"), v))+ .collect();+ let producers = ProducerRegistry::build(+ &producers::load_all(&env).expect("invalid producer config"),+ HashMap::from([(ProducerName::Ingestion, handle)]),+ )+ .expect("failed to create producer");+ let sink = KafkaSink::new(+ producers.get(ProducerName::Ingestion),+ test_topics(),+ EnvelopeCompression::None,+ );(cluster, sink)}diff --git a/rust/capture/src/sinks/registry.rs b/rust/capture/src/sinks/registry.rsindex 5177bfd21494..73b50af11714 100644--- a/rust/capture/src/sinks/registry.rs+++ b/rust/capture/src/sinks/registry.rs@@ -14,7 +14,7 @@//! and `AiOverflow` is the opt-in overflow valve — unset means routing never//! selects it.-use crate::config::KafkaConfig;+use crate::config::KafkaTopicsConfig;/// Which configured output a routing decision selects, named **pipeline +/// lane** — the vocabulary the refactor converges on (typed per-pipeline@@ -179,19 +179,19 @@ impl TopicTable {}}-impl From<&KafkaConfig> for TopicTable {- fn from(config: &KafkaConfig) -> Self {+impl From<&KafkaTopicsConfig> for TopicTable {+ fn from(config: &KafkaTopicsConfig) -> Self {Self {- main: config.kafka_topic.clone(),- overflow: config.kafka_overflow_topic.clone(),- historical: config.kafka_historical_topic.clone(),- client_ingestion_warning: config.kafka_client_ingestion_warning_topic.clone(),- heatmaps: config.kafka_heatmaps_topic.clone(),- replay_overflow: config.kafka_replay_overflow_topic.clone(),- dlq: config.kafka_dlq_topic.clone(),- error_tracking: config.kafka_error_tracking_topic.clone(),- ai_events: config.capture_analytics_ai_events_topic.clone(),- ai_events_overflow: config.capture_analytics_ai_events_overflow_topic.clone(),+ 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(),}}}diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex 31215d78f11a..942d2d286444 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -112,7 +112,7 @@ mod tests {use crate::config::EnvelopeCompression;- use crate::config::{CaptureMode, Config, KafkaConfig};+ use crate::config::{CaptureMode, Config, KafkaTopicsConfig};use crate::v1::analytics::types::{Event, Options, RawOptions};fn test_config() -> Config {@@ -165,71 +165,20 @@ mod tests {is_mirror_deploy: false,log_level: Level::INFO,verbose_sample_percent: 0.0,- kafka: KafkaConfig {- kafka_producer_linger_ms: 0,- kafka_producer_queue_mib: 10,- kafka_message_timeout_ms: 10000,- kafka_producer_message_max_bytes: 1000000,- kafka_topic_metadata_refresh_interval_ms: 10000,- kafka_compression_codec: "none".to_string(),- kafka_hosts: "kafka:9092".to_string(),- kafka_topic: "events_plugin_ingestion".to_string(),- kafka_overflow_topic: "events_plugin_ingestion_overflow".to_string(),- kafka_historical_topic: "events_plugin_ingestion_historical".to_string(),- kafka_client_ingestion_warning_topic: "events_plugin_ingestion".to_string(),- kafka_error_tracking_topic: "error_tracking_events".to_string(),- kafka_heatmaps_topic: "events_plugin_ingestion".to_string(),- kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),- kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),- outputs_completeness_check_enabled: true,- capture_analytics_ai_events_topic: "events_plugin_ingestion_ai".to_string(),- capture_analytics_ai_events_overflow_topic: None,- kafka_traces_topic: "ingestion_traces".to_string(),- kafka_metrics_topic: "ingestion_metrics".to_string(),- kafka_tls: false,- kafka_client_id: String::new(),- kafka_metadata_max_age_ms: 60000,- kafka_producer_max_retries: 2,- kafka_producer_acks: "all".to_string(),- kafka_socket_timeout_ms: 60000,- kafka_producer_batch_num_messages: 10000,- kafka_producer_batch_size: 1000000,- kafka_producer_max_in_flight_requests: 1000000,- kafka_producer_sticky_partitioning_linger_ms: 10,- kafka_producer_enable_idempotence: false,- kafka_producer_partitioner: "murmur2_random".to_string(),- kafka_broker_address_family: String::new(),- kafka_log_connection_close: true,- kafka_producer_queue_buffering_max_messages: 100000,- kafka_retry_backoff_max_ms: 1000,- kafka_socket_send_buffer_bytes: 0,- kafka_socket_receive_buffer_bytes: 0,- kafka_traces_hosts: None,- kafka_traces_tls: None,- kafka_traces_client_id: None,- kafka_traces_compression_codec: None,- kafka_traces_producer_acks: None,- kafka_traces_producer_linger_ms: None,- kafka_traces_producer_queue_mib: None,- kafka_traces_message_timeout_ms: None,- kafka_traces_producer_message_max_bytes: None,- kafka_traces_producer_max_retries: None,- kafka_traces_topic_metadata_refresh_interval_ms: None,- kafka_traces_metadata_max_age_ms: None,- kafka_metrics_hosts: None,- kafka_metrics_tls: None,- kafka_metrics_client_id: None,- kafka_metrics_compression_codec: None,- kafka_metrics_producer_acks: None,- kafka_metrics_producer_linger_ms: None,- kafka_metrics_producer_queue_mib: None,- kafka_metrics_message_timeout_ms: None,- kafka_metrics_producer_message_max_bytes: None,- kafka_metrics_producer_max_retries: None,- kafka_metrics_topic_metadata_refresh_interval_ms: None,- kafka_metrics_metadata_max_age_ms: None,- kafka_replay_envelope_compression: EnvelopeCompression::None,+ 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,},+ replay_envelope_compression: EnvelopeCompression::None,+ outputs_completeness_check_enabled: true,otel_url: None,otel_sampling_rate: 0.0,otel_service_name: "capture-testing".to_string(),diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex af76b9beef5c..b9a7c213d188 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -870,7 +870,6 @@ impl TestStateBuilder {let cfg_env: HashMap<String, String> = [("REDIS_URL", "redis://localhost:6379/"),("CAPTURE_MODE", "events"),- ("KAFKA_HOSTS", "localhost:9092"),("KAFKA_TOPIC", "events_plugin_ingestion"),].into_iter()diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 067e984d4cac..d8d7e9e40698 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -26,12 +26,28 @@ use tokio::net::TcpListener;use tokio::time::timeout;use tracing::{info, warn, Level};-use capture::config::{CaptureMode, Config, EnvelopeCompression, KafkaConfig};+use capture::config::{CaptureMode, Config, EnvelopeCompression, KafkaTopicsConfig};use capture::server::serve;use capture::setup;use common_continuous_profiling::ContinuousProfilingConfig;use limiters::redis::{QuotaResource, OVERFLOW_LIMITER_CACHE_KEY, QUOTA_LIMITER_CACHE_KEY};+pub const TEST_KAFKA_HOSTS: &str = "kafka:9092";++/// Settings for the `INGESTION` producer every test server publishes through.+pub fn test_producer_env() -> HashMap<String, String> {+ [+ ("METADATA_BROKER_LIST", TEST_KAFKA_HOSTS),+ ("LINGER_MS", "0"), // Send messages as soon as possible+ ("QUEUE_BUFFERING_MAX_KBYTES", "10240"),+ ("MESSAGE_TIMEOUT_MS", "10000"), // 10s, ACKs can be slow on low volumes, should be tuned+ ("TOPIC_METADATA_REFRESH_INTERVAL_MS", "10000"),+ ]+ .into_iter()+ .map(|(k, v)| (format!("KAFKA_INGESTION_PRODUCER_{k}"), v.to_string()))+ .collect()+}+pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {print_sink: false,noop_sink: false,@@ -83,71 +99,20 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {is_mirror_deploy: false,log_level: Level::INFO,verbose_sample_percent: 0.0_f32,- kafka: KafkaConfig {- kafka_producer_linger_ms: 0, // Send messages as soon as possible- kafka_producer_queue_mib: 10,- kafka_message_timeout_ms: 10000, // 10s, ACKs can be slow on low volumes, should be tuned- kafka_producer_message_max_bytes: 1000000, // 1MB, rdkafka default- kafka_topic_metadata_refresh_interval_ms: 10000,- kafka_compression_codec: "none".to_string(),- kafka_hosts: "kafka:9092".to_string(),- kafka_topic: "events_plugin_ingestion".to_string(),- kafka_overflow_topic: "events_plugin_ingestion_overflow".to_string(),- kafka_historical_topic: "events_plugin_ingestion_historical".to_string(),- kafka_client_ingestion_warning_topic: "events_plugin_ingestion".to_string(),- kafka_error_tracking_topic: "error_tracking_events".to_string(),- kafka_heatmaps_topic: "events_plugin_ingestion".to_string(),- kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),- kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),- outputs_completeness_check_enabled: true,- capture_analytics_ai_events_topic: "events_plugin_ingestion_ai".to_string(),- capture_analytics_ai_events_overflow_topic: None,- kafka_traces_topic: "ingestion_traces".to_string(),- kafka_metrics_topic: "ingestion_metrics".to_string(),- kafka_tls: false,- kafka_client_id: "".to_string(),- kafka_metadata_max_age_ms: 60000,- kafka_producer_max_retries: 2,- kafka_producer_acks: "all".to_string(),- kafka_socket_timeout_ms: 60000,- kafka_producer_batch_num_messages: 10000,- kafka_producer_batch_size: 1000000,- kafka_producer_max_in_flight_requests: 1000000,- kafka_producer_sticky_partitioning_linger_ms: 10,- kafka_producer_enable_idempotence: false,- kafka_producer_partitioner: "murmur2_random".to_string(),- kafka_broker_address_family: String::new(),- kafka_log_connection_close: true,- kafka_producer_queue_buffering_max_messages: 100000,- kafka_retry_backoff_max_ms: 1000,- kafka_socket_send_buffer_bytes: 0,- kafka_socket_receive_buffer_bytes: 0,- kafka_traces_hosts: None,- kafka_traces_tls: None,- kafka_traces_client_id: None,- kafka_traces_compression_codec: None,- kafka_traces_producer_acks: None,- kafka_traces_producer_linger_ms: None,- kafka_traces_producer_queue_mib: None,- kafka_traces_message_timeout_ms: None,- kafka_traces_producer_message_max_bytes: None,- kafka_traces_producer_max_retries: None,- kafka_traces_topic_metadata_refresh_interval_ms: None,- kafka_traces_metadata_max_age_ms: None,- kafka_metrics_hosts: None,- kafka_metrics_tls: None,- kafka_metrics_client_id: None,- kafka_metrics_compression_codec: None,- kafka_metrics_producer_acks: None,- kafka_metrics_producer_linger_ms: None,- kafka_metrics_producer_queue_mib: None,- kafka_metrics_message_timeout_ms: None,- kafka_metrics_producer_message_max_bytes: None,- kafka_metrics_producer_max_retries: None,- kafka_metrics_topic_metadata_refresh_interval_ms: None,- kafka_metrics_metadata_max_age_ms: None,- kafka_replay_envelope_compression: EnvelopeCompression::None,+ 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,},+ replay_envelope_compression: EnvelopeCompression::None,+ outputs_completeness_check_enabled: true,otel_url: None,otel_sampling_rate: 0.0,otel_service_name: "capture-testing".to_string(),@@ -190,7 +155,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {pub fn v1_sink_env_for_topic(sink: &str, topic: &str) -> HashMap<String, String> {let prefix = format!("CAPTURE_V1_SINK_{}_", sink.to_uppercase());[- ("KAFKA_HOSTS", DEFAULT_CONFIG.kafka.kafka_hosts.as_str()),+ ("KAFKA_HOSTS", TEST_KAFKA_HOSTS),("KAFKA_TOPIC_MAIN", topic),("KAFKA_TOPIC_HISTORICAL", topic),("KAFKA_TOPIC_OVERFLOW", topic),@@ -225,8 +190,8 @@ pub struct ServerHandle {impl ServerHandle {pub async fn for_topics(main: &EphemeralTopic, historical: &EphemeralTopic) -> Self {let mut config = DEFAULT_CONFIG.clone();- config.kafka.kafka_topic = main.topic_name().to_string();- config.kafka.kafka_historical_topic = historical.topic_name().to_string();+ config.kafka_topics.main = main.topic_name().to_string();+ config.kafka_topics.historical = historical.topic_name().to_string();Self::for_config(config).await}/// Like `for_topics`, with the synthetic ingestion warnings emitter enabled@@ -239,18 +204,17 @@ impl ServerHandle {warnings_topic: &EphemeralTopic,) -> Self {let mut config = DEFAULT_CONFIG.clone();- config.kafka.kafka_topic = main.topic_name().to_string();- config.kafka.kafka_historical_topic = historical.topic_name().to_string();+ config.kafka_topics.main = main.topic_name().to_string();+ config.kafka_topics.historical = historical.topic_name().to_string();config.capture_ingestion_warnings_enabled = true;- config.capture_ingestion_warnings_kafka_hosts = config.kafka.kafka_hosts.clone();- config.capture_ingestion_warnings_kafka_tls = config.kafka.kafka_tls;+ config.capture_ingestion_warnings_kafka_hosts = TEST_KAFKA_HOSTS.to_string();config.capture_ingestion_warnings_kafka_topic = warnings_topic.topic_name().to_string();Self::for_config(config).await}pub async fn for_recordings(main: &EphemeralTopic) -> Self {let mut config = DEFAULT_CONFIG.clone();- config.kafka.kafka_topic = main.topic_name().to_string();+ config.kafka_topics.main = main.topic_name().to_string();config.capture_mode = CaptureMode::Recordings;Self::for_config(config).await}@@ -264,11 +228,10 @@ impl ServerHandle {warnings_topic: &EphemeralTopic,) -> Self {let mut config = DEFAULT_CONFIG.clone();- config.kafka.kafka_topic = main.topic_name().to_string();+ config.kafka_topics.main = main.topic_name().to_string();config.capture_mode = CaptureMode::Recordings;config.capture_ingestion_warnings_enabled = true;- config.capture_ingestion_warnings_kafka_hosts = config.kafka.kafka_hosts.clone();- config.capture_ingestion_warnings_kafka_tls = config.kafka.kafka_tls;+ config.capture_ingestion_warnings_kafka_hosts = TEST_KAFKA_HOSTS.to_string();config.capture_ingestion_warnings_kafka_topic = warnings_topic.topic_name().to_string();Self::for_config(config).await}@@ -298,8 +261,7 @@ impl ServerHandle {config.capture_ingestion_warnings_enabled = true;// The emitter reads only its own dedicated config now (no v0 KAFKA_*// fallback), so point it at the same ephemeral broker as the main sink.- config.capture_ingestion_warnings_kafka_hosts = config.kafka.kafka_hosts.clone();- config.capture_ingestion_warnings_kafka_tls = config.kafka.kafka_tls;+ config.capture_ingestion_warnings_kafka_hosts = TEST_KAFKA_HOSTS.to_string();config.capture_ingestion_warnings_kafka_topic = warnings_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@@ -313,7 +275,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.capture_analytics_ai_events_topic = topic.topic_name().to_string();+ config.kafka_topics.ai_events = 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}@@ -324,8 +286,11 @@ impl ServerHandle {pub async fn for_config_with_sink_env(config: Config,- sink_env: HashMap<String, String>,+ mut sink_env: HashMap<String, String>,) -> Self {+ for (key, value) in test_producer_env() {+ sink_env.entry(key).or_insert(value);+ }let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let addr = listener.local_addr().unwrap();@@ -476,10 +441,7 @@ impl EphemeralTopic {let mut config = ClientConfig::new();let group_id = random_string("capture_it", 12);config.set("group.id", &group_id);- config.set(- "bootstrap.servers",- DEFAULT_CONFIG.kafka.kafka_hosts.clone(),- );+ config.set("bootstrap.servers", TEST_KAFKA_HOSTS);config.set("debug", "consumer,cgrp,topic,fetch");config.set("socket.timeout.ms", "30000");// RedPanda compatibility settings@@ -720,10 +682,7 @@ impl Drop for EphemeralTopic {async fn delete_topic(topic: String) {let mut config = ClientConfig::new();- config.set(- "bootstrap.servers",- DEFAULT_CONFIG.kafka.kafka_hosts.clone(),- );+ config.set("bootstrap.servers", TEST_KAFKA_HOSTS);let admin = AdminClient::from_config(&config).expect("failed to create admin client");admin.delete_topics(&[&topic], &AdminOptions::default())diff --git a/rust/capture/tests/events.rs b/rust/capture/tests/events.rsindex 03bd4ae148c2..af9e769dd65f 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.kafka_topic = main_topic.topic_name().to_string();- config.kafka.kafka_historical_topic = histo_topic.topic_name().to_string();- config.kafka.kafka_overflow_topic = overflow_topic.topic_name().to_string();+ 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.drop_events_by_token_distinct_id = Some(format!("{token}:{dropped_id}"));let server = ServerHandle::for_config(config).await;@@ -343,12 +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 sightconfig.ingestion_force_overflow_by_token_distinct_id = Some(format!("{token1},{key2}"));- config.kafka.kafka_hosts = "localhost:9092".to_string();- config.kafka.kafka_producer_linger_ms = 0; // Send messages immediately- config.kafka.kafka_message_timeout_ms = 10000; // 10s timeout- config.kafka.kafka_producer_max_retries = 3;- config.kafka.kafka_topic = topic.topic_name().to_string();- config.kafka.kafka_overflow_topic = overflow_topic.topic_name().to_string();+ config.kafka_topics.main = topic.topic_name().to_string();+ config.kafka_topics.overflow = 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();@@ -523,12 +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 sightconfig.ingestion_force_overflow_by_token_distinct_id = Some(format!("{token1},{key2}"));- config.kafka.kafka_hosts = "localhost:9092".to_string();- config.kafka.kafka_producer_linger_ms = 0; // Send messages immediately- config.kafka.kafka_message_timeout_ms = 10000; // 10s timeout- config.kafka.kafka_producer_max_retries = 3;- config.kafka.kafka_topic = topic.topic_name().to_string();- config.kafka.kafka_overflow_topic = overflow_topic.topic_name().to_string();+ config.kafka_topics.main = topic.topic_name().to_string();+ config.kafka_topics.overflow = overflow_topic.topic_name().to_string();config.overflow_enabled = true;config.overflow_preserve_partition_locality = true;config.overflow_burst_limit = NonZeroU32::new(10).unwrap();@@ -693,12 +685,8 @@ async fn it_should_not_set_force_disable_person_processing_header_when_rate_limilet mut config = DEFAULT_CONFIG.clone();// NO forced overflow keys - only rate limitingconfig.ingestion_force_overflow_by_token_distinct_id = None;- config.kafka.kafka_hosts = "localhost:9092".to_string();- config.kafka.kafka_producer_linger_ms = 0;- config.kafka.kafka_message_timeout_ms = 10000;- config.kafka.kafka_producer_max_retries = 3;- config.kafka.kafka_topic = topic.topic_name().to_string();- config.kafka.kafka_overflow_topic = overflow_topic.topic_name().to_string();+ config.kafka_topics.main = topic.topic_name().to_string();+ config.kafka_topics.overflow = overflow_topic.topic_name().to_string();config.overflow_enabled = true;// Very low limits to trigger rate-based overflowconfig.overflow_burst_limit = NonZeroU32::new(1).unwrap();@@ -781,12 +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.kafka_hosts = "localhost:9092".to_string();- config.kafka.kafka_producer_linger_ms = 0; // Send messages immediately- config.kafka.kafka_message_timeout_ms = 10000; // 10s timeout- config.kafka.kafka_producer_max_retries = 3;- config.kafka.kafka_topic = topic.topic_name().to_string();- config.kafka.kafka_historical_topic = historical_topic.topic_name().to_string();+ config.kafka_topics.main = topic.topic_name().to_string();+ config.kafka_topics.historical = 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();@@ -858,12 +842,8 @@ async fn it_overflows_events_on_burst() -> Result<()> {let overflow_topic = EphemeralTopic::new().await;let mut config = DEFAULT_CONFIG.clone();- config.kafka.kafka_hosts = "localhost:9092".to_string();- config.kafka.kafka_producer_linger_ms = 0; // Send messages immediately- config.kafka.kafka_message_timeout_ms = 10000; // 10s timeout- config.kafka.kafka_producer_max_retries = 3;- config.kafka.kafka_topic = topic.topic_name().to_string();- config.kafka.kafka_overflow_topic = overflow_topic.topic_name().to_string();+ config.kafka_topics.main = topic.topic_name().to_string();+ config.kafka_topics.overflow = 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();@@ -926,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.kafka_topic = topic.topic_name().to_string();+ config.kafka_topics.main = 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();@@ -970,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.kafka_topic = topic.topic_name().to_string();- config.kafka.kafka_overflow_topic = overflow_topic.topic_name().to_string();+ config.kafka_topics.main = topic.topic_name().to_string();+ config.kafka_topics.overflow = 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();@@ -1114,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.kafka_topic = topic.topic_name().to_string();+ config.kafka_topics.main = topic.topic_name().to_string();let server = ServerHandle::for_config(config).await;for payload in [@@ -1168,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.kafka_topic = main_topic.topic_name().to_string();- config.kafka.kafka_client_ingestion_warning_topic = warnings_topic.topic_name().to_string();- config.kafka.kafka_error_tracking_topic = error_tracking_topic.topic_name().to_string();- config.kafka.kafka_heatmaps_topic = heatmaps_topic.topic_name().to_string();+ 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();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.rsindex 6ebc1f664fbf..c31daf3dc817 100644--- a/rust/capture/tests/integration_person_processing_matrix.rs+++ b/rust/capture/tests/integration_person_processing_matrix.rs@@ -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));+ let sink = KafkaSinkBase::with_producer(producer.clone(), TopicTable::from(&cfg.kafka_topics));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.rsindex 2062b0223993..a1d969809fd7 100644--- a/rust/capture/tests/recordings.rs+++ b/rust/capture/tests/recordings.rs@@ -381,9 +381,8 @@ async fn it_applies_overflow_limits() -> Result<()> {let mut config = DEFAULT_CONFIG.clone();config.redis_key_prefix = redis.key_prefix();- config.kafka.kafka_topic = topic.topic_name().to_string();- config.kafka.kafka_replay_overflow_topic = overflow_topic.topic_name().to_string();- config.kafka.kafka_replay_overflow_topic = overflow_topic.topic_name().to_string();+ config.kafka_topics.main = topic.topic_name().to_string();+ config.kafka_topics.replay_overflow = 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.rsindex dfeddca10612..050b16bae25a 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.kafka_topic = main_topic.topic_name().to_string();- config.kafka.kafka_dlq_topic = dlq_topic.topic_name().to_string();+ config.kafka_topics.main = main_topic.topic_name().to_string();+ config.kafka_topics.dlq = 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.kafka_topic = main_topic.topic_name().to_string();+ config.kafka_topics.main = 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.kafka_topic = main_topic.topic_name().to_string();- config.kafka.capture_analytics_ai_events_topic = ai_topic.topic_name().to_string();+ config.kafka_topics.main = main_topic.topic_name().to_string();+ config.kafka_topics.ai_events = ai_topic.topic_name().to_string();let server = ServerHandle::for_config(config).await;let batch = json!([@@ -234,10 +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.kafka_topic = main_topic.topic_name().to_string();- config.kafka.capture_analytics_ai_events_topic = ai_topic.topic_name().to_string();- config.kafka.capture_analytics_ai_events_overflow_topic =- Some(ai_overflow_topic.topic_name().to_string());+ 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.overflow_enabled = true;config.overflow_burst_limit = NonZeroU32::new(10).unwrap();config.overflow_per_second_limit = NonZeroU32::new(10).unwrap();