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.

refactor(capture): decouple v1 RequestContext from analytics Context (#64184)

Eli Reisman24cd5fb71b78
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index b232dcadd269..69f1cd4615f6 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -259,6 +259,10 @@ pub struct Config {
/// Maximum decompressed body size the v1 endpoint will accept (bytes).
#[envconfig(default = "52428800")]
pub capture_v1_max_decompressed_body_bytes: usize,
+
+ /// Batch size threshold for parallel scatter-gather serialization; 0 disables fanout.
+ #[envconfig(default = "8")]
+ pub capture_v1_scatter_gather_min_batch: usize,
}
#[derive(Envconfig, Clone)]
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rs
index bff0cce82106..5cf9ef7768b0 100644
--- a/rust/capture/src/router.rs
+++ b/rust/capture/src/router.rs
@@ -82,6 +82,7 @@ pub struct State {
/// V1 sink router for the new capture analytics pipeline.
/// When present, the v1 analytics handler publishes events through this.
pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,
+ pub capture_v1_scatter_gather_min_batch: usize,
}
#[derive(Clone, Copy)]
@@ -149,6 +150,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
overflow_limiter: Option<Arc<OverflowLimiter>>,
replay_overflow_limiter: Option<Arc<RedisLimiter>>,
v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,
+ capture_v1_scatter_gather_min_batch: usize,
) -> Router {
let state = State {
sink,
@@ -174,6 +176,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
overflow_limiter,
replay_overflow_limiter,
v1_sink_router,
+ capture_v1_scatter_gather_min_batch,
};
// Very permissive CORS policy, as old SDK versions
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index e2ee231fcd37..c7984966d2a1 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -326,6 +326,7 @@ pub async fn build_components(
overflow_limiter,
replay_overflow_limiter,
v1_sink_router.clone(),
+ config.capture_v1_scatter_gather_min_batch,
);
info!(
diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rs
index 6bfe74910e5c..a1f0799cc8a7 100644
--- a/rust/capture/src/v1/analytics/constants.rs
+++ b/rust/capture/src/v1/analytics/constants.rs
@@ -8,13 +8,6 @@ use axum::http::HeaderValue;
/// SDKs are expected to layer their own jittered exponential backoff on top of this floor.
pub const DEFAULT_RETRY_AFTER_SECS: HeaderValue = HeaderValue::from_static("1");
-// ---------------------------------------------------------------------------
-// Supported content encodings
-// ---------------------------------------------------------------------------
-
-/// Allowlist of content encodings the capture endpoint will decompress.
-pub const SUPPORTED_ENCODINGS: &[&str] = &["gzip", "deflate", "br", "zstd"];
-
// ---------------------------------------------------------------------------
// Route paths
// ---------------------------------------------------------------------------
diff --git a/rust/capture/src/v1/analytics/context.rs b/rust/capture/src/v1/analytics/context.rs
new file mode 100644
index 000000000000..1f0e801cd6f3
--- /dev/null
+++ b/rust/capture/src/v1/analytics/context.rs
@@ -0,0 +1,62 @@
+use std::ops::{Deref, DerefMut};
+
+use axum::http::{HeaderMap, Method};
+use axum_client_ip::InsecureClientIp;
+
+use super::query::Query;
+use super::types::Batch;
+use crate::v1::context::RequestContext;
+use crate::v1::Error;
+
+/// Analytics-mode request context: the shared [`RequestContext`] plus the
+/// typed analytics [`Query`] refined from `req.raw_query`. Derefs to
+/// `RequestContext` so shared contracts (`Event`, `Sink`, logging) consume it
+/// transparently.
+pub struct Context {
+ pub req: RequestContext,
+ pub query: Query,
+}
+
+impl Context {
+ pub fn new(
+ headers: &HeaderMap,
+ ip: &InsecureClientIp,
+ raw_query: Option<String>,
+ method: Method,
+ path: &'static str,
+ ) -> Result<Self, Error> {
+ // Validate the request first, then refine the typed query from the raw
+ // string. `Query` is currently empty so parsing never fails; the seam
+ // is here for when analytics adds real query params.
+ let req = RequestContext::new(headers, ip, raw_query, method, path)?;
+ let query = match req.raw_query.as_deref() {
+ Some(raw) => serde_urlencoded::from_str(raw)
+ .map_err(|e| Error::InvalidQueryParam(format!("invalid query string: {e}")))?,
+ None => Query::default(),
+ };
+ Ok(Self { req, query })
+ }
+
+ /// Stamp request-level batch metadata from the analytics batch envelope.
+ pub fn set_batch_metadata(&mut self, batch: &Batch) {
+ self.req.set_batch_metadata(
+ Some(batch.created_at.clone()),
+ batch.capture_internal.unwrap_or(false),
+ batch.historical_migration,
+ );
+ }
+}
+
+impl Deref for Context {
+ type Target = RequestContext;
+
+ fn deref(&self) -> &RequestContext {
+ &self.req
+ }
+}
+
+impl DerefMut for Context {
+ fn deref_mut(&mut self) -> &mut RequestContext {
+ &mut self.req
+ }
+}
diff --git a/rust/capture/src/v1/analytics/handler.rs b/rust/capture/src/v1/analytics/handler.rs
index 63bb4f908947..e10c1f9f35b5 100644
--- a/rust/capture/src/v1/analytics/handler.rs
+++ b/rust/capture/src/v1/analytics/handler.rs
@@ -1,22 +1,21 @@
use axum::body::Body;
-use axum::extract::{MatchedPath, Query as AxumQuery, State};
+use axum::extract::{MatchedPath, RawQuery, State};
use axum::http::{header, HeaderMap, Method};
use axum::response::IntoResponse;
use axum_client_ip::InsecureClientIp;
use super::constants::{CAPTURE_V1_PATH, CAPTURE_V1_PATH_TRAILING};
-use super::query::Query;
+use super::context::Context;
use super::types::Batch;
use tracing::Level;
use crate::v1::constants::*;
-use crate::v1::context::Context;
use crate::{ctx_log, log_stat_error, router, v1};
pub async fn handle_request(
state: State<router::State>,
headers: HeaderMap,
- query: AxumQuery<Query>,
+ RawQuery(raw_query): RawQuery,
ip: InsecureClientIp,
method: Method,
path: MatchedPath,
@@ -30,8 +29,16 @@ pub async fn handle_request(
CAPTURE_V1_PATH
}
};
- let mut context = Context::new(&headers, &ip, &query, method.clone(), static_path)
- .map_err(|err| log_and_return_header_error(err, &headers, &ip, &query, &method, &path))?;
+ let mut context = Context::new(
+ &headers,
+ &ip,
+ raw_query.clone(),
+ method.clone(),
+ static_path,
+ )
+ .map_err(|err| {
+ log_and_return_header_error(err, &headers, &ip, raw_query.as_deref(), &method, &path)
+ })?;
// TODO: purposely chatty, for now
ctx_log!(Level::INFO, context, "handle_request called");
@@ -110,7 +117,7 @@ fn log_and_return_header_error(
err: v1::Error,
headers: &HeaderMap,
ip: &InsecureClientIp,
- query: &AxumQuery<Query>,
+ raw_query: Option<&str>,
method: &Method,
path: &MatchedPath,
) -> v1::Error {
@@ -136,7 +143,7 @@ fn log_and_return_header_error(
content_encoding = %content_encoding,
client_ip = %ip.0,
method = %method,
- query = ?query.0,
+ query = ?raw_query,
path = %path.as_str(),
"{}", msg
),
@@ -151,12 +158,12 @@ fn log_and_return_header_error(
content_encoding = %content_encoding,
client_ip = %ip.0,
method = %method,
- query = ?query.0,
+ query = ?raw_query,
path = %path.as_str(),
"{}", msg
),
}
- err.stat_error(None::<&Context>);
+ err.stat_error(None::<&crate::v1::context::RequestContext>);
err
}
diff --git a/rust/capture/src/v1/analytics/mod.rs b/rust/capture/src/v1/analytics/mod.rs
index 73d05cd515b5..65d620d0995a 100644
--- a/rust/capture/src/v1/analytics/mod.rs
+++ b/rust/capture/src/v1/analytics/mod.rs
@@ -1,4 +1,5 @@
pub mod constants;
+pub mod context;
pub mod handler;
pub mod process;
pub mod query;
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index 4e74251963ee..e1a037c68cb9 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -21,11 +21,12 @@ use crate::v0_request::DataType;
use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};
use tracing::Level;
+use super::context::Context;
use crate::router;
-use crate::v1::context::Context;
+use crate::v1::context::RequestContext;
use crate::v1::sinks::event::Event as SinkEvent;
use crate::v1::sinks::types::SinkResult;
-use crate::v1::sinks::Destination;
+use crate::v1::sinks::{serialize_batch, Destination};
use crate::v1::Error;
/// Maps event name to its Kafka destination, mirroring legacy DataType assignment.
@@ -97,27 +98,28 @@ pub async fn process_batch(
)
.record(processing_start.elapsed().as_secs_f64());
- // Publish to v1 sink, merge results, build response
+ // Serialize (hoisted out of the sink; parallel for large batches), then
+ // publish and merge results before building the response.
let sink_router = state
.v1_sink_router
.as_ref()
.ok_or_else(|| Error::ServiceUnavailable("v1 sink router not configured".into()))?;
- let event_refs: Vec<&(dyn SinkEvent + Send + Sync)> = events
- .iter()
- .filter(|e| SinkEvent::should_publish(*e))
- .map(|e| {
- let r: &(dyn SinkEvent + Send + Sync) = e;
- r
- })
- .collect();
+ // serialize_batch consumes the events and hands them back, so we can keep
+ // correlating results to them and build the response.
+ let (mut events, serialized) =
+ serialize_batch(events, context, state.capture_v1_scatter_gather_min_batch).await;
let sink_results = sink_router
- .publish_batch(sink_router.default_sink(), context, &event_refs)
+ .publish_batch(sink_router.default_sink(), context, &serialized.prepared)
.await
.map_err(|e| Error::InternalError(e.to_string()))?;
- merge_sink_results(&mut events, &sink_results);
+ // Serialize-step failures and sink results are both per-event SinkResults;
+ // merge them together so serialization drops surface in the response.
+ let mut all_results = serialized.failures;
+ all_results.extend(sink_results);
+ merge_sink_results(&mut events, &all_results);
Ok(BatchResponse::build(context, &events))
}
@@ -183,7 +185,7 @@ fn validate_batch(batch: &Batch) -> Result<(), Error> {
Ok(())
}
-fn validate_events(context: &Context, batch: Batch) -> Result<Vec<WrappedEvent>, Error> {
+fn validate_events(context: &RequestContext, batch: Batch) -> Result<Vec<WrappedEvent>, Error> {
let mut events: Vec<WrappedEvent> = Vec::with_capacity(batch.batch.len());
let mut seen: HashSet<Uuid> = HashSet::with_capacity(batch.batch.len());
let mut illegal_distinct_id_count: u64 = 0;
@@ -254,7 +256,7 @@ fn validate_events(context: &Context, batch: Batch) -> Result<Vec<WrappedEvent>,
Ok(events)
}
-fn observe_malformed_events(context: &Context, events: &[WrappedEvent]) {
+fn observe_malformed_events(context: &RequestContext, events: &[WrappedEvent]) {
let mut malformed: HashMap<&'static str, u64> = HashMap::new();
for event in events.iter() {
@@ -316,7 +318,7 @@ fn validate_event(event: &Event) -> Result<DateTime<Utc>, Error> {
}
fn normalize_timestamp(
- context: &Context,
+ context: &RequestContext,
event: &Event,
raw_event_ts: DateTime<Utc>,
) -> DateTime<Utc> {
@@ -336,7 +338,7 @@ fn normalize_timestamp(
fn apply_historical_rerouting(
cfg: &router::HistoricalConfig,
- context: &Context,
+ context: &RequestContext,
events: &mut [WrappedEvent],
) {
for event in events.iter_mut() {
@@ -366,7 +368,11 @@ fn apply_historical_rerouting(
}
}
-fn apply_overflow_stamping(limiter: &OverflowLimiter, ctx: &Context, events: &mut [WrappedEvent]) {
+fn apply_overflow_stamping(
+ limiter: &OverflowLimiter,
+ ctx: &RequestContext,
+ events: &mut [WrappedEvent],
+) {
for event in events.iter_mut() {
if event.destination != Destination::AnalyticsMain {
continue;
@@ -468,7 +474,7 @@ async fn apply_restrictions(
async fn apply_token_distinct_id_limits(
limiter: &GlobalRateLimiter,
- context: &Context,
+ context: &RequestContext,
events: &mut [WrappedEvent],
) {
let mut limited_distinct_ids: HashSet<&str> = HashSet::new();
@@ -546,7 +552,7 @@ mod tests {
};
use crate::v1::analytics::constants::CAPTURE_V1_PATH;
use crate::v1::analytics::types::{Batch, Event, Options};
- use crate::v1::sinks::Destination;
+ use crate::v1::sinks::{Destination, DEFAULT_SCATTER_GATHER_MIN_BATCH};
use crate::v1::test_utils::{
self, find_by_did, malformed_wrapped_event, raw_obj, valid_event, wrapped_event,
wrapped_event_at,
@@ -989,8 +995,8 @@ mod tests {
DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
}
- fn ctx_with_skew(server_received_at: DateTime<Utc>, skew: Duration) -> Context {
- Context {
+ fn ctx_with_skew(server_received_at: DateTime<Utc>, skew: Duration) -> RequestContext {
+ RequestContext {
api_token: "phc_test".to_string(),
user_agent: "test/1.0".to_string(),
content_type: "application/json".to_string(),
@@ -1000,7 +1006,7 @@ mod tests {
request_id: Uuid::new_v4(),
client_timestamp: server_received_at + skew,
client_ip: std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
- query: crate::v1::analytics::query::Query::default(),
+ raw_query: None,
method: axum::http::Method::POST,
path: CAPTURE_V1_PATH,
server_received_at,
@@ -1646,7 +1652,7 @@ mod tests {
GlobalRateLimiter::new_with(MockLimiter::new(keys))
}
- fn td_context() -> Context {
+ fn td_context() -> RequestContext {
let mut ctx = test_utils::test_context();
ctx.api_token = "phc_tok".to_string();
ctx
@@ -2464,7 +2470,7 @@ mod tests {
let mut state = test_state.state;
state.v1_sink_router = None;
- let mut ctx = test_utils::test_context();
+ let mut ctx = test_utils::test_analytics_context();
let batch = valid_batch(vec![valid_event()]);
let err = process_batch(&state, &mut ctx, batch).await.unwrap_err();
@@ -2479,7 +2485,7 @@ mod tests {
let test_state = crate::v1::test_utils::TestStateBuilder::new().build();
let state = test_state.state;
- let mut ctx = test_utils::test_context();
+ let mut ctx = test_utils::test_analytics_context();
// Every event is invalid — empty name, empty distinct_id, bad timestamp.
let batch = valid_batch(vec![
Event {
@@ -2561,27 +2567,23 @@ mod tests {
let mut ctx = test_utils::test_context();
ctx.created_at = None;
- let mut events = vec![
+ let events = vec![
wrapped_event("$pageview", "user-1"),
wrapped_event("$identify", "user-2"),
wrapped_event("button_clicked", "user-3"),
];
- let event_refs: Vec<&(dyn crate::v1::sinks::event::Event + Send + Sync)> = events
- .iter()
- .filter(|e| SinkEvent::should_publish(*e))
- .map(|e| {
- let r: &(dyn crate::v1::sinks::event::Event + Send + Sync) = e;
- r
- })
- .collect();
+ let (mut events, serialized) =
+ serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;
let sink_results = router
- .publish_batch(router.default_sink(), &ctx, &event_refs)
+ .publish_batch(router.default_sink(), &ctx, &serialized.prepared)
.await
.unwrap();
- merge_sink_results(&mut events, &sink_results);
+ let mut all_results = serialized.failures;
+ all_results.extend(sink_results);
+ merge_sink_results(&mut events, &all_results);
let resp = BatchResponse::build(&ctx, &events);
assert!(!resp.has_retry);
@@ -2598,7 +2600,7 @@ mod tests {
let mut ctx = test_utils::test_context();
ctx.created_at = None;
- let mut events = vec![
+ let events = vec![
wrapped_event("$pageview", "user-1"),
wrapped_event("$pageview", "user-2")
.with_result(EventResult::Drop, Some("billing_limit_exceeded")),
@@ -2606,23 +2608,19 @@ mod tests {
.with_result(EventResult::Warning, Some("person_processing_disabled")),
];
- let event_refs: Vec<&(dyn crate::v1::sinks::event::Event + Send + Sync)> = events
- .iter()
- .filter(|e| SinkEvent::should_publish(*e))
- .map(|e| {
- let r: &(dyn crate::v1::sinks::event::Event + Send + Sync) = e;
- r
- })
- .collect();
+ let (mut events, serialized) =
+ serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;
- assert_eq!(event_refs.len(), 2); // only Ok + Warning are published
+ assert_eq!(serialized.prepared.len(), 2); // only Ok + Warning are published
let sink_results = router
- .publish_batch(router.default_sink(), &ctx, &event_refs)
+ .publish_batch(router.default_sink(), &ctx, &serialized.prepared)
.await
.unwrap();
- merge_sink_results(&mut events, &sink_results);
+ let mut all_results = serialized.failures;
+ all_results.extend(sink_results);
+ merge_sink_results(&mut events, &all_results);
let resp = BatchResponse::build(&ctx, &events);
assert!(!resp.has_retry);
@@ -2643,30 +2641,26 @@ mod tests {
let mut ctx = test_utils::test_context();
ctx.created_at = None;
- let mut events = vec![
+ let events = vec![
wrapped_event("$pageview", "user-1")
.with_result(EventResult::Drop, Some("billing_limit_exceeded")),
wrapped_event("$pageview", "user-2")
.with_result(EventResult::Drop, Some("billing_limit_exceeded")),
];
- let event_refs: Vec<&(dyn crate::v1::sinks::event::Event + Send + Sync)> = events
- .iter()
- .filter(|e| SinkEvent::should_publish(*e))
- .map(|e| {
- let r: &(dyn crate::v1::sinks::event::Event + Send + Sync) = e;
- r
- })
- .collect();
+ let (mut events, serialized) =
+ serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;
- assert!(event_refs.is_empty());
+ assert!(serialized.prepared.is_empty());
let sink_results = router
- .publish_batch(router.default_sink(), &ctx, &event_refs)
+ .publish_batch(router.default_sink(), &ctx, &serialized.prepared)
.await
.unwrap();
- merge_sink_results(&mut events, &sink_results);
+ let mut all_results = serialized.failures;
+ all_results.extend(sink_results);
+ merge_sink_results(&mut events, &all_results);
let resp = BatchResponse::build(&ctx, &events);
assert!(!resp.has_retry);
@@ -2681,24 +2675,20 @@ mod tests {
let mut ctx = test_utils::test_context();
ctx.created_at = None;
- let mut events =
+ let events =
vec![wrapped_event("$pageview", "user-1").with_destination(Destination::Overflow)];
- let event_refs: Vec<&(dyn crate::v1::sinks::event::Event + Send + Sync)> = events
- .iter()
- .filter(|e| SinkEvent::should_publish(*e))
- .map(|e| {
- let r: &(dyn crate::v1::sinks::event::Event + Send + Sync) = e;
- r
- })
- .collect();
+ let (mut events, serialized) =
+ serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;
let sink_results = router
- .publish_batch(router.default_sink(), &ctx, &event_refs)
+ .publish_batch(router.default_sink(), &ctx, &serialized.prepared)
.await
.unwrap();
- merge_sink_results(&mut events, &sink_results);
+ let mut all_results = serialized.failures;
+ all_results.extend(sink_results);
+ merge_sink_results(&mut events, &all_results);
let resp = BatchResponse::build(&ctx, &events);
assert!(!resp.has_retry);
diff --git a/rust/capture/src/v1/analytics/response.rs b/rust/capture/src/v1/analytics/response.rs
index 37a7eefe4b51..f1a21e39d3ee 100644
--- a/rust/capture/src/v1/analytics/response.rs
+++ b/rust/capture/src/v1/analytics/response.rs
@@ -6,7 +6,7 @@ use uuid::Uuid;
use super::constants::{CAPTURE_V1_BATCH_OUTCOMES, DEFAULT_RETRY_AFTER_SECS};
use super::types::{EventResult, WrappedEvent};
-use crate::v1::context::Context;
+use crate::v1::context::RequestContext;
// ---------------------------------------------------------------------------
// BatchEntryStatus
@@ -48,7 +48,7 @@ pub struct BatchResponse {
impl BatchResponse {
/// Build the response from a processed batch of WrappedEvents.
/// Call this after sink publishing and result merging are complete.
- pub fn build(ctx: &Context, events: &[WrappedEvent]) -> Self {
+ pub fn build(ctx: &RequestContext, events: &[WrappedEvent]) -> Self {
let mut has_retry = false;
let entries: Vec<(Uuid, BatchEntryStatus)> = events
.iter()
diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rs
index 23a5eb60c763..b195d11a8a9b 100644
--- a/rust/capture/src/v1/analytics/types.rs
+++ b/rust/capture/src/v1/analytics/types.rs
@@ -22,7 +22,7 @@ impl io::Write for StringWriter<'_> {
}
}
-use crate::v1::context::Context;
+use crate::v1::context::RequestContext;
use crate::v1::sinks::event::Event as SinkEvent;
use crate::v1::sinks::Destination;
@@ -137,7 +137,7 @@ impl SinkEvent for WrappedEvent {
// 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 {
+ fn headers(&self, ctx: &RequestContext) -> 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
@@ -189,7 +189,7 @@ impl SinkEvent for WrappedEvent {
}
}
- fn partition_key(&self, ctx: &Context) -> String {
+ fn partition_key(&self, ctx: &RequestContext) -> String {
use std::fmt::Write;
let mut buf = String::with_capacity(128);
match (
@@ -209,7 +209,7 @@ impl SinkEvent for WrappedEvent {
buf
}
- fn serialize(&self, ctx: &Context) -> anyhow::Result<String> {
+ fn serialize(&self, ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {
let spliced = self.build_spliced_properties(ctx)?;
let properties: &RawValue = spliced.as_deref().unwrap_or(&self.event.properties);
let ingestion_data = IngestionData {
@@ -249,16 +249,16 @@ impl SinkEvent for WrappedEvent {
historical_migration: ctx.historical_migration,
};
- let mut buf = String::with_capacity(data.len() + 512);
- serde_json::to_writer(StringWriter(&mut buf), &ie)
+ let mut buf = Vec::with_capacity(data.len() + 512);
+ serde_json::to_writer(&mut buf, &ie)
.map_err(|e| anyhow::anyhow!("serializing IngestionEvent: {e:#}"))?;
- Ok(buf)
+ Ok(bytes::Bytes::from(buf))
}
}
impl WrappedEvent {
#[allow(unused_assignments)]
- fn build_property_injections(&self, ctx: &Context) -> anyhow::Result<String> {
+ fn build_property_injections(&self, ctx: &RequestContext) -> anyhow::Result<String> {
let mut buf = String::with_capacity(256);
let mut first = true;
@@ -310,7 +310,10 @@ impl WrappedEvent {
/// 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, ctx: &Context) -> anyhow::Result<Option<Box<RawValue>>> {
+ fn build_spliced_properties(
+ &self,
+ ctx: &RequestContext,
+ ) -> anyhow::Result<Option<Box<RawValue>>> {
let injection = self.build_property_injections(ctx)?;
if injection.is_empty() {
return Ok(None);
@@ -1024,7 +1027,7 @@ mod tests {
DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
}
- fn serialize_ctx() -> crate::v1::context::Context {
+ fn serialize_ctx() -> crate::v1::context::RequestContext {
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));
@@ -1066,11 +1069,11 @@ mod tests {
fn serialize_and_parse(
wrapped: &WrappedEvent,
- ctx: &crate::v1::context::Context,
+ ctx: &crate::v1::context::RequestContext,
) -> (CapturedEvent, RawEvent) {
let buf = wrapped.serialize(ctx).expect("serialize failed");
let captured: CapturedEvent =
- serde_json::from_str(&buf).expect("v1 output must deserialize as CapturedEvent");
+ serde_json::from_slice(&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)
@@ -1424,7 +1427,7 @@ mod tests {
assert_eq!(wrapped.event.options.cookieless_mode, Some(false));
let ctx = serialize_ctx();
let buf = wrapped.serialize(&ctx).unwrap();
- let val: Value = serde_json::from_str(&buf).unwrap();
+ let val: Value = serde_json::from_slice(&buf).unwrap();
assert!(
val.get("is_cookieless_mode").is_none(),
"is_cookieless_mode should be absent when false"
@@ -1445,7 +1448,7 @@ mod tests {
let wrapped = pageview_event();
let ctx = serialize_ctx();
let buf = wrapped.serialize(&ctx).unwrap();
- let val: Value = serde_json::from_str(&buf).unwrap();
+ let val: Value = serde_json::from_slice(&buf).unwrap();
assert!(
val.get("historical_migration").is_none(),
"historical_migration should be absent when false"
diff --git a/rust/capture/src/v1/constants.rs b/rust/capture/src/v1/constants.rs
index d9edd2239e54..800227970b0a 100644
--- a/rust/capture/src/v1/constants.rs
+++ b/rust/capture/src/v1/constants.rs
@@ -21,6 +21,15 @@ pub const POSTHOG_REQUEST_ID: &str = "PostHog-Request-Id";
/// Header carrying the SDK-side timestamp of the request.
pub const POSTHOG_REQUEST_TIMESTAMP: &str = "PostHog-Request-Timestamp";
+// ---------------------------------------------------------------------------
+// Supported content encodings
+// ---------------------------------------------------------------------------
+
+/// Allowlist of content encodings the capture endpoint will decompress.
+/// Lives at the v1 level (not in analytics/) so request-context decoding is
+/// CaptureMode-agnostic.
+pub const SUPPORTED_ENCODINGS: &[&str] = &["gzip", "deflate", "br", "zstd"];
+
// ---------------------------------------------------------------------------
// Required request headers
// ---------------------------------------------------------------------------
@@ -68,6 +77,19 @@ pub(super) const CAPTURE_V1_PAYLOAD_SIZE: &str = "capture_v1_payload_size_bytes"
/// configured in prometheus.rs (CLOCK_SKEW_SECONDS).
pub(super) const CAPTURE_V1_CLOCK_SKEW_SECONDS: &str = "capture_v1_clock_skew_seconds";
+/// Histogram of batch serialize wall-time (label: batch_size bucket). Sink- and
+/// product-agnostic by design — faceting comes from the per-mode service
+/// deployment (capture-analytics / capture-replay / capture-ai).
+pub(super) const CAPTURE_V1_SERIALIZE_DURATION_SECONDS: &str =
+ "capture_v1_serialize_duration_seconds";
+
+/// Counter of events that failed to serialize (non-panic, fatal/non-retriable).
+pub(super) const CAPTURE_V1_SERIALIZE_FAILED_TOTAL: &str = "capture_v1_serialize_failed_total";
+
+/// Counter of events whose serialization panicked. The panic is isolated per
+/// event (caught), so the rest of the batch still serializes and publishes.
+pub(super) const CAPTURE_V1_SERIALIZE_PANIC_TOTAL: &str = "capture_v1_serialize_panic_total";
+
// ---------------------------------------------------------------------------
// Fallback values
// ---------------------------------------------------------------------------
diff --git a/rust/capture/src/v1/context.rs b/rust/capture/src/v1/context.rs
index 619c0c28ad6c..0e8099664e8c 100644
--- a/rust/capture/src/v1/context.rs
+++ b/rust/capture/src/v1/context.rs
@@ -1,19 +1,19 @@
use std::net::IpAddr;
-use axum::extract::Query as AxumQuery;
use axum::http::{header, HeaderMap, Method};
use axum_client_ip::InsecureClientIp;
use chrono::{DateTime, Utc};
use uuid::Uuid;
use crate::token::validate_token;
-use crate::v1::analytics::constants::SUPPORTED_ENCODINGS;
-use crate::v1::analytics::query::Query;
use crate::v1::constants::*;
use crate::v1::Error;
-#[derive(Debug)]
-pub struct Context {
+/// CaptureMode-agnostic request context shared by every v1 capture mode.
+/// Product-specific query state lives in a per-mode wrapper (e.g.
+/// `v1::analytics::Context`) that carries `raw_query` refined into a typed view.
+#[derive(Debug, Clone)]
+pub struct RequestContext {
pub api_token: String,
pub user_agent: String,
pub content_type: String,
@@ -23,7 +23,9 @@ pub struct Context {
pub request_id: Uuid,
pub client_timestamp: DateTime<Utc>,
pub client_ip: IpAddr,
- pub query: Query,
+ /// Raw, un-parsed request query string. Each capture mode refines this into
+ /// its own typed query when wrapping into a product context.
+ pub raw_query: Option<String>,
pub method: Method,
pub path: &'static str,
pub server_received_at: DateTime<Utc>,
@@ -42,7 +44,7 @@ fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, Error>
})
}
-impl Context {
+impl RequestContext {
pub fn clock_skew(&self) -> chrono::Duration {
self.client_timestamp
.signed_duration_since(self.server_received_at)
@@ -66,7 +68,7 @@ impl Context {
pub fn new(
headers: &HeaderMap,
ip: &InsecureClientIp,
- query: &AxumQuery<Query>,
+ raw_query: Option<String>,
method: Method,
path: &'static str,
) -> Result<Self, Error> {
@@ -167,7 +169,7 @@ impl Context {
request_id,
client_timestamp,
client_ip: ip.0,
- query: query.0.clone(),
+ raw_query,
method,
path,
server_received_at: Utc::now(),
@@ -177,10 +179,18 @@ impl Context {
})
}
- pub fn set_batch_metadata(&mut self, batch: &crate::v1::analytics::types::Batch) {
- self.created_at = Some(batch.created_at.clone());
- self.capture_internal = batch.capture_internal.unwrap_or(false);
- self.historical_migration = batch.historical_migration;
+ /// Stamp request-level batch metadata. Takes primitives (not an
+ /// analytics `Batch`) so the shared context stays CaptureMode-agnostic;
+ /// product wrappers extract these from their own batch envelope.
+ pub fn set_batch_metadata(
+ &mut self,
+ created_at: Option<String>,
+ capture_internal: bool,
+ historical_migration: bool,
+ ) {
+ self.created_at = created_at;
+ self.capture_internal = capture_internal;
+ self.historical_migration = historical_migration;
}
}
@@ -188,7 +198,6 @@ impl Context {
mod tests {
use std::net::{IpAddr, Ipv4Addr};
- use axum::extract::Query as AxumQuery;
use axum::http::{HeaderMap, HeaderValue, Method};
use axum_client_ip::InsecureClientIp;
use uuid::Uuid;
@@ -196,11 +205,11 @@ mod tests {
use super::*;
use crate::v1::analytics::constants::CAPTURE_V1_PATH;
- fn test_context(headers: &HeaderMap) -> Result<Context, Error> {
- Context::new(
+ fn test_context(headers: &HeaderMap) -> Result<RequestContext, Error> {
+ RequestContext::new(
headers,
&InsecureClientIp(IpAddr::V4(Ipv4Addr::LOCALHOST)),
- &AxumQuery(Query::default()),
+ None,
Method::POST,
CAPTURE_V1_PATH,
)
diff --git a/rust/capture/src/v1/error.rs b/rust/capture/src/v1/error.rs
index 90e2541920c8..c514e0ef28a1 100644
--- a/rust/capture/src/v1/error.rs
+++ b/rust/capture/src/v1/error.rs
@@ -8,7 +8,7 @@ use tracing::Level;
use crate::v1::analytics::constants::DEFAULT_RETRY_AFTER_SECS;
use crate::v1::constants::{CAPTURE_V1_ERROR_METRIC, CAPTURE_V1_UNKNOWN_PATH};
-use crate::v1::context::Context;
+use crate::v1::context::RequestContext;
#[derive(Debug, Clone, Serialize)]
pub struct ErrorResponse {
@@ -34,6 +34,10 @@ pub enum Error {
MissingRequiredHeaders(Vec<String>),
#[error("invalid header value: {0}")]
InvalidHeaderValue(String),
+ #[error("invalid query parameter: {0}")]
+ InvalidQueryParam(String),
+ #[error("request is missing required query parameters: {0:?}")]
+ MissingQueryParam(Vec<String>),
#[error("failed to decode request: {0}")]
RequestDecodingError(String),
#[error("failed to parse request: {0}")]
@@ -109,6 +113,8 @@ impl Error {
match self {
Self::MissingRequiredHeaders(_) => "missing_required_headers",
Self::InvalidHeaderValue(_) => "invalid_header_value",
+ Self::InvalidQueryParam(_) => "invalid_query_param",
+ Self::MissingQueryParam(_) => "missing_query_params",
Self::RequestDecodingError(_) => "request_decoding_error",
Self::RequestParsingError(_) => "request_parsing_error",
Self::EmptyBody => "empty_body",
@@ -166,6 +172,8 @@ impl Error {
// 4xx client errors: warn
Self::MissingRequiredHeaders(_)
| Self::InvalidHeaderValue(_)
+ | Self::InvalidQueryParam(_)
+ | Self::MissingQueryParam(_)
| Self::RequestDecodingError(_)
| Self::RequestParsingError(_)
| Self::EmptyBody
@@ -206,7 +214,7 @@ impl Error {
}
}
- pub(crate) fn stat_error(&self, ctx: Option<&Context>) {
+ pub(crate) fn stat_error(&self, ctx: Option<&RequestContext>) {
let path = ctx.map(|c| c.path).unwrap_or(CAPTURE_V1_UNKNOWN_PATH);
let status = self.status_code().as_str().to_owned();
counter!(
@@ -223,6 +231,8 @@ impl Error {
match self {
Self::MissingRequiredHeaders(_)
| Self::InvalidHeaderValue(_)
+ | Self::InvalidQueryParam(_)
+ | Self::MissingQueryParam(_)
| Self::RequestDecodingError(_)
| Self::RequestParsingError(_)
| Self::EmptyBody
@@ -278,7 +288,7 @@ impl Error {
}
}
-/// Emits a `tracing::event!` at the given level with all `v1::Context`
+/// Emits a `tracing::event!` at the given level with all `RequestContext`
/// fields expanded as structured log tags.
///
/// Usage:
@@ -301,18 +311,18 @@ macro_rules! ctx_log {
content_encoding = ?ctx.content_encoding,
client_ip = %ctx.client_ip,
method = %ctx.method,
- query = ?ctx.query,
+ query = ?ctx.raw_query,
path = %ctx.path,
$($rest)+
)
}};
}
-/// Logs at the error's `log_level()` with all `v1::Context` fields,
+/// Logs at the error's `log_level()` with all `RequestContext` fields,
/// then bumps the error metric counter via `stat_error()`.
///
-/// Always requires a `&Context`. For the pre-Context header-error path,
-/// inline the tracing call directly.
+/// Always requires a context that derefs to `&RequestContext`. For the
+/// pre-context header-error path, inline the tracing call directly.
///
/// Usage:
/// `log_stat_error!(err, &context)`
@@ -443,6 +453,8 @@ mod tests {
#[case::empty_batch(Error::EmptyBatch)]
#[case::payload_too_large(Error::PayloadTooLarge("big".into()))]
#[case::unsupported_content_type(Error::UnsupportedContentType("text/plain".into()))]
+ #[case::invalid_query_param(Error::InvalidQueryParam("bad param".into()))]
+ #[case::missing_query_param(Error::MissingQueryParam(vec!["foo".into()]))]
#[tokio::test]
async fn non_retryable_errors_omit_retry_after(#[case] err: Error) {
let resp = err.into_response();
@@ -452,4 +464,33 @@ mod tests {
resp.status()
);
}
+
+ #[rstest]
+ #[case::invalid_query_param(
+ Error::InvalidQueryParam("invalid query string: missing field `x`".into()),
+ StatusCode::BAD_REQUEST,
+ "invalid_query_param",
+ "invalid query parameter: invalid query string: missing field `x`"
+ )]
+ #[case::missing_query_param(
+ Error::MissingQueryParam(vec!["foo".into(), "bar".into()]),
+ StatusCode::BAD_REQUEST,
+ "missing_query_params",
+ "request is missing required query parameters: [\"foo\", \"bar\"]"
+ )]
+ #[tokio::test]
+ async fn query_param_errors_status_tag_and_description(
+ #[case] err: Error,
+ #[case] expected_status: StatusCode,
+ #[case] expected_tag: &str,
+ #[case] expected_description: &str,
+ ) {
+ assert_eq!(err.status_code(), expected_status);
+ assert_eq!(err.tag(), expected_tag);
+ let resp = err.into_response();
+ assert_eq!(resp.status(), expected_status);
+ let body = response_body(resp).await;
+ assert_eq!(body["error"], expected_tag);
+ assert_eq!(body["error_description"], expected_description);
+ }
}
diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index 0c347552f4f0..422abbf85680 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -240,6 +240,7 @@ mod tests {
capture_v1_sinks: String::new(),
capture_v1_max_compressed_body_bytes: 10 * 1024 * 1024,
capture_v1_max_decompressed_body_bytes: 50 * 1024 * 1024,
+ capture_v1_scatter_gather_min_batch: 8,
}
}
diff --git a/rust/capture/src/v1/sinks/DESIGN.md b/rust/capture/src/v1/sinks/DESIGN.md
index fd0c7e71f70d..a2e905a5e37d 100644
--- a/rust/capture/src/v1/sinks/DESIGN.md
+++ b/rust/capture/src/v1/sinks/DESIGN.md
@@ -29,6 +29,11 @@ they register their own paths under the same scheme.
└──────┬───────┘
│ Vec<WrappedEvent>
▼
+ ┌──────────────┐
+ │serialize_batch│─ scatter-gather (prepare.rs)
+ └──────┬────────┘
+ │ Vec<PreparedEvent>
+ ▼
┌─────────────┐
│ Router │─── resolves SinkName
└──────┬───────┘
@@ -55,8 +60,15 @@ Key properties:
WarpStream during a migration).
- **Per-event results** — `publish_batch` returns one `Box<dyn SinkResult>`
per published event, correlating outcomes back to request events by UUID.
-- **Owned-return API** — `serialize()` and `partition_key()` each return
- a fresh `String`, keeping the trait simple and parallelism-ready.
+- **Hoisted serialization** — events are serialized into storage-agnostic
+ `PreparedEvent`s by `serialize_batch` (`prepare.rs`) _before_ any sink is
+ touched. Sinks consume `&[PreparedEvent]`, never raw `Event` trait objects.
+ This isolates CPU-bound encoding from sink I/O, lets the same prepared
+ batch fan out to multiple sinks without re-encoding, and enables the
+ scatter-gather parallelism described in [section 2a](#2a-serialize_batch-scatter-gather).
+- **Owned-payload API** — `Event::serialize()` returns `bytes::Bytes` and
+ `partition_key()` returns a fresh `String`, keeping the trait simple and
+ cheap to move into spawned tasks.
---
@@ -68,7 +80,8 @@ graph TD
constants["constants.rs<br>DEFAULT_PRODUCE_TIMEOUT,<br>SINK_LIVENESS_DEADLINE,<br>SINK_STALL_THRESHOLD"]
event["event.rs<br>trait Event"]
sink["sink.rs<br>trait Sink"]
- types["types.rs<br>Destination, Outcome,<br>trait SinkResult,<br>BatchSummary"]
+ types["types.rs<br>Destination, Outcome,<br>trait SinkResult, BatchSummary,<br>PreparedEvent, SerializationFailure"]
+ prepare["prepare.rs<br>serialize_batch,<br>SerializedBatch"]
router["router.rs<br>Router,<br>RouterError"]
kmod["kafka/mod.rs<br>KafkaProducerTrait"]
@@ -84,9 +97,13 @@ graph TD
mod --> event
mod --> sink
mod --> types
+ mod --> prepare
mod --> router
mod --> kmod
+ prepare --> event
+ prepare --> types
+
kmod --> kconfig
kmod --> kctx
kmod --> kprod
@@ -113,9 +130,10 @@ Two layers:
```rust
pub use event::Event;
pub use kafka::KafkaSink;
+pub use prepare::{serialize_batch, SerializedBatch};
pub use router::{Router, RouterError};
pub use sink::Sink;
-pub use types::{Destination, Outcome, SinkResult};
+pub use types::{Destination, Outcome, PreparedEvent, SerializationFailure, SinkResult};
```
---
@@ -133,18 +151,20 @@ pub trait Sink: Send + Sync {
async fn publish_batch(
&self,
- ctx: &Context,
- events: &[&(dyn Event + Send + Sync)],
+ ctx: &RequestContext,
+ events: &[PreparedEvent],
) -> Vec<Box<dyn SinkResult>>;
async fn flush(&self) -> anyhow::Result<()>;
}
```
-Each `Sink` owns its identity (`name`), accepts a batch of trait-object
-events, and returns one `Box<dyn SinkResult>` per _published_ event.
-Skipped events (not publishable, or `Destination::Drop`) produce no
-result entry.
+Each `Sink` owns its identity (`name`), accepts a batch of
+already-serialized `PreparedEvent`s, and returns one `Box<dyn SinkResult>`
+per event it attempts. Events that never reach the sink — filtered by
+`should_publish()` or routed to `Destination::Drop` during
+`serialize_batch` — are simply absent from the input slice. A
+`Destination` with no configured topic still produces no result entry.
`KafkaSink<P: KafkaProducerTrait>` is currently the only implementation.
It is generic over the producer trait so tests inject `MockProducer`
@@ -209,13 +229,13 @@ pub trait Event: Send + Sync {
fn uuid(&self) -> Uuid;
fn should_publish(&self) -> bool;
fn destination(&self) -> &Destination;
- fn headers(&self, ctx: &Context) -> CapturedEventHeaders;
- fn partition_key(&self, ctx: &Context) -> String;
- fn serialize(&self, ctx: &Context) -> anyhow::Result<String>;
+ fn headers(&self, ctx: &RequestContext) -> CapturedEventHeaders;
+ fn partition_key(&self, ctx: &RequestContext) -> String;
+ fn serialize(&self, ctx: &RequestContext) -> anyhow::Result<bytes::Bytes>;
}
```
-`headers` receives the request `Context` so each `Event` implementation
+`headers` receives the request `RequestContext` so each `Event` implementation
can combine batch-scoped fields (token, now, historical_migration) with
event-scoped fields into a single `CapturedEventHeaders`
(`common_types`). The sink converts the returned struct to its
@@ -227,16 +247,26 @@ The analytics capture endpoint's `WrappedEvent` implements this trait
Other capture endpoints (e.g. session replay, exceptions) provide
their own `Event` implementations without changing any sink code.
+### Context split
+
+Trait methods take `&RequestContext` — the mode-agnostic request context
+(token, IP, timing, raw query string) shared by every future capture mode.
+The analytics endpoint wraps it in `analytics::Context { req, query }`,
+which `Deref`s to `RequestContext`, so the typed `Query` stays an
+analytics-only concern while the sink layer remains capture-mode-agnostic.
+
### Owned-return serialization
-`partition_key(ctx)` and `serialize(ctx)` each return a fresh owned
-`String`. This trades a small per-event allocation for a simpler trait
-contract that needs no shared mutable buffers — making the prep loop
-trivially parallelizable if needed in the future.
+`serialize(ctx)` returns `bytes::Bytes` and `partition_key(ctx)` returns a
+fresh owned `String`. `Bytes` is zero-copy to construct from a `Vec<u8>`
+and cheap (refcounted) to clone, so a `PreparedEvent` can be moved into a
+tokio task and fanned out to multiple sinks without re-encoding.
+The owned contract needs no shared mutable buffers, which is what makes
+the scatter-gather prep loop safe to parallelize.
`WrappedEvent::serialize` pre-sizes its buffer via
-`String::with_capacity(data.len() + 512)` to minimize reallocations
-for typical payloads.
+`Vec::with_capacity(data.len() + 512)` to minimize reallocations
+for typical payloads, then returns `Bytes::from(buf)`.
### Skip mechanisms
@@ -256,7 +286,7 @@ timestamp, session_id, etc.):
```text
┌──────────────────────────────────────────────┐
- │ event.headers(ctx: &Context) │
+ │ event.headers(ctx: &RequestContext) │
│ │
│ CapturedEventHeaders { │
│ token, ◄─ from ctx │
@@ -286,6 +316,106 @@ a single structured type flows from event to transport.
---
+## 2a. serialize_batch (scatter-gather)
+
+`serialize_batch` (`prepare.rs`) is the mode-agnostic step that turns a
+`Vec<E: Event>` into a `SerializedBatch` _before_ the router/sink layer.
+It is generic over the `Event` impl, so analytics, replay, and AI capture
+modes share one implementation.
+
+```rust
+pub async fn serialize_batch<E: Event + Send + Sync + 'static>(
+ events: Vec<E>,
+ ctx: &RequestContext,
+ scatter_gather_threshold: usize,
+) -> (Vec<E>, SerializedBatch);
+
+pub struct SerializedBatch {
+ pub prepared: Vec<PreparedEvent>, // publishable, in input order
+ pub failures: Vec<Box<dyn SinkResult>>, // SerializationFailure per failed event
+}
+```
+
+The caller gets its `Vec<E>` back so it can still build the per-event HTTP
+response after publishing (the prepared events alone don't carry the
+original request event). Recovery uses `Arc::try_unwrap` after the spawned
+tasks finish — see "Ownership" below.
+
+### PreparedEvent
+
+```rust
+pub struct PreparedEvent {
+ pub uuid: Uuid,
+ pub destination: Destination,
+ pub payload: bytes::Bytes,
+ pub headers: CapturedEventHeaders,
+ pub partition_key: String, // raw; the sink decides whether to null it
+}
+```
+
+Storage-agnostic and fully owned. It carries everything a sink needs to
+produce a record, so the sink does no serialization and holds no reference
+back into the request. `Bytes` makes it cheap to clone across a dual-write.
+
+### Sequential vs parallel
+
+The threshold is configurable via `CAPTURE_V1_SCATTER_GATHER_MIN_BATCH`
+(default 8). Set to 0 to force sequential serialization for all batch
+sizes (useful for modes like replay where batches are always single large events).
+
+```text
+ scatter_gather_threshold == 0 OR events.len() < threshold
+ └── serialize inline on the request task (no spawn overhead)
+
+ events.len() >= threshold (threshold > 0)
+ └── Arc<Vec<E>> + Arc<RequestContext>
+ └── JoinSet of tokio tasks (spawn, not spawn_blocking), one per event index
+ └── each task: catch_unwind(prepare_one(&events[i], &ctx))
+ └── collect by index → preserves input order
+```
+
+Small batches stay inline because a `JoinSet` of tokio tasks costs more
+than the serialization itself for a handful of events. Large batches fan
+out across the async worker pool to cut tail latency on big payloads. We
+use `spawn` (not `spawn_blocking`) to match v0's `send_batch`: per-event
+serialize is short CPU work, so concurrent execution is naturally bounded
+by `worker_threads` (~num_cpus) and excess events queue cheaply, rather
+than spawning one blocking-pool task per event and risking saturation of
+the shared `spawn_blocking` pool on very large batches. Both paths produce
+identical output (ordering, skips, failures)
+— verified by parity tests in `prepare.rs`.
+
+### Panic isolation
+
+Each event is serialized inside `std::panic::catch_unwind`. A panic in one
+event's `serialize` becomes a `SerializationFailure { is_panic: true }`
+for that event only; the rest of the batch is unaffected. Regular `Err`
+returns become `SerializationFailure::from_error`. Both are fatal
+(non-retriable) — re-running the same bytes would panic/err again.
+
+### Ownership (Arc::try_unwrap)
+
+`spawn` requires `'static`, so the parallel path wraps the events
+in `Arc<Vec<E>>` and tasks borrow by index. After the `JoinSet` drains,
+every task has dropped its `Arc` clone, so `Arc::try_unwrap` reclaims the
+sole-owner `Vec<E>` and hands it back to the caller. This is why
+`serialize_batch` can be parallel yet still return owned events.
+
+### Metrics
+
+| Metric | Type | Labels | When |
+|---|---|---|---|
+| `capture_v1_serialize_duration_seconds` | histogram | `batch_size` | Per-batch serialize wall-time (sequential or parallel) |
+| `capture_v1_serialize_failed_total` | counter | — | Per event that failed to serialize |
+| `capture_v1_serialize_panic_total` | counter | — | Per event whose `serialize` panicked |
+
+These are sink- and product-agnostic (serialization happens before any
+sink is chosen). Per-mode faceting comes from the Kubernetes deployment
+(`capture-analytics` / `-replay` / `-ai`) via the `namespace` label
+injected by the metrics pipeline.
+
+---
+
## 3. SinkResult and outcome model
### The SinkResult trait
@@ -310,6 +440,11 @@ result. The per-event heap allocation is a deliberate trade-off for
simplicity; at current batch sizes the cost is negligible compared to
Kafka I/O.
+Two types implement `SinkResult`: `KafkaResult` (sink-level produce
+outcomes) and `SerializationFailure` (pre-sink serialize failures from
+`serialize_batch`). `process_batch` concatenates both into one
+`Vec<Box<dyn SinkResult>>` before correlating outcomes back to events.
+
### Outcome
```rust
@@ -344,11 +479,14 @@ Captures every failure mode within a single configured sink:
| Variant | Outcome | When |
|---|---|---|
| `SinkUnavailable` | `RetriableError` | Producer health gate failed |
-| `SerializationFailed(String)` | `FatalError` | `serialize` returned `Err` |
| `Produce(ProduceError)` | Depends on `ProduceError::is_retriable()` | rdkafka send or delivery error |
| `Timeout` | `Timeout` | Ack not received within `produce_timeout` |
| `TaskPanicked` | `RetriableError` | Ack task panicked (should not happen with `FuturesUnordered`) |
+Serialization failures are no longer a sink concern — they are produced by
+`serialize_batch` as `SerializationFailure` (see
+[section 2a](#2a-serialize_batch-scatter-gather)) before any sink runs.
+
### BatchSummary
`BatchSummary::from_results` aggregates a `&[Box<dyn SinkResult>]` into
@@ -428,13 +566,11 @@ corresponds 1:1 to a published event.
┌──────────────────────────▼───────────────────────────────────────┐
│ Phase 1: Enqueue (sequential, per-partition ordering preserved) │
│ │
- │ for each event: │
- │ ├── should_publish()? → skip if false │
+ │ input: &[PreparedEvent] (already serialized by serialize_batch)│
+ │ for each prepared event: │
│ ├── topic_for(destination)? → skip if Drop/None │
- │ ├── event.serialize(ctx) → payload String │
- │ ├── event.headers(ctx) → CapturedEventHeaders │
- │ ├── should_null_partition_key(headers, dest)? │
- │ │ └── false → event.partition_key(ctx) → Some(key) │
+ │ ├── payload: prepared.payload (Bytes, no re-encode) │
+ │ ├── effective_partition_key(prepared.partition_key, dest)? │
│ ├── CapturedEventHeaders → OwnedHeaders (via From) │
│ └── producer.send(ProduceRecord) │
│ ├── Ok(ack_future) → push to FuturesUnordered │
@@ -480,18 +616,17 @@ corresponds 1:1 to a published event.
### Phase 1 — Enqueue
-Events are sent sequentially to preserve per-partition ordering. Two
-reusable `String` buffers (`payload_buf`, `key_buf`) are cleared and
-rewritten each iteration, amortizing allocations to zero after the first
-event.
+Events arrive already serialized as `PreparedEvent`s, so Phase 1 does no
+encoding — it reads `prepared.payload` (`Bytes`) directly. Events are sent
+sequentially to preserve per-partition ordering.
If `producer.send()` returns `QueueFull`, the event is failed immediately
as a retriable error. Backpressure is handled by librdkafka's internal
queue and the client-level retry mechanism, not an app-level sleep loop.
-After serialization and header construction, `effective_partition_key()`
-(`kafka/sink.rs`) decides whether the partition key should be nulled.
-Events always write a key via `partition_key()`; the sink nulls it when
+`effective_partition_key()` (`kafka/sink.rs`) decides whether the
+prepared key should be nulled. Prepared events always carry a key;
+the sink nulls it when
`force_disable_person_processing` is set and the destination is
`AnalyticsMain` or `Overflow`. In that case `None` is passed to rdkafka
so it round-robins; passing `Some("")` would hash to a single
@@ -752,7 +887,7 @@ Constructed by `KafkaProducer::new(sink, &KafkaConfig, handle, capture_mode)`:
pub struct ProduceRecord<'a> {
pub topic: &'a str,
pub key: Option<&'a str>,
- pub payload: &'a str,
+ pub payload: &'a [u8],
pub headers: OwnedHeaders,
}
```
@@ -891,7 +1026,11 @@ request-level context (`path`, `attempt`).
| `capture_v1_kafka_publish_total` | counter | `mode`, `cluster`, `outcome`, `path`, `attempt` (capped at "6+"), `destination` | Every event outcome (success, error, timeout, reject) |
| `capture_v1_kafka_ack_duration_seconds` | histogram | `mode`, `cluster`, `outcome`, `path`, `attempt` (capped at "6+"), `destination` | Per-event broker-ack latency (successful send → ack resolution), including `outcome="timeout"` for acks that miss `produce_timeout` |
| `capture_v1_kafka_enqueue_duration_seconds` | histogram | `mode`, `cluster`, `path`, `attempt` (capped at "6+") | Per-batch enqueue wall-time (the `enqueue_events` call), isolated from broker-ack latency |
-| `capture_v1_kafka_serialize_duration_seconds` | histogram | `mode`, `cluster`, `path`, `attempt` (capped at "6+"), `batch_size` | Per-batch serialization time (serialize + partition-key + enqueue loop), bucketed by batch size for latency/size correlation |
+
+Serialization timing now lives in `capture_v1_serialize_duration_seconds`
+(emitted by `serialize_batch`, see
+[section 2a](#2a-serialize_batch-scatter-gather)) — it is no longer a
+sink-path metric.
Cardinality note: the `destination` label is bounded at 9 values
(`Destination::as_tag()` collapses all `Custom(_)` topics to `custom`)
@@ -920,7 +1059,7 @@ All error-related metrics use stable, low-cardinality tags derived from:
- `error_code_tag()` — maps `RDKafkaErrorCode` variants to snake_case strings
(e.g. `queue_full`, `message_size_too_large`, `all_brokers_down`)
- `KafkaSinkError::as_tag()` — sink-level tags
- (e.g. `sink_unavailable`, `serialization_failed`, `timeout`)
+ (e.g. `sink_unavailable`, `timeout`, `task_panicked`)
- `ProduceError::as_tag()` — producer-level tags
(e.g. `event_too_big`, `delivery_cancelled`)
@@ -935,7 +1074,6 @@ request-scoped context (token, path, attempt) to the log line.
| `WARN` (via `ctx_log!`) | Partial batch failure | `kafka/sink.rs` |
| `ERROR` (via `ctx_log!`) | Full batch failure | `kafka/sink.rs` |
| `ERROR` (via `ctx_log!`) | Producer not ready | `kafka/sink.rs` |
-| `ERROR` (via `ctx_log!`) | Event serialization failed | `kafka/sink.rs` |
| `error!` | rdkafka client error callback | `kafka/context.rs` |
| `error!` | All brokers down | `kafka/context.rs` |
| `info!` | Producer connected | `kafka/producer.rs` |
@@ -978,7 +1116,8 @@ keeping the Sink trait unaware of topic names.
Partition key construction is split between the `Event` implementation
and the sink:
-1. **`Event::partition_key(ctx)`** returns an owned key String.
+1. **`Event::partition_key(ctx)`** returns an owned key String, captured
+ into `PreparedEvent.partition_key` by `serialize_batch`.
For analytics events (`WrappedEvent`):
```text
@@ -993,19 +1132,19 @@ and the sink:
```
2. **`should_null_partition_key()`** (`kafka/sink.rs`) decides whether
- the key should be nulled before sending to the producer:
+ the prepared key should be nulled before sending to the producer:
```rust
-fn effective_partition_key<'a>(
- key_buf: &'a str,
+fn should_null_partition_key(
force_disable_person_processing: bool,
destination: &Destination,
-) -> Option<&'a str>
+) -> bool
```
If `force_disable_person_processing` is set and the destination is
- `AnalyticsMain` or `Overflow`, the function returns `None`. Otherwise
- it returns `Some(key_buf)`.
+ `AnalyticsMain` or `Overflow`, it returns `true` and the sink passes
+ `None` to rdkafka. Otherwise the sink passes
+ `Some(prepared.partition_key)`.
Key design choices:
@@ -1173,8 +1312,9 @@ Sent records are captured as `OwnedProduceRecord` (owned copies of
### Test infrastructure (sink_tests.rs)
`FakeEvent` implements `Event` with configurable destination, publish
-flag, partition key, payload (including injectable serialization errors),
-and headers.
+flag, partition key, payload, and headers. Serialize-failure scenarios
+(errors, panics) are covered in `prepare.rs` tests, not the sink — the
+sink only ever sees already-prepared events.
`TestHarness` / `HarnessBuilder` wrap sink construction with a
`lifecycle::Manager` so tests can verify health heartbeat interactions.
diff --git a/rust/capture/src/v1/sinks/event.rs b/rust/capture/src/v1/sinks/event.rs
index f8c3022bddd7..29ba3b72cb39 100644
--- a/rust/capture/src/v1/sinks/event.rs
+++ b/rust/capture/src/v1/sinks/event.rs
@@ -1,7 +1,7 @@
use common_types::CapturedEventHeaders;
use uuid::Uuid;
-use crate::v1::context::Context;
+use crate::v1::context::RequestContext;
use crate::v1::sinks::Destination;
/// Transport-agnostic trait declaring an event's identity, routing intent,
@@ -20,18 +20,21 @@ pub trait Event: Send + Sync {
fn destination(&self) -> &Destination;
/// Resolve the full set of transport headers for this event, using the
- /// supplied [`Context`] for batch-scoped fields (token, now,
+ /// supplied [`RequestContext`] for batch-scoped fields (token, now,
/// historical_migration) alongside any event-owned fields. Sinks convert
/// the returned [`CapturedEventHeaders`] to their backend-specific format
/// (e.g. `rdkafka::message::OwnedHeaders` via the `From` impl in
/// `common_types`).
- fn headers(&self, ctx: &Context) -> CapturedEventHeaders;
+ fn headers(&self, ctx: &RequestContext) -> CapturedEventHeaders;
/// Return the partition key for this event.
/// The sink decides whether to use it or null it based on routing policy
/// (e.g. force_disable_person_processing).
- fn partition_key(&self, ctx: &Context) -> String;
+ fn partition_key(&self, ctx: &RequestContext) -> String;
- /// Serialize the event payload and return the JSON string.
- fn serialize(&self, ctx: &Context) -> anyhow::Result<String>;
+ /// Serialize the event payload and return the raw bytes. `Bytes` (not
+ /// `String`) so non-UTF-8 / binary payloads (e.g. replay) share this
+ /// contract, and so a serialized payload can be cheaply cloned across
+ /// multiple sinks (dual-write) without re-encoding.
+ fn serialize(&self, ctx: &RequestContext) -> anyhow::Result<bytes::Bytes>;
}
diff --git a/rust/capture/src/v1/sinks/kafka/constants.rs b/rust/capture/src/v1/sinks/kafka/constants.rs
index e996a818b805..821c792f5ab7 100644
--- a/rust/capture/src/v1/sinks/kafka/constants.rs
+++ b/rust/capture/src/v1/sinks/kafka/constants.rs
@@ -11,10 +11,6 @@ pub(super) const KAFKA_ACK_DURATION_SECONDS: &str = "capture_v1_kafka_ack_durati
/// Per-batch enqueue wall-time histogram.
pub(super) const KAFKA_ENQUEUE_DURATION_SECONDS: &str = "capture_v1_kafka_enqueue_duration_seconds";
-/// Per-batch serialization time histogram (labeled by batch_size bucket).
-pub(super) const KAFKA_SERIALIZE_DURATION_SECONDS: &str =
- "capture_v1_kafka_serialize_duration_seconds";
-
/// Produce-level error counter (distinct from ack errors).
pub(super) const KAFKA_PRODUCE_ERRORS_TOTAL: &str = "capture_v1_kafka_produce_errors_total";
diff --git a/rust/capture/src/v1/sinks/kafka/mock.rs b/rust/capture/src/v1/sinks/kafka/mock.rs
index 525eb183e396..1be572771ce8 100644
--- a/rust/capture/src/v1/sinks/kafka/mock.rs
+++ b/rust/capture/src/v1/sinks/kafka/mock.rs
@@ -25,7 +25,7 @@ impl<'a> From<ProduceRecord<'a>> for OwnedProduceRecord {
Self {
topic: r.topic.to_owned(),
key: r.key.map(str::to_owned),
- payload: r.payload.to_owned(),
+ payload: String::from_utf8_lossy(r.payload).into_owned(),
}
}
}
@@ -35,7 +35,7 @@ impl<'a> From<&ProduceRecord<'a>> for OwnedProduceRecord {
Self {
topic: r.topic.to_owned(),
key: r.key.map(str::to_owned),
- payload: r.payload.to_owned(),
+ payload: String::from_utf8_lossy(r.payload).into_owned(),
}
}
}
diff --git a/rust/capture/src/v1/sinks/kafka/producer.rs b/rust/capture/src/v1/sinks/kafka/producer.rs
index 784a1d4d1271..42c8313df747 100644
--- a/rust/capture/src/v1/sinks/kafka/producer.rs
+++ b/rust/capture/src/v1/sinks/kafka/producer.rs
@@ -75,7 +75,7 @@ impl ProduceError {
pub struct ProduceRecord<'a> {
pub topic: &'a str,
pub key: Option<&'a str>,
- pub payload: &'a str,
+ pub payload: &'a [u8],
pub headers: OwnedHeaders,
}
@@ -243,7 +243,7 @@ impl super::KafkaProducerTrait for KafkaProducer {
let returned_record = ProduceRecord {
topic: returned.topic,
key: returned.key,
- payload: returned.payload.unwrap_or(""),
+ payload: returned.payload.unwrap_or(&[]),
headers: returned.headers.unwrap_or_else(OwnedHeaders::new),
};
Err((produce_error_from_kafka(e), returned_record))
diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rs
index f191c58b83a9..d4405df44b15 100644
--- a/rust/capture/src/v1/sinks/kafka/sink.rs
+++ b/rust/capture/src/v1/sinks/kafka/sink.rs
@@ -13,10 +13,9 @@ use tracing::Level;
use uuid::Uuid;
use crate::config::CaptureMode;
-use crate::v1::context::Context;
-use crate::v1::sinks::event::Event;
+use crate::v1::context::RequestContext;
use crate::v1::sinks::sink::Sink;
-use crate::v1::sinks::types::{BatchSummary, Destination, Outcome, SinkResult};
+use crate::v1::sinks::types::{BatchSummary, Destination, Outcome, PreparedEvent, SinkResult};
use crate::v1::sinks::{Config, SinkName};
use super::constants::*;
@@ -24,19 +23,6 @@ use super::producer::ProduceRecord;
use super::types::{KafkaResult, KafkaSinkError};
use super::KafkaProducerTrait;
-/// Bounded batch-size bucket for the serialize_duration histogram label.
-/// 5 values keeps cardinality manageable while giving visibility into
-/// the batch-size / latency relationship.
-fn batch_size_bucket(n: usize) -> &'static str {
- match n {
- 0..=1 => "1",
- 2..=8 => "2-8",
- 9..=32 => "9-32",
- 33..=128 => "33-128",
- _ => "129+",
- }
-}
-
/// Returns true when the partition key should be nulled — i.e. when person
/// processing is force-disabled for Main/Overflow destinations, spreading
/// load across partitions instead of hotspotting on a single key.
@@ -100,18 +86,15 @@ impl<P: KafkaProducerTrait> KafkaSink<P> {
}
}
-/// 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>> {
+/// Reject every event in `events` as `SinkUnavailable`, incrementing a single
+/// counter per destination for the batch. Inputs are already serialized and
+/// publishable (non-publishable events never reach a sink).
+fn reject_all(events: &[PreparedEvent], labels: &MetricLabels) -> Vec<Box<dyn SinkResult>> {
let enqueued_at = Utc::now();
- let publishable: Vec<_> = events.iter().filter(|e| e.should_publish()).collect();
let mut by_dest: std::collections::HashMap<&'static str, u64> =
std::collections::HashMap::new();
- for e in &publishable {
- *by_dest.entry(e.destination().as_tag()).or_default() += 1;
+ for e in events {
+ *by_dest.entry(e.destination.as_tag()).or_default() += 1;
}
for (dest_tag, count) in &by_dest {
counter!(
@@ -125,11 +108,11 @@ fn reject_publishable(
)
.increment(*count);
}
- publishable
- .into_iter()
+ events
+ .iter()
.map(|e| -> Box<dyn SinkResult> {
Box::new(KafkaResult::err(
- e.uuid(),
+ e.uuid,
KafkaSinkError::SinkUnavailable,
enqueued_at,
))
@@ -156,81 +139,42 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {
/// 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)],
+ events: &[PreparedEvent],
labels: &MetricLabels,
enqueued_at: DateTime<Utc>,
results: &mut Vec<Box<dyn SinkResult>>,
pending: &mut FuturesUnordered<AckFuture>,
enqueued_keys: &mut Vec<(Uuid, &'static str, Instant)>,
) {
- let serialize_start = Instant::now();
-
for event in events {
- if !event.should_publish() {
- continue;
- }
-
- let uuid = event.uuid();
- let dest_tag = event.destination().as_tag();
+ let uuid = event.uuid;
+ let dest_tag = event.destination.as_tag();
- let topic = match self.config.kafka.topic_for(event.destination()) {
+ let topic = match self.config.kafka.topic_for(&event.destination) {
Some(t) => t,
None => continue,
};
- let payload = match event.serialize(ctx) {
- Ok(p) => p,
- Err(e) => {
- crate::ctx_log!(
- Level::ERROR,
- ctx,
- sink = labels.sink,
- event_uuid = %uuid,
- error = %e,
- "event serialization failed, dropping event"
- );
- counter!(
- KAFKA_PUBLISH_TOTAL,
- "mode" => labels.mode,
- "cluster" => labels.sink,
- "outcome" => Outcome::FatalError.as_tag(),
- "path" => labels.path,
- "attempt" => labels.attempt,
- "destination" => dest_tag,
- )
- .increment(1);
- results.push(Box::new(KafkaResult::err(
- uuid,
- KafkaSinkError::SerializationFailed(format!("{e:#}")),
- enqueued_at,
- )));
- continue;
- }
- };
-
- let captured_headers = event.headers(ctx);
-
let key = if should_null_partition_key(
- captured_headers
+ event
+ .headers
.force_disable_person_processing
.unwrap_or(false),
- event.destination(),
+ &event.destination,
) {
None
} else {
- Some(event.partition_key(ctx))
+ Some(event.partition_key.as_str())
};
- let headers: rdkafka::message::OwnedHeaders = captured_headers.into();
+ let headers: rdkafka::message::OwnedHeaders = event.headers.clone().into();
let record = ProduceRecord {
topic,
- key: key.as_deref(),
- payload: &payload,
+ key,
+ payload: event.payload.as_ref(),
headers,
};
@@ -261,16 +205,6 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {
}
}
}
-
- histogram!(
- KAFKA_SERIALIZE_DURATION_SECONDS,
- "mode" => labels.mode,
- "cluster" => labels.sink,
- "path" => labels.path,
- "attempt" => labels.attempt,
- "batch_size" => batch_size_bucket(events.len()),
- )
- .record(serialize_start.elapsed().as_secs_f64());
}
/// Phase 2: drain ack futures with a per-sink deadline. Dropping remaining
@@ -408,8 +342,8 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {
async fn publish_batch(
&self,
- ctx: &Context,
- events: &[&(dyn Event + Send + Sync)],
+ ctx: &RequestContext,
+ events: &[PreparedEvent],
) -> Vec<Box<dyn SinkResult>> {
let labels = MetricLabels {
sink: self.name.as_str(),
@@ -426,7 +360,7 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {
mode = labels.mode,
"producer not ready — rejecting batch"
);
- return reject_publishable(events, &labels);
+ return reject_all(events, &labels);
}
let enqueued_at = Utc::now();
@@ -437,7 +371,6 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {
// Enqueue wall-time, isolated from per-event broker-ack latency.
let enqueue_start = Instant::now();
self.enqueue_events(
- ctx,
events,
&labels,
enqueued_at,
diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rs
index b911f1e13901..0847f20dc851 100644
--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs
+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs
@@ -8,7 +8,7 @@ use rstest::rstest;
use uuid::Uuid;
use crate::config::CaptureMode;
-use crate::v1::context::Context;
+use crate::v1::context::RequestContext;
use crate::v1::sinks::event::Event;
use crate::v1::sinks::sink::Sink;
use crate::v1::sinks::types::{BatchSummary, Outcome};
@@ -76,11 +76,6 @@ impl FakeEvent {
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
@@ -105,22 +100,24 @@ impl Event for FakeEvent {
&self.destination
}
- fn headers(&self, _ctx: &Context) -> CapturedEventHeaders {
+ fn headers(&self, _ctx: &RequestContext) -> CapturedEventHeaders {
self.event_headers.clone()
}
- fn partition_key(&self, _ctx: &Context) -> String {
+ fn partition_key(&self, _ctx: &RequestContext) -> String {
self.partition_key.clone().unwrap_or_default()
}
- fn serialize(&self, _ctx: &Context) -> anyhow::Result<String> {
+ fn serialize(&self, _ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {
match &self.payload {
- Ok(p) => Ok(p.clone()),
+ Ok(p) => Ok(bytes::Bytes::from(p.clone())),
Err(e) => Err(anyhow::anyhow!(e.clone())),
}
}
}
+use crate::v1::test_utils::prepared;
+
// ---------------------------------------------------------------------------
// TestHarness
// ---------------------------------------------------------------------------
@@ -129,7 +126,7 @@ struct TestHarness {
sink: KafkaSink<MockProducer>,
producer: Arc<MockProducer>,
handle: lifecycle::Handle,
- ctx: Context,
+ ctx: RequestContext,
_monitor: lifecycle::MonitorGuard,
}
@@ -273,7 +270,7 @@ impl HarnessBuilder {
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 events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -301,7 +298,7 @@ async fn non_publishable_events_skipped() {
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 events = prepared(&[&e1, &e2, &e3], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -319,7 +316,7 @@ async fn non_publishable_events_skipped() {
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 events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -336,7 +333,7 @@ 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 events = prepared(&[&e1, &e2], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -361,7 +358,7 @@ async fn queue_full_is_immediate_retriable() {
})
.build();
let event = FakeEvent::ok("evt-1");
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+ let events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -384,7 +381,7 @@ async fn send_error_fatal_event_too_big() {
})
.build();
let event = FakeEvent::ok("evt-1");
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+ let events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -403,7 +400,7 @@ async fn ack_error_retriable_delivery_cancelled() {
.ack_error(|| ProduceError::DeliveryCancelled)
.build();
let event = FakeEvent::ok("evt-1");
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+ let events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -429,7 +426,7 @@ async fn ack_error_retriable_topic_auth() {
})
.build();
let event = FakeEvent::ok("evt-1");
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+ let events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -451,7 +448,7 @@ async fn produce_timeout_single() {
.produce_timeout(Duration::from_millis(50))
.build();
let event = FakeEvent::ok("evt-1");
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+ let events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -470,7 +467,7 @@ async fn produce_timeout_batch_all_pending_get_timeout() {
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 events = prepared(&[&e1, &e2, &e3], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -482,89 +479,7 @@ async fn produce_timeout_batch_all_pending_get_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
+// Flush delegates to producer
// ---------------------------------------------------------------------------
#[tokio::test]
@@ -602,7 +517,7 @@ async fn destination_routes_to_correct_topic(
) {
let h = TestHarness::new();
let event = FakeEvent::ok("evt-1").with_destination(destination);
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+ let events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -625,7 +540,7 @@ async fn batch_summary_with_timeouts() {
.build();
let e1 = FakeEvent::ok("evt-1");
let e2 = FakeEvent::ok("evt-2");
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2];
+ let events = prepared(&[&e1, &e2], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
let summary = BatchSummary::from_results(&results);
@@ -652,7 +567,7 @@ async fn slow_ack_within_timeout_batch_all_succeed() {
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 events = prepared(&[&e1, &e2, &e3], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -694,7 +609,6 @@ enum FailureMode {
Timeout,
SendError,
AckError,
- SerializationError,
}
fn health_harness(mode: &FailureMode) -> TestHarness {
@@ -713,17 +627,16 @@ fn health_harness(mode: &FailureMode) -> TestHarness {
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 health_events() -> Vec<FakeEvent> {
+ vec![
+ FakeEvent::ok("evt-1"),
+ FakeEvent::ok("evt-2"),
+ FakeEvent::ok("evt-3"),
+ ]
}
fn expected_outcome(mode: &FailureMode) -> Outcome {
@@ -731,7 +644,6 @@ fn expected_outcome(mode: &FailureMode) -> Outcome {
FailureMode::Timeout => Outcome::Timeout,
FailureMode::SendError => Outcome::RetriableError,
FailureMode::AckError => Outcome::RetriableError,
- FailureMode::SerializationError => Outcome::FatalError,
}
}
@@ -739,13 +651,12 @@ fn expected_outcome(mode: &FailureMode) -> Outcome {
#[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 owned_events = health_events();
let refs: Vec<&FakeEvent> = owned_events.iter().collect();
- let events: Vec<&(dyn Event + Send + Sync)> = vec![refs[0], refs[1], refs[2]];
+ let events = prepared(&refs, &h.ctx);
let expected = expected_outcome(&mode);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -773,7 +684,7 @@ async fn health_refreshed_on_full_success() {
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 events = prepared(&[&e1, &e2, &e3], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
for r in &results {
@@ -788,7 +699,7 @@ async fn health_refreshed_on_full_success() {
}
// ---------------------------------------------------------------------------
-// Health: mixed batch (some succeed, some fail) -> heartbeat refreshed
+// Health: partial success (some send errors) -> heartbeat still fires
// ---------------------------------------------------------------------------
#[tokio::test]
@@ -796,21 +707,31 @@ 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)
+ .send_error(|| ProduceError::Kafka {
+ code: RDKafkaErrorCode::QueueFull,
+ })
+ .send_error_count(1)
.build();
let e1 = FakeEvent::ok("evt-1");
- let e2 = FakeEvent::ok("evt-2").with_payload(Err("bad".into()));
+ let e2 = FakeEvent::ok("evt-2");
let e3 = FakeEvent::ok("evt-3");
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2, &e3];
+ let events = prepared(&[&e1, &e2, &e3], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
- let summary = BatchSummary::from_results(&results);
- assert!(summary.succeeded > 0);
- assert!(summary.fatal > 0);
+ let outcomes: Vec<Outcome> = results.iter().map(|r| r.outcome()).collect();
+ assert!(
+ outcomes.contains(&Outcome::RetriableError),
+ "at least one event should fail"
+ );
+ assert!(
+ outcomes.contains(&Outcome::Success),
+ "at least one event should succeed"
+ );
tokio::time::sleep(HEALTH_TEST_HEALTHY_SLEEP).await;
assert!(
h.handle.is_healthy(),
- "handle should stay healthy when at least one event succeeded"
+ "handle should stay healthy when at least one event succeeds"
);
}
@@ -840,7 +761,7 @@ async fn force_disable_null_key_policy(
.with_partition_key(Some("phc_test:user-1"))
.with_destination(destination)
.with_headers(headers);
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];
+ let events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -855,7 +776,7 @@ async fn force_disable_null_key_policy(
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 events = prepared(&[&event], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -877,7 +798,7 @@ async fn some_partition_key_propagates_as_some() {
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 events = prepared(&[&wrapped], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -911,7 +832,7 @@ async fn realistic_single_pageview_round_trip() {
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 events = prepared(&[&batch[0], &batch[1], &batch[2]], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -949,7 +870,7 @@ 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 events = prepared(&[&wrapped], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -967,7 +888,7 @@ async fn realistic_dropped_event_not_published() {
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 events = prepared(&[&wrapped], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -996,7 +917,7 @@ async fn mixed_send_error_and_ack_error_in_batch() {
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 events = prepared(&[&e1, &e2, &e3], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -1034,7 +955,7 @@ async fn partial_timeout_with_send_error() {
.build();
let e1 = FakeEvent::ok("evt-1");
let e2 = FakeEvent::ok("evt-2");
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2];
+ let events = prepared(&[&e1, &e2], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -1050,37 +971,6 @@ async fn partial_timeout_with_send_error() {
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"));
-}
-
// ===========================================================================
// Realistic WrappedEvent — destination routing, property injection, options
// ===========================================================================
@@ -1090,7 +980,7 @@ async fn realistic_exception_routes_to_exception_topic() {
let h = TestHarness::new();
let wrapped = test_utils::wrapped_event("$exception", "user-1")
.with_destination(Destination::ExceptionErrorTracking);
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+ let events = prepared(&[&wrapped], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -1106,7 +996,7 @@ async fn realistic_heatmap_routes_to_heatmap_topic() {
let h = TestHarness::new();
let wrapped =
test_utils::wrapped_event("$$heatmap", "user-1").with_destination(Destination::HeatmapMain);
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+ let events = prepared(&[&wrapped], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -1122,7 +1012,7 @@ async fn realistic_session_id_injected_into_properties() {
let h = TestHarness::new();
let mut wrapped = test_utils::wrapped_event("$pageview", "user-1");
wrapped.event.session_id = Some("sess-123".to_string());
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+ let events = prepared(&[&wrapped], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -1142,7 +1032,7 @@ async fn realistic_window_id_injected_into_properties() {
let h = TestHarness::new();
let mut wrapped = test_utils::wrapped_event("$pageview", "user-1");
wrapped.event.window_id = Some("win-456".to_string());
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+ let events = prepared(&[&wrapped], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -1162,7 +1052,7 @@ async fn realistic_cookieless_partition_key() {
let h = TestHarness::new();
let mut wrapped = test_utils::wrapped_event("$pageview", "user-1");
wrapped.event.options.cookieless_mode = Some(true);
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+ let events = prepared(&[&wrapped], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -1190,7 +1080,7 @@ async fn realistic_spread_destinations_routes_correctly(
let h = TestHarness::new();
let all = test_utils::realistic_spread_destinations();
let ev = &all[idx];
- let events: Vec<&(dyn Event + Send + Sync)> = vec![ev];
+ let events = prepared(&[ev], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
@@ -1215,7 +1105,7 @@ async fn realistic_force_disable_pp_null_partition_key() {
let wrapped = test_utils::wrapped_event("$pageview", "user-1")
.with_force_disable_person_processing(true)
.with_destination(Destination::AnalyticsMain);
- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
+ let events = prepared(&[&wrapped], &h.ctx);
let results = h.sink.publish_batch(&h.ctx, &events).await;
diff --git a/rust/capture/src/v1/sinks/kafka/types.rs b/rust/capture/src/v1/sinks/kafka/types.rs
index f8be56338d69..cbc2f30a1311 100644
--- a/rust/capture/src/v1/sinks/kafka/types.rs
+++ b/rust/capture/src/v1/sinks/kafka/types.rs
@@ -56,7 +56,6 @@ pub fn error_code_tag(code: RDKafkaErrorCode) -> &'static str {
#[derive(Debug)]
pub enum KafkaSinkError {
SinkUnavailable,
- SerializationFailed(String),
Produce(ProduceError),
Timeout,
TaskPanicked,
@@ -66,7 +65,6 @@ impl KafkaSinkError {
pub fn outcome(&self) -> Outcome {
match self {
Self::SinkUnavailable => Outcome::RetriableError,
- Self::SerializationFailed(_) => Outcome::FatalError,
Self::Produce(e) => {
if e.is_retriable() {
Outcome::RetriableError
@@ -82,7 +80,6 @@ impl KafkaSinkError {
pub fn as_tag(&self) -> &'static str {
match self {
Self::SinkUnavailable => "sink_unavailable",
- Self::SerializationFailed(_) => "serialization_failed",
Self::Produce(e) => e.as_tag(),
Self::Timeout => "timeout",
Self::TaskPanicked => "task_panicked",
@@ -92,7 +89,6 @@ impl KafkaSinkError {
pub fn detail(&self) -> Cow<'_, str> {
match self {
Self::SinkUnavailable => Cow::Borrowed("sink unavailable"),
- Self::SerializationFailed(m) => Cow::Owned(format!("serialization failed: {m}")),
Self::Produce(e) => Cow::Owned(format!("{e}")),
Self::Timeout => Cow::Borrowed("produce timeout"),
Self::TaskPanicked => Cow::Borrowed("task panicked during delivery"),
diff --git a/rust/capture/src/v1/sinks/mod.rs b/rust/capture/src/v1/sinks/mod.rs
index 802d484c04a7..c8f887192e69 100644
--- a/rust/capture/src/v1/sinks/mod.rs
+++ b/rust/capture/src/v1/sinks/mod.rs
@@ -1,6 +1,7 @@
pub mod constants;
pub mod event;
pub mod kafka;
+pub mod prepare;
pub mod router;
pub mod sink;
pub mod types;
@@ -13,9 +14,10 @@ use envconfig::Envconfig;
pub use event::Event;
pub use kafka::KafkaSink;
+pub use prepare::{serialize_batch, SerializedBatch, DEFAULT_SCATTER_GATHER_MIN_BATCH};
pub use router::{Router, RouterError};
pub use sink::Sink;
-pub use types::{Destination, Outcome, SinkResult};
+pub use types::{Destination, Outcome, PreparedEvent, SerializationFailure, SinkResult};
// ---------------------------------------------------------------------------
// SinkName
diff --git a/rust/capture/src/v1/sinks/prepare.rs b/rust/capture/src/v1/sinks/prepare.rs
new file mode 100644
index 000000000000..6f377e5401bc
--- /dev/null
+++ b/rust/capture/src/v1/sinks/prepare.rs
@@ -0,0 +1,455 @@
+//! Hoisted, CaptureMode-agnostic serialize step.
+//!
+//! `serialize_batch` turns a batch of [`Event`]s into [`PreparedEvent`]s
+//! (owned, storage-agnostic) before any [`Sink`](super::sink::Sink) sees them.
+//! Pulling serialization out of the Sink lets every capture mode (analytics,
+//! replay, AI) share one CPU-bound step and enables serialize-once /
+//! fan-out-to-many-sinks for dual-write topologies.
+//!
+//! Small batches serialize sequentially; large batches scatter across tokio
+//! tasks and gather back in input order. Per-event panics are isolated so one
+//! bad event never fails the whole request.
+
+use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::sync::Arc;
+use std::time::Instant;
+
+use metrics::{counter, histogram};
+use tokio::task::JoinSet;
+use tracing::Level;
+use uuid::Uuid;
+
+use crate::v1::constants::{
+ CAPTURE_V1_SERIALIZE_DURATION_SECONDS, CAPTURE_V1_SERIALIZE_FAILED_TOTAL,
+ CAPTURE_V1_SERIALIZE_PANIC_TOTAL,
+};
+use crate::v1::context::RequestContext;
+use crate::v1::sinks::event::Event;
+use crate::v1::sinks::types::{PreparedEvent, SerializationFailure, SinkResult};
+
+/// Default scatter-gather threshold; overridden by `CAPTURE_V1_SCATTER_GATHER_MIN_BATCH`.
+pub const DEFAULT_SCATTER_GATHER_MIN_BATCH: usize = 8;
+
+/// Outcome of the serialize step: events ready to publish (input order) plus
+/// per-event failures, each already a `SinkResult` so the caller can merge them
+/// straight into the batch's result set.
+pub struct SerializedBatch {
+ pub prepared: Vec<PreparedEvent>,
+ pub failures: Vec<Box<dyn SinkResult>>,
+}
+
+/// Per-event result before aggregation. `Skipped` mirrors the Sink's existing
+/// behavior of silently dropping `should_publish() == false` events.
+// Prepared is the hot, dominant variant and is immediately drained into a
+// Vec<PreparedEvent>; boxing it just to even out variant sizes would add a
+// heap allocation per successful event.
+#[allow(clippy::large_enum_variant)]
+enum Slot {
+ Prepared(PreparedEvent),
+ Skipped,
+ Failed(SerializationFailure),
+}
+
+/// Serialize one event, honoring `should_publish`. Pure and panic-free at this
+/// layer — panic isolation is the caller's (`run_one`) job.
+fn prepare_one<E: Event>(ev: &E, ctx: &RequestContext) -> anyhow::Result<Option<PreparedEvent>> {
+ if !ev.should_publish() {
+ return Ok(None);
+ }
+ let payload = ev.serialize(ctx)?;
+ Ok(Some(PreparedEvent {
+ uuid: ev.uuid(),
+ destination: ev.destination().clone(),
+ payload,
+ headers: ev.headers(ctx),
+ partition_key: ev.partition_key(ctx),
+ }))
+}
+
+/// Run `prepare_one` with panic isolation so a single misbehaving event (e.g. a
+/// `serialize` impl that panics) is recorded as a failure instead of aborting
+/// the batch / poisoning the worker.
+fn run_one<E: Event>(ev: &E, ctx: &RequestContext) -> Slot {
+ let uuid = ev.uuid();
+ match catch_unwind(AssertUnwindSafe(|| prepare_one(ev, ctx))) {
+ Ok(Ok(Some(prepared))) => Slot::Prepared(prepared),
+ Ok(Ok(None)) => Slot::Skipped,
+ Ok(Err(e)) => Slot::Failed(SerializationFailure::from_error(uuid, format!("{e:#}"))),
+ Err(_) => Slot::Failed(SerializationFailure::panicked(uuid)),
+ }
+}
+
+/// Serialize a whole batch into `PreparedEvent`s, preserving input order for
+/// the prepared events so downstream per-partition ordering is unaffected.
+///
+/// Consumes `events` so the parallel path can share them across tokio tasks
+/// via `Arc`, then hands ownership back (alongside the results) so the caller
+/// can keep correlating results to events and build its response. `ctx` is
+/// cloned once and shared across tasks.
+pub async fn serialize_batch<E>(
+ events: Vec<E>,
+ ctx: &RequestContext,
+ scatter_gather_threshold: usize,
+) -> (Vec<E>, SerializedBatch)
+where
+ E: Event + 'static,
+{
+ let start = Instant::now();
+ let n = events.len();
+
+ // 0 disables fanout entirely (e.g. replay's single large consolidated event).
+ let (events, slots): (Vec<E>, Vec<Slot>) = if scatter_gather_threshold == 0
+ || n < scatter_gather_threshold
+ {
+ let slots = events.iter().map(|ev| run_one(ev, ctx)).collect();
+ (events, slots)
+ } else {
+ let uuids: Vec<Uuid> = events.iter().map(|ev| ev.uuid()).collect();
+ let events = Arc::new(events);
+ let ctx = Arc::new(ctx.clone());
+ let mut set: JoinSet<(usize, Slot)> = JoinSet::new();
+ for i in 0..n {
+ let events = Arc::clone(&events);
+ let ctx = Arc::clone(&ctx);
+ // Spawn onto the async runtime workers (not spawn_blocking): the
+ // per-event work is short CPU, so concurrent execution is naturally
+ // bounded by worker_threads (~num_cpus) and excess events queue
+ // cheaply. This mirrors v0's send_batch and avoids saturating the
+ // shared spawn_blocking pool on huge batches.
+ set.spawn(async move { (i, run_one(&events[i], &ctx)) });
+ }
+
+ // Gather out-of-completion-order results back into input order.
+ let mut indexed: Vec<Option<Slot>> = (0..n).map(|_| None).collect();
+ while let Some(joined) = set.join_next().await {
+ // run_one catches panics internally, so a JoinError is unexpected;
+ // leave that slot empty and let the fill below record it as a panic.
+ if let Ok((i, slot)) = joined {
+ indexed[i] = Some(slot);
+ }
+ }
+ let slots = indexed
+ .into_iter()
+ .enumerate()
+ .map(|(i, slot)| slot.unwrap_or(Slot::Failed(SerializationFailure::panicked(uuids[i]))))
+ .collect();
+ // Every worker has been joined, so all worker Arc clones are dropped and
+ // this is the sole owner — recover the Vec to hand back to the caller.
+ let events = Arc::try_unwrap(events)
+ .unwrap_or_else(|_| unreachable!("serialize workers outlived their join"));
+ (events, slots)
+ };
+
+ let mut prepared = Vec::with_capacity(n);
+ let mut failures: Vec<Box<dyn SinkResult>> = Vec::new();
+ let mut failed_count = 0u64;
+ let mut panic_count = 0u64;
+ for slot in slots {
+ match slot {
+ Slot::Prepared(p) => prepared.push(p),
+ Slot::Skipped => {}
+ Slot::Failed(f) => {
+ if f.is_panic() {
+ crate::ctx_log!(Level::ERROR, ctx,
+ event_uuid = %f.uuid(),
+ "event serialization panicked, dropping event"
+ );
+ panic_count += 1;
+ } else {
+ crate::ctx_log!(Level::ERROR, ctx,
+ event_uuid = %f.uuid(),
+ error = %f.detail_str(),
+ "event serialization failed, dropping event"
+ );
+ failed_count += 1;
+ }
+ failures.push(Box::new(f));
+ }
+ }
+ }
+
+ histogram!(CAPTURE_V1_SERIALIZE_DURATION_SECONDS, "batch_size" => batch_size_bucket(n))
+ .record(start.elapsed().as_secs_f64());
+ if failed_count > 0 {
+ counter!(CAPTURE_V1_SERIALIZE_FAILED_TOTAL).increment(failed_count);
+ }
+ if panic_count > 0 {
+ counter!(CAPTURE_V1_SERIALIZE_PANIC_TOTAL).increment(panic_count);
+ }
+
+ (events, SerializedBatch { prepared, failures })
+}
+
+/// Low-cardinality batch-size bucket for the serialize-duration histogram.
+fn batch_size_bucket(n: usize) -> &'static str {
+ match n {
+ 0..=1 => "1",
+ 2..=8 => "2-8",
+ 9..=32 => "9-32",
+ 33..=128 => "33-128",
+ _ => "129+",
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use common_types::CapturedEventHeaders;
+ use rstest::rstest;
+
+ use super::*;
+ use crate::v1::sinks::types::{Destination, Outcome};
+ use crate::v1::test_utils::test_context;
+
+ 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,
+ skip_heatmap_processing: None,
+ dlq_reason: None,
+ dlq_timestamp: None,
+ dlq_step: None,
+ content_encoding: None,
+ }
+ }
+
+ enum Behavior {
+ Ok(Vec<u8>),
+ Err,
+ Panic,
+ }
+
+ struct FakeEvent {
+ uuid: Uuid,
+ publish: bool,
+ destination: Destination,
+ partition_key: String,
+ behavior: Behavior,
+ }
+
+ impl FakeEvent {
+ fn ok(payload: &str, key: &str) -> Self {
+ Self {
+ uuid: Uuid::new_v4(),
+ publish: true,
+ destination: Destination::AnalyticsMain,
+ partition_key: key.to_string(),
+ behavior: Behavior::Ok(payload.as_bytes().to_vec()),
+ }
+ }
+
+ fn with_behavior(mut self, behavior: Behavior) -> Self {
+ self.behavior = behavior;
+ self
+ }
+
+ fn not_publishable(mut self) -> Self {
+ self.publish = false;
+ self
+ }
+ }
+
+ impl Event for FakeEvent {
+ fn uuid(&self) -> Uuid {
+ self.uuid
+ }
+
+ fn should_publish(&self) -> bool {
+ self.publish
+ }
+
+ fn destination(&self) -> &Destination {
+ &self.destination
+ }
+
+ fn headers(&self, _ctx: &RequestContext) -> CapturedEventHeaders {
+ empty_captured_headers()
+ }
+
+ fn partition_key(&self, _ctx: &RequestContext) -> String {
+ self.partition_key.clone()
+ }
+
+ fn serialize(&self, _ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {
+ match &self.behavior {
+ Behavior::Ok(bytes) => Ok(bytes::Bytes::from(bytes.clone())),
+ Behavior::Err => Err(anyhow::anyhow!("boom")),
+ Behavior::Panic => panic!("serialize panic"),
+ }
+ }
+ }
+
+ /// Build `n` happy-path events whose payloads encode their input index, so
+ /// ordering can be asserted regardless of the seq vs parallel path taken.
+ fn ordered_events(n: usize) -> Vec<FakeEvent> {
+ (0..n)
+ .map(|i| FakeEvent::ok(&format!("payload-{i}"), &format!("key-{i}")))
+ .collect()
+ }
+
+ /// Parity + ordering across the sequential (<8) and parallel (>=8) paths:
+ /// every prepared event must come back in input order with its own payload.
+ #[rstest]
+ #[case::sequential_small(1)]
+ #[case::sequential_boundary(7)]
+ #[case::parallel_boundary(8)]
+ #[case::parallel_large(64)]
+ #[tokio::test]
+ async fn preserves_order_and_payloads(#[case] n: usize) {
+ let ctx = test_context();
+ let (events, out) =
+ serialize_batch(ordered_events(n), &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;
+
+ assert_eq!(events.len(), n, "events must be handed back intact");
+ assert_eq!(out.prepared.len(), n);
+ assert!(out.failures.is_empty());
+ for (i, prepared) in out.prepared.iter().enumerate() {
+ assert_eq!(prepared.payload.as_ref(), format!("payload-{i}").as_bytes());
+ assert_eq!(prepared.partition_key, format!("key-{i}"));
+ assert_eq!(prepared.destination, Destination::AnalyticsMain);
+ }
+ }
+
+ #[rstest]
+ #[case::sequential(3)]
+ #[case::parallel(16)]
+ #[tokio::test]
+ async fn skips_non_publishable_without_failure(#[case] n: usize) {
+ let ctx = test_context();
+ let mut events = ordered_events(n);
+ events[1] = FakeEvent::ok("ignored", "key-1").not_publishable();
+
+ let (returned, out) = serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;
+
+ assert_eq!(returned.len(), n, "all events handed back intact");
+ assert_eq!(out.prepared.len(), n - 1);
+ assert!(out.failures.is_empty());
+ // Payloads preserve input order, skipping index 1.
+ let mut expected_idx = 0;
+ for prepared in &out.prepared {
+ if expected_idx == 1 {
+ expected_idx += 1;
+ }
+ assert_eq!(
+ prepared.payload.as_ref(),
+ format!("payload-{expected_idx}").as_bytes()
+ );
+ expected_idx += 1;
+ }
+ }
+
+ /// A serialize error is isolated: the good events still come through and the
+ /// failure surfaces as a fatal, non-retriable `SinkResult`.
+ #[rstest]
+ #[case::sequential(3)]
+ #[case::parallel(16)]
+ #[tokio::test]
+ async fn serialize_error_isolated(#[case] n: usize) {
+ let ctx = test_context();
+ let mut events = ordered_events(n);
+ let bad_uuid = events[1].uuid;
+ events[1] = FakeEvent::ok("ignored", "key-1").with_behavior(Behavior::Err);
+ events[1].uuid = bad_uuid;
+
+ let (events, out) = serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;
+
+ assert_eq!(events.len(), n);
+ assert_eq!(out.prepared.len(), n - 1);
+ assert_eq!(out.failures.len(), 1);
+ let failure = &out.failures[0];
+ assert_eq!(failure.key(), bad_uuid);
+ assert_eq!(failure.outcome(), Outcome::FatalError);
+ assert_eq!(failure.cause(), Some("serialization_failed"));
+ assert!(failure.elapsed().is_none());
+ }
+
+ /// A panicking `serialize` is caught: the rest of the batch is unaffected
+ /// and the panic is reported as its own failure cause.
+ #[rstest]
+ #[case::sequential(3)]
+ #[case::parallel(16)]
+ #[tokio::test]
+ async fn serialize_panic_isolated(#[case] n: usize) {
+ let ctx = test_context();
+ let mut events = ordered_events(n);
+ events[2] = FakeEvent::ok("ignored", "key-2").with_behavior(Behavior::Panic);
+
+ let (events, out) = serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;
+
+ assert_eq!(events.len(), n);
+ assert_eq!(out.prepared.len(), n - 1);
+ assert_eq!(out.failures.len(), 1);
+ assert_eq!(out.failures[0].cause(), Some("serialization_panic"));
+ assert_eq!(out.failures[0].outcome(), Outcome::FatalError);
+ }
+
+ /// Panic failures preserve the correct event UUID (not nil).
+ #[rstest]
+ #[case::sequential(3)]
+ #[case::parallel(16)]
+ #[tokio::test]
+ async fn panic_failure_preserves_uuid(#[case] n: usize) {
+ let ctx = test_context();
+ let mut events = ordered_events(n);
+ let panic_uuid = events[1].uuid;
+ events[1] = FakeEvent::ok("ignored", "key-1").with_behavior(Behavior::Panic);
+ events[1].uuid = panic_uuid;
+
+ let (_events, out) = serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;
+
+ assert_eq!(out.failures.len(), 1);
+ assert_eq!(out.failures[0].key(), panic_uuid);
+ assert_eq!(out.failures[0].cause(), Some("serialization_panic"));
+ }
+
+ #[tokio::test]
+ async fn empty_batch_is_empty() {
+ let ctx = test_context();
+ let (events, out) = serialize_batch(
+ Vec::<FakeEvent>::new(),
+ &ctx,
+ DEFAULT_SCATTER_GATHER_MIN_BATCH,
+ )
+ .await;
+ assert!(events.is_empty());
+ assert!(out.prepared.is_empty());
+ assert!(out.failures.is_empty());
+ }
+
+ #[tokio::test]
+ async fn threshold_zero_forces_sequential_for_large_batch() {
+ let ctx = test_context();
+ let (events, out) = serialize_batch(ordered_events(64), &ctx, 0).await;
+ assert_eq!(events.len(), 64);
+ assert_eq!(out.prepared.len(), 64);
+ assert!(out.failures.is_empty());
+ }
+
+ #[tokio::test]
+ async fn custom_threshold_boundary() {
+ let ctx = test_context();
+ let (_, below) = serialize_batch(ordered_events(63), &ctx, 64).await;
+ let (_, at) = serialize_batch(ordered_events(64), &ctx, 64).await;
+ assert_eq!(below.prepared.len(), 63);
+ assert_eq!(at.prepared.len(), 64);
+ }
+
+ #[test]
+ fn batch_size_bucket_boundaries() {
+ assert_eq!(batch_size_bucket(0), "1");
+ assert_eq!(batch_size_bucket(1), "1");
+ assert_eq!(batch_size_bucket(2), "2-8");
+ assert_eq!(batch_size_bucket(8), "2-8");
+ assert_eq!(batch_size_bucket(9), "9-32");
+ assert_eq!(batch_size_bucket(32), "9-32");
+ assert_eq!(batch_size_bucket(33), "33-128");
+ assert_eq!(batch_size_bucket(128), "33-128");
+ assert_eq!(batch_size_bucket(129), "129+");
+ }
+}
diff --git a/rust/capture/src/v1/sinks/router.rs b/rust/capture/src/v1/sinks/router.rs
index c7cf606d7de4..386d403582ce 100644
--- a/rust/capture/src/v1/sinks/router.rs
+++ b/rust/capture/src/v1/sinks/router.rs
@@ -4,10 +4,9 @@ use std::fmt;
use futures::stream::FuturesUnordered;
use futures::StreamExt;
-use crate::v1::context::Context;
-use crate::v1::sinks::event::Event;
+use crate::v1::context::RequestContext;
use crate::v1::sinks::sink::Sink;
-use crate::v1::sinks::types::SinkResult;
+use crate::v1::sinks::types::{PreparedEvent, SinkResult};
use crate::v1::sinks::SinkName;
// ---------------------------------------------------------------------------
@@ -57,12 +56,12 @@ impl Router {
self.sinks.keys().copied().collect()
}
- /// Publish a batch of events to the named sink.
+ /// Publish a batch of already-serialized events to the named sink.
pub async fn publish_batch(
&self,
sink: SinkName,
- ctx: &Context,
- events: &[&(dyn Event + Send + Sync)],
+ ctx: &RequestContext,
+ events: &[PreparedEvent],
) -> Result<Vec<Box<dyn SinkResult>>, RouterError> {
let target = self
.sinks
@@ -75,10 +74,12 @@ impl Router {
pub async fn publish(
&self,
sink: SinkName,
- ctx: &Context,
- event: &(dyn Event + Send + Sync),
+ ctx: &RequestContext,
+ event: &PreparedEvent,
) -> Result<Option<Box<dyn SinkResult>>, RouterError> {
- let results = self.publish_batch(sink, ctx, &[event]).await?;
+ let results = self
+ .publish_batch(sink, ctx, std::slice::from_ref(event))
+ .await?;
Ok(results.into_iter().next())
}
@@ -117,7 +118,7 @@ mod tests {
use uuid::Uuid;
use crate::config::CaptureMode;
- use crate::v1::context::Context;
+ use crate::v1::context::RequestContext;
use crate::v1::sinks::event::Event;
use crate::v1::sinks::kafka::mock::MockProducer;
use crate::v1::sinks::kafka::sink::KafkaSink;
@@ -129,6 +130,8 @@ mod tests {
// -- Test helpers --------------------------------------------------------
+ use crate::v1::test_utils::prepared;
+
struct FakeEvent {
parsed_uuid: Uuid,
publish: bool,
@@ -143,11 +146,6 @@ mod tests {
destination: Destination::AnalyticsMain,
}
}
-
- fn with_publish(mut self, p: bool) -> Self {
- self.publish = p;
- self
- }
}
impl Event for FakeEvent {
@@ -161,7 +159,7 @@ mod tests {
fn destination(&self) -> &Destination {
&self.destination
}
- fn headers(&self, _ctx: &Context) -> CapturedEventHeaders {
+ fn headers(&self, _ctx: &RequestContext) -> CapturedEventHeaders {
CapturedEventHeaders {
token: None,
distinct_id: None,
@@ -179,11 +177,11 @@ mod tests {
content_encoding: None,
}
}
- fn partition_key(&self, _ctx: &Context) -> String {
+ fn partition_key(&self, _ctx: &RequestContext) -> String {
format!("key:{}", self.uuid())
}
- fn serialize(&self, _ctx: &Context) -> anyhow::Result<String> {
- Ok(r#"{"event":"test"}"#.to_string())
+ fn serialize(&self, _ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {
+ Ok(bytes::Bytes::from(r#"{"event":"test"}"#.to_string()))
}
}
@@ -222,7 +220,7 @@ mod tests {
(router, handle, monitor)
}
- fn test_ctx() -> Context {
+ fn test_ctx() -> RequestContext {
let mut ctx = crate::v1::test_utils::test_context();
ctx.created_at = None;
ctx
@@ -251,7 +249,7 @@ mod tests {
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 events = prepared(&[&event], &ctx);
let results = router
.publish_batch(SinkName::Msk, &ctx, &events)
@@ -266,7 +264,7 @@ mod tests {
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];
+ let events = prepared(&[&event], &ctx);
match router.publish_batch(SinkName::Ws, &ctx, &events).await {
Err(RouterError::SinkNotFound(SinkName::Ws)) => {}
@@ -280,29 +278,24 @@ mod tests {
let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);
let ctx = test_ctx();
let event = FakeEvent::ok("evt-1");
+ let prepared = prepared(&[&event], &ctx);
- let result = router.publish(SinkName::Msk, &ctx, &event).await.unwrap();
+ let result = router
+ .publish(SinkName::Msk, &ctx, &prepared[0])
+ .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");
+ let prepared = prepared(&[&event], &ctx);
- match router.publish(SinkName::Ws, &ctx, &event).await {
+ match router.publish(SinkName::Ws, &ctx, &prepared[0]).await {
Err(RouterError::SinkNotFound(SinkName::Ws)) => {}
Err(e) => panic!("expected SinkNotFound(Ws), got: {e}"),
Ok(_) => panic!("expected error, got Ok"),
diff --git a/rust/capture/src/v1/sinks/sink.rs b/rust/capture/src/v1/sinks/sink.rs
index e6475372df97..7ec6dd5c8c2b 100644
--- a/rust/capture/src/v1/sinks/sink.rs
+++ b/rust/capture/src/v1/sinks/sink.rs
@@ -1,8 +1,7 @@
use async_trait::async_trait;
-use crate::v1::context::Context;
-use crate::v1::sinks::event::Event;
-use crate::v1::sinks::types::SinkResult;
+use crate::v1::context::RequestContext;
+use crate::v1::sinks::types::{PreparedEvent, SinkResult};
use crate::v1::sinks::SinkName;
/// Backend-agnostic publishing interface for a single sink target.
@@ -11,12 +10,13 @@ pub trait Sink: Send + Sync {
/// Identity of this sink (used for metrics and logging).
fn name(&self) -> SinkName;
- /// Publish a batch of events. Returns one result per published event --
- /// skipped events (should_publish false / Destination::Drop) produce no result.
+ /// Publish a batch of already-serialized events. Returns one result per
+ /// event the sink attempted; events the sink itself drops (e.g. a
+ /// destination with no configured topic) produce no result.
async fn publish_batch(
&self,
- ctx: &Context,
- events: &[&(dyn Event + Send + Sync)],
+ ctx: &RequestContext,
+ events: &[PreparedEvent],
) -> Vec<Box<dyn SinkResult>>;
/// Flush the underlying producer for graceful shutdown.
diff --git a/rust/capture/src/v1/sinks/types.rs b/rust/capture/src/v1/sinks/types.rs
index 3a34a5e20401..33216b418206 100644
--- a/rust/capture/src/v1/sinks/types.rs
+++ b/rust/capture/src/v1/sinks/types.rs
@@ -2,6 +2,7 @@ use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
+use common_types::CapturedEventHeaders;
use uuid::Uuid;
/// Kafka topic routing for a processed event.
@@ -154,6 +155,91 @@ pub trait SinkResult: Send + Sync {
fn elapsed(&self) -> Option<std::time::Duration>;
}
+// ---------------------------------------------------------------------------
+// PreparedEvent
+// ---------------------------------------------------------------------------
+
+/// Storage-agnostic, fully-owned output of the serialize step. Produced by
+/// [`serialize_batch`](super::prepare::serialize_batch) and consumed by any
+/// [`Sink`](super::sink::Sink). Owns its payload (`Bytes`) so it can be cloned
+/// across multiple sinks (dual-write) without re-encoding and moved into
+/// spawned tasks. The Sink resolves `destination` to a concrete backend target
+/// and applies its own routing policy (e.g. nulling `partition_key`).
+#[derive(Debug, Clone)]
+pub struct PreparedEvent {
+ pub uuid: Uuid,
+ pub destination: Destination,
+ pub payload: bytes::Bytes,
+ pub headers: CapturedEventHeaders,
+ /// Raw key; the Sink decides whether to use or null it per routing policy.
+ pub partition_key: String,
+}
+
+// ---------------------------------------------------------------------------
+// SerializationFailure
+// ---------------------------------------------------------------------------
+
+/// `SinkResult` for an event that failed during the serialize step (before any
+/// sink saw it). Always fatal (non-retriable) and has no ack latency.
+#[derive(Debug, Clone)]
+pub struct SerializationFailure {
+ uuid: Uuid,
+ cause: &'static str,
+ detail: String,
+}
+
+impl SerializationFailure {
+ pub fn from_error(uuid: Uuid, detail: String) -> Self {
+ Self {
+ uuid,
+ cause: "serialization_failed",
+ detail,
+ }
+ }
+
+ pub fn panicked(uuid: Uuid) -> Self {
+ Self {
+ uuid,
+ cause: "serialization_panic",
+ detail: "serialization task panicked".to_string(),
+ }
+ }
+
+ pub fn is_panic(&self) -> bool {
+ self.cause == "serialization_panic"
+ }
+
+ pub fn uuid(&self) -> Uuid {
+ self.uuid
+ }
+
+ pub fn detail_str(&self) -> &str {
+ &self.detail
+ }
+}
+
+impl SinkResult for SerializationFailure {
+ fn key(&self) -> Uuid {
+ self.uuid
+ }
+
+ fn outcome(&self) -> Outcome {
+ Outcome::FatalError
+ }
+
+ fn cause(&self) -> Option<&'static str> {
+ Some(self.cause)
+ }
+
+ fn detail(&self) -> Option<Cow<'_, str>> {
+ Some(Cow::Borrowed(&self.detail))
+ }
+
+ fn elapsed(&self) -> Option<std::time::Duration> {
+ None
+ }
+}
+
// ---------------------------------------------------------------------------
// BatchSummary
// ---------------------------------------------------------------------------
diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rs
index 59a88f85b7b0..a9698901cf25 100644
--- a/rust/capture/src/v1/test_utils.rs
+++ b/rust/capture/src/v1/test_utils.rs
@@ -8,11 +8,30 @@ use serde_json::value::RawValue;
use uuid::Uuid;
use crate::v1::analytics::constants::CAPTURE_V1_PATH;
+use crate::v1::analytics::context::Context as AnalyticsContext;
use crate::v1::analytics::query::Query;
use crate::v1::analytics::types::{Event, EventResult, Options, WrappedEvent};
-use crate::v1::context::Context;
+use crate::v1::context::RequestContext;
+use crate::v1::sinks::event::Event as SinkEvent;
+use crate::v1::sinks::types::PreparedEvent;
use crate::v1::sinks::Destination;
+/// Serialize publishable events into `PreparedEvent`s for driving sinks in tests.
+/// Accepts `&[&dyn Event]` (integration) or `&[&ConcreteType]` (unit) via `?Sized`.
+pub fn prepared<E: SinkEvent + ?Sized>(events: &[&E], ctx: &RequestContext) -> Vec<PreparedEvent> {
+ events
+ .iter()
+ .filter(|e| e.should_publish())
+ .map(|e| PreparedEvent {
+ uuid: e.uuid(),
+ destination: e.destination().clone(),
+ payload: e.serialize(ctx).expect("test payload must serialize"),
+ headers: e.headers(ctx),
+ partition_key: e.partition_key(ctx),
+ })
+ .collect()
+}
+
pub fn raw_obj(s: &str) -> Box<RawValue> {
RawValue::from_string(s.to_owned()).unwrap()
}
@@ -26,8 +45,8 @@ pub fn default_options() -> Options {
}
}
-pub fn test_context() -> Context {
- Context {
+pub fn test_context() -> RequestContext {
+ RequestContext {
api_token: "phc_test_token".to_string(),
user_agent: "test-agent/1.0".to_string(),
content_type: "application/json".to_string(),
@@ -37,7 +56,7 @@ pub fn test_context() -> Context {
request_id: Uuid::new_v4(),
client_timestamp: Utc::now(),
client_ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
- query: Query::default(),
+ raw_query: None,
method: Method::POST,
path: CAPTURE_V1_PATH,
server_received_at: Utc::now(),
@@ -47,6 +66,15 @@ pub fn test_context() -> Context {
}
}
+/// Analytics-mode context wrapping [`test_context`] for tests that drive
+/// `process_batch` (which takes `&mut analytics::Context`).
+pub fn test_analytics_context() -> AnalyticsContext {
+ AnalyticsContext {
+ req: test_context(),
+ query: Query::default(),
+ }
+}
+
pub fn valid_event() -> Event {
Event {
event: "$pageview".to_string(),
@@ -386,13 +414,13 @@ impl WrappedEventMut for WrappedEvent {
/// and its inner data field round-trips through RawEvent.
pub fn assert_round_trip(
wrapped: &WrappedEvent,
- ctx: &Context,
+ ctx: &RequestContext,
) -> (common_types::CapturedEvent, common_types::RawEvent) {
use crate::v1::sinks::event::Event as SinkEvent;
let buf = wrapped.serialize(ctx).expect("serialize failed");
let captured: common_types::CapturedEvent =
- serde_json::from_str(&buf).expect("v1 output must deserialize as CapturedEvent");
+ serde_json::from_slice(&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");
@@ -799,6 +827,7 @@ impl TestStateBuilder {
overflow_limiter,
replay_overflow_limiter: None,
v1_sink_router: Some(Arc::new(v1_router)),
+ capture_v1_scatter_gather_min_batch: 8,
};
TestState {
diff --git a/rust/capture/src/v1/util.rs b/rust/capture/src/v1/util.rs
index d5fd5b06f248..d9591b31a637 100644
--- a/rust/capture/src/v1/util.rs
+++ b/rust/capture/src/v1/util.rs
@@ -215,7 +215,7 @@ mod tests {
#[test]
fn encoding_tag_covers_supported_encodings_and_identity() {
// Keep in lockstep with SUPPORTED_ENCODINGS.
- for enc in crate::v1::analytics::constants::SUPPORTED_ENCODINGS {
+ for enc in crate::v1::constants::SUPPORTED_ENCODINGS {
assert_eq!(
encoding_tag(Some(enc)),
*enc,
diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rs
index 4a5a1b8ea219..3b2493cc2041 100644
--- a/rust/capture/tests/common/integration_utils.rs
+++ b/rust/capture/tests/common/integration_utils.rs
@@ -1109,6 +1109,7 @@ fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
),
sink,
)
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index 1d341b348bcc..3f8d2133b2cd 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -161,6 +161,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
capture_v1_sinks: String::new(),
capture_v1_max_compressed_body_bytes: 10 * 1024 * 1024,
capture_v1_max_decompressed_body_bytes: 50 * 1024 * 1024,
+ capture_v1_scatter_gather_min_batch: 8,
});
/// Build the per-sink env snapshot the v1 sink loader expects, with every
diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rs
index db2bea9861b5..7d2cc31aaf8a 100644
--- a/rust/capture/tests/integration_ai_endpoint.rs
+++ b/rust/capture/tests/integration_ai_endpoint.rs
@@ -195,6 +195,7 @@ fn setup_ai_test_router() -> Router {
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
)
}
@@ -1656,6 +1657,7 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
@@ -2569,6 +2571,7 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Rout
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
@@ -2777,6 +2780,7 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturin
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
@@ -2930,6 +2934,7 @@ fn setup_ai_test_router_with_overflow_limiter(
Some(overflow_limiter), // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rs
index af70dbf638f6..5a3d2ae9d038 100644
--- a/rust/capture/tests/integration_ai_restrictions.rs
+++ b/rust/capture/tests/integration_ai_restrictions.rs
@@ -193,6 +193,7 @@ async fn setup_ai_router_with_restriction(
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
@@ -510,6 +511,7 @@ async fn setup_ai_router_with_redirect_to_topic(
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
@@ -584,6 +586,7 @@ async fn setup_ai_router_with_force_overflow_and_limiter(
Some(overflow_limiter), // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rs
index 640ca0f3f315..2d6bda4c2db9 100644
--- a/rust/capture/tests/integration_analytics_restrictions.rs
+++ b/rust/capture/tests/integration_analytics_restrictions.rs
@@ -127,6 +127,7 @@ async fn setup_analytics_router_with_restriction(
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
@@ -469,6 +470,7 @@ async fn setup_analytics_router_with_redirect_to_topic(
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rs
index b3f822c3e8d4..6eda5307011b 100644
--- a/rust/capture/tests/integration_otel_endpoint.rs
+++ b/rust/capture/tests/integration_otel_endpoint.rs
@@ -185,6 +185,7 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOption
options.overflow_limiter, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
TestClient::new(app)
diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rs
index 0c958401398a..ab66d253c67e 100644
--- a/rust/capture/tests/integration_replay_restrictions.rs
+++ b/rust/capture/tests/integration_replay_restrictions.rs
@@ -129,6 +129,7 @@ async fn setup_recordings_router_with_restriction(
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
@@ -497,6 +498,7 @@ async fn setup_recordings_router_with_redirect_to_topic(
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(router, sink_clone)
diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rs
index 55e76c7e8f44..925a2e3c4358 100644
--- a/rust/capture/tests/quota_limiters.rs
+++ b/rust/capture/tests/quota_limiters.rs
@@ -151,6 +151,7 @@ async fn setup_router_with_limits(
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
(app, sink)
@@ -1201,6 +1202,7 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
let client = TestClient::new(app);
@@ -1289,6 +1291,7 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
let client = TestClient::new(app);
@@ -1381,6 +1384,7 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
let client = TestClient::new(app);
@@ -1810,6 +1814,7 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {
None, // overflow_limiter
None, // replay_overflow_limiter
None, // v1_sink_router
+ 8, // capture_v1_scatter_gather_min_batch
);
let client = TestClient::new(app);
diff --git a/rust/capture/tests/v1_pipeline.rs b/rust/capture/tests/v1_pipeline.rs
index 68f58124baed..2c585dc687c9 100644
--- a/rust/capture/tests/v1_pipeline.rs
+++ b/rust/capture/tests/v1_pipeline.rs
@@ -32,7 +32,7 @@ async fn run_batch_with_state(
) -> (Result<BatchResponse, Error>, test_utils::TestState) {
let batch: Batch = serde_json::from_slice(payload).expect("payload must parse as Batch");
let ts = builder.build();
- let mut ctx = test_utils::test_context();
+ let mut ctx = test_utils::test_analytics_context();
let result = process_batch(&ts.state, &mut ctx, batch).await;
(result, ts)
}
@@ -138,7 +138,7 @@ async fn all_events_quota_dropped() {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
loop {
let batch: Batch = serde_json::from_slice(&payload).expect("payload must parse as Batch");
- let mut ctx = test_utils::test_context();
+ let mut ctx = test_utils::test_analytics_context();
ctx.api_token = "*".to_string();
let result = process_batch(&ts.state, &mut ctx, batch).await;
if result.is_err() {
@@ -226,7 +226,7 @@ async fn compression_round_trip(#[case] encoding: Option<&str>) {
};
let ts = TestStateBuilder::new().build();
- let mut ctx = test_utils::test_context();
+ let mut ctx = test_utils::test_analytics_context();
if encoding.is_some() {
ctx.content_encoding = encoding.map(String::from);
}
diff --git a/rust/capture/tests/v1_sink_integration.rs b/rust/capture/tests/v1_sink_integration.rs
index 4c5209e425c7..0e0747aaf1fb 100644
--- a/rust/capture/tests/v1_sink_integration.rs
+++ b/rust/capture/tests/v1_sink_integration.rs
@@ -19,14 +19,14 @@ use anyhow::Result;
use common_types::{CapturedEvent, RawEvent};
use capture::config::CaptureMode;
-use capture::v1::context::Context;
+use capture::v1::context::RequestContext;
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};
+use capture::v1::test_utils::{self, prepared, WrappedEventMut};
fn v1_kafka_config(topic: &str) -> capture::v1::sinks::kafka::config::Config {
let env: std::collections::HashMap<String, String> = [
@@ -49,7 +49,7 @@ fn v1_kafka_config(topic: &str) -> capture::v1::sinks::kafka::config::Config {
envconfig::Envconfig::init_from_hashmap(&env).unwrap()
}
-fn v1_test_context() -> Context {
+fn v1_test_context() -> RequestContext {
let mut ctx = test_utils::test_context();
ctx.api_token = "phc_integration_test_token".to_string();
ctx
@@ -103,7 +103,7 @@ async fn v1_single_pageview_round_trip() -> Result<()> {
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;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert_eq!(results.len(), 1);
assert_eq!(results[0].key(), wrapped.uuid);
@@ -144,7 +144,7 @@ async fn v1_batch_round_trip() -> Result<()> {
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;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert_eq!(results.len(), 3);
for r in &results {
@@ -185,7 +185,7 @@ async fn v1_kafka_headers_round_trip() -> Result<()> {
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;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert_eq!(results[0].outcome(), Outcome::Success);
let (_event_json, headers) = topic.next_message_with_headers()?;
@@ -219,7 +219,7 @@ async fn v1_partition_key_round_trip() -> Result<()> {
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;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert_eq!(results[0].outcome(), Outcome::Success);
let key = topic.next_message_key()?;
@@ -248,7 +248,7 @@ async fn v1_dropped_event_not_published() -> Result<()> {
);
let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
- let results = sink.publish_batch(&ctx, &events).await;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert!(results.is_empty());
topic.assert_empty();
@@ -274,7 +274,7 @@ async fn v1_exception_event_round_trip() -> Result<()> {
wrapped.destination = capture::v1::sinks::Destination::ExceptionErrorTracking;
let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
- let results = sink.publish_batch(&ctx, &events).await;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert_eq!(results.len(), 1);
assert_eq!(results[0].outcome(), Outcome::Success);
@@ -307,7 +307,7 @@ async fn v1_cookieless_mode_partition_key() -> Result<()> {
wrapped.event.options.cookieless_mode = Some(true);
let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
- let results = sink.publish_batch(&ctx, &events).await;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert_eq!(results[0].outcome(), Outcome::Success);
let key = topic.next_message_key()?;
@@ -345,7 +345,7 @@ async fn v1_all_options_property_injection() -> Result<()> {
wrapped.event.window_id = Some("win-opt-test".to_string());
let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
- let results = sink.publish_batch(&ctx, &events).await;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert_eq!(results[0].outcome(), Outcome::Success);
let event_json = topic.next_event()?;
@@ -388,7 +388,7 @@ async fn v1_empty_options_no_injection() -> Result<()> {
wrapped.event.window_id = None;
let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];
- let results = sink.publish_batch(&ctx, &events).await;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert_eq!(results[0].outcome(), Outcome::Success);
let event_json = topic.next_event()?;
@@ -424,7 +424,7 @@ async fn v1_multi_destination_batch() -> Result<()> {
.with_destination(capture::v1::sinks::Destination::Overflow);
let events: Vec<&(dyn Event + Send + Sync)> = vec![&main_ev, &hist_ev, &overflow_ev];
- let results = sink.publish_batch(&ctx, &events).await;
+ let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;
assert_eq!(results.len(), 3);
for r in &results {
assert_eq!(r.outcome(), Outcome::Success);