Skip to content

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

feat(capture): integrate v1 router in critical path (#61029)

Eli Reismancfd269fbe4e0
diff --git a/rust/capture/src/main.rs b/rust/capture/src/main.rs
index a7c79eec9e58..1a3ae4be7bf9 100644
--- a/rust/capture/src/main.rs
+++ b/rust/capture/src/main.rs
@@ -130,7 +130,7 @@ async fn main() {
.expect("could not bind port");
tracing::info!("listening on {:?}", listener.local_addr().unwrap());
- let components = setup::build_components(config, handles).await;
+ let components = setup::build_components(config, std::env::vars().collect(), handles).await;
serve(listener, components).await;
diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rs
index 6ec31f4a7ddb..0f6e3089858d 100644
--- a/rust/capture/src/router.rs
+++ b/rust/capture/src/router.rs
@@ -336,12 +336,25 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +
.layer(DefaultBodyLimit::max(otel::OTEL_BODY_SIZE));
let mut router = match capture_mode {
- CaptureMode::Events | CaptureMode::Ai => Router::new()
- .merge(batch_router)
- .merge(event_router)
- .merge(test_router)
- .merge(ai_router)
- .merge(otel_router),
+ CaptureMode::Events | CaptureMode::Ai => {
+ let mut events_router = Router::new()
+ .merge(batch_router)
+ .merge(event_router)
+ .merge(test_router)
+ .merge(ai_router)
+ .merge(otel_router);
+ // The v1 analytics endpoint is only routable when a v1 sink is
+ // configured. Without a sink the handler can't publish, so we keep
+ // the path unregistered (404) rather than advertising an endpoint
+ // that can only ever return 503. This also isolates the route to
+ // deployments that opt in via CAPTURE_V1_SINKS.
+ if state.v1_sink_router.is_some() {
+ events_router = events_router.merge(crate::v1::analytics::router::router().layer(
+ DefaultBodyLimit::max(state.capture_v1_max_compressed_body_bytes),
+ ));
+ }
+ events_router
+ }
CaptureMode::Recordings => Router::new().merge(recordings_router),
};
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index e185549ba961..9456aa22eb2c 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -109,7 +109,11 @@ pub struct CaptureComponents {
pub http1_header_read_timeout_ms: Option<u64>,
}
-pub async fn build_components(config: Config, handles: LifecycleHandles) -> CaptureComponents {
+pub async fn build_components(
+ config: Config,
+ sink_env: HashMap<String, String>,
+ handles: LifecycleHandles,
+) -> CaptureComponents {
let LifecycleHandles {
server,
sink: sink_handle,
@@ -287,7 +291,7 @@ pub async fn build_components(config: Config, handles: LifecycleHandles) -> Capt
let v1_sink_router = if !config.capture_v1_sinks.is_empty() {
Some(
- create_v1_sink_router(&config, v1_sink_handles)
+ create_v1_sink_router(&config, &sink_env, v1_sink_handles)
.unwrap_or_else(|e| panic!("fatal: v1 sink router creation failed: {e:#}")),
)
} else {
@@ -341,9 +345,10 @@ pub async fn build_components(config: Config, handles: LifecycleHandles) -> Capt
fn create_v1_sink_router(
config: &Config,
+ sink_env: &HashMap<String, String>,
handles: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle>,
) -> anyhow::Result<Arc<crate::v1::sinks::Router>> {
- let sinks_cfg = crate::v1::sinks::load_sinks(&config.capture_v1_sinks)
+ let sinks_cfg = crate::v1::sinks::load_sinks_from(&config.capture_v1_sinks, sink_env)
.context("failed to parse CAPTURE_V1_SINKS")?;
sinks_cfg
.validate()
@@ -538,7 +543,7 @@ mod tests {
})
.collect();
- let err = create_v1_sink_router(&config, handles)
+ let err = create_v1_sink_router(&config, &HashMap::new(), handles)
.err()
.expect("should fail with invalid config");
let msg = format!("{err:#}");
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index a336445035d6..ed6aeaaba45f 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -1,5 +1,6 @@
#![allow(dead_code)]
+use std::collections::HashMap;
use std::default::Default;
use std::net::SocketAddr;
use std::num::NonZeroU32;
@@ -162,6 +163,29 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
capture_v1_max_decompressed_body_bytes: 50 * 1024 * 1024,
});
+/// Build the per-sink env snapshot the v1 sink loader expects, with every
+/// topic pointing at a single (ephemeral) topic. Mirrors the env layout from
+/// `v1::sinks::load_sink_config`: keys are `CAPTURE_V1_SINK_<NAME>_KAFKA_*`.
+pub fn v1_sink_env_for_topic(sink: &str, topic: &str) -> HashMap<String, String> {
+ let prefix = format!("CAPTURE_V1_SINK_{}_", sink.to_uppercase());
+ [
+ ("KAFKA_HOSTS", DEFAULT_CONFIG.kafka.kafka_hosts.as_str()),
+ ("KAFKA_TOPIC_MAIN", topic),
+ ("KAFKA_TOPIC_HISTORICAL", topic),
+ ("KAFKA_TOPIC_OVERFLOW", topic),
+ ("KAFKA_TOPIC_DLQ", topic),
+ ("KAFKA_TOPIC_EXCEPTION", topic),
+ ("KAFKA_TOPIC_HEATMAP", topic),
+ ("KAFKA_TOPIC_CLIENT_INGESTION_WARNING", topic),
+ ("KAFKA_LINGER_MS", "0"),
+ ("KAFKA_COMPRESSION_CODEC", "none"),
+ ("KAFKA_MESSAGE_TIMEOUT_MS", "10000"),
+ ]
+ .into_iter()
+ .map(|(k, v)| (format!("{prefix}{k}"), v.to_string()))
+ .collect()
+}
+
static TRACING_INIT: Once = Once::new();
pub fn setup_tracing() {
TRACING_INIT.call_once(|| {
@@ -189,7 +213,27 @@ impl ServerHandle {
config.capture_mode = CaptureMode::Recordings;
Self::for_config(config).await
}
+
+ /// Boots a server with the v1 analytics pipeline enabled: a single `msk`
+ /// sink whose topics all point at `topic`, injected via a deterministic env
+ /// snapshot (no global `std::env` mutation, so parallel tests don't race on
+ /// distinct ephemeral topics). The v1 route is merged because
+ /// `v1_sink_router` ends up `Some`.
+ pub async fn for_v1_topic(topic: &EphemeralTopic) -> Self {
+ let mut config = DEFAULT_CONFIG.clone();
+ config.capture_v1_sinks = "msk".to_string();
+ let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());
+ Self::for_config_with_sink_env(config, sink_env).await
+ }
+
pub async fn for_config(config: Config) -> Self {
+ Self::for_config_with_sink_env(config, std::env::vars().collect()).await
+ }
+
+ pub async fn for_config_with_sink_env(
+ config: Config,
+ sink_env: HashMap<String, String>,
+ ) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
@@ -203,7 +247,7 @@ impl ServerHandle {
let handles = setup::register_components(&mut manager, &config);
let _monitor = manager.monitor_background();
- let components = setup::build_components(config, handles).await;
+ let components = setup::build_components(config, sink_env, handles).await;
tokio::spawn(async move { serve(listener, components).await });
@@ -237,6 +281,28 @@ impl ServerHandle {
.expect("failed to send request")
}
+ /// POST a v1 analytics batch to `/i/v1/analytics/events` with the full set
+ /// of headers `Context::new` requires (auth + the custom PostHog-* headers).
+ pub async fn capture_v1<T: Into<reqwest::Body>>(
+ &self,
+ token: &str,
+ body: T,
+ ) -> reqwest::Response {
+ self.client
+ .post(format!("http://{:?}/i/v1/analytics/events", self.addr))
+ .header("authorization", format!("Bearer {token}"))
+ .header("PostHog-Sdk-Info", "posthog-rust/1.0.0")
+ .header("PostHog-Attempt", "1")
+ .header("PostHog-Request-Id", uuid::Uuid::new_v4().to_string())
+ .header("PostHog-Request-Timestamp", "2026-03-19T14:30:00.000Z")
+ .header("content-type", "application/json")
+ .header("user-agent", "test-client/1.0")
+ .body(body)
+ .send()
+ .await
+ .expect("failed to send request")
+ }
+
pub async fn capture_recording<T: Into<reqwest::Body>>(
&self,
body: T,
diff --git a/rust/capture/tests/header_timeout.rs b/rust/capture/tests/header_timeout.rs
index 7fd7827fae10..b2cec31bc9ff 100644
--- a/rust/capture/tests/header_timeout.rs
+++ b/rust/capture/tests/header_timeout.rs
@@ -30,7 +30,7 @@ async fn start_server_with_header_timeout(
let handles = setup::register_components(&mut manager, &config);
let _monitor = manager.monitor_background();
- let components = setup::build_components(config, handles).await;
+ let components = setup::build_components(config, std::env::vars().collect(), handles).await;
tokio::spawn(async move { serve(listener, components).await });
diff --git a/rust/capture/tests/v1_http_integration.rs b/rust/capture/tests/v1_http_integration.rs
new file mode 100644
index 000000000000..5931c49b5224
--- /dev/null
+++ b/rust/capture/tests/v1_http_integration.rs
@@ -0,0 +1,146 @@
+//! HTTP-level integration tests for the v1 analytics pipeline.
+//!
+//! These tests verify the full server path:
+//! POST /i/v1/analytics/events -> router -> handler -> process_batch
+//! -> v1 sink router -> real Kafka -> consumer -> CapturedEvent
+//!
+//! Requires Docker Kafka (same rig as the other integration tests).
+//!
+//! Scope is deliberately narrow: route gating (404 when no sink is configured)
+//! and the HTTP->Kafka round trip for a single event and a small batch. Payload
+//! shape, header parity, partition keys, and destination routing are already
+//! covered at the sink layer by `v1_sink_integration.rs` — we don't re-test
+//! them here.
+
+#[path = "common/utils.rs"]
+mod utils;
+use utils::*;
+
+use anyhow::Result;
+use common_types::CapturedEvent;
+use uuid::Uuid;
+
+use capture::v1::analytics::types::Event;
+use capture::v1::test_utils::{batch_payload, valid_event};
+
+const TOKEN: &str = "phc_http_integration_token";
+
+/// A fresh `$pageview` event with a unique UUID and the given distinct_id.
+fn pageview(distinct_id: &str) -> Event {
+ let mut e = valid_event();
+ e.uuid = Uuid::new_v4().to_string();
+ e.distinct_id = distinct_id.to_string();
+ e
+}
+
+fn named(distinct_id: &str, name: &str) -> Event {
+ let mut e = pageview(distinct_id);
+ e.event = name.to_string();
+ e
+}
+
+async fn parse_body(res: reqwest::Response) -> serde_json::Value {
+ let bytes = res.bytes().await.expect("failed to read response body");
+ serde_json::from_slice(&bytes).expect("response body must be JSON")
+}
+
+// ---------------------------------------------------------------------------
+// Route gating: the v1 endpoint is unregistered (404) without a v1 sink
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn v1_route_unregistered_without_sink() {
+ setup_tracing();
+ // DEFAULT_CONFIG has capture_v1_sinks empty -> v1_sink_router is None ->
+ // the route is never merged, so the path 404s rather than 503s.
+ let server = ServerHandle::for_config(DEFAULT_CONFIG.clone()).await;
+
+ let payload = batch_payload(&[pageview("user-404")]);
+ let res = server.capture_v1(TOKEN, payload).await;
+
+ assert_eq!(
+ res.status(),
+ reqwest::StatusCode::NOT_FOUND,
+ "v1 route must not be registered when no v1 sink is configured"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Single event: HTTP -> real Kafka round trip
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn v1_http_single_event_to_kafka() -> Result<()> {
+ setup_tracing();
+ let topic = EphemeralTopic::new().await;
+ let server = ServerHandle::for_v1_topic(&topic).await;
+
+ let ev = pageview("http-user-1");
+ let uuid = ev.uuid.clone();
+ let payload = batch_payload(std::slice::from_ref(&ev));
+
+ let res = server.capture_v1(TOKEN, payload).await;
+ assert_eq!(res.status(), reqwest::StatusCode::OK);
+
+ let body = parse_body(res).await;
+ assert_eq!(
+ body["results"][uuid.as_str()]["result"],
+ "ok",
+ "event should be acked ok in the response body: {body}"
+ );
+
+ let captured: CapturedEvent = serde_json::from_value(topic.next_event()?)?;
+ assert_eq!(captured.uuid.to_string(), uuid);
+ assert_eq!(captured.distinct_id, "http-user-1");
+ assert_eq!(captured.event, "$pageview");
+ assert_eq!(captured.token, TOKEN);
+
+ topic.assert_empty();
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// Small batch: HTTP -> real Kafka round trip
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn v1_http_batch_to_kafka() -> Result<()> {
+ setup_tracing();
+ let topic = EphemeralTopic::new().await;
+ let server = ServerHandle::for_v1_topic(&topic).await;
+
+ let events = vec![
+ pageview("http-batch-0"),
+ named("http-batch-1", "$identify"),
+ named("http-batch-2", "button_clicked"),
+ ];
+ let uuids: Vec<String> = events.iter().map(|e| e.uuid.clone()).collect();
+ let payload = batch_payload(&events);
+
+ let res = server.capture_v1(TOKEN, payload).await;
+ assert_eq!(res.status(), reqwest::StatusCode::OK);
+
+ let body = parse_body(res).await;
+ for uuid in &uuids {
+ assert_eq!(
+ body["results"][uuid.as_str()]["result"],
+ "ok",
+ "every event should be acked ok: {body}"
+ );
+ }
+
+ let mut distinct_ids = Vec::new();
+ for _ in 0..events.len() {
+ let captured: CapturedEvent = serde_json::from_value(topic.next_event()?)?;
+ assert_eq!(captured.token, TOKEN);
+ distinct_ids.push(captured.distinct_id.clone());
+ }
+ distinct_ids.sort();
+ assert_eq!(
+ distinct_ids,
+ vec!["http-batch-0", "http-batch-1", "http-batch-2"]
+ );
+
+ topic.assert_empty();
+ Ok(())
+}
diff --git a/rust/capture/tests/v1_sink_integration.rs b/rust/capture/tests/v1_sink_integration.rs
index 2a87ee7497b3..4c5209e425c7 100644
--- a/rust/capture/tests/v1_sink_integration.rs
+++ b/rust/capture/tests/v1_sink_integration.rs
@@ -5,9 +5,8 @@
//!
//! Requires Docker Kafka (same rig as legacy integration tests).
//!
-//! TODO(v1): add HTTP-level integration tests (ServerHandle + POST /i/v1/analytics/events)
-//! and process_batch orchestration tests once the v1 HTTP router is merged into the
-//! main application and process_batch is fully implemented (currently a stub).
+//! HTTP-level round trips (POST /i/v1/analytics/events -> Kafka) live in
+//! `v1_http_integration.rs`; this file stays focused on the sink layer.
#[path = "common/utils.rs"]
mod utils;