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 v1): KafkaProducer implementation and test suite (#53647)

Eli Reisman8e2b9459352e
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index ae675fd89d41..38af843a76a1 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1718,6 +1718,7 @@ dependencies = [
"base64 0.22.1",
"brotli",
"bytes",
+ "capture",
"chrono",
"common-alloc",
"common-continuous-profiling",
diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.toml
index 8520d46043e5..2fc9a4d35743 100644
--- a/rust/capture/Cargo.toml
+++ b/rust/capture/Cargo.toml
@@ -4,6 +4,9 @@ version = "0.1.0"
edition = "2021"
publish = false
+[features]
+test-utils = []
+
[lints]
workspace = true
@@ -59,6 +62,7 @@ futures = { workspace = true }
sha2 = { workspace = true }
[dev-dependencies]
+capture = { path = ".", features = ["test-utils"] }
assert-json-diff = { workspace = true }
brotli = "8"
zstd = "0.13"
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index 31265f776e0c..0365ab33c32f 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -91,11 +91,12 @@ fn validate_events(context: &Context, batch: Batch) -> Result<HashMap<Uuid, Wrap
uuid,
WrappedEvent {
event,
+ uuid,
adjusted_timestamp: Some(adjusted),
result: EventResult::Ok,
details: None,
destination: Destination::default(),
- skip_person_processing: false,
+ force_disable_person_processing: false,
},
);
}
@@ -104,11 +105,12 @@ fn validate_events(context: &Context, batch: Batch) -> Result<HashMap<Uuid, Wrap
uuid,
WrappedEvent {
event,
+ uuid,
adjusted_timestamp: None,
result: EventResult::Drop,
details: Some(err.tag()),
destination: Destination::default(),
- skip_person_processing: false,
+ force_disable_person_processing: false,
},
);
}
@@ -285,7 +287,7 @@ async fn apply_restrictions(
}
if applied.skip_person_processing() {
- event.skip_person_processing = true;
+ event.force_disable_person_processing = true;
}
}
}
@@ -306,7 +308,7 @@ async fn apply_token_distinct_id_limits(
GlobalRateLimitKey::TokenDistinctId(&context.api_token, &event.event.distinct_id)
.to_cache_key();
if limiter.is_limited(&cache_key, 1).await.is_some() {
- event.skip_person_processing = true;
+ event.force_disable_person_processing = true;
event.details = Some(DETAIL_RATE_LIMITED_TOKEN_DISTINCT_ID);
limited_distinct_ids.insert(event.event.distinct_id.as_str());
} else {
@@ -824,7 +826,7 @@ mod tests {
let ev = find_by_did(&events, "user-1");
assert_eq!(ev.result, EventResult::Ok);
assert_eq!(ev.destination, Destination::AnalyticsMain);
- assert!(!ev.skip_person_processing);
+ assert!(!ev.force_disable_person_processing);
}
#[tokio::test]
@@ -952,7 +954,7 @@ mod tests {
}
#[tokio::test]
- async fn restrictions_skip_person_processing() {
+ async fn restrictions_force_disable_person_processing() {
let service = restriction_service(
"phc_token",
vec![Restriction {
@@ -971,7 +973,7 @@ mod tests {
let ev = find_by_did(&events, "user-1");
assert_eq!(ev.result, EventResult::Ok);
assert_eq!(ev.destination, Destination::AnalyticsMain);
- assert!(ev.skip_person_processing);
+ assert!(ev.force_disable_person_processing);
}
#[tokio::test]
@@ -1133,7 +1135,7 @@ mod tests {
let limited_ev = find_by_did(&events, "user-2");
assert_eq!(limited_ev.result, EventResult::Ok);
assert_eq!(limited_ev.destination, Destination::AnalyticsMain);
- assert!(limited_ev.skip_person_processing);
+ assert!(limited_ev.force_disable_person_processing);
assert_eq!(
limited_ev.details,
Some(DETAIL_RATE_LIMITED_TOKEN_DISTINCT_ID)
@@ -1173,7 +1175,10 @@ mod tests {
Destination::AnalyticsMain,
"should stay on main topic"
);
- assert!(ev.skip_person_processing, "should skip person processing");
+ assert!(
+ ev.force_disable_person_processing,
+ "should skip person processing"
+ );
assert_eq!(
ev.details,
Some(DETAIL_RATE_LIMITED_TOKEN_DISTINCT_ID),
@@ -1187,7 +1192,7 @@ mod tests {
let limiter = mock_limiter(vec!["phc_tok:user-2"]);
let ctx = td_context();
let pre_drop = wrapped_event("$pageview", "user-1");
- let pre_drop_uuid = Uuid::parse_str(pre_drop.event.uuid()).unwrap();
+ let pre_drop_uuid = pre_drop.uuid;
let mut events = events_map(vec![pre_drop, wrapped_event("$identify", "user-2")]);
// Simulate event already dropped by restrictions
events.get_mut(&pre_drop_uuid).unwrap().result = EventResult::Drop;
@@ -1203,7 +1208,7 @@ mod tests {
let limited = find_by_did(&events, "user-2");
assert_eq!(limited.result, EventResult::Ok);
assert_eq!(limited.destination, Destination::AnalyticsMain);
- assert!(limited.skip_person_processing);
+ assert!(limited.force_disable_person_processing);
assert_eq!(limited.details, Some(DETAIL_RATE_LIMITED_TOKEN_DISTINCT_ID));
}
@@ -1271,14 +1276,14 @@ mod tests {
let mut ctx = test_utils::test_context();
ctx.historical_migration = true;
let ev = wrapped_event("$pageview", "user-1");
- let uuid = Uuid::parse_str(ev.event.uuid()).unwrap();
+ let ev_uuid = ev.uuid;
let mut events = events_map(vec![ev]);
- events.get_mut(&uuid).unwrap().destination = Destination::Overflow;
+ events.get_mut(&ev_uuid).unwrap().destination = Destination::Overflow;
apply_historical_rerouting(&cfg, &ctx, &mut events);
assert_eq!(
- events.get(&uuid).unwrap().destination,
+ events.get(&ev_uuid).unwrap().destination,
Destination::Overflow
);
}
@@ -1289,15 +1294,15 @@ mod tests {
let mut ctx = test_utils::test_context();
ctx.historical_migration = true;
let ev = wrapped_event("$pageview", "user-1");
- let uuid = Uuid::parse_str(ev.event.uuid()).unwrap();
+ let ev_uuid = ev.uuid;
let mut events = events_map(vec![ev]);
- let e = events.get_mut(&uuid).unwrap();
+ let e = events.get_mut(&ev_uuid).unwrap();
e.result = EventResult::Drop;
e.destination = Destination::Drop;
apply_historical_rerouting(&cfg, &ctx, &mut events);
- assert_eq!(events.get(&uuid).unwrap().destination, Destination::Drop);
+ assert_eq!(events.get(&ev_uuid).unwrap().destination, Destination::Drop);
}
#[test]
@@ -1319,7 +1324,7 @@ mod tests {
let mut ctx = test_utils::test_context();
ctx.historical_migration = true;
let dlq_ev = wrapped_event("$identify", "user-2");
- let dlq_uuid = Uuid::parse_str(dlq_ev.event.uuid()).unwrap();
+ let dlq_uuid = dlq_ev.uuid;
let mut events = events_map(vec![wrapped_event("$pageview", "user-1"), dlq_ev]);
events.get_mut(&dlq_uuid).unwrap().destination = Destination::Dlq;
diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rs
index 42b59c59e3a4..d39ed71f7578 100644
--- a/rust/capture/src/v1/analytics/types.rs
+++ b/rust/capture/src/v1/analytics/types.rs
@@ -1,9 +1,29 @@
-use chrono::{DateTime, Utc};
-use common_types::HasEventName;
+use std::io;
+use std::ops::Not;
+
+use chrono::{DateTime, SecondsFormat, Utc};
+use common_types::{CapturedEventHeaders, HasEventName};
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use uuid::Uuid;
+/// Safe adapter for writing serde_json output into a `String` buffer.
+/// `from_utf8` on serde_json output is essentially free (JSON mandates UTF-8).
+struct StringWriter<'a>(&'a mut String);
+
+impl io::Write for StringWriter<'_> {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ let s = std::str::from_utf8(buf).map_err(io::Error::other)?;
+ self.0.push_str(s);
+ Ok(buf.len())
+ }
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+use crate::v1::context::Context;
+use crate::v1::sinks::event::Event as SinkEvent;
use crate::v1::sinks::Destination;
fn empty_raw_object() -> Box<RawValue> {
@@ -27,7 +47,7 @@ pub struct Batch {
pub created_at: String,
#[serde(default)]
pub historical_migration: bool,
- #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(default)]
pub capture_internal: Option<bool>,
pub batch: Vec<Event>,
}
@@ -50,9 +70,7 @@ pub struct Event {
pub uuid: String,
pub distinct_id: String,
pub timestamp: String,
- #[serde(skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
pub window_id: Option<String>,
pub options: Options,
#[serde(default = "empty_raw_object")]
@@ -70,12 +88,245 @@ impl Event {
#[derive(Debug)]
pub struct WrappedEvent {
pub event: Event,
+ /// Pre-parsed UUID from Event.uuid, set once during validate_events.
+ pub uuid: Uuid,
// Post-skew-adjustment timestamp for Kafka export, None if event is malformed
pub adjusted_timestamp: Option<DateTime<Utc>>,
pub result: EventResult,
pub details: Option<&'static str>,
pub destination: Destination,
- pub skip_person_processing: bool,
+ pub force_disable_person_processing: bool,
+}
+
+impl SinkEvent for WrappedEvent {
+ // Pre-parsed UUID for result correlation. By the Sink stage,
+ // we know ALL well-formed incoming events have a valid UUID.
+ fn uuid(&self) -> Uuid {
+ self.uuid
+ }
+
+ // Helps the Sink implementations filter events that were marked
+ // as ineligible for publishing in the request preprocessing step.
+ fn should_publish(&self) -> bool {
+ self.result == EventResult::Ok && self.destination != Destination::Drop
+ }
+
+ // Resolve the storage-agnostic Destination scope for this event.
+ // The config for each Sink implementation knows how to resolve
+ // these to topics (etc.) depending on the sink type
+ fn destination(&self) -> &Destination {
+ &self.destination
+ }
+
+ // Returns the full typed header set for this event, combining per-request
+ // context fields (token, now, historical_migration) with event-owned
+ // fields. Sinks convert the returned CapturedEventHeaders to their
+ // backend-specific format (e.g. OwnedHeaders for Kafka) via the From impl
+ // in common_types — same conversion legacy capture uses.
+ fn headers(&self, ctx: &Context) -> CapturedEventHeaders {
+ // v0 compat: downstream consumers key on "force_disable_person_processing".
+ // v1 decouples overflow routing from person-processing (unlike v0 where
+ // overflow ForceLimited unconditionally sets this); operators configure
+ // this flag alongside ForceOverflow when needed.
+ let force_disable_person_processing = if self.force_disable_person_processing {
+ Some(true)
+ } else {
+ None
+ };
+
+ // historical_migration header follows legacy CapturedEvent::to_headers()
+ // convention: emitted only when enabled for the batch.
+ let historical_migration = if ctx.historical_migration {
+ Some(true)
+ } else {
+ None
+ };
+
+ let (dlq_reason, dlq_step, dlq_timestamp) = if self.destination == Destination::Dlq {
+ (
+ Some("event_restriction".to_string()),
+ Some("capture".to_string()),
+ Some(Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true)),
+ )
+ } else {
+ (None, None, None)
+ };
+
+ CapturedEventHeaders {
+ token: Some(ctx.api_token.clone()),
+ distinct_id: Some(self.event.distinct_id.clone()),
+ session_id: self.event.session_id.clone(),
+ timestamp: self
+ .adjusted_timestamp
+ .map(|ts| ts.timestamp_millis().to_string()),
+ event: Some(self.event.event.clone()),
+ uuid: Some(self.event.uuid().to_owned()),
+ now: Some(
+ ctx.server_received_at
+ .to_rfc3339_opts(SecondsFormat::AutoSi, true),
+ ),
+ force_disable_person_processing,
+ historical_migration,
+ dlq_reason,
+ dlq_step,
+ dlq_timestamp,
+ }
+ }
+
+ fn partition_key<'buf>(&self, ctx: &Context, buf: &'buf mut String) -> Option<&'buf str> {
+ use std::fmt::Write;
+ // v0 parity: only drop partition key for main/overflow analytics.
+ // DLQ, Historical, and Custom destinations always retain their key
+ // even when person processing is disabled via event restrictions.
+ if self.force_disable_person_processing
+ && matches!(
+ self.destination,
+ Destination::AnalyticsMain | Destination::Overflow
+ )
+ {
+ return None;
+ }
+ match (
+ self.event.options.cookieless_mode == Some(true),
+ ctx.capture_internal,
+ ) {
+ (true, true) => {
+ let _ = write!(buf, "{}:127.0.0.1", ctx.api_token);
+ }
+ (true, false) => {
+ let _ = write!(buf, "{}:{}", ctx.api_token, ctx.client_ip);
+ }
+ (false, _) => {
+ let _ = write!(buf, "{}:{}", ctx.api_token, self.event.distinct_id);
+ }
+ }
+ Some(buf.as_str())
+ }
+
+ fn serialize_into(&self, ctx: &Context, buf: &mut String) -> anyhow::Result<()> {
+ let spliced = self.build_spliced_properties()?;
+ let properties: &RawValue = spliced.as_deref().unwrap_or(&self.event.properties);
+ let ingestion_data = IngestionData {
+ event: &self.event.event,
+ distinct_id: Some(&self.event.distinct_id),
+ uuid: Some(self.uuid),
+ properties,
+ timestamp: Some(&self.event.timestamp),
+ };
+ let data = serde_json::to_string(&ingestion_data)
+ .map_err(|e| anyhow::anyhow!("serializing IngestionData: {e:#}"))?;
+
+ let ip;
+ let ip_ref: &str = if ctx.capture_internal {
+ "127.0.0.1"
+ } else {
+ ip = ctx.client_ip.to_string();
+ &ip
+ };
+ let timestamp = self.adjusted_timestamp.ok_or_else(|| {
+ anyhow::anyhow!("serialize_into called on event without adjusted_timestamp")
+ })?;
+ let now = ctx
+ .server_received_at
+ .to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true);
+ let ie = IngestionEvent {
+ uuid: self.uuid,
+ distinct_id: &self.event.distinct_id,
+ ip: ip_ref,
+ data: &data,
+ now: &now,
+ sent_at: Some(ctx.client_timestamp),
+ token: &ctx.api_token,
+ event: &self.event.event,
+ timestamp,
+ is_cookieless_mode: self.event.options.cookieless_mode.unwrap_or(false),
+ historical_migration: ctx.historical_migration,
+ };
+
+ serde_json::to_string(&ie)
+ .map(|s| buf.push_str(&s))
+ .map_err(|e| anyhow::anyhow!("serializing IngestionEvent: {e:#}"))
+ }
+}
+
+impl WrappedEvent {
+ #[allow(unused_assignments)]
+ fn build_property_injections(&self) -> anyhow::Result<String> {
+ let mut buf = String::with_capacity(256);
+ let mut first = true;
+
+ macro_rules! inject {
+ ($buf:expr, $first:expr, $key:expr, $val:expr) => {{
+ if !$first {
+ $buf.push(',');
+ }
+ $first = false;
+ $buf.push('"');
+ $buf.push_str($key);
+ $buf.push_str("\":");
+ serde_json::to_writer(StringWriter(&mut $buf), $val)
+ .map_err(|e| anyhow::anyhow!("injecting {}: {e:#}", $key))?;
+ }};
+ }
+
+ if let Some(ref sid) = self.event.session_id {
+ inject!(buf, first, "$session_id", sid);
+ }
+ if let Some(ref wid) = self.event.window_id {
+ inject!(buf, first, "$window_id", wid);
+ }
+ if let Some(cm) = self.event.options.cookieless_mode {
+ inject!(buf, first, "$cookieless_mode", &cm);
+ }
+ if let Some(dsa) = self.event.options.disable_skew_adjustment {
+ inject!(buf, first, "$ignore_sent_at", &dsa);
+ }
+ if let Some(ref pti) = self.event.options.product_tour_id {
+ inject!(buf, first, "$product_tour_id", pti);
+ }
+ if let Some(ppp) = self.event.options.process_person_profile {
+ inject!(buf, first, "$process_person_profile", &ppp);
+ }
+
+ Ok(buf)
+ }
+
+ /// Build spliced properties if injection is needed, or return None
+ /// to signal the caller should borrow `self.event.properties` directly.
+ fn build_spliced_properties(&self) -> anyhow::Result<Option<Box<RawValue>>> {
+ let injection = self.build_property_injections()?;
+ if injection.is_empty() {
+ return Ok(None);
+ }
+
+ let raw = self.event.properties.get();
+ if !raw.starts_with('{') {
+ return Err(anyhow::anyhow!(
+ "properties must be a JSON object for injection, got: {:.32}",
+ raw,
+ ));
+ }
+ if raw.len() < 2 {
+ return Err(anyhow::anyhow!(
+ "properties too short ({} bytes) for JSON object",
+ raw.len()
+ ));
+ }
+ let prefix = &raw[..raw.len() - 1];
+ let has_existing = !raw[1..].trim_start().starts_with('}');
+
+ let mut buf = String::with_capacity(raw.len() + injection.len() + 2);
+ buf.push_str(prefix);
+ if has_existing {
+ buf.push(',');
+ }
+ buf.push_str(&injection);
+ buf.push('}');
+
+ RawValue::from_string(buf)
+ .map(Some)
+ .map_err(|e| anyhow::anyhow!("property surgery produced invalid JSON: {e:#}"))
+ }
}
/// Shim implementation of HasEventName for CaptureQuotaLimiter compatibility.
@@ -97,53 +348,52 @@ impl HasEventName for WrappedEvent {
}
}
-/// The Kafka-ready event produced by the v1 analytics pipeline.
-/// Replaces legacy `CapturedEvent` from `common_types`.
-///
-/// Constructed from a valid `WrappedEvent` + request `Context` in a future
-/// transformation step within `process_batch`, before being handed to a
-/// `v1::Sink` for publishing. The sink should not perform any enrichment
-/// or property inspection -- all transformations happen at construction time.
+/// The Kafka payload produced by `WrappedEvent::serialize_into`.
///
-/// Checks needed at construction time (from legacy parity):
-/// - `Context.capture_internal`: if true, redact `ip` to "127.0.0.1"
-/// AND force the Kafka partition key to `token:127.0.0.1` to match
-/// the IP redaction (otherwise the key references a real IP while the
-/// payload carries a redacted one). See `CapturedEvent::key()` in
-/// `common_types/event.rs` for the v0 key derivation pattern.
-/// - `Options.cookieless_mode`: controls Kafka partition key selection
-/// (true -> partition by token:ip, false -> token:distinct_id).
-/// Non-boolean values are rejected at deserialization by serde.
+/// Field order matches `CapturedEvent` from `common_types` so that serde's
+/// derived `Serialize` emits JSON keys in the same order as v0. Serde
+/// annotations (`skip_serializing_if`) also match CapturedEvent exactly.
///
-/// Will implement the upcoming `v1::Sink` trait to abstract serialization
-/// and partition key derivation.
-// TODO(v1::Sink): when publishing to Kafka, re-apply `$` prefixes to these
-// fields for legacy consumer compatibility:
-// Event: session_id -> $session_id, window_id -> $window_id
-// Options: cookieless_mode -> $cookieless_mode,
-// disable_skew_adjustment -> $disable_skew_adjustment,
-// product_tour_id -> $product_tour_id,
-// process_person_profile -> $process_person_profile
+/// Borrows from `WrappedEvent` and `Context` to avoid per-event heap
+/// allocations -- the struct is created, serialized, and dropped within
+/// a single `serialize_into` call.
#[derive(Debug, Serialize)]
-pub struct IngestionEvent {
- pub uuid: String,
- pub distinct_id: String,
- pub ip: String,
- pub event: String,
+pub struct IngestionEvent<'a> {
+ pub uuid: Uuid,
+ pub distinct_id: &'a str,
+ pub ip: &'a str,
+ pub data: &'a str,
+ pub now: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sent_at: Option<DateTime<Utc>>,
+ pub token: &'a str,
+ pub event: &'a str,
pub timestamp: DateTime<Utc>,
- pub token: String,
+ #[serde(skip_serializing_if = "<&bool>::not", default)]
pub is_cookieless_mode: bool,
- // TODO: custom build this serialized JSON from Event's raw payload
- // and inject event.options including legacy $-prefixes
- pub data: String,
- pub now: String,
- #[serde(skip)]
- pub destination: Destination,
- #[serde(skip)]
- pub skip_person_processing: bool,
- /// Maps back to the originating WrappedEvent via HashMap key for result tracking.
- #[serde(skip)]
- pub uuid_key: Uuid,
+ #[serde(skip_serializing_if = "<&bool>::not", default)]
+ pub historical_migration: bool,
+}
+
+/// The inner `data` payload: a simplified RawEvent-shaped struct for
+/// constructing the double-encoded JSON in `IngestionEvent.data`.
+///
+/// Omitted vs RawEvent:
+/// - `token`: v1 uses Authorization header; downstream handles absence
+/// - `offset`: dead field; Node.js ingestion parses but never reads it
+/// - `$set`/`$set_once` at top level: legacy Python SDK cruft; v1 schema
+/// does not support these at top level (clients send them inside
+/// `properties`, where they pass through the opaque blob as-is)
+#[derive(Debug, Serialize)]
+pub struct IngestionData<'a> {
+ pub event: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub distinct_id: Option<&'a str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub uuid: Option<Uuid>,
+ pub properties: &'a RawValue,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub timestamp: Option<&'a str>,
}
#[cfg(test)]
@@ -440,4 +690,860 @@ mod tests {
let garbage = b"this is not json at all {{{";
assert!(serde_json::from_slice::<Batch>(garbage).is_err());
}
+
+ // --- SinkEvent impl for WrappedEvent ---
+
+ use crate::v1::sinks::event::Event as SinkEventTrait;
+ use crate::v1::sinks::Destination;
+ use crate::v1::test_utils;
+ use common_types::HasEventName;
+
+ fn ok_wrapped(event_name: &str, distinct_id: &str) -> WrappedEvent {
+ test_utils::wrapped_event(event_name, distinct_id)
+ }
+
+ #[test]
+ fn should_publish_ok_and_non_drop() {
+ let ev = ok_wrapped("$pageview", "user-1");
+ assert!(ev.should_publish());
+ }
+
+ #[test]
+ fn should_publish_false_when_dropped() {
+ let mut ev = ok_wrapped("$pageview", "user-1");
+ ev.result = EventResult::Drop;
+ assert!(!ev.should_publish());
+ }
+
+ #[test]
+ fn should_publish_false_when_destination_drop() {
+ let mut ev = ok_wrapped("$pageview", "user-1");
+ ev.destination = Destination::Drop;
+ assert!(!ev.should_publish());
+ }
+
+ #[test]
+ fn should_publish_false_when_limited() {
+ let mut ev = ok_wrapped("$pageview", "user-1");
+ ev.result = EventResult::Limited;
+ assert!(!ev.should_publish());
+ }
+
+ #[test]
+ fn headers_base_fields_always_present() {
+ let ctx = test_utils::test_context();
+ let ev = ok_wrapped("$pageview", "user-1");
+ let h = ev.headers(&ctx);
+ assert_eq!(h.distinct_id.as_deref(), Some("user-1"));
+ assert_eq!(h.event.as_deref(), Some("$pageview"));
+ assert!(h.uuid.is_some());
+ assert!(h.timestamp.is_some());
+ assert!(h.force_disable_person_processing.is_none());
+ assert!(h.session_id.is_none());
+ assert!(h.dlq_reason.is_none());
+ }
+
+ #[test]
+ fn headers_timestamp_is_millis_epoch() {
+ let ctx = test_utils::test_context();
+ let ev = ok_wrapped("$pageview", "user-1");
+ let h = ev.headers(&ctx);
+ let ts_str = h.timestamp.expect("timestamp should be set");
+ let ts_millis: i64 = ts_str.parse().expect("timestamp should be numeric millis");
+ assert_eq!(ts_millis, ev.adjusted_timestamp.unwrap().timestamp_millis());
+ }
+
+ #[test]
+ fn headers_omit_timestamp_when_none() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-1");
+ ev.adjusted_timestamp = None;
+ let h = ev.headers(&ctx);
+ assert!(h.timestamp.is_none());
+ }
+
+ #[test]
+ fn headers_include_session_id_when_present() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-1");
+ ev.event.session_id = Some("sess-abc".to_string());
+ let h = ev.headers(&ctx);
+ assert_eq!(h.session_id.as_deref(), Some("sess-abc"));
+ }
+
+ #[test]
+ fn headers_omit_session_id_when_none() {
+ let ctx = test_utils::test_context();
+ let ev = ok_wrapped("$pageview", "user-1");
+ assert!(ev.event.session_id.is_none());
+ let h = ev.headers(&ctx);
+ assert!(h.session_id.is_none());
+ }
+
+ #[test]
+ fn headers_include_force_disable_person_processing() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-1");
+ ev.force_disable_person_processing = true;
+ let h = ev.headers(&ctx);
+ assert_eq!(h.force_disable_person_processing, Some(true));
+ }
+
+ #[test]
+ fn headers_omit_force_disable_person_processing_when_false() {
+ let ctx = test_utils::test_context();
+ let ev = ok_wrapped("$pageview", "user-1");
+ assert!(!ev.force_disable_person_processing);
+ let h = ev.headers(&ctx);
+ assert!(h.force_disable_person_processing.is_none());
+ }
+
+ #[test]
+ fn headers_include_dlq_headers_when_destination_dlq() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-1");
+ ev.destination = Destination::Dlq;
+ let h = ev.headers(&ctx);
+ assert_eq!(h.dlq_reason.as_deref(), Some("event_restriction"));
+ assert_eq!(h.dlq_step.as_deref(), Some("capture"));
+ let dlq_ts = h.dlq_timestamp.expect("dlq_timestamp should be set");
+ assert!(
+ chrono::DateTime::parse_from_rfc3339(&dlq_ts).is_ok(),
+ "dlq_timestamp should be valid RFC3339: {dlq_ts}"
+ );
+ }
+
+ #[test]
+ fn headers_omit_dlq_headers_when_not_dlq() {
+ let ctx = test_utils::test_context();
+ let ev = ok_wrapped("$pageview", "user-1");
+ assert_ne!(ev.destination, Destination::Dlq);
+ let h = ev.headers(&ctx);
+ assert!(h.dlq_reason.is_none());
+ assert!(h.dlq_step.is_none());
+ assert!(h.dlq_timestamp.is_none());
+ }
+
+ #[test]
+ fn headers_include_token_from_ctx() {
+ // Absorbs coverage from the removed build_context_headers token test:
+ // the api_token on the batch context must flow verbatim onto every
+ // event's typed headers.
+ let ctx = test_utils::test_context();
+ let ev = ok_wrapped("$pageview", "user-1");
+ let h = ev.headers(&ctx);
+ assert_eq!(h.token, Some(ctx.api_token.clone()));
+ }
+
+ #[test]
+ fn headers_now_uses_server_received_at_autosi_rfc3339() {
+ // Absorbs coverage from the removed build_context_headers now test,
+ // and asserts the legacy-aligned format upgrade (SecondsFormat::AutoSi,
+ // matches IngestionEvent.now and legacy CapturedEvent::to_headers()).
+ let ctx = test_utils::test_context();
+ let ev = ok_wrapped("$pageview", "user-1");
+ let h = ev.headers(&ctx);
+ let now = h
+ .now
+ .expect("now should be set from ctx.server_received_at");
+ assert_eq!(
+ now,
+ ctx.server_received_at
+ .to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true)
+ );
+ // Double-check the value is a valid RFC3339 timestamp regardless of
+ // how the format is spelled out.
+ assert!(
+ chrono::DateTime::parse_from_rfc3339(&now).is_ok(),
+ "now should be valid RFC3339: {now}"
+ );
+ }
+
+ #[test]
+ fn headers_historical_migration_from_ctx() {
+ // Absorbs coverage from the removed build_context_headers
+ // historical_migration tests (set → Some(true); unset → None),
+ // matching legacy CapturedEvent::to_headers() convention.
+ let ev = ok_wrapped("$pageview", "user-1");
+
+ let mut ctx = test_utils::test_context();
+ ctx.historical_migration = true;
+ let h = ev.headers(&ctx);
+ assert_eq!(h.historical_migration, Some(true));
+
+ ctx.historical_migration = false;
+ let h = ev.headers(&ctx);
+ assert!(h.historical_migration.is_none());
+ }
+
+ fn partition_key_str(ev: &WrappedEvent, ctx: &Context) -> Option<String> {
+ let mut buf = String::new();
+ ev.partition_key(ctx, &mut buf).map(String::from)
+ }
+
+ #[test]
+ fn partition_key_normal_mode() {
+ let ctx = test_utils::test_context();
+ let ev = ok_wrapped("$pageview", "user-42");
+ assert_eq!(
+ partition_key_str(&ev, &ctx),
+ Some(format!("{}:user-42", ctx.api_token))
+ );
+ }
+
+ #[test]
+ fn partition_key_cookieless_mode() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-42");
+ ev.event.options.cookieless_mode = Some(true);
+ assert_eq!(
+ partition_key_str(&ev, &ctx),
+ Some(format!("{}:{}", ctx.api_token, ctx.client_ip))
+ );
+ }
+
+ #[test]
+ fn partition_key_cookieless_capture_internal() {
+ let mut ctx = test_utils::test_context();
+ ctx.capture_internal = true;
+ let mut ev = ok_wrapped("$pageview", "user-42");
+ ev.event.options.cookieless_mode = Some(true);
+ assert_eq!(
+ partition_key_str(&ev, &ctx),
+ Some(format!("{}:127.0.0.1", ctx.api_token))
+ );
+ }
+
+ #[test]
+ fn destination_returns_event_destination() {
+ let mut ev = ok_wrapped("$pageview", "user-1");
+ ev.destination = Destination::Overflow;
+ assert_eq!(*ev.destination(), Destination::Overflow);
+ }
+
+ // --- partition key + force_disable_person_processing × destination ---
+
+ #[test]
+ fn partition_key_force_disable_analytics_main() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-42");
+ ev.force_disable_person_processing = true;
+ ev.destination = Destination::AnalyticsMain;
+ assert_eq!(partition_key_str(&ev, &ctx), None);
+ }
+
+ #[test]
+ fn partition_key_force_disable_overflow() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-42");
+ ev.force_disable_person_processing = true;
+ ev.destination = Destination::Overflow;
+ assert_eq!(partition_key_str(&ev, &ctx), None);
+ }
+
+ #[test]
+ fn partition_key_force_disable_dlq() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-42");
+ ev.force_disable_person_processing = true;
+ ev.destination = Destination::Dlq;
+ assert_eq!(
+ partition_key_str(&ev, &ctx),
+ Some(format!("{}:user-42", ctx.api_token))
+ );
+ }
+
+ #[test]
+ fn partition_key_force_disable_historical() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-42");
+ ev.force_disable_person_processing = true;
+ ev.destination = Destination::AnalyticsHistorical;
+ assert_eq!(
+ partition_key_str(&ev, &ctx),
+ Some(format!("{}:user-42", ctx.api_token))
+ );
+ }
+
+ #[test]
+ fn partition_key_force_disable_custom() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-42");
+ ev.force_disable_person_processing = true;
+ ev.destination = Destination::Custom("my_topic".into());
+ assert_eq!(
+ partition_key_str(&ev, &ctx),
+ Some(format!("{}:user-42", ctx.api_token))
+ );
+ }
+
+ #[test]
+ fn partition_key_force_disable_cookieless_dlq() {
+ let ctx = test_utils::test_context();
+ let mut ev = ok_wrapped("$pageview", "user-42");
+ ev.force_disable_person_processing = true;
+ ev.destination = Destination::Dlq;
+ ev.event.options.cookieless_mode = Some(true);
+ assert_eq!(
+ partition_key_str(&ev, &ctx),
+ Some(format!("{}:{}", ctx.api_token, ctx.client_ip))
+ );
+ }
+
+ // --- HasEventName impl for WrappedEvent ---
+
+ #[test]
+ fn event_name_returns_event_field() {
+ let ev = ok_wrapped("$pageview", "user-1");
+ assert_eq!(ev.event_name(), "$pageview");
+ }
+
+ #[test]
+ fn has_property_product_tour_id_some() {
+ let mut ev = ok_wrapped("survey sent", "user-1");
+ ev.event.options.product_tour_id = Some("tour-123".into());
+ assert!(ev.has_property("product_tour_id"));
+ }
+
+ #[test]
+ fn has_property_product_tour_id_none() {
+ let ev = ok_wrapped("survey sent", "user-1");
+ assert!(!ev.has_property("product_tour_id"));
+ }
+
+ #[test]
+ fn has_property_unknown_key() {
+ let ev = ok_wrapped("$pageview", "user-1");
+ assert!(!ev.has_property("unknown_key"));
+ }
+
+ // --- serialize_into ---
+
+ use std::net::{IpAddr, Ipv4Addr};
+
+ use common_types::{CapturedEvent, RawEvent};
+ use serde_json::Value;
+
+ fn raw_obj(s: &str) -> Box<RawValue> {
+ RawValue::from_string(s.to_owned()).unwrap()
+ }
+
+ fn dt(s: &str) -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
+ }
+
+ fn serialize_ctx() -> crate::v1::context::Context {
+ let mut ctx = test_utils::test_context();
+ ctx.api_token = "phc_project_abc123".to_string();
+ ctx.client_ip = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 42));
+ ctx.client_timestamp = dt("2026-03-19T14:30:01.500Z");
+ ctx.server_received_at = dt("2026-03-19T14:30:00.000Z");
+ ctx.capture_internal = false;
+ ctx.historical_migration = false;
+ ctx
+ }
+
+ fn pageview_event() -> WrappedEvent {
+ let uuid = Uuid::new_v4();
+ WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-42".to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: Some("sess-01jq9abc".to_string()),
+ window_id: Some("win-xyz789".to_string()),
+ options: Options {
+ cookieless_mode: Some(false),
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: Some(true),
+ },
+ properties: raw_obj(
+ r#"{"$current_url":"https://app.example.com/dashboard","$browser":"Chrome","custom_prop":42}"#,
+ ),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:53.123Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ }
+ }
+
+ fn serialize_and_parse(
+ wrapped: &WrappedEvent,
+ ctx: &crate::v1::context::Context,
+ ) -> (CapturedEvent, RawEvent) {
+ let mut buf = String::new();
+ wrapped
+ .serialize_into(ctx, &mut buf)
+ .expect("serialize_into failed");
+ let captured: CapturedEvent =
+ serde_json::from_str(&buf).expect("v1 output must deserialize as CapturedEvent");
+ let data: RawEvent =
+ serde_json::from_str(&captured.data).expect("data field must deserialize as RawEvent");
+ (captured, data)
+ }
+
+ #[test]
+ fn serialize_round_trip_basic() {
+ let wrapped = pageview_event();
+ let ctx = serialize_ctx();
+ let (captured, data) = serialize_and_parse(&wrapped, &ctx);
+
+ assert_eq!(captured.uuid, wrapped.uuid);
+ assert_eq!(captured.distinct_id, "user-42");
+ assert_eq!(captured.ip, "203.0.113.42");
+ assert_eq!(captured.token, "phc_project_abc123");
+ assert_eq!(captured.event, "$pageview");
+ assert_eq!(captured.timestamp, wrapped.adjusted_timestamp.unwrap());
+ assert!(!captured.is_cookieless_mode);
+ assert!(!captured.historical_migration);
+
+ assert_eq!(data.event, "$pageview");
+ assert_eq!(data.distinct_id, Some(Value::String("user-42".to_string())));
+ assert_eq!(data.timestamp.as_deref(), Some("2026-03-19T14:29:58.123Z"));
+
+ let props = &data.properties;
+ assert_eq!(props["$current_url"], "https://app.example.com/dashboard");
+ assert_eq!(props["$browser"], "Chrome");
+ assert_eq!(props["custom_prop"], 42);
+ assert_eq!(props["$session_id"], "sess-01jq9abc");
+ assert_eq!(props["$window_id"], "win-xyz789");
+ assert_eq!(props["$cookieless_mode"], false);
+ assert_eq!(props["$process_person_profile"], true);
+ }
+
+ #[test]
+ fn serialize_ip_redaction_capture_internal() {
+ let wrapped = pageview_event();
+ let mut ctx = serialize_ctx();
+ ctx.capture_internal = true;
+ let (captured, _) = serialize_and_parse(&wrapped, &ctx);
+ assert_eq!(captured.ip, "127.0.0.1");
+ }
+
+ #[test]
+ fn serialize_ip_normal() {
+ let wrapped = pageview_event();
+ let ctx = serialize_ctx();
+ let (captured, _) = serialize_and_parse(&wrapped, &ctx);
+ assert_eq!(captured.ip, "203.0.113.42");
+ }
+
+ #[test]
+ fn serialize_all_options_injected() {
+ let uuid = Uuid::new_v4();
+ let wrapped = WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-42".to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: Some("sess-01jq9abc".to_string()),
+ window_id: Some("win-xyz789".to_string()),
+ options: Options {
+ cookieless_mode: Some(true),
+ disable_skew_adjustment: Some(true),
+ product_tour_id: Some("tour-onboarding-v2".to_string()),
+ process_person_profile: Some(false),
+ },
+ properties: raw_obj(r#"{"existing":"value"}"#),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:53.123Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ };
+
+ let ctx = serialize_ctx();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+ let props = &data.properties;
+
+ assert_eq!(props["existing"], "value");
+ assert_eq!(props["$session_id"], "sess-01jq9abc");
+ assert_eq!(props["$window_id"], "win-xyz789");
+ assert_eq!(props["$cookieless_mode"], true);
+ assert_eq!(props["$ignore_sent_at"], true);
+ assert_eq!(props["$product_tour_id"], "tour-onboarding-v2");
+ assert_eq!(props["$process_person_profile"], false);
+ }
+
+ #[test]
+ fn serialize_partial_options() {
+ let uuid = Uuid::new_v4();
+ let wrapped = WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-42".to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: Some("sess-abc".to_string()),
+ window_id: None,
+ options: Options {
+ cookieless_mode: Some(false),
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: None,
+ },
+ properties: raw_obj(r#"{"x":1}"#),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:53.123Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ };
+
+ let ctx = serialize_ctx();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+ let props = &data.properties;
+
+ assert_eq!(props["$session_id"], "sess-abc");
+ assert_eq!(props["$cookieless_mode"], false);
+ assert!(!props.contains_key("$window_id"));
+ assert!(!props.contains_key("$ignore_sent_at"));
+ assert!(!props.contains_key("$product_tour_id"));
+ assert!(!props.contains_key("$process_person_profile"));
+ }
+
+ #[test]
+ fn serialize_empty_properties_no_options() {
+ let uuid = Uuid::new_v4();
+ let wrapped = WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-42".to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: None,
+ window_id: None,
+ options: Options {
+ cookieless_mode: None,
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: None,
+ },
+ properties: raw_obj("{}"),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:53.123Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ };
+
+ let ctx = serialize_ctx();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+ assert!(data.properties.is_empty());
+ }
+
+ #[test]
+ fn serialize_empty_properties_with_options() {
+ let uuid = Uuid::new_v4();
+ let wrapped = WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-42".to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: Some("sess-abc".to_string()),
+ window_id: None,
+ options: Options {
+ cookieless_mode: Some(true),
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: None,
+ },
+ properties: raw_obj("{}"),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:53.123Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ };
+
+ let ctx = serialize_ctx();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+ let props = &data.properties;
+ assert_eq!(props["$session_id"], "sess-abc");
+ assert_eq!(props["$cookieless_mode"], true);
+ assert_eq!(props.len(), 2);
+ }
+
+ #[test]
+ fn serialize_existing_properties_preserved() {
+ let uuid = Uuid::new_v4();
+ let wrapped = WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-42".to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: Some("sess-abc".to_string()),
+ window_id: None,
+ options: Options {
+ cookieless_mode: None,
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: None,
+ },
+ properties: raw_obj(
+ r#"{"$lib":"posthog-js","$lib_version":"1.150.0","$referrer":"https://google.com"}"#,
+ ),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:53.123Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ };
+
+ let ctx = serialize_ctx();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+ let props = &data.properties;
+ assert_eq!(props["$lib"], "posthog-js");
+ assert_eq!(props["$lib_version"], "1.150.0");
+ assert_eq!(props["$referrer"], "https://google.com");
+ assert_eq!(props["$session_id"], "sess-abc");
+ }
+
+ #[test]
+ fn serialize_is_cookieless_mode_true() {
+ let mut wrapped = pageview_event();
+ wrapped.event.options.cookieless_mode = Some(true);
+ let ctx = serialize_ctx();
+ let (captured, data) = serialize_and_parse(&wrapped, &ctx);
+ assert!(captured.is_cookieless_mode);
+ assert_eq!(data.properties["$cookieless_mode"], true);
+ }
+
+ #[test]
+ fn serialize_is_cookieless_mode_false_skipped() {
+ let wrapped = pageview_event();
+ assert_eq!(wrapped.event.options.cookieless_mode, Some(false));
+ let ctx = serialize_ctx();
+ let mut buf = String::new();
+ wrapped.serialize_into(&ctx, &mut buf).unwrap();
+ let val: Value = serde_json::from_str(&buf).unwrap();
+ assert!(
+ val.get("is_cookieless_mode").is_none(),
+ "is_cookieless_mode should be absent when false"
+ );
+ }
+
+ #[test]
+ fn serialize_historical_migration_true() {
+ let wrapped = pageview_event();
+ let mut ctx = serialize_ctx();
+ ctx.historical_migration = true;
+ let (captured, _) = serialize_and_parse(&wrapped, &ctx);
+ assert!(captured.historical_migration);
+ }
+
+ #[test]
+ fn serialize_historical_migration_false_skipped() {
+ let wrapped = pageview_event();
+ let ctx = serialize_ctx();
+ let mut buf = String::new();
+ wrapped.serialize_into(&ctx, &mut buf).unwrap();
+ let val: Value = serde_json::from_str(&buf).unwrap();
+ assert!(
+ val.get("historical_migration").is_none(),
+ "historical_migration should be absent when false"
+ );
+ }
+
+ #[test]
+ fn serialize_sent_at_present() {
+ let wrapped = pageview_event();
+ let ctx = serialize_ctx();
+ let (captured, _) = serialize_and_parse(&wrapped, &ctx);
+ assert!(captured.sent_at.is_some());
+ }
+
+ #[test]
+ fn serialize_data_timestamp_is_original_not_adjusted() {
+ let wrapped = pageview_event();
+ let ctx = serialize_ctx();
+ let (captured, data) = serialize_and_parse(&wrapped, &ctx);
+ assert_eq!(
+ data.timestamp.as_deref(),
+ Some("2026-03-19T14:29:58.123Z"),
+ "data.timestamp should be the original client timestamp"
+ );
+ assert_eq!(
+ captured.timestamp,
+ dt("2026-03-19T14:29:53.123Z"),
+ "captured.timestamp should be the adjusted timestamp"
+ );
+ }
+
+ #[test]
+ fn serialize_process_person_profile_in_properties() {
+ let mut wrapped = pageview_event();
+ wrapped.event.options.process_person_profile = Some(false);
+ wrapped.force_disable_person_processing = false;
+ let ctx = serialize_ctx();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+ assert_eq!(data.properties["$process_person_profile"], false);
+ }
+
+ #[test]
+ fn serialize_force_disable_does_not_affect_data() {
+ let uuid = Uuid::new_v4();
+ let wrapped = WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-42".to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: None,
+ window_id: None,
+ options: Options {
+ cookieless_mode: None,
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: None,
+ },
+ properties: raw_obj(r#"{"x":1}"#),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:53.123Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: true,
+ };
+
+ let ctx = serialize_ctx();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+ assert!(
+ !data
+ .properties
+ .contains_key("force_disable_person_processing"),
+ "force_disable_person_processing must not appear in properties"
+ );
+ assert!(
+ !data.properties.contains_key("$process_person_profile"),
+ "$process_person_profile must not appear when options.process_person_profile is None"
+ );
+ }
+
+ #[test]
+ fn serialize_identify_event() {
+ let uuid = Uuid::new_v4();
+ let wrapped = WrappedEvent {
+ event: Event {
+ event: "$identify".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-99".to_string(),
+ timestamp: "2026-03-19T14:30:00.000Z".to_string(),
+ session_id: None,
+ window_id: None,
+ options: Options {
+ cookieless_mode: None,
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: Some(true),
+ },
+ properties: raw_obj(r#"{"$browser":"Safari","$os":"macOS"}"#),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:55.000Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ };
+
+ let ctx = serialize_ctx();
+ let (captured, data) = serialize_and_parse(&wrapped, &ctx);
+ assert_eq!(captured.event, "$identify");
+ assert_eq!(captured.uuid, uuid);
+ assert_eq!(data.event, "$identify");
+ assert_eq!(data.properties["$browser"], "Safari");
+ assert_eq!(data.properties["$os"], "macOS");
+ assert_eq!(data.properties["$process_person_profile"], true);
+ }
+
+ // --- A3: property injection safety ---
+
+ #[test]
+ fn serialize_array_properties_rejected() {
+ let uuid = Uuid::new_v4();
+ let wrapped = WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-42".to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: Some("sess-abc".to_string()),
+ window_id: None,
+ options: Options {
+ cookieless_mode: None,
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: None,
+ },
+ properties: raw_obj("[1,2,3]"),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:53.123Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ };
+
+ let ctx = serialize_ctx();
+ let mut buf = String::new();
+ let err = wrapped.serialize_into(&ctx, &mut buf).unwrap_err();
+ assert!(
+ err.to_string().contains("must be a JSON object"),
+ "expected object guard, got: {err}"
+ );
+ }
+
+ #[test]
+ fn serialize_whitespace_padded_empty_object() {
+ let uuid = Uuid::new_v4();
+ let wrapped = WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: "user-42".to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: Some("sess-abc".to_string()),
+ window_id: None,
+ options: Options {
+ cookieless_mode: None,
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: None,
+ },
+ properties: raw_obj("{ }"),
+ },
+ uuid,
+ adjusted_timestamp: Some(dt("2026-03-19T14:29:53.123Z")),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ };
+
+ let ctx = serialize_ctx();
+ let (_, data) = serialize_and_parse(&wrapped, &ctx);
+ assert_eq!(data.properties["$session_id"], "sess-abc");
+ assert_eq!(data.properties.len(), 1);
+ }
}
diff --git a/rust/capture/src/v1/mod.rs b/rust/capture/src/v1/mod.rs
index c7d79e82e64a..b2178d7f53b7 100644
--- a/rust/capture/src/v1/mod.rs
+++ b/rust/capture/src/v1/mod.rs
@@ -4,8 +4,8 @@ pub mod context;
pub mod error;
pub mod quota_limiter_shim;
pub mod sinks;
-#[cfg(test)]
-pub(crate) mod test_utils;
+#[cfg(any(test, feature = "test-utils"))]
+pub mod test_utils;
pub mod util;
pub use error::Error;
diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index b30546ff4650..df498bae05e4 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -269,10 +269,11 @@ mod tests {
}
fn make_event(name: &str, product_tour_id: Option<&str>) -> WrappedEvent {
+ let uuid = Uuid::now_v7();
WrappedEvent {
event: Event {
event: name.to_string(),
- uuid: Uuid::now_v7().to_string(),
+ uuid: uuid.to_string(),
distinct_id: "test_user".to_string(),
timestamp: "2026-03-26T12:00:00.000Z".to_string(),
session_id: None,
@@ -285,6 +286,7 @@ mod tests {
},
properties: RawValue::from_string("{}".to_owned()).unwrap(),
},
+ uuid,
adjusted_timestamp: Some(
DateTime::parse_from_rfc3339("2026-03-26T12:00:00Z")
.unwrap()
@@ -293,7 +295,7 @@ mod tests {
result: EventResult::Ok,
details: None,
destination: Destination::AnalyticsMain,
- skip_person_processing: false,
+ force_disable_person_processing: false,
}
}
@@ -367,7 +369,7 @@ mod tests {
async fn global_limit_preserves_all_event_states() {
let limiter = build_limiter("tok", true, &[]).await;
let bad = make_event("bad_event", None);
- let bad_uuid = Uuid::parse_str(bad.event.uuid()).unwrap();
+ let bad_uuid = bad.uuid;
let mut events = events_map(vec![make_event("$pageview", None), bad]);
// Pre-mark one event as Drop (e.g. from validation)
let bad_ev = events.get_mut(&bad_uuid).unwrap();
@@ -475,7 +477,7 @@ mod tests {
async fn survey_limit_excludes_product_tour_events() {
let limiter = build_limiter("tok", false, &[QuotaResource::Surveys]).await;
let tour_ev = make_event("survey sent", Some("tour-123"));
- let tour_uuid = Uuid::parse_str(tour_ev.event.uuid()).unwrap();
+ let tour_uuid = tour_ev.uuid;
let mut events = events_map(vec![make_event("survey sent", None), tour_ev]);
let result = apply_quota_limits(&limiter, "tok", &mut events).await;
@@ -625,7 +627,7 @@ mod tests {
// No global limit, but exceptions limited
let limiter = build_limiter("tok", false, &[QuotaResource::Exceptions]).await;
let pv = make_event("$pageview", None);
- let pv_uuid = Uuid::parse_str(pv.event.uuid()).unwrap();
+ let pv_uuid = pv.uuid;
let mut events = events_map(vec![make_event("$exception", None), pv]);
// Pre-mark pageview as Drop from a prior validation step
let pv_ev = events.get_mut(&pv_uuid).unwrap();
@@ -641,7 +643,7 @@ mod tests {
async fn mixed_pre_existing_and_scoped_still_ok_if_some_remain() {
let limiter = build_limiter("tok", false, &[QuotaResource::Exceptions]).await;
let pv = make_event("$pageview", None);
- let pv_uuid = Uuid::parse_str(pv.event.uuid()).unwrap();
+ let pv_uuid = pv.uuid;
let mut events = events_map(vec![
make_event("$exception", None),
pv,
diff --git a/rust/capture/src/v1/sinks/constants.rs b/rust/capture/src/v1/sinks/constants.rs
index be3c287cdbe2..b751bd43e233 100644
--- a/rust/capture/src/v1/sinks/constants.rs
+++ b/rust/capture/src/v1/sinks/constants.rs
@@ -1,6 +1,5 @@
use std::time::Duration;
-#[allow(dead_code)]
pub(crate) const DEFAULT_PRODUCE_TIMEOUT: Duration = Duration::from_secs(30);
// Lifecycle Handle configuration for v1 sinks.
diff --git a/rust/capture/src/v1/sinks/event.rs b/rust/capture/src/v1/sinks/event.rs
index b7cb2682a80f..04d80c9eead8 100644
--- a/rust/capture/src/v1/sinks/event.rs
+++ b/rust/capture/src/v1/sinks/event.rs
@@ -8,7 +8,7 @@ use crate::v1::sinks::Destination;
/// metadata, and serialization. The [`Sink`](super::sink::Sink) implementation
/// resolves `destination()` to a concrete backend target using its own config.
pub trait Event: Send + Sync {
- /// Pre-parsed UUID for result correlation. Copy, zero alloc.
+ /// Pre-parsed UUID for result correlation.
fn uuid(&self) -> Uuid;
/// Whether this event should be published. Events returning false are
@@ -27,10 +27,10 @@ pub trait Event: Send + Sync {
/// `common_types`).
fn headers(&self, ctx: &Context) -> CapturedEventHeaders;
- /// Resolve the partition key for this message, and write
- /// to the supplied buffer. Called by Sinks that write to
- /// event streams (Kafka, WarpStream etc.)
- fn write_partition_key(&self, ctx: &Context, buf: &mut String);
+ /// Resolve the partition key for this message into the supplied buffer.
+ /// Returns `Some(key)` for consistent routing, `None` to let the
+ /// transport decide (e.g. round-robin across partitions).
+ fn partition_key<'buf>(&self, ctx: &Context, buf: &'buf mut String) -> Option<&'buf str>;
/// Serialize the event payload into a caller-provided buffer.
fn serialize_into(&self, ctx: &Context, buf: &mut String) -> anyhow::Result<()>;
diff --git a/rust/capture/src/v1/sinks/kafka/config.rs b/rust/capture/src/v1/sinks/kafka/config.rs
index 36dc92e9b1c4..817f74386de5 100644
--- a/rust/capture/src/v1/sinks/kafka/config.rs
+++ b/rust/capture/src/v1/sinks/kafka/config.rs
@@ -57,6 +57,43 @@ pub struct Config {
#[envconfig(default = "10000")]
pub statistics_interval_ms: u32,
+ // -- v0 parity settings (defaults from production charts/argocd/capture) --
+ /// Partitioning strategy. Must be murmur2_random for v0 parity
+ /// (python-kafka compat). librdkafka default varies by version.
+ #[envconfig(default = "murmur2_random")]
+ pub partitioner: String,
+ /// Max retry attempts per message. Production default: 4 (tuned for
+ /// MSK failover with socket_timeout_ms=5000, message_timeout_ms=30000).
+ #[envconfig(default = "4")]
+ pub max_retries: u32,
+ #[envconfig(default = "1000000")]
+ pub max_in_flight_requests: u32,
+ /// How long (ms) the producer sticks to a random partition for keyless
+ /// messages before switching. Affects distribution of events with
+ /// force_disable_person_processing (no partition key).
+ #[envconfig(default = "10")]
+ pub sticky_partitioning_linger_ms: u32,
+
+ /// IP family for broker connections. Empty = let librdkafka decide (default);
+ /// "v4" / "v6" / "any" force-select. Matches legacy KAFKA_BROKER_ADDRESS_FAMILY.
+ #[envconfig(default = "")]
+ pub broker_address_family: String,
+ /// Log broker connection close events. librdkafka default = true.
+ #[envconfig(default = "true")]
+ pub log_connection_close: bool,
+ /// Max messages buffered in the producer queue. librdkafka default = 100_000.
+ #[envconfig(default = "100000")]
+ pub queue_buffering_max_messages: u32,
+ /// Upper bound on exponential retry backoff (ms). librdkafka default = 1000.
+ #[envconfig(default = "1000")]
+ pub retry_backoff_max_ms: u32,
+ /// TCP socket send buffer size in bytes. 0 = use OS default. librdkafka default = 0.
+ #[envconfig(default = "0")]
+ pub socket_send_buffer_bytes: u32,
+ /// TCP socket receive buffer size in bytes. 0 = use OS default. librdkafka default = 0.
+ #[envconfig(default = "0")]
+ pub socket_receive_buffer_bytes: u32,
+
// -- QueueFull backpressure --
/// Max enqueue retry attempts when rdkafka returns QueueFull.
/// 0 = no retries (immediate failure, pre-backpressure behavior).
@@ -170,6 +207,16 @@ mod tests {
env.insert("STATISTICS_INTERVAL_MS".into(), "5000".into());
env.insert("ENQUEUE_RETRY_MAX".into(), "5".into());
env.insert("ENQUEUE_POLL_MS".into(), "50".into());
+ env.insert("PARTITIONER".into(), "consistent_random".into());
+ env.insert("MAX_RETRIES".into(), "6".into());
+ env.insert("MAX_IN_FLIGHT_REQUESTS".into(), "500000".into());
+ env.insert("STICKY_PARTITIONING_LINGER_MS".into(), "20".into());
+ env.insert("BROKER_ADDRESS_FAMILY".into(), "v4".into());
+ env.insert("LOG_CONNECTION_CLOSE".into(), "false".into());
+ env.insert("QUEUE_BUFFERING_MAX_MESSAGES".into(), "250000".into());
+ env.insert("RETRY_BACKOFF_MAX_MS".into(), "2000".into());
+ env.insert("SOCKET_SEND_BUFFER_BYTES".into(), "65536".into());
+ env.insert("SOCKET_RECEIVE_BUFFER_BYTES".into(), "65536".into());
let cfg = Config::init_from_hashmap(&env).unwrap();
assert_eq!(cfg.hosts, "localhost:9092");
@@ -190,6 +237,16 @@ mod tests {
assert_eq!(cfg.statistics_interval_ms, 5000);
assert_eq!(cfg.enqueue_retry_max, 5);
assert_eq!(cfg.enqueue_poll_ms, 50);
+ assert_eq!(cfg.partitioner, "consistent_random");
+ assert_eq!(cfg.max_retries, 6);
+ assert_eq!(cfg.max_in_flight_requests, 500000);
+ assert_eq!(cfg.sticky_partitioning_linger_ms, 20);
+ assert_eq!(cfg.broker_address_family, "v4");
+ assert!(!cfg.log_connection_close);
+ assert_eq!(cfg.queue_buffering_max_messages, 250000);
+ assert_eq!(cfg.retry_backoff_max_ms, 2000);
+ assert_eq!(cfg.socket_send_buffer_bytes, 65536);
+ assert_eq!(cfg.socket_receive_buffer_bytes, 65536);
assert_eq!(cfg.topic_main, "events_main");
}
@@ -214,6 +271,16 @@ mod tests {
assert_eq!(cfg.statistics_interval_ms, 10000);
assert_eq!(cfg.enqueue_retry_max, 3);
assert_eq!(cfg.enqueue_poll_ms, 33);
+ assert_eq!(cfg.partitioner, "murmur2_random");
+ assert_eq!(cfg.max_retries, 4);
+ assert_eq!(cfg.max_in_flight_requests, 1000000);
+ assert_eq!(cfg.sticky_partitioning_linger_ms, 10);
+ assert_eq!(cfg.broker_address_family, "");
+ assert!(cfg.log_connection_close);
+ assert_eq!(cfg.queue_buffering_max_messages, 100000);
+ assert_eq!(cfg.retry_backoff_max_ms, 1000);
+ assert_eq!(cfg.socket_send_buffer_bytes, 0);
+ assert_eq!(cfg.socket_receive_buffer_bytes, 0);
}
#[test]
diff --git a/rust/capture/src/v1/sinks/kafka/mock.rs b/rust/capture/src/v1/sinks/kafka/mock.rs
index 5b53bdcb9a0b..525eb183e396 100644
--- a/rust/capture/src/v1/sinks/kafka/mock.rs
+++ b/rust/capture/src/v1/sinks/kafka/mock.rs
@@ -54,7 +54,6 @@ pub struct MockProducer {
ack_error: Option<fn() -> ProduceError>,
ack_delay: Option<Duration>,
ready_override: Option<bool>,
- #[allow(dead_code)]
handle: lifecycle::Handle,
}
@@ -72,7 +71,6 @@ impl MockProducer {
}
}
- #[allow(dead_code)]
pub fn with_send_error(mut self, f: fn() -> ProduceError) -> Self {
self.send_error = Some(f);
self
@@ -80,36 +78,30 @@ impl MockProducer {
/// Limit send errors to the first `n` calls. After `n` errors the
/// send_error function is bypassed and sends succeed normally.
- #[allow(dead_code)]
pub fn with_send_error_count(mut self, n: u32) -> Self {
self.send_error_remaining = Arc::new(AtomicU32::new(n));
self
}
- #[allow(dead_code)]
pub fn with_ack_error(mut self, f: fn() -> ProduceError) -> Self {
self.ack_error = Some(f);
self
}
- #[allow(dead_code)]
pub fn with_ack_delay(mut self, d: Duration) -> Self {
self.ack_delay = Some(d);
self
}
- #[allow(dead_code)]
pub fn with_not_ready(mut self) -> Self {
self.ready_override = Some(false);
self
}
- #[allow(dead_code)]
pub fn record_count(&self) -> usize {
self.records.lock().unwrap().len()
}
- #[allow(dead_code)]
pub fn with_records<F, R>(&self, f: F) -> R
where
F: FnOnce(&[OwnedProduceRecord]) -> R,
@@ -118,7 +110,6 @@ impl MockProducer {
f(&guard)
}
- #[allow(dead_code)]
pub fn clear(&self) {
self.records.lock().unwrap().clear();
}
diff --git a/rust/capture/src/v1/sinks/kafka/mod.rs b/rust/capture/src/v1/sinks/kafka/mod.rs
index 8e3c2329bf87..aa02447860b7 100644
--- a/rust/capture/src/v1/sinks/kafka/mod.rs
+++ b/rust/capture/src/v1/sinks/kafka/mod.rs
@@ -2,8 +2,14 @@ pub mod config;
pub mod context;
pub mod mock;
pub mod producer;
+pub mod sink;
pub mod types;
+#[cfg(test)]
+mod sink_tests;
+
+pub use sink::KafkaSink;
+
use std::future::Future;
use std::time::Duration;
diff --git a/rust/capture/src/v1/sinks/kafka/producer.rs b/rust/capture/src/v1/sinks/kafka/producer.rs
index 4c99f456fd43..f2a76dc74330 100644
--- a/rust/capture/src/v1/sinks/kafka/producer.rs
+++ b/rust/capture/src/v1/sinks/kafka/producer.rs
@@ -105,7 +105,6 @@ impl Future for SendHandle {
pub struct KafkaProducer {
inner: FutureProducer<KafkaContext>,
- #[allow(dead_code)]
handle: lifecycle::Handle,
sink: SinkName,
}
@@ -146,8 +145,41 @@ impl KafkaProducer {
"metadata.max.age.ms",
config.metadata_max_age_ms.to_string(),
)
- .set("socket.timeout.ms", config.socket_timeout_ms.to_string());
+ .set("socket.timeout.ms", config.socket_timeout_ms.to_string())
+ .set("partitioner", &config.partitioner)
+ .set("message.send.max.retries", config.max_retries.to_string())
+ .set(
+ "max.in.flight.requests.per.connection",
+ config.max_in_flight_requests.to_string(),
+ )
+ .set(
+ "sticky.partitioning.linger.ms",
+ config.sticky_partitioning_linger_ms.to_string(),
+ )
+ .set(
+ "log.connection.close",
+ config.log_connection_close.to_string(),
+ )
+ .set(
+ "queue.buffering.max.messages",
+ config.queue_buffering_max_messages.to_string(),
+ )
+ .set(
+ "retry.backoff.max.ms",
+ config.retry_backoff_max_ms.to_string(),
+ )
+ .set(
+ "socket.send.buffer.bytes",
+ config.socket_send_buffer_bytes.to_string(),
+ )
+ .set(
+ "socket.receive.buffer.bytes",
+ config.socket_receive_buffer_bytes.to_string(),
+ );
+ if !config.broker_address_family.is_empty() {
+ client_config.set("broker.address.family", &config.broker_address_family);
+ }
if !config.client_id.is_empty() {
client_config.set("client.id", &config.client_id);
}
diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rs
new file mode 100644
index 000000000000..8d4d2f78b147
--- /dev/null
+++ b/rust/capture/src/v1/sinks/kafka/sink.rs
@@ -0,0 +1,450 @@
+use std::collections::HashSet;
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use futures::stream::FuturesUnordered;
+use futures::StreamExt;
+use metrics::{counter, histogram};
+use tracing::Level;
+use uuid::Uuid;
+
+use crate::config::CaptureMode;
+use crate::v1::context::Context;
+use crate::v1::sinks::event::Event;
+use crate::v1::sinks::sink::Sink;
+use crate::v1::sinks::types::{BatchSummary, Outcome, SinkResult};
+use crate::v1::sinks::{Config, SinkName};
+
+use super::producer::ProduceRecord;
+use super::types::{KafkaResult, KafkaSinkError};
+use super::KafkaProducerTrait;
+
+/// Shared label values for metrics emitted within a single `publish_batch` call.
+/// All fields are `&'static str` (zero-cost) or `SharedString` (Arc-based, so
+/// `.clone()` is a refcount bump rather than a heap allocation).
+struct MetricLabels {
+ sink: &'static str,
+ mode: &'static str,
+ path: metrics::SharedString,
+ attempt: metrics::SharedString,
+}
+
+pub struct KafkaSink<P: KafkaProducerTrait> {
+ name: SinkName,
+ producer: Arc<P>,
+ config: Config,
+ capture_mode: CaptureMode,
+ handle: lifecycle::Handle,
+}
+
+impl<P: KafkaProducerTrait> KafkaSink<P> {
+ pub fn new(
+ name: SinkName,
+ producer: Arc<P>,
+ config: Config,
+ capture_mode: CaptureMode,
+ handle: lifecycle::Handle,
+ ) -> Self {
+ Self {
+ name,
+ producer,
+ config,
+ capture_mode,
+ handle,
+ }
+ }
+}
+
+/// Reject every publishable event in `events` as `SinkUnavailable`,
+/// incrementing a single counter for the batch.
+fn reject_publishable(
+ events: &[&(dyn Event + Send + Sync)],
+ labels: &MetricLabels,
+) -> Vec<Box<dyn SinkResult>> {
+ let enqueued_at = Utc::now();
+ let publishable: Vec<_> = events.iter().filter(|e| e.should_publish()).collect();
+ counter!(
+ "capture_v1_kafka_publish_total",
+ "mode" => labels.mode,
+ "cluster" => labels.sink,
+ "outcome" => Outcome::RetriableError.as_tag(),
+ "path" => labels.path.clone(),
+ "attempt" => labels.attempt.clone(),
+ )
+ .increment(publishable.len() as u64);
+ publishable
+ .into_iter()
+ .map(|e| -> Box<dyn SinkResult> {
+ Box::new(KafkaResult::err(
+ e.uuid(),
+ KafkaSinkError::SinkUnavailable,
+ enqueued_at,
+ ))
+ })
+ .collect()
+}
+
+type AckFuture = Pin<
+ Box<
+ dyn Future<
+ Output = (
+ Uuid,
+ DateTime<Utc>,
+ Result<(), super::producer::ProduceError>,
+ ),
+ > + Send,
+ >,
+>;
+
+impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {
+ /// Phase 1: serialize and enqueue events to the producer sequentially,
+ /// preserving per-partition ordering. Returns early results for
+ /// serialization / send failures and collects ack futures for events
+ /// that were successfully enqueued.
+ #[allow(clippy::too_many_arguments)]
+ async fn enqueue_events(
+ &self,
+ ctx: &Context,
+ events: &[&(dyn Event + Send + Sync)],
+ labels: &MetricLabels,
+ enqueued_at: DateTime<Utc>,
+ results: &mut Vec<Box<dyn SinkResult>>,
+ pending: &mut FuturesUnordered<AckFuture>,
+ enqueued_keys: &mut Vec<Uuid>,
+ ) {
+ let mut payload_buf = String::with_capacity(4096);
+ let mut key_buf = String::with_capacity(128);
+
+ for event in events {
+ if !event.should_publish() {
+ continue;
+ }
+
+ let uuid = event.uuid();
+
+ let topic = match self.config.kafka.topic_for(event.destination()) {
+ Some(t) => t,
+ None => continue,
+ };
+
+ payload_buf.clear();
+ if let Err(e) = event.serialize_into(ctx, &mut payload_buf) {
+ crate::ctx_log!(
+ Level::ERROR,
+ ctx,
+ sink = labels.sink,
+ event_uuid = %uuid,
+ error = %e,
+ "event serialization failed, dropping event"
+ );
+ counter!(
+ "capture_v1_kafka_publish_total",
+ "mode" => labels.mode,
+ "cluster" => labels.sink,
+ "outcome" => Outcome::FatalError.as_tag(),
+ "path" => labels.path.clone(),
+ "attempt" => labels.attempt.clone(),
+ )
+ .increment(1);
+ results.push(Box::new(KafkaResult::err(
+ uuid,
+ KafkaSinkError::SerializationFailed(format!("{e:#}")),
+ enqueued_at,
+ )));
+ continue;
+ }
+
+ let headers: rdkafka::message::OwnedHeaders = event.headers(ctx).into();
+
+ key_buf.clear();
+ let key = event.partition_key(ctx, &mut key_buf);
+
+ let mut record = ProduceRecord {
+ topic,
+ key,
+ payload: &payload_buf,
+ headers,
+ };
+
+ let enqueue_retry_max = self.config.kafka.enqueue_retry_max;
+ let enqueue_poll = Duration::from_millis(self.config.kafka.enqueue_poll_ms as u64);
+ let mut hit_queue_full = false;
+
+ for enqueue_attempt in 0..=enqueue_retry_max {
+ if enqueue_attempt > 0 {
+ tokio::time::sleep(enqueue_poll).await;
+ }
+
+ match self.producer.send(record) {
+ Ok(ack_future) => {
+ if hit_queue_full {
+ counter!(
+ "capture_v1_kafka_queue_full_retries_total",
+ "mode" => labels.mode,
+ "cluster" => labels.sink,
+ "result" => "recovered",
+ )
+ .increment(1);
+ }
+ enqueued_keys.push(uuid);
+ pending.push(Box::pin(async move {
+ let result = ack_future.await;
+ (uuid, Utc::now(), result)
+ }));
+ break;
+ }
+ Err((e, returned_record))
+ if e.is_queue_full() && enqueue_attempt < enqueue_retry_max =>
+ {
+ hit_queue_full = true;
+ record = returned_record;
+ continue;
+ }
+ Err((e, _)) => {
+ if hit_queue_full || e.is_queue_full() {
+ counter!(
+ "capture_v1_kafka_queue_full_retries_total",
+ "mode" => labels.mode,
+ "cluster" => labels.sink,
+ "result" => "exhausted",
+ )
+ .increment(1);
+ }
+ let sink_err = KafkaSinkError::Produce(e);
+ let outcome = sink_err.outcome();
+ counter!(
+ "capture_v1_kafka_publish_total",
+ "mode" => labels.mode,
+ "cluster" => labels.sink,
+ "outcome" => outcome.as_tag(),
+ "path" => labels.path.clone(),
+ "attempt" => labels.attempt.clone(),
+ )
+ .increment(1);
+ results.push(Box::new(KafkaResult::err(uuid, sink_err, enqueued_at)));
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ /// Phase 2: drain ack futures with a per-sink deadline. Dropping remaining
+ /// futures on timeout is safe — the underlying DeliveryFuture is a
+ /// oneshot::Receiver; dropping it just means rdkafka's delivery callback
+ /// send() returns Err (silently ignored). The message still completes in
+ /// librdkafka (or times out via message.timeout.ms).
+ async fn drain_acks(
+ &self,
+ labels: &MetricLabels,
+ enqueued_at: DateTime<Utc>,
+ results: &mut Vec<Box<dyn SinkResult>>,
+ pending: &mut FuturesUnordered<AckFuture>,
+ ) -> HashSet<Uuid> {
+ let deadline = tokio::time::Instant::now() + self.config.produce_timeout;
+ let mut resolved_keys: HashSet<Uuid> = HashSet::new();
+
+ loop {
+ match tokio::time::timeout_at(deadline, pending.next()).await {
+ Ok(Some((uuid, completed_at, ack))) => {
+ resolved_keys.insert(uuid);
+ match ack {
+ Ok(()) => {
+ counter!(
+ "capture_v1_kafka_publish_total",
+ "mode" => labels.mode,
+ "cluster" => labels.sink,
+ "outcome" => Outcome::Success.as_tag(),
+ "path" => labels.path.clone(),
+ "attempt" => labels.attempt.clone(),
+ )
+ .increment(1);
+ let elapsed = completed_at.signed_duration_since(enqueued_at);
+ if let Ok(secs) = elapsed.to_std() {
+ histogram!(
+ "capture_v1_kafka_ack_duration_seconds",
+ "mode" => labels.mode,
+ "cluster" => labels.sink,
+ "outcome" => Outcome::Success.as_tag(),
+ "path" => labels.path.clone(),
+ "attempt" => labels.attempt.clone(),
+ )
+ .record(secs.as_secs_f64());
+ }
+ results.push(Box::new(
+ KafkaResult::ok(uuid, enqueued_at).with_completed_at(completed_at),
+ ));
+ }
+ Err(e) => {
+ let sink_err = KafkaSinkError::Produce(e);
+ let outcome = sink_err.outcome();
+ counter!(
+ "capture_v1_kafka_publish_total",
+ "mode" => labels.mode,
+ "cluster" => labels.sink,
+ "outcome" => outcome.as_tag(),
+ "path" => labels.path.clone(),
+ "attempt" => labels.attempt.clone(),
+ )
+ .increment(1);
+ results.push(Box::new(
+ KafkaResult::err(uuid, sink_err, enqueued_at)
+ .with_completed_at(completed_at),
+ ));
+ }
+ }
+ }
+ Ok(None) => break,
+ Err(_) => break,
+ }
+ }
+ resolved_keys
+ }
+
+ /// Phase 3: identify enqueued events whose acks were not resolved before
+ /// the deadline and emit timeout results.
+ fn collect_timeouts(
+ labels: &MetricLabels,
+ enqueued_at: DateTime<Utc>,
+ enqueued_keys: Vec<Uuid>,
+ resolved_keys: &HashSet<Uuid>,
+ results: &mut Vec<Box<dyn SinkResult>>,
+ ) {
+ let timed_out_keys: Vec<_> = enqueued_keys
+ .into_iter()
+ .filter(|k| !resolved_keys.contains(k))
+ .collect();
+ if timed_out_keys.is_empty() {
+ return;
+ }
+ counter!(
+ "capture_v1_kafka_publish_total",
+ "mode" => labels.mode,
+ "cluster" => labels.sink,
+ "outcome" => Outcome::Timeout.as_tag(),
+ "path" => labels.path.clone(),
+ "attempt" => labels.attempt.clone(),
+ )
+ .increment(timed_out_keys.len() as u64);
+ let gave_up_at = Utc::now();
+ for uuid in timed_out_keys {
+ results.push(Box::new(
+ KafkaResult::err(uuid, KafkaSinkError::Timeout, enqueued_at)
+ .with_completed_at(gave_up_at),
+ ));
+ }
+ }
+}
+
+#[async_trait]
+impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {
+ fn name(&self) -> SinkName {
+ self.name
+ }
+
+ async fn publish_batch(
+ &self,
+ ctx: &Context,
+ events: &[&(dyn Event + Send + Sync)],
+ ) -> Vec<Box<dyn SinkResult>> {
+ let labels = MetricLabels {
+ sink: self.name.as_str(),
+ mode: self.capture_mode.as_tag(),
+ path: ctx.path.clone().into(),
+ attempt: ctx.attempt.to_string().into(),
+ };
+
+ if !self.producer.is_ready() {
+ crate::ctx_log!(
+ Level::ERROR,
+ ctx,
+ sink = labels.sink,
+ mode = labels.mode,
+ "producer not ready — rejecting batch"
+ );
+ return reject_publishable(events, &labels);
+ }
+
+ let enqueued_at = Utc::now();
+ let mut results: Vec<Box<dyn SinkResult>> = Vec::new();
+ let mut pending: FuturesUnordered<AckFuture> = FuturesUnordered::new();
+ let mut enqueued_keys: Vec<Uuid> = Vec::new();
+
+ self.enqueue_events(
+ ctx,
+ events,
+ &labels,
+ enqueued_at,
+ &mut results,
+ &mut pending,
+ &mut enqueued_keys,
+ )
+ .await;
+
+ let resolved_keys = self
+ .drain_acks(&labels, enqueued_at, &mut results, &mut pending)
+ .await;
+
+ Self::collect_timeouts(
+ &labels,
+ enqueued_at,
+ enqueued_keys,
+ &resolved_keys,
+ &mut results,
+ );
+
+ let summary = BatchSummary::from_results(&results);
+ if summary.all_ok() {
+ crate::ctx_log!(Level::DEBUG, ctx,
+ sink = labels.sink,
+ mode = labels.mode,
+ %summary,
+ "batch published");
+ } else if summary.succeeded == 0 {
+ crate::ctx_log!(Level::ERROR, ctx,
+ sink = labels.sink,
+ mode = labels.mode,
+ %summary,
+ errors = ?summary.errors,
+ "batch fully failed");
+ } else {
+ crate::ctx_log!(Level::WARN, ctx,
+ sink = labels.sink,
+ mode = labels.mode,
+ %summary,
+ errors = ?summary.errors,
+ "batch partially failed");
+ }
+ for (tag, count) in &summary.errors {
+ counter!(
+ "capture_v1_kafka_produce_errors_total",
+ "cluster" => labels.sink,
+ "mode" => labels.mode,
+ "error" => *tag
+ )
+ .increment(*count as u64);
+ }
+
+ if summary.succeeded > 0 {
+ self.handle.report_healthy();
+ }
+ results
+ }
+
+ async fn flush(&self) -> anyhow::Result<()> {
+ let timeout = self.config.produce_timeout;
+ let producer = self.producer.clone();
+ let name_str = self.name.as_str();
+ tokio::task::spawn_blocking(move || {
+ producer
+ .flush(timeout)
+ .map_err(|e| anyhow::anyhow!("{name_str}: flush error: {e:#}"))
+ })
+ .await
+ .map_err(|e| anyhow::anyhow!("flush task panicked: {e:#}"))?
+ }
+}
diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rs
new file mode 100644
index 000000000000..971947cc63a9
--- /dev/null
+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs
@@ -0,0 +1,1134 @@
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Duration;
+
+use common_types::{CapturedEvent, CapturedEventHeaders, RawEvent};
+use rdkafka::error::RDKafkaErrorCode;
+use rstest::rstest;
+use uuid::Uuid;
+
+use crate::config::CaptureMode;
+use crate::v1::context::Context;
+use crate::v1::sinks::event::Event;
+use crate::v1::sinks::sink::Sink;
+use crate::v1::sinks::types::{BatchSummary, Outcome};
+use crate::v1::sinks::{Config, Destination, SinkName};
+use crate::v1::test_utils::{self, WrappedEventMut};
+
+use super::mock::MockProducer;
+use super::producer::ProduceError;
+use super::sink::KafkaSink;
+
+/// All-None CapturedEventHeaders for stubbing FakeEvent. `CapturedEventHeaders`
+/// does not derive `Default` in common_types; keep the literal here so the
+/// stub doesn't leak unrelated fields into sink_tests.
+fn empty_captured_headers() -> CapturedEventHeaders {
+ CapturedEventHeaders {
+ token: None,
+ distinct_id: None,
+ session_id: None,
+ timestamp: None,
+ event: None,
+ uuid: None,
+ now: None,
+ force_disable_person_processing: None,
+ historical_migration: None,
+ dlq_reason: None,
+ dlq_step: None,
+ dlq_timestamp: None,
+ }
+}
+
+// ---------------------------------------------------------------------------
+// FakeEvent
+// ---------------------------------------------------------------------------
+
+struct FakeEvent {
+ parsed_uuid: Uuid,
+ publish: bool,
+ destination: Destination,
+ partition_key: Option<String>,
+ payload: Result<String, String>,
+ event_headers: CapturedEventHeaders,
+}
+
+impl FakeEvent {
+ fn ok(uuid: &str) -> Self {
+ Self {
+ parsed_uuid: Uuid::new_v4(),
+ publish: true,
+ destination: Destination::AnalyticsMain,
+ partition_key: Some(format!("phc_test:{uuid}")),
+ payload: Ok(r#"{"event":"test"}"#.to_string()),
+ event_headers: empty_captured_headers(),
+ }
+ }
+
+ fn with_destination(mut self, d: Destination) -> Self {
+ self.destination = d;
+ self
+ }
+
+ fn with_publish(mut self, p: bool) -> Self {
+ self.publish = p;
+ self
+ }
+
+ fn with_payload(mut self, p: Result<String, String>) -> Self {
+ self.payload = p;
+ self
+ }
+
+ fn with_partition_key(mut self, k: Option<&str>) -> Self {
+ self.partition_key = k.map(String::from);
+ self
+ }
+}
+
+impl Event for FakeEvent {
+ fn uuid(&self) -> Uuid {
+ self.parsed_uuid
+ }
+
+ fn should_publish(&self) -> bool {
+ self.publish
+ }
+
+ fn destination(&self) -> &Destination {
+ &self.destination
+ }
+
+ fn headers(&self, _ctx: &Context) -> CapturedEventHeaders {
+ self.event_headers.clone()
+ }
+
+ fn partition_key<'buf>(&self, _ctx: &Context, buf: &'buf mut String) -> Option<&'buf str> {
+ match &self.partition_key {
+ Some(k) => {
+ buf.push_str(k);
+ Some(buf.as_str())
+ }
+ None => None,
+ }
+ }
+
+ fn serialize_into(&self, _ctx: &Context, buf: &mut String) -> anyhow::Result<()> {
+ match &self.payload {
+ Ok(p) => {
+ buf.push_str(p);
+ Ok(())
+ }
+ Err(e) => Err(anyhow::anyhow!(e.clone())),
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// TestHarness
+// ---------------------------------------------------------------------------
+
+struct TestHarness {
+ sink: KafkaSink<MockProducer>,
+ producer: Arc<MockProducer>,
+ handle: lifecycle::Handle,
+ ctx: Context,
+ _monitor: lifecycle::MonitorGuard,
+}
+
+impl TestHarness {
+ fn new() -> Self {
+ Self::builder().build()
+ }
+
+ fn builder() -> HarnessBuilder {
+ HarnessBuilder {
+ produce_timeout: Duration::from_secs(30),
+ send_error: None,
+ send_error_count: None,
+ ack_error: None,
+ ack_delay: None,
+ not_ready: false,
+ liveness: None,
+ enqueue_retry_max: None,
+ enqueue_poll_ms: None,
+ }
+ }
+}
+
+struct HarnessBuilder {
+ produce_timeout: Duration,
+ send_error: Option<fn() -> ProduceError>,
+ send_error_count: Option<u32>,
+ ack_error: Option<fn() -> ProduceError>,
+ ack_delay: Option<Duration>,
+ not_ready: bool,
+ liveness: Option<(Duration, Duration)>,
+ enqueue_retry_max: Option<u32>,
+ enqueue_poll_ms: Option<u32>,
+}
+
+impl HarnessBuilder {
+ fn produce_timeout(mut self, d: Duration) -> Self {
+ self.produce_timeout = d;
+ self
+ }
+
+ fn send_error(mut self, f: fn() -> ProduceError) -> Self {
+ self.send_error = Some(f);
+ self
+ }
+
+ fn send_error_count(mut self, n: u32) -> Self {
+ self.send_error_count = Some(n);
+ self
+ }
+
+ fn ack_error(mut self, f: fn() -> ProduceError) -> Self {
+ self.ack_error = Some(f);
+ self
+ }
+
+ fn ack_delay(mut self, d: Duration) -> Self {
+ self.ack_delay = Some(d);
+ self
+ }
+
+ fn not_ready(mut self) -> Self {
+ self.not_ready = true;
+ self
+ }
+
+ fn with_liveness(mut self, deadline: Duration, poll_interval: Duration) -> Self {
+ self.liveness = Some((deadline, poll_interval));
+ self
+ }
+
+ fn enqueue_retry_max(mut self, n: u32) -> Self {
+ self.enqueue_retry_max = Some(n);
+ self
+ }
+
+ fn enqueue_poll_ms(mut self, ms: u32) -> Self {
+ self.enqueue_poll_ms = Some(ms);
+ self
+ }
+
+ fn build(self) -> TestHarness {
+ let mut builder = lifecycle::Manager::builder("test")
+ .with_trap_signals(false)
+ .with_prestop_check(false);
+
+ if let Some((_, poll_interval)) = self.liveness {
+ builder = builder.with_health_poll_interval(poll_interval);
+ }
+
+ let mut manager = builder.build();
+
+ let mut opts = lifecycle::ComponentOptions::new();
+ if let Some((deadline, _)) = self.liveness {
+ opts = opts.with_liveness_deadline(deadline);
+ }
+ let handle = manager.register("kafka_sink_test", opts);
+ handle.report_healthy();
+
+ let monitor = manager.monitor_background();
+
+ let mut mock = MockProducer::new(SinkName::Msk, handle.clone());
+ if let Some(f) = self.send_error {
+ mock = mock.with_send_error(f);
+ }
+ if let Some(n) = self.send_error_count {
+ mock = mock.with_send_error_count(n);
+ }
+ if let Some(f) = self.ack_error {
+ mock = mock.with_ack_error(f);
+ }
+ if let Some(d) = self.ack_delay {
+ mock = mock.with_ack_delay(d);
+ }
+ if self.not_ready {
+ mock = mock.with_not_ready();
+ }
+
+ let producer = Arc::new(mock);
+
+ let mut kafka_config = crate::v1::test_utils::test_kafka_config();
+ if let Some(n) = self.enqueue_retry_max {
+ kafka_config.enqueue_retry_max = n;
+ }
+ if let Some(ms) = self.enqueue_poll_ms {
+ kafka_config.enqueue_poll_ms = ms;
+ }
+
+ let config = Config {
+ produce_timeout: self.produce_timeout,
+ kafka: kafka_config,
+ };
+
+ let sink = KafkaSink::new(
+ SinkName::Msk,
+ Arc::clone(&producer),
+ config,
+ CaptureMode::Events,
+ handle.clone(),
+ );
+
+ TestHarness {
+ sink,
+ producer,
+ handle,
+ ctx: {
+ let mut ctx = crate::v1::test_utils::test_context();
+ ctx.created_at = None;
+ ctx
+ },
+ _monitor: monitor,
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// 1. Happy path (single event)
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn single_event_success() {
+ let h = TestHarness::new();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].key(), event.parsed_uuid);
+ assert_eq!(results[0].outcome(), Outcome::Success);
+ assert!(results[0].cause().is_none());
+ assert!(results[0].elapsed().is_some());
+
+ assert_eq!(h.producer.record_count(), 1);
+ h.producer.with_records(|records| {
+ assert_eq!(records[0].topic, "events_main");
+ assert_eq!(records[0].payload, r#"{"event":"test"}"#);
+ assert_eq!(records[0].key.as_deref(), Some("phc_test:evt-1"));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// 2. Non-publishable events silently skipped
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn non_publishable_events_skipped() {
+ let h = TestHarness::new();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2").with_publish(false);
+ let e3 = FakeEvent::ok("evt-3");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2, &e3];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].key(), e1.parsed_uuid);
+ assert_eq!(results[1].key(), e3.parsed_uuid);
+ assert_eq!(h.producer.record_count(), 2);
+}
+
+// ---------------------------------------------------------------------------
+// 3. Destination::Drop skips without result
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn destination_drop_skips_without_result() {
+ let h = TestHarness::new();
+ let event = FakeEvent::ok("evt-1").with_destination(Destination::Drop);
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert!(results.is_empty());
+ assert_eq!(h.producer.record_count(), 0);
+}
+
+// ---------------------------------------------------------------------------
+// 4. Sink unavailable (producer not ready)
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn sink_unavailable() {
+ let h = TestHarness::builder().not_ready().build();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 2);
+ for r in &results {
+ assert_eq!(r.outcome(), Outcome::RetriableError);
+ assert_eq!(r.cause(), Some("sink_unavailable"));
+ }
+ assert_eq!(h.producer.record_count(), 0);
+}
+
+// ---------------------------------------------------------------------------
+// 5. Send-time retriable error (queue full)
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn send_error_retriable_queue_full() {
+ let h = TestHarness::builder()
+ .send_error(|| ProduceError::Kafka {
+ code: RDKafkaErrorCode::QueueFull,
+ })
+ .enqueue_retry_max(0)
+ .build();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].key(), event.parsed_uuid);
+ assert_eq!(results[0].outcome(), Outcome::RetriableError);
+ assert_eq!(results[0].cause(), Some("queue_full"));
+ assert_eq!(h.producer.record_count(), 0);
+}
+
+// ---------------------------------------------------------------------------
+// 5b. QueueFull retry succeeds after drain
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn queue_full_retry_succeeds_after_drain() {
+ let h = TestHarness::builder()
+ .send_error(|| ProduceError::Kafka {
+ code: RDKafkaErrorCode::QueueFull,
+ })
+ .send_error_count(2)
+ .enqueue_retry_max(3)
+ .enqueue_poll_ms(1)
+ .build();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].key(), event.parsed_uuid);
+ assert_eq!(results[0].outcome(), Outcome::Success);
+ assert_eq!(h.producer.record_count(), 1);
+}
+
+// ---------------------------------------------------------------------------
+// 5c. QueueFull retry exhausted
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn queue_full_retry_exhausted() {
+ let h = TestHarness::builder()
+ .send_error(|| ProduceError::Kafka {
+ code: RDKafkaErrorCode::QueueFull,
+ })
+ .enqueue_retry_max(2)
+ .enqueue_poll_ms(1)
+ .build();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].key(), event.parsed_uuid);
+ assert_eq!(results[0].outcome(), Outcome::RetriableError);
+ assert_eq!(results[0].cause(), Some("queue_full"));
+ assert_eq!(h.producer.record_count(), 0);
+}
+
+// ---------------------------------------------------------------------------
+// 5d. QueueFull retry disabled (enqueue_retry_max = 0)
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn queue_full_retry_zero_max_disables_retry() {
+ let h = TestHarness::builder()
+ .send_error(|| ProduceError::Kafka {
+ code: RDKafkaErrorCode::QueueFull,
+ })
+ .send_error_count(1)
+ .enqueue_retry_max(0)
+ .enqueue_poll_ms(1)
+ .build();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].outcome(), Outcome::RetriableError);
+ assert_eq!(results[0].cause(), Some("queue_full"));
+ assert_eq!(h.producer.record_count(), 0);
+}
+
+// ---------------------------------------------------------------------------
+// 6. Send-time fatal error (event too big)
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn send_error_fatal_event_too_big() {
+ let h = TestHarness::builder()
+ .send_error(|| ProduceError::EventTooBig {
+ message: "too big".into(),
+ })
+ .build();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].outcome(), Outcome::FatalError);
+ assert_eq!(results[0].cause(), Some("event_too_big"));
+}
+
+// ---------------------------------------------------------------------------
+// 7. Ack-time retriable error (delivery cancelled)
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn ack_error_retriable_delivery_cancelled() {
+ let h = TestHarness::builder()
+ .ack_error(|| ProduceError::DeliveryCancelled)
+ .build();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].key(), event.parsed_uuid);
+ assert_eq!(results[0].outcome(), Outcome::RetriableError);
+ assert_eq!(results[0].cause(), Some("delivery_cancelled"));
+ assert!(results[0].elapsed().is_some());
+ // Enqueue succeeded before ack failed
+ assert_eq!(h.producer.record_count(), 1);
+}
+
+// ---------------------------------------------------------------------------
+// 8. Ack-time retriable kafka error (topic auth failed — infrastructure
+// misconfiguration, may succeed on a different pod)
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn ack_error_retriable_topic_auth() {
+ let h = TestHarness::builder()
+ .ack_error(|| ProduceError::Kafka {
+ code: RDKafkaErrorCode::TopicAuthorizationFailed,
+ })
+ .build();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].outcome(), Outcome::RetriableError);
+ assert_eq!(results[0].cause(), Some("topic_authorization_failed"));
+ assert!(results[0].elapsed().is_some());
+ assert_eq!(h.producer.record_count(), 1);
+}
+
+// ---------------------------------------------------------------------------
+// 9. Produce timeout
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn produce_timeout_single() {
+ let h = TestHarness::builder()
+ .ack_delay(Duration::from_secs(60))
+ .produce_timeout(Duration::from_millis(50))
+ .build();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].key(), event.parsed_uuid);
+ assert_eq!(results[0].outcome(), Outcome::Timeout);
+ assert_eq!(results[0].cause(), Some("timeout"));
+}
+
+#[tokio::test]
+async fn produce_timeout_batch_all_pending_get_timeout() {
+ let h = TestHarness::builder()
+ .ack_delay(Duration::from_secs(60))
+ .produce_timeout(Duration::from_millis(50))
+ .build();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2");
+ let e3 = FakeEvent::ok("evt-3");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2, &e3];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 3);
+ for r in &results {
+ assert_eq!(r.outcome(), Outcome::Timeout);
+ assert_eq!(r.cause(), Some("timeout"));
+ }
+}
+
+// ---------------------------------------------------------------------------
+// 10. Serialization failure
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn serialization_failure() {
+ let h = TestHarness::new();
+ let event = FakeEvent::ok("evt-1").with_payload(Err("bad json".into()));
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].key(), event.parsed_uuid);
+ assert_eq!(results[0].outcome(), Outcome::FatalError);
+ assert_eq!(results[0].cause(), Some("serialization_failed"));
+ assert!(
+ results[0].detail().unwrap().contains("bad json"),
+ "expected detail to contain 'bad json', got: {:?}",
+ results[0].detail()
+ );
+ assert_eq!(h.producer.record_count(), 0);
+}
+
+// ---------------------------------------------------------------------------
+// 11. Mixed batch (some succeed, some fail)
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn mixed_batch_success_and_serialize_error() {
+ let h = TestHarness::new();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2").with_payload(Err("serialize error".into()));
+ let e3 = FakeEvent::ok("evt-3");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2, &e3];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 3);
+
+ // Serialization errors are returned inline before ack results, so evt-2
+ // appears first in the results vec (pushed during Phase 1), while evt-1
+ // and evt-3 are appended during Phase 2 (ack drain). Order among the
+ // ack results may vary, so collect into maps.
+ let by_key: HashMap<Uuid, _> = results.iter().map(|r| (r.key(), r)).collect();
+
+ assert_eq!(by_key[&e1.parsed_uuid].outcome(), Outcome::Success);
+ assert_eq!(by_key[&e2.parsed_uuid].outcome(), Outcome::FatalError);
+ assert_eq!(
+ by_key[&e2.parsed_uuid].cause(),
+ Some("serialization_failed")
+ );
+ assert_eq!(by_key[&e3.parsed_uuid].outcome(), Outcome::Success);
+
+ // Only the two successful events were enqueued
+ assert_eq!(h.producer.record_count(), 2);
+}
+
+// ---------------------------------------------------------------------------
+// 12. BatchSummary correctness
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn batch_summary_from_mixed_results() {
+ let h = TestHarness::new();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2").with_payload(Err("ser error".into()));
+ let e3 = FakeEvent::ok("evt-3");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2, &e3];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+ let summary = BatchSummary::from_results(&results);
+
+ assert_eq!(summary.total, 3);
+ assert_eq!(summary.succeeded, 2);
+ assert_eq!(summary.retriable, 0);
+ assert_eq!(summary.fatal, 1);
+ assert_eq!(summary.timed_out, 0);
+ assert!(!summary.all_ok());
+ assert_eq!(summary.errors.get("serialization_failed").copied(), Some(1));
+}
+
+// ---------------------------------------------------------------------------
+// 13. Flush delegates to producer
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn flush_ok() {
+ let h = TestHarness::new();
+ assert!(h.sink.flush().await.is_ok());
+}
+
+// ---------------------------------------------------------------------------
+// 14. Sink::name() returns configured name
+// ---------------------------------------------------------------------------
+
+#[test]
+fn sink_name_returns_configured_name() {
+ let h = TestHarness::new();
+ assert_eq!(h.sink.name(), SinkName::Msk);
+}
+
+// ---------------------------------------------------------------------------
+// Topic routing for non-default destinations
+// ---------------------------------------------------------------------------
+
+#[rstest]
+#[case::historical(Destination::AnalyticsHistorical, "events_hist")]
+#[case::overflow(Destination::Overflow, "events_overflow")]
+#[case::dlq(Destination::Dlq, "events_dlq")]
+#[case::custom(Destination::Custom("my_topic".into()), "my_topic")]
+#[tokio::test]
+async fn destination_routes_to_correct_topic(
+ #[case] destination: Destination,
+ #[case] expected_topic: &str,
+) {
+ let h = TestHarness::new();
+ let event = FakeEvent::ok("evt-1").with_destination(destination);
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].outcome(), Outcome::Success);
+ h.producer.with_records(|records| {
+ assert_eq!(records[0].topic, expected_topic);
+ });
+}
+
+// ---------------------------------------------------------------------------
+// BatchSummary with timeout results
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn batch_summary_with_timeouts() {
+ let h = TestHarness::builder()
+ .ack_delay(Duration::from_secs(60))
+ .produce_timeout(Duration::from_millis(50))
+ .build();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+ let summary = BatchSummary::from_results(&results);
+
+ assert_eq!(summary.total, 2);
+ assert_eq!(summary.succeeded, 0);
+ assert_eq!(summary.retriable, 0);
+ assert_eq!(summary.fatal, 0);
+ assert_eq!(summary.timed_out, 2);
+ assert!(!summary.all_ok());
+ assert_eq!(summary.errors.get("timeout").copied(), Some(2));
+}
+
+// ===========================================================================
+// Health heartbeat tests
+//
+// Production-proportional timing (100x faster, same ratios):
+// production: liveness_deadline=30s, health_poll=2s, produce_timeout=30s
+// test: liveness_deadline=300ms, health_poll=20ms, produce_timeout=300ms
+// ===========================================================================
+
+const HEALTH_TEST_LIVENESS_DEADLINE: Duration = Duration::from_millis(300);
+const HEALTH_TEST_POLL_INTERVAL: Duration = Duration::from_millis(20);
+const HEALTH_TEST_PRODUCE_TIMEOUT: Duration = Duration::from_millis(300);
+/// Sleep long enough for the liveness deadline to expire + poll to detect it.
+const HEALTH_TEST_UNHEALTHY_SLEEP: Duration = Duration::from_millis(500);
+/// Sleep just long enough for the poll to run, but well before deadline expiry.
+const HEALTH_TEST_HEALTHY_SLEEP: Duration = Duration::from_millis(50);
+
+// ---------------------------------------------------------------------------
+// Health: no heartbeat when every event fails (parameterized by failure mode)
+// ---------------------------------------------------------------------------
+
+enum FailureMode {
+ Timeout,
+ SendError,
+ AckError,
+ SerializationError,
+}
+
+fn health_harness(mode: &FailureMode) -> TestHarness {
+ let mut b = TestHarness::builder()
+ .with_liveness(HEALTH_TEST_LIVENESS_DEADLINE, HEALTH_TEST_POLL_INTERVAL)
+ .produce_timeout(HEALTH_TEST_PRODUCE_TIMEOUT);
+ match mode {
+ FailureMode::Timeout => {
+ b = b.ack_delay(Duration::from_secs(10));
+ }
+ FailureMode::SendError => {
+ b = b
+ .send_error(|| ProduceError::Kafka {
+ code: RDKafkaErrorCode::QueueFull,
+ })
+ .enqueue_retry_max(0);
+ }
+ FailureMode::AckError => {
+ b = b.ack_error(|| ProduceError::DeliveryCancelled);
+ }
+ FailureMode::SerializationError => {}
+ }
+ b.build()
+}
+
+fn health_events(mode: &FailureMode) -> Vec<FakeEvent> {
+ let make = |id: &str| match mode {
+ FailureMode::SerializationError => FakeEvent::ok(id).with_payload(Err("bad".into())),
+ _ => FakeEvent::ok(id),
+ };
+ vec![make("evt-1"), make("evt-2"), make("evt-3")]
+}
+
+fn expected_outcome(mode: &FailureMode) -> Outcome {
+ match mode {
+ FailureMode::Timeout => Outcome::Timeout,
+ FailureMode::SendError => Outcome::RetriableError,
+ FailureMode::AckError => Outcome::RetriableError,
+ FailureMode::SerializationError => Outcome::FatalError,
+ }
+}
+
+#[rstest]
+#[case::timeout(FailureMode::Timeout)]
+#[case::send_error(FailureMode::SendError)]
+#[case::ack_error(FailureMode::AckError)]
+#[case::serialization_error(FailureMode::SerializationError)]
+#[tokio::test]
+async fn health_not_refreshed_on_full_failure(#[case] mode: FailureMode) {
+ let h = health_harness(&mode);
+ let owned_events = health_events(&mode);
+ let refs: Vec<&FakeEvent> = owned_events.iter().collect();
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![refs[0], refs[1], refs[2]];
+ let expected = expected_outcome(&mode);
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+ for r in &results {
+ assert_eq!(r.outcome(), expected);
+ }
+
+ tokio::time::sleep(HEALTH_TEST_UNHEALTHY_SLEEP).await;
+ assert!(
+ !h.handle.is_healthy(),
+ "handle should be unhealthy after full {expected:?} batch"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Health: all events succeed -> heartbeat refreshed -> is_healthy stays true
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn health_refreshed_on_full_success() {
+ let h = TestHarness::builder()
+ .with_liveness(HEALTH_TEST_LIVENESS_DEADLINE, HEALTH_TEST_POLL_INTERVAL)
+ .produce_timeout(HEALTH_TEST_PRODUCE_TIMEOUT)
+ .build();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2");
+ let e3 = FakeEvent::ok("evt-3");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2, &e3];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+ for r in &results {
+ assert_eq!(r.outcome(), Outcome::Success);
+ }
+
+ tokio::time::sleep(HEALTH_TEST_HEALTHY_SLEEP).await;
+ assert!(
+ h.handle.is_healthy(),
+ "handle should stay healthy after successful batch"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Health: mixed batch (some succeed, some fail) -> heartbeat refreshed
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn health_refreshed_on_partial_success() {
+ let h = TestHarness::builder()
+ .with_liveness(HEALTH_TEST_LIVENESS_DEADLINE, HEALTH_TEST_POLL_INTERVAL)
+ .produce_timeout(HEALTH_TEST_PRODUCE_TIMEOUT)
+ .build();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2").with_payload(Err("bad".into()));
+ let e3 = FakeEvent::ok("evt-3");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2, &e3];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+ let summary = BatchSummary::from_results(&results);
+ assert!(summary.succeeded > 0);
+ assert!(summary.fatal > 0);
+
+ tokio::time::sleep(HEALTH_TEST_HEALTHY_SLEEP).await;
+ assert!(
+ h.handle.is_healthy(),
+ "handle should stay healthy when at least one event succeeded"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Partition key: None vs Some
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn none_partition_key_propagates_as_none() {
+ let h = TestHarness::new();
+ let event = FakeEvent::ok("evt-1").with_partition_key(None);
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].outcome(), Outcome::Success);
+ h.producer.with_records(|records| {
+ assert_eq!(
+ records[0].key, None,
+ "None partition key must propagate as None"
+ );
+ });
+}
+
+#[tokio::test]
+async fn some_partition_key_propagates_as_some() {
+ let h = TestHarness::new();
+ let event = FakeEvent::ok("evt-1").with_partition_key(Some("phc_test:user-1"));
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].outcome(), Outcome::Success);
+ h.producer.with_records(|records| {
+ assert_eq!(records[0].key.as_deref(), Some("phc_test:user-1"));
+ });
+}
+
+// ===========================================================================
+// Realistic WrappedEvent round-trip tests
+//
+// These use production-shaped fixtures from test_utils and verify the
+// MockProducer payload deserializes as CapturedEvent + RawEvent.
+// ===========================================================================
+
+#[tokio::test]
+async fn realistic_single_pageview_round_trip() {
+ let h = TestHarness::new();
+ let wrapped = test_utils::realistic_pageview("user-42");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].key(), wrapped.uuid);
+ assert_eq!(results[0].outcome(), Outcome::Success);
+
+ h.producer.with_records(|records| {
+ assert_eq!(records.len(), 1);
+ assert_eq!(records[0].topic, "events_main");
+
+ let captured: CapturedEvent =
+ serde_json::from_str(&records[0].payload).expect("must deserialize as CapturedEvent");
+ assert_eq!(captured.uuid, wrapped.uuid);
+ assert_eq!(captured.distinct_id, "user-42");
+ assert_eq!(captured.event, "$pageview");
+
+ let data: RawEvent =
+ serde_json::from_str(&captured.data).expect("data must deserialize as RawEvent");
+ assert_eq!(data.event, "$pageview");
+ assert_eq!(data.properties["$browser"], "Chrome");
+ assert_eq!(
+ data.properties["$session_id"],
+ "01jq9abc-def0-1234-5678-9abcdef01234"
+ );
+ assert_eq!(data.properties["$process_person_profile"], true);
+ });
+}
+
+#[tokio::test]
+async fn realistic_batch_round_trip() {
+ let h = TestHarness::new();
+ let batch = test_utils::realistic_batch();
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&batch[0], &batch[1], &batch[2]];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 3);
+ for r in &results {
+ assert_eq!(r.outcome(), Outcome::Success);
+ }
+
+ h.producer.with_records(|records| {
+ assert_eq!(records.len(), 3);
+ for record in records {
+ let captured: CapturedEvent =
+ serde_json::from_str(&record.payload).expect("must deserialize as CapturedEvent");
+ let _data: RawEvent =
+ serde_json::from_str(&captured.data).expect("data must deserialize as RawEvent");
+ }
+
+ let names: Vec<&str> = records
+ .iter()
+ .map(|r| {
+ let c: CapturedEvent = serde_json::from_str(&r.payload).unwrap();
+ match c.event.as_str() {
+ "$pageview" => "$pageview",
+ "$identify" => "$identify",
+ _ => "custom",
+ }
+ })
+ .collect();
+ assert_eq!(names, vec!["$pageview", "$identify", "custom"]);
+ });
+}
+
+#[tokio::test]
+async fn realistic_event_with_destination_mutation() {
+ let h = TestHarness::new();
+ let wrapped = test_utils::realistic_pageview("user-42")
+ .with_destination(Destination::AnalyticsHistorical);
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].outcome(), Outcome::Success);
+ h.producer.with_records(|records| {
+ assert_eq!(records[0].topic, "events_hist");
+ });
+}
+
+#[tokio::test]
+async fn realistic_dropped_event_not_published() {
+ use crate::v1::analytics::types::EventResult;
+
+ let h = TestHarness::new();
+ let wrapped = test_utils::realistic_pageview("user-42")
+ .with_result(EventResult::Drop, Some("rate_limited"));
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert!(results.is_empty());
+ assert_eq!(h.producer.record_count(), 0);
+}
+
+// ===========================================================================
+// Coverage gap fills (C5)
+// ===========================================================================
+
+// ---------------------------------------------------------------------------
+// Mixed send error + ack error in one batch: first event fails at send,
+// remaining events fail at ack. Verifies both error types are reported.
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn mixed_send_error_and_ack_error_in_batch() {
+ let h = TestHarness::builder()
+ .send_error(|| ProduceError::Kafka {
+ code: RDKafkaErrorCode::QueueFull,
+ })
+ .send_error_count(1)
+ .enqueue_retry_max(0)
+ .ack_error(|| ProduceError::DeliveryCancelled)
+ .build();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2");
+ let e3 = FakeEvent::ok("evt-3");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2, &e3];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 3);
+ let by_key: HashMap<Uuid, _> = results.iter().map(|r| (r.key(), r)).collect();
+
+ // evt-1: send error (queue_full)
+ assert_eq!(by_key[&e1.parsed_uuid].outcome(), Outcome::RetriableError);
+ assert_eq!(by_key[&e1.parsed_uuid].cause(), Some("queue_full"));
+
+ // evt-2 and evt-3: enqueued successfully, but ack error (delivery_cancelled)
+ assert_eq!(by_key[&e2.parsed_uuid].outcome(), Outcome::RetriableError);
+ assert_eq!(by_key[&e2.parsed_uuid].cause(), Some("delivery_cancelled"));
+ assert_eq!(by_key[&e3.parsed_uuid].outcome(), Outcome::RetriableError);
+ assert_eq!(by_key[&e3.parsed_uuid].cause(), Some("delivery_cancelled"));
+
+ // Only evt-2 and evt-3 were enqueued (evt-1 failed at send)
+ assert_eq!(h.producer.record_count(), 2);
+}
+
+// ---------------------------------------------------------------------------
+// Partial timeout: first event fails at send (immediate), remaining time out.
+// Verifies mixed Outcome::RetriableError and Outcome::Timeout in one batch.
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn partial_timeout_with_send_error() {
+ let h = TestHarness::builder()
+ .send_error(|| ProduceError::Kafka {
+ code: RDKafkaErrorCode::QueueFull,
+ })
+ .send_error_count(1)
+ .enqueue_retry_max(0)
+ .ack_delay(Duration::from_secs(60))
+ .produce_timeout(Duration::from_millis(50))
+ .build();
+ let e1 = FakeEvent::ok("evt-1");
+ let e2 = FakeEvent::ok("evt-2");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 2);
+ let by_key: HashMap<Uuid, _> = results.iter().map(|r| (r.key(), r)).collect();
+
+ // evt-1: immediate send error
+ assert_eq!(by_key[&e1.parsed_uuid].outcome(), Outcome::RetriableError);
+ assert_eq!(by_key[&e1.parsed_uuid].cause(), Some("queue_full"));
+
+ // evt-2: enqueued successfully, but ack times out
+ assert_eq!(by_key[&e2.parsed_uuid].outcome(), Outcome::Timeout);
+ assert_eq!(by_key[&e2.parsed_uuid].cause(), Some("timeout"));
+}
+
+// ---------------------------------------------------------------------------
+// Partial timeout: serialization failure + timeout in one batch.
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn partial_timeout_with_serialization_error() {
+ let h = TestHarness::builder()
+ .ack_delay(Duration::from_secs(60))
+ .produce_timeout(Duration::from_millis(50))
+ .build();
+ let e1 = FakeEvent::ok("evt-1").with_payload(Err("bad".into()));
+ let e2 = FakeEvent::ok("evt-2");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2];
+
+ let results = h.sink.publish_batch(&h.ctx, &events).await;
+
+ assert_eq!(results.len(), 2);
+ let by_key: HashMap<Uuid, _> = results.iter().map(|r| (r.key(), r)).collect();
+
+ // evt-1: serialization failure (immediate, fatal)
+ assert_eq!(by_key[&e1.parsed_uuid].outcome(), Outcome::FatalError);
+ assert_eq!(
+ by_key[&e1.parsed_uuid].cause(),
+ Some("serialization_failed")
+ );
+
+ // evt-2: enqueued, times out
+ assert_eq!(by_key[&e2.parsed_uuid].outcome(), Outcome::Timeout);
+ assert_eq!(by_key[&e2.parsed_uuid].cause(), Some("timeout"));
+}
diff --git a/rust/capture/src/v1/sinks/kafka/types.rs b/rust/capture/src/v1/sinks/kafka/types.rs
index 481241380b20..3479b7150a27 100644
--- a/rust/capture/src/v1/sinks/kafka/types.rs
+++ b/rust/capture/src/v1/sinks/kafka/types.rs
@@ -126,13 +126,11 @@ impl KafkaResult {
}
}
- #[allow(dead_code)]
pub(crate) fn with_completed_at(mut self, t: DateTime<Utc>) -> Self {
self.completed_at = Some(t);
self
}
- #[allow(dead_code)]
pub fn error(&self) -> Option<&KafkaSinkError> {
self.error.as_ref()
}
diff --git a/rust/capture/src/v1/sinks/mod.rs b/rust/capture/src/v1/sinks/mod.rs
index 2f88602c83e1..2690ea1960db 100644
--- a/rust/capture/src/v1/sinks/mod.rs
+++ b/rust/capture/src/v1/sinks/mod.rs
@@ -1,12 +1,19 @@
pub mod constants;
pub mod event;
pub mod kafka;
+pub mod router;
pub mod sink;
pub mod types;
+use std::collections::HashMap;
use std::str::FromStr;
+use std::time::Duration;
+
+use envconfig::Envconfig;
pub use event::Event;
+pub use kafka::KafkaSink;
+pub use router::{Router, RouterError};
pub use sink::Sink;
pub use types::{Destination, Outcome, SinkResult};
@@ -62,10 +69,173 @@ impl std::fmt::Display for SinkName {
}
}
+// ---------------------------------------------------------------------------
+// Config (per-sink composite)
+// ---------------------------------------------------------------------------
+
+/// Composite per-sink configuration. Contains the transport-agnostic
+/// produce timeout alongside transport-specific config (Kafka today,
+/// S3/etc. in the future).
+#[derive(Clone, Debug)]
+pub struct Config {
+ pub produce_timeout: Duration,
+ pub kafka: kafka::config::Config,
+}
+
+impl Config {
+ pub fn validate(&self) -> anyhow::Result<()> {
+ let msg_timeout = Duration::from_millis(self.kafka.message_timeout_ms as u64);
+ anyhow::ensure!(
+ self.produce_timeout >= msg_timeout,
+ "produce_timeout ({:?}) must be >= message_timeout_ms ({:?}) \
+ to avoid ghost deliveries after application-level timeout",
+ self.produce_timeout,
+ msg_timeout,
+ );
+ self.kafka.validate()?;
+ Ok(())
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Sinks (loaded collection)
+// ---------------------------------------------------------------------------
+
+/// Parsed set of v1 sink configs. The first entry in the CSV is the
+/// default sink for single-write mode.
+pub struct Sinks {
+ pub default: SinkName,
+ pub configs: HashMap<SinkName, Config>,
+}
+
+impl Sinks {
+ pub fn validate(&self) -> anyhow::Result<()> {
+ anyhow::ensure!(!self.configs.is_empty(), "no v1 sinks configured");
+ anyhow::ensure!(
+ self.configs.contains_key(&self.default),
+ "default sink '{}' is not present in configured sinks",
+ self.default,
+ );
+ for (&name, cfg) in &self.configs {
+ cfg.validate()
+ .map_err(|e| anyhow::anyhow!("sink {}: {e}", name))?;
+ }
+ Ok(())
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Loaders
+// ---------------------------------------------------------------------------
+
+/// Production entry point: reads env vars and loads sink configs.
+pub fn load_sinks(sinks_csv: &str) -> anyhow::Result<Sinks> {
+ let env: HashMap<String, String> = std::env::vars().collect();
+ load_sinks_from(sinks_csv, &env)
+}
+
+/// Testable core: loads sink configs from a provided env snapshot.
+pub fn load_sinks_from(sinks_csv: &str, env: &HashMap<String, String>) -> anyhow::Result<Sinks> {
+ let names: Vec<SinkName> = sinks_csv
+ .split(',')
+ .filter(|s| !s.trim().is_empty())
+ .map(|s| s.parse::<SinkName>())
+ .collect::<Result<_, _>>()
+ .map_err(|e| anyhow::anyhow!("bad CAPTURE_V1_SINKS: {e}"))?;
+
+ anyhow::ensure!(!names.is_empty(), "CAPTURE_V1_SINKS is empty");
+ let default = names[0];
+
+ let mut configs = HashMap::new();
+ for name in names {
+ let config = load_sink_config(name, env)
+ .map_err(|e| anyhow::anyhow!("sink {}: {e}", name.as_str()))?;
+ configs.insert(name, config);
+ }
+ Ok(Sinks { default, configs })
+}
+
+/// Load a single sink's config by stripping its env prefix and splitting
+/// keys by the `KAFKA_` sub-prefix.
+fn load_sink_config(name: SinkName, env: &HashMap<String, String>) -> anyhow::Result<Config> {
+ let prefix = name.env_prefix();
+
+ // Collect prefixes of other sinks so we can skip keys that belong to a
+ // longer prefix (e.g. MSK_ALT_ keys when loading MSK_).
+ let other_prefixes: Vec<&str> = [SinkName::Msk, SinkName::MskAlt, SinkName::Ws]
+ .iter()
+ .filter(|n| **n != name)
+ .map(|n| n.env_prefix())
+ .collect();
+
+ let mut kafka_map = HashMap::new();
+ let mut sink_map = HashMap::new();
+ for (k, v) in env {
+ if let Some(rest) = k.strip_prefix(prefix) {
+ if other_prefixes.iter().any(|op| k.starts_with(op)) {
+ continue;
+ }
+ if let Some(kafka_key) = rest.strip_prefix("KAFKA_") {
+ kafka_map.insert(kafka_key.to_string(), v.clone());
+ } else {
+ sink_map.insert(rest.to_string(), v.clone());
+ }
+ }
+ }
+
+ let kafka = kafka::config::Config::init_from_hashmap(&kafka_map)
+ .map_err(|e| anyhow::anyhow!("kafka config: {e}"))?;
+
+ let produce_timeout_ms: u64 = sink_map
+ .get("PRODUCE_TIMEOUT_MS")
+ .map(|v| v.parse::<u64>())
+ .transpose()
+ .map_err(|e| anyhow::anyhow!("bad PRODUCE_TIMEOUT_MS: {e}"))?
+ .unwrap_or(constants::DEFAULT_PRODUCE_TIMEOUT.as_millis() as u64);
+
+ Ok(Config {
+ produce_timeout: Duration::from_millis(produce_timeout_ms),
+ kafka,
+ })
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
#[cfg(test)]
mod tests {
+ use std::collections::HashMap;
+ use std::time::Duration;
+
use super::*;
+ /// Build a minimal valid env hashmap for a given SinkName.
+ fn test_env_for(name: SinkName) -> HashMap<String, String> {
+ let prefix = name.env_prefix();
+ [
+ (
+ format!("{prefix}PRODUCE_TIMEOUT_MS"),
+ constants::DEFAULT_PRODUCE_TIMEOUT.as_millis().to_string(),
+ ),
+ (format!("{prefix}KAFKA_HOSTS"), "localhost:9092".into()),
+ (format!("{prefix}KAFKA_TOPIC_MAIN"), "events_main".into()),
+ (
+ format!("{prefix}KAFKA_TOPIC_HISTORICAL"),
+ "events_hist".into(),
+ ),
+ (
+ format!("{prefix}KAFKA_TOPIC_OVERFLOW"),
+ "events_overflow".into(),
+ ),
+ (format!("{prefix}KAFKA_TOPIC_DLQ"), "events_dlq".into()),
+ ]
+ .into_iter()
+ .collect()
+ }
+
+ // -- SinkName tests --
+
#[test]
fn parse_valid_names() {
assert_eq!("msk".parse::<SinkName>().unwrap(), SinkName::Msk);
@@ -105,4 +275,221 @@ mod tests {
assert_eq!(parsed, name);
}
}
+
+ // -- load_sink_config tests --
+
+ #[test]
+ fn two_pass_split_routes_kafka_keys() {
+ let env = test_env_for(SinkName::Msk);
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ assert_eq!(cfg.kafka.hosts, "localhost:9092");
+ assert_eq!(cfg.produce_timeout, constants::DEFAULT_PRODUCE_TIMEOUT);
+ }
+
+ #[test]
+ fn produce_timeout_default() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.remove("CAPTURE_V1_SINK_MSK_PRODUCE_TIMEOUT_MS");
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ assert_eq!(cfg.produce_timeout, constants::DEFAULT_PRODUCE_TIMEOUT);
+ }
+
+ #[test]
+ fn produce_timeout_custom() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.insert(
+ "CAPTURE_V1_SINK_MSK_PRODUCE_TIMEOUT_MS".into(),
+ "45000".into(),
+ );
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ assert_eq!(cfg.produce_timeout, Duration::from_millis(45000));
+ }
+
+ #[test]
+ fn produce_timeout_invalid() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.insert(
+ "CAPTURE_V1_SINK_MSK_PRODUCE_TIMEOUT_MS".into(),
+ "abc".into(),
+ );
+ assert!(load_sink_config(SinkName::Msk, &env).is_err());
+ }
+
+ #[test]
+ fn kafka_sub_prefix_stripped() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.insert("CAPTURE_V1_SINK_MSK_KAFKA_LINGER_MS".into(), "50".into());
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ assert_eq!(cfg.kafka.linger_ms, 50);
+ }
+
+ #[test]
+ fn msk_alt_keys_do_not_leak_into_msk_config() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.insert(
+ "CAPTURE_V1_SINK_MSK_ALT_KAFKA_HOSTS".into(),
+ "alt-host:9092".into(),
+ );
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ assert_eq!(
+ cfg.kafka.hosts, "localhost:9092",
+ "MSK_ALT host should not leak into MSK config"
+ );
+ }
+
+ #[test]
+ fn non_kafka_keys_ignored_by_kafka_config() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.insert(
+ "CAPTURE_V1_SINK_MSK_SOME_FUTURE_FIELD".into(),
+ "whatever".into(),
+ );
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ assert_eq!(cfg.kafka.hosts, "localhost:9092");
+ }
+
+ #[test]
+ fn missing_kafka_hosts_errors() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.remove("CAPTURE_V1_SINK_MSK_KAFKA_HOSTS");
+ assert!(load_sink_config(SinkName::Msk, &env).is_err());
+ }
+
+ // -- load_sinks_from tests --
+
+ #[test]
+ fn single_sink_csv() {
+ let env = test_env_for(SinkName::Msk);
+ let sinks = load_sinks_from("msk", &env).unwrap();
+ assert_eq!(sinks.default, SinkName::Msk);
+ assert_eq!(sinks.configs.len(), 1);
+ assert!(sinks.configs.contains_key(&SinkName::Msk));
+ }
+
+ #[test]
+ fn multi_sink_csv() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.extend(test_env_for(SinkName::Ws));
+ let sinks = load_sinks_from("msk,ws", &env).unwrap();
+ assert_eq!(sinks.default, SinkName::Msk);
+ assert_eq!(sinks.configs.len(), 2);
+ }
+
+ #[test]
+ fn default_is_first_entry() {
+ let mut env = test_env_for(SinkName::Ws);
+ env.extend(test_env_for(SinkName::Msk));
+ let sinks = load_sinks_from("ws,msk", &env).unwrap();
+ assert_eq!(sinks.default, SinkName::Ws);
+ }
+
+ #[test]
+ fn empty_csv_errors() {
+ let env = HashMap::new();
+ assert!(load_sinks_from("", &env).is_err());
+ }
+
+ #[test]
+ fn unknown_name_in_csv_errors() {
+ let env = test_env_for(SinkName::Msk);
+ assert!(load_sinks_from("msk,bogus", &env).is_err());
+ }
+
+ #[test]
+ fn missing_env_for_listed_sink_errors() {
+ let env = HashMap::new();
+ assert!(load_sinks_from("msk", &env).is_err());
+ }
+
+ // -- validation tests --
+
+ #[test]
+ fn config_validate_ok() {
+ let env = test_env_for(SinkName::Msk);
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ assert!(cfg.validate().is_ok());
+ }
+
+ #[test]
+ fn config_validate_timeout_too_short() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.insert(
+ "CAPTURE_V1_SINK_MSK_PRODUCE_TIMEOUT_MS".into(),
+ "15000".into(),
+ );
+ env.insert(
+ "CAPTURE_V1_SINK_MSK_KAFKA_MESSAGE_TIMEOUT_MS".into(),
+ "20000".into(),
+ );
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ let err = cfg.validate().unwrap_err();
+ assert!(
+ err.to_string().contains("produce_timeout"),
+ "expected produce_timeout in error: {err}"
+ );
+ }
+
+ #[test]
+ fn config_validate_empty_hosts() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.insert("CAPTURE_V1_SINK_MSK_KAFKA_HOSTS".into(), "".into());
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ let err = cfg.validate().unwrap_err();
+ assert!(
+ err.to_string().contains("empty kafka hosts"),
+ "expected empty hosts in error: {err}"
+ );
+ }
+
+ #[test]
+ fn sinks_validate_empty_map() {
+ let sinks = Sinks {
+ default: SinkName::Msk,
+ configs: HashMap::new(),
+ };
+ assert!(sinks.validate().is_err());
+ }
+
+ #[test]
+ fn config_validate_propagates_kafka_validation() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.insert("CAPTURE_V1_SINK_MSK_KAFKA_QUEUE_MIB".into(), "0".into());
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ let err = cfg.validate().unwrap_err();
+ assert!(
+ err.to_string().contains("queue_mib"),
+ "expected queue_mib in error: {err}"
+ );
+ }
+
+ #[test]
+ fn sinks_validate_default_not_in_configs() {
+ let env = test_env_for(SinkName::Msk);
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ let sinks = Sinks {
+ default: SinkName::Ws,
+ configs: [(SinkName::Msk, cfg)].into_iter().collect(),
+ };
+ let err = sinks.validate().unwrap_err();
+ assert!(
+ err.to_string().contains("default sink"),
+ "expected 'default sink' in error: {err}"
+ );
+ }
+
+ #[test]
+ fn sinks_validate_propagates_config_error() {
+ let mut env = test_env_for(SinkName::Msk);
+ env.insert("CAPTURE_V1_SINK_MSK_KAFKA_HOSTS".into(), "".into());
+ let cfg = load_sink_config(SinkName::Msk, &env).unwrap();
+ let sinks = Sinks {
+ default: SinkName::Msk,
+ configs: [(SinkName::Msk, cfg)].into_iter().collect(),
+ };
+ let err = sinks.validate().unwrap_err();
+ assert!(
+ err.to_string().contains("sink msk"),
+ "expected sink name in error: {err}"
+ );
+ }
}
diff --git a/rust/capture/src/v1/sinks/router.rs b/rust/capture/src/v1/sinks/router.rs
new file mode 100644
index 000000000000..bf702c163da3
--- /dev/null
+++ b/rust/capture/src/v1/sinks/router.rs
@@ -0,0 +1,319 @@
+use std::collections::HashMap;
+use std::fmt;
+
+use futures::stream::FuturesUnordered;
+use futures::StreamExt;
+
+use crate::v1::context::Context;
+use crate::v1::sinks::event::Event;
+use crate::v1::sinks::sink::Sink;
+use crate::v1::sinks::types::SinkResult;
+use crate::v1::sinks::SinkName;
+
+// ---------------------------------------------------------------------------
+// RouterError
+// ---------------------------------------------------------------------------
+
+/// Batch-level routing errors. These are caller bugs (requesting a sink that
+/// doesn't exist), not per-event concerns.
+#[derive(Debug)]
+pub enum RouterError {
+ SinkNotFound(SinkName),
+}
+
+impl fmt::Display for RouterError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::SinkNotFound(name) => write!(f, "sink not found: {name}"),
+ }
+ }
+}
+
+impl std::error::Error for RouterError {}
+
+// ---------------------------------------------------------------------------
+// Router
+// ---------------------------------------------------------------------------
+
+/// Routes publish requests to the appropriate [`Sink`] by [`SinkName`].
+///
+/// Owns the mapping of configured sink names to concrete sink implementations
+/// and the default sink for single-write mode.
+pub struct Router {
+ default: SinkName,
+ sinks: HashMap<SinkName, Box<dyn Sink>>,
+}
+
+impl Router {
+ pub fn new(default: SinkName, sinks: HashMap<SinkName, Box<dyn Sink>>) -> Self {
+ Self { default, sinks }
+ }
+
+ pub fn default_sink(&self) -> SinkName {
+ self.default
+ }
+
+ pub fn available_sinks(&self) -> Vec<SinkName> {
+ self.sinks.keys().copied().collect()
+ }
+
+ /// Publish a batch of events to the named sink.
+ pub async fn publish_batch(
+ &self,
+ sink: SinkName,
+ ctx: &Context,
+ events: &[&(dyn Event + Send + Sync)],
+ ) -> Result<Vec<Box<dyn SinkResult>>, RouterError> {
+ let target = self
+ .sinks
+ .get(&sink)
+ .ok_or(RouterError::SinkNotFound(sink))?;
+ Ok(target.publish_batch(ctx, events).await)
+ }
+
+ /// Convenience wrapper for single-event publish.
+ pub async fn publish(
+ &self,
+ sink: SinkName,
+ ctx: &Context,
+ event: &(dyn Event + Send + Sync),
+ ) -> Result<Option<Box<dyn SinkResult>>, RouterError> {
+ let results = self.publish_batch(sink, ctx, &[event]).await?;
+ Ok(results.into_iter().next())
+ }
+
+ /// Flush all sinks concurrently for graceful shutdown.
+ pub async fn flush(&self) -> anyhow::Result<()> {
+ let mut futs = FuturesUnordered::new();
+ for (name, sink) in &self.sinks {
+ let name = *name;
+ futs.push(async move { sink.flush().await.map_err(|e| (name, e)) });
+ }
+ let mut errors: Vec<String> = Vec::new();
+ while let Some(result) = futs.next().await {
+ if let Err((name, e)) = result {
+ errors.push(format!("sink {name}: {e:#}"));
+ }
+ }
+ if errors.is_empty() {
+ Ok(())
+ } else {
+ Err(anyhow::anyhow!("{}", errors.join("; ")))
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashMap;
+ use std::sync::Arc;
+ use std::time::Duration;
+
+ use common_types::CapturedEventHeaders;
+ use uuid::Uuid;
+
+ use crate::config::CaptureMode;
+ use crate::v1::context::Context;
+ use crate::v1::sinks::event::Event;
+ use crate::v1::sinks::kafka::mock::MockProducer;
+ use crate::v1::sinks::kafka::sink::KafkaSink;
+ use crate::v1::sinks::sink::Sink;
+ use crate::v1::sinks::types::Outcome;
+ use crate::v1::sinks::{Config, Destination, SinkName};
+
+ use super::*;
+
+ // -- Test helpers --------------------------------------------------------
+
+ struct FakeEvent {
+ parsed_uuid: Uuid,
+ publish: bool,
+ destination: Destination,
+ }
+
+ impl FakeEvent {
+ fn ok(_uuid: &str) -> Self {
+ Self {
+ parsed_uuid: Uuid::new_v4(),
+ publish: true,
+ destination: Destination::AnalyticsMain,
+ }
+ }
+
+ fn with_publish(mut self, p: bool) -> Self {
+ self.publish = p;
+ self
+ }
+ }
+
+ impl Event for FakeEvent {
+ fn uuid(&self) -> Uuid {
+ self.parsed_uuid
+ }
+
+ fn should_publish(&self) -> bool {
+ self.publish
+ }
+ fn destination(&self) -> &Destination {
+ &self.destination
+ }
+ fn headers(&self, _ctx: &Context) -> CapturedEventHeaders {
+ CapturedEventHeaders {
+ token: None,
+ distinct_id: None,
+ session_id: None,
+ timestamp: None,
+ event: None,
+ uuid: None,
+ now: None,
+ force_disable_person_processing: None,
+ historical_migration: None,
+ dlq_reason: None,
+ dlq_step: None,
+ dlq_timestamp: None,
+ }
+ }
+ fn partition_key<'buf>(&self, _ctx: &Context, buf: &'buf mut String) -> Option<&'buf str> {
+ use std::fmt::Write;
+ let _ = write!(buf, "key:{}", self.uuid());
+ Some(buf.as_str())
+ }
+ fn serialize_into(&self, _ctx: &Context, buf: &mut String) -> anyhow::Result<()> {
+ buf.push_str(r#"{"event":"test"}"#);
+ Ok(())
+ }
+ }
+
+ fn build_sink(name: SinkName, handle: lifecycle::Handle) -> Box<dyn Sink> {
+ let producer = Arc::new(MockProducer::new(name, handle.clone()));
+ let config = Config {
+ produce_timeout: Duration::from_secs(30),
+ kafka: crate::v1::test_utils::test_kafka_config(),
+ };
+ Box::new(KafkaSink::new(
+ name,
+ producer,
+ config,
+ CaptureMode::Events,
+ handle,
+ ))
+ }
+
+ fn test_router(
+ default: SinkName,
+ names: &[SinkName],
+ ) -> (Router, lifecycle::Handle, lifecycle::MonitorGuard) {
+ let mut manager = lifecycle::Manager::builder("test")
+ .with_trap_signals(false)
+ .with_prestop_check(false)
+ .build();
+ let handle = manager.register("router_test", lifecycle::ComponentOptions::new());
+ handle.report_healthy();
+ let monitor = manager.monitor_background();
+
+ let sinks: HashMap<SinkName, Box<dyn Sink>> = names
+ .iter()
+ .map(|&n| (n, build_sink(n, handle.clone())))
+ .collect();
+ let router = Router::new(default, sinks);
+ (router, handle, monitor)
+ }
+
+ fn test_ctx() -> Context {
+ let mut ctx = crate::v1::test_utils::test_context();
+ ctx.created_at = None;
+ ctx
+ }
+
+ // -- Tests ---------------------------------------------------------------
+
+ #[test]
+ fn default_sink_returns_configured_default() {
+ let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);
+ assert_eq!(router.default_sink(), SinkName::Msk);
+ }
+
+ #[test]
+ fn available_sinks_returns_all_configured() {
+ let (router, _handle, _monitor) =
+ test_router(SinkName::Msk, &[SinkName::Msk, SinkName::Ws]);
+ let mut available = router.available_sinks();
+ available.sort_by_key(|n| n.as_str());
+ assert_eq!(available, vec![SinkName::Msk, SinkName::Ws]);
+ }
+
+ #[tokio::test]
+ async fn publish_batch_routes_to_correct_sink() {
+ let (router, _handle, _monitor) =
+ test_router(SinkName::Msk, &[SinkName::Msk, SinkName::Ws]);
+ let ctx = test_ctx();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ let results = router
+ .publish_batch(SinkName::Msk, &ctx, &events)
+ .await
+ .unwrap();
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].outcome(), Outcome::Success);
+ }
+
+ #[tokio::test]
+ async fn publish_batch_sink_not_found() {
+ let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);
+ let ctx = test_ctx();
+ let event = FakeEvent::ok("evt-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+
+ match router.publish_batch(SinkName::Ws, &ctx, &events).await {
+ Err(RouterError::SinkNotFound(SinkName::Ws)) => {}
+ Err(e) => panic!("expected SinkNotFound(Ws), got: {e}"),
+ Ok(_) => panic!("expected error, got Ok"),
+ }
+ }
+
+ #[tokio::test]
+ async fn publish_single_event_success() {
+ let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);
+ let ctx = test_ctx();
+ let event = FakeEvent::ok("evt-1");
+
+ let result = router.publish(SinkName::Msk, &ctx, &event).await.unwrap();
+ assert!(result.is_some());
+ assert_eq!(result.unwrap().outcome(), Outcome::Success);
+ }
+
+ #[tokio::test]
+ async fn publish_single_non_publishable_returns_none() {
+ let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);
+ let ctx = test_ctx();
+ let event = FakeEvent::ok("evt-1").with_publish(false);
+
+ let result = router.publish(SinkName::Msk, &ctx, &event).await.unwrap();
+ assert!(result.is_none());
+ }
+
+ #[tokio::test]
+ async fn publish_sink_not_found() {
+ let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);
+ let ctx = test_ctx();
+ let event = FakeEvent::ok("evt-1");
+
+ match router.publish(SinkName::Ws, &ctx, &event).await {
+ Err(RouterError::SinkNotFound(SinkName::Ws)) => {}
+ Err(e) => panic!("expected SinkNotFound(Ws), got: {e}"),
+ Ok(_) => panic!("expected error, got Ok"),
+ }
+ }
+
+ #[tokio::test]
+ async fn flush_all_sinks() {
+ let (router, _handle, _monitor) =
+ test_router(SinkName::Msk, &[SinkName::Msk, SinkName::Ws]);
+ assert!(router.flush().await.is_ok());
+ }
+}
diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rs
index bc57c6236e54..b7501b2360de 100644
--- a/rust/capture/src/v1/test_utils.rs
+++ b/rust/capture/src/v1/test_utils.rs
@@ -61,10 +61,11 @@ pub fn valid_event() -> Event {
}
pub fn wrapped_event(event_name: &str, distinct_id: &str) -> WrappedEvent {
+ let uuid = Uuid::new_v4();
WrappedEvent {
event: Event {
event: event_name.to_string(),
- uuid: Uuid::new_v4().to_string(),
+ uuid: uuid.to_string(),
distinct_id: distinct_id.to_string(),
timestamp: "2026-03-19T14:29:58.123Z".to_string(),
session_id: None,
@@ -72,6 +73,7 @@ pub fn wrapped_event(event_name: &str, distinct_id: &str) -> WrappedEvent {
options: default_options(),
properties: raw_obj("{}"),
},
+ uuid,
adjusted_timestamp: Some(
DateTime::parse_from_rfc3339("2026-03-19T14:29:58.123Z")
.unwrap()
@@ -80,15 +82,16 @@ pub fn wrapped_event(event_name: &str, distinct_id: &str) -> WrappedEvent {
result: EventResult::Ok,
details: None,
destination: Destination::default(),
- skip_person_processing: false,
+ force_disable_person_processing: false,
}
}
pub fn wrapped_event_at(timestamp: DateTime<Utc>) -> WrappedEvent {
+ let uuid = Uuid::new_v4();
WrappedEvent {
event: Event {
event: "$pageview".to_string(),
- uuid: Uuid::new_v4().to_string(),
+ uuid: uuid.to_string(),
distinct_id: "user-1".to_string(),
timestamp: timestamp.to_rfc3339(),
session_id: None,
@@ -96,19 +99,21 @@ pub fn wrapped_event_at(timestamp: DateTime<Utc>) -> WrappedEvent {
options: default_options(),
properties: raw_obj("{}"),
},
+ uuid,
adjusted_timestamp: Some(timestamp),
result: EventResult::Ok,
details: None,
destination: Destination::default(),
- skip_person_processing: false,
+ force_disable_person_processing: false,
}
}
pub fn malformed_wrapped_event() -> WrappedEvent {
+ let uuid = Uuid::new_v4();
WrappedEvent {
event: Event {
event: String::new(),
- uuid: Uuid::new_v4().to_string(),
+ uuid: uuid.to_string(),
distinct_id: "user-1".to_string(),
timestamp: "bad".to_string(),
session_id: None,
@@ -116,19 +121,17 @@ pub fn malformed_wrapped_event() -> WrappedEvent {
options: default_options(),
properties: raw_obj("{}"),
},
+ uuid,
adjusted_timestamp: None,
result: EventResult::Drop,
details: Some("missing_event_name"),
destination: Destination::default(),
- skip_person_processing: false,
+ force_disable_person_processing: false,
}
}
pub fn events_map(events: Vec<WrappedEvent>) -> HashMap<Uuid, WrappedEvent> {
- events
- .into_iter()
- .map(|e| (Uuid::parse_str(e.event.uuid()).unwrap(), e))
- .collect()
+ events.into_iter().map(|e| (e.uuid, e)).collect()
}
pub fn find_by_did<'a>(
@@ -140,3 +143,187 @@ pub fn find_by_did<'a>(
.find(|e| e.event.distinct_id == distinct_id)
.unwrap()
}
+
+pub fn test_kafka_config() -> crate::v1::sinks::kafka::config::Config {
+ let env: std::collections::HashMap<String, String> = [
+ ("HOSTS", "localhost:9092"),
+ ("TOPIC_MAIN", "events_main"),
+ ("TOPIC_HISTORICAL", "events_hist"),
+ ("TOPIC_OVERFLOW", "events_overflow"),
+ ("TOPIC_DLQ", "events_dlq"),
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect();
+ envconfig::Envconfig::init_from_hashmap(&env).unwrap()
+}
+
+// ---------------------------------------------------------------------------
+// Realistic fixture builders
+// ---------------------------------------------------------------------------
+
+/// A realistic $pageview event with typical posthog-js properties.
+pub fn realistic_pageview(distinct_id: &str) -> WrappedEvent {
+ let uuid = Uuid::new_v4();
+ WrappedEvent {
+ event: Event {
+ event: "$pageview".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: distinct_id.to_string(),
+ timestamp: "2026-03-19T14:29:58.123Z".to_string(),
+ session_id: Some("01jq9abc-def0-1234-5678-9abcdef01234".to_string()),
+ window_id: Some("01jq9xyz-0000-4321-8765-fedcba987654".to_string()),
+ options: Options {
+ cookieless_mode: Some(false),
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: Some(true),
+ },
+ properties: raw_obj(
+ r#"{"$current_url":"https://app.example.com/dashboard","$referrer":"https://google.com","$browser":"Chrome","$browser_version":"120.0","$os":"Mac OS X","$lib":"posthog-js","$lib_version":"1.150.0","custom_prop":42}"#,
+ ),
+ },
+ uuid,
+ adjusted_timestamp: Some(
+ DateTime::parse_from_rfc3339("2026-03-19T14:29:53.123Z")
+ .unwrap()
+ .with_timezone(&Utc),
+ ),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ }
+}
+
+/// A realistic $identify event.
+pub fn realistic_identify(distinct_id: &str) -> WrappedEvent {
+ let uuid = Uuid::new_v4();
+ WrappedEvent {
+ event: Event {
+ event: "$identify".to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: distinct_id.to_string(),
+ timestamp: "2026-03-19T14:30:01.000Z".to_string(),
+ session_id: Some("01jq9abc-def0-1234-5678-9abcdef01234".to_string()),
+ window_id: None,
+ options: Options {
+ cookieless_mode: None,
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: Some(true),
+ },
+ properties: raw_obj(
+ r#"{"$set":{"email":"[email protected]","name":"Test User"},"$set_once":{"created_at":"2026-01-01"},"$browser":"Safari","$os":"iOS"}"#,
+ ),
+ },
+ uuid,
+ adjusted_timestamp: Some(
+ DateTime::parse_from_rfc3339("2026-03-19T14:29:56.000Z")
+ .unwrap()
+ .with_timezone(&Utc),
+ ),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ }
+}
+
+/// A realistic custom event.
+pub fn realistic_custom(distinct_id: &str, event_name: &str) -> WrappedEvent {
+ let uuid = Uuid::new_v4();
+ WrappedEvent {
+ event: Event {
+ event: event_name.to_string(),
+ uuid: uuid.to_string(),
+ distinct_id: distinct_id.to_string(),
+ timestamp: "2026-03-19T14:30:05.500Z".to_string(),
+ session_id: Some("01jq9abc-def0-1234-5678-9abcdef01234".to_string()),
+ window_id: Some("01jq9xyz-0000-4321-8765-fedcba987654".to_string()),
+ options: Options {
+ cookieless_mode: None,
+ disable_skew_adjustment: None,
+ product_tour_id: None,
+ process_person_profile: Some(true),
+ },
+ properties: raw_obj(
+ r#"{"button_id":"cta-signup","$current_url":"https://app.example.com/pricing"}"#,
+ ),
+ },
+ uuid,
+ adjusted_timestamp: Some(
+ DateTime::parse_from_rfc3339("2026-03-19T14:30:00.500Z")
+ .unwrap()
+ .with_timezone(&Utc),
+ ),
+ result: EventResult::Ok,
+ details: None,
+ destination: Destination::AnalyticsMain,
+ force_disable_person_processing: false,
+ }
+}
+
+/// A realistic 3-event batch for round-trip tests.
+pub fn realistic_batch() -> Vec<WrappedEvent> {
+ vec![
+ realistic_pageview("user-42"),
+ realistic_identify("user-42"),
+ realistic_custom("user-42", "button_clicked"),
+ ]
+}
+
+/// Builder for mutating a WrappedEvent after creation.
+pub trait WrappedEventMut {
+ fn with_destination(self, d: Destination) -> Self;
+ fn with_force_disable_person_processing(self, v: bool) -> Self;
+ fn with_result(self, r: EventResult, details: Option<&'static str>) -> Self;
+ fn with_properties(self, raw: &str) -> Self;
+}
+
+impl WrappedEventMut for WrappedEvent {
+ fn with_destination(mut self, d: Destination) -> Self {
+ self.destination = d;
+ self
+ }
+
+ fn with_force_disable_person_processing(mut self, v: bool) -> Self {
+ self.force_disable_person_processing = v;
+ self
+ }
+
+ fn with_result(mut self, r: EventResult, details: Option<&'static str>) -> Self {
+ self.result = r;
+ self.details = details;
+ self
+ }
+
+ fn with_properties(mut self, raw: &str) -> Self {
+ self.event.properties = raw_obj(raw);
+ self
+ }
+}
+
+/// Assert that a serialized WrappedEvent round-trips through CapturedEvent
+/// and its inner data field round-trips through RawEvent.
+pub fn assert_round_trip(
+ wrapped: &WrappedEvent,
+ ctx: &Context,
+) -> (common_types::CapturedEvent, common_types::RawEvent) {
+ use crate::v1::sinks::event::Event as SinkEvent;
+
+ let mut buf = String::new();
+ wrapped
+ .serialize_into(ctx, &mut buf)
+ .expect("serialize_into failed");
+ let captured: common_types::CapturedEvent =
+ serde_json::from_str(&buf).expect("v1 output must deserialize as CapturedEvent");
+ let data: common_types::RawEvent =
+ serde_json::from_str(&captured.data).expect("data field must deserialize as RawEvent");
+
+ assert_eq!(captured.uuid, wrapped.uuid);
+ assert_eq!(captured.distinct_id, wrapped.event.distinct_id);
+ assert_eq!(captured.event, wrapped.event.event);
+
+ (captured, data)
+}
diff --git a/rust/capture/tests/v1_sink_integration.rs b/rust/capture/tests/v1_sink_integration.rs
new file mode 100644
index 000000000000..7d02c24a61d4
--- /dev/null
+++ b/rust/capture/tests/v1_sink_integration.rs
@@ -0,0 +1,254 @@
+//! Sink-level integration tests for the v1 analytics pipeline.
+//!
+//! These tests verify the end-to-end path:
+//! WrappedEvent -> KafkaSink.publish_batch() -> real Kafka -> consumer -> CapturedEvent
+//!
+//! Requires Docker Kafka (same rig as legacy integration tests).
+//!
+//! TODO(v1): add HTTP-level integration tests (ServerHandle + POST /i/v1/general/events)
+//! and process_batch orchestration tests once the v1 HTTP router is merged into the
+//! main application and process_batch is fully implemented (currently a stub).
+
+#[path = "common/utils.rs"]
+mod utils;
+use utils::*;
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::Result;
+use common_types::{CapturedEvent, RawEvent};
+
+use capture::config::CaptureMode;
+use capture::v1::context::Context;
+use capture::v1::sinks::event::Event;
+use capture::v1::sinks::kafka::producer::KafkaProducer;
+use capture::v1::sinks::kafka::KafkaSink;
+use capture::v1::sinks::sink::Sink;
+use capture::v1::sinks::types::Outcome;
+use capture::v1::sinks::{Config, SinkName};
+use capture::v1::test_utils::{self, WrappedEventMut};
+
+fn v1_kafka_config(topic: &str) -> capture::v1::sinks::kafka::config::Config {
+ let env: std::collections::HashMap<String, String> = [
+ ("HOSTS", "kafka:9092"),
+ ("TOPIC_MAIN", topic),
+ ("TOPIC_HISTORICAL", topic),
+ ("TOPIC_OVERFLOW", topic),
+ ("TOPIC_DLQ", topic),
+ ("LINGER_MS", "0"),
+ ("COMPRESSION_CODEC", "none"),
+ ("MESSAGE_TIMEOUT_MS", "10000"),
+ ("QUEUE_MIB", "10"),
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect();
+ envconfig::Envconfig::init_from_hashmap(&env).unwrap()
+}
+
+fn v1_test_context() -> Context {
+ let mut ctx = test_utils::test_context();
+ ctx.api_token = "phc_integration_test_token".to_string();
+ ctx
+}
+
+async fn build_v1_sink(topic: &str) -> (KafkaSink<KafkaProducer>, lifecycle::MonitorGuard) {
+ let mut manager = lifecycle::Manager::builder("v1-sink-integration-test")
+ .with_trap_signals(false)
+ .with_prestop_check(false)
+ .build();
+ let handle = manager.register("v1_kafka", lifecycle::ComponentOptions::new());
+ handle.report_healthy();
+ let monitor = manager.monitor_background();
+
+ let kafka_config = v1_kafka_config(topic);
+ let producer = KafkaProducer::new(
+ SinkName::Msk,
+ &kafka_config,
+ handle.clone(),
+ CaptureMode::Events.as_tag(),
+ )
+ .expect("failed to create v1 KafkaProducer");
+
+ let config = Config {
+ produce_timeout: Duration::from_secs(10),
+ kafka: kafka_config,
+ };
+
+ let sink = KafkaSink::new(
+ SinkName::Msk,
+ Arc::new(producer),
+ config,
+ CaptureMode::Events,
+ handle,
+ );
+
+ (sink, monitor)
+}
+
+// ---------------------------------------------------------------------------
+// Single realistic pageview round-trip
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn v1_single_pageview_round_trip() -> Result<()> {
+ setup_tracing();
+ let topic = EphemeralTopic::new().await;
+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;
+ let ctx = v1_test_context();
+
+ let wrapped = test_utils::realistic_pageview("integ-user-1");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+
+ let results = sink.publish_batch(&ctx, &events).await;
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].key(), wrapped.uuid);
+ assert_eq!(results[0].outcome(), Outcome::Success);
+
+ let event_json = topic.next_event()?;
+ let captured: CapturedEvent = serde_json::from_value(event_json)?;
+ assert_eq!(captured.uuid, wrapped.uuid);
+ assert_eq!(captured.distinct_id, "integ-user-1");
+ assert_eq!(captured.event, "$pageview");
+ assert_eq!(captured.token, "phc_integration_test_token");
+
+ let data: RawEvent = serde_json::from_str(&captured.data)?;
+ assert_eq!(data.event, "$pageview");
+ assert_eq!(data.properties["$browser"], "Chrome");
+ assert_eq!(
+ data.properties["$session_id"],
+ "01jq9abc-def0-1234-5678-9abcdef01234"
+ );
+ assert_eq!(data.properties["$process_person_profile"], true);
+ assert_eq!(data.properties["custom_prop"], 42);
+
+ topic.assert_empty();
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// 3-event realistic batch round-trip
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn v1_batch_round_trip() -> Result<()> {
+ setup_tracing();
+ let topic = EphemeralTopic::new().await;
+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;
+ let ctx = v1_test_context();
+
+ let batch = test_utils::realistic_batch();
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&batch[0], &batch[1], &batch[2]];
+
+ let results = sink.publish_batch(&ctx, &events).await;
+
+ assert_eq!(results.len(), 3);
+ for r in &results {
+ assert_eq!(r.outcome(), Outcome::Success);
+ }
+
+ let mut event_names = Vec::new();
+ for _ in 0..3 {
+ let json = topic.next_event()?;
+ let captured: CapturedEvent = serde_json::from_value(json)?;
+ let data: RawEvent = serde_json::from_str(&captured.data)?;
+ assert_eq!(captured.distinct_id, "user-42");
+ assert_eq!(captured.token, "phc_integration_test_token");
+ event_names.push(data.event.clone());
+ }
+
+ event_names.sort();
+ assert_eq!(
+ event_names,
+ vec!["$identify", "$pageview", "button_clicked"]
+ );
+
+ topic.assert_empty();
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// Verify Kafka headers round-trip
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn v1_kafka_headers_round_trip() -> Result<()> {
+ setup_tracing();
+ let topic = EphemeralTopic::new().await;
+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;
+ let ctx = v1_test_context();
+
+ let wrapped = test_utils::realistic_pageview("integ-user-headers");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+
+ let results = sink.publish_batch(&ctx, &events).await;
+ assert_eq!(results[0].outcome(), Outcome::Success);
+
+ let (_event_json, headers) = topic.next_message_with_headers()?;
+
+ assert_eq!(
+ headers.get("token").map(|s| s.as_str()),
+ Some("phc_integration_test_token")
+ );
+ assert_eq!(
+ headers.get("distinct_id").map(|s| s.as_str()),
+ Some("integ-user-headers")
+ );
+ assert_eq!(headers.get("event").map(|s| s.as_str()), Some("$pageview"));
+ assert!(headers.contains_key("uuid"));
+ assert!(headers.contains_key("timestamp"));
+
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// Partition key verification
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn v1_partition_key_round_trip() -> Result<()> {
+ setup_tracing();
+ let topic = EphemeralTopic::new().await;
+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;
+ let ctx = v1_test_context();
+
+ let wrapped = test_utils::realistic_pageview("integ-user-pkey");
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+
+ let results = sink.publish_batch(&ctx, &events).await;
+ assert_eq!(results[0].outcome(), Outcome::Success);
+
+ let key = topic.next_message_key()?;
+ assert_eq!(
+ key.as_deref(),
+ Some("phc_integration_test_token:integ-user-pkey")
+ );
+
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// Dropped event not published
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn v1_dropped_event_not_published() -> Result<()> {
+ setup_tracing();
+ let topic = EphemeralTopic::new().await;
+ let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;
+ let ctx = v1_test_context();
+
+ let wrapped = test_utils::realistic_pageview("integ-user-dropped").with_result(
+ capture::v1::analytics::types::EventResult::Drop,
+ Some("rate_limited"),
+ );
+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+
+ let results = sink.publish_batch(&ctx, &events).await;
+ assert!(results.is_empty());
+
+ topic.assert_empty();
+ Ok(())
+}