:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(personhog): proxy identity and lifecycle calls through the router (#99527)
Zach Brown036e8210d7cd
diff --git a/rust/personhog-router/src/backend/replica.rs b/rust/personhog-router/src/backend/channel.rssimilarity index 53%rename from rust/personhog-router/src/backend/replica.rsrename to rust/personhog-router/src/backend/channel.rsindex be27ba870eec..d26582da3c96 100644--- a/rust/personhog-router/src/backend/replica.rs+++ b/rust/personhog-router/src/backend/channel.rs@@ -4,16 +4,21 @@ use std::time::Duration;use tonic::transport::{Channel, Endpoint};use tracing::info;+use crate::backend::discovery::DiscoveryReadiness;use crate::config::RetryConfig;-pub struct ReplicaBackend {+/// Channels to a backend whose pods are interchangeable (replica or+/// identity), handed out round-robin.+pub struct ChannelBackend {+ role: &'static str,channels: Vec<Channel>,next_idx: AtomicUsize,retry_config: RetryConfig,+ readiness: Option<DiscoveryReadiness>,}#[derive(Clone)]-pub struct ReplicaDnsConfig {+pub struct DnsBackendConfig {pub url: String,pub timeout: Duration,pub retry_config: RetryConfig,@@ -22,9 +27,9 @@ pub struct ReplicaDnsConfig {pub num_channels: usize,}-fn build_dns_endpoint(config: &ReplicaDnsConfig) -> Endpoint {+fn build_dns_endpoint(role: &str, config: &DnsBackendConfig) -> Endpoint {let mut endpoint = Channel::from_shared(config.url.clone())- .unwrap_or_else(|e| panic!("invalid replica URL '{}': {e}", config.url))+ .unwrap_or_else(|e| panic!("invalid {role} URL '{}': {e}", config.url)).timeout(config.timeout).tcp_nodelay(true);if let Some(interval) = config.keepalive_interval {@@ -38,42 +43,56 @@ fn build_dns_endpoint(config: &ReplicaDnsConfig) -> Endpoint {endpoint}-impl ReplicaBackend {+impl ChannelBackend {/// DNS discovery: opens multiple lazy channels to the ClusterIP service URL/// with round-robin selection across them.- pub fn new_dns(config: ReplicaDnsConfig) -> Self {+ pub fn new_dns(role: &'static str, config: DnsBackendConfig) -> Self {let num = config.num_channels.max(1);let channels: Vec<Channel> = (0..num)- .map(|_| build_dns_endpoint(&config).connect_lazy())+ .map(|_| build_dns_endpoint(role, &config).connect_lazy()).collect();info!(+ role,url = config.url,num_channels = num,mode = "dns",- "created replica backend"+ "created channel backend");Self {+ role,channels,next_idx: AtomicUsize::new(0),retry_config: config.retry_config,+ readiness: None,}}/// K8s discovery: single balanced channel fed by an EndpointDiscovery task/// that watches EndpointSlices. Tower's p2c balancer handles per-request/// load distribution, so a single channel is sufficient.- pub fn new_k8s(channel: Channel, retry_config: RetryConfig) -> Self {- info!(mode = "k8s", "created replica backend");+ pub fn new_k8s(+ role: &'static str,+ channel: Channel,+ retry_config: RetryConfig,+ readiness: DiscoveryReadiness,+ ) -> Self {+ info!(role, mode = "k8s", "created channel backend");Self {+ role,channels: vec![channel],next_idx: AtomicUsize::new(0),retry_config,+ readiness: Some(readiness),}}+ pub fn role(&self) -> &'static str {+ self.role+ }+pub fn channel(&self) -> Channel {let idx = self.next_idx.fetch_add(1, Ordering::Relaxed) % self.channels.len();self.channels[idx].clone()@@ -82,25 +101,36 @@ impl ReplicaBackend {pub fn retry_config(&self) -> &RetryConfig {&self.retry_config}++ /// False only while EndpointSlice discovery has no member to dial; a DNS+ /// pool resolves on connect and always reports true.+ pub fn has_endpoints(&self) -> bool {+ self.readiness+ .as_ref()+ .is_none_or(DiscoveryReadiness::is_ready)+ }}#[cfg(test)]mod tests {use super::*;- fn make_backend() -> ReplicaBackend {- ReplicaBackend::new_dns(ReplicaDnsConfig {- url: "http://localhost:50051".to_string(),- timeout: Duration::from_secs(1),- retry_config: RetryConfig {- max_retries: 0,- initial_backoff_ms: 1,- max_backoff_ms: 1,+ fn make_backend() -> ChannelBackend {+ ChannelBackend::new_dns(+ "replica",+ DnsBackendConfig {+ url: "http://localhost:50051".to_string(),+ timeout: Duration::from_secs(1),+ retry_config: RetryConfig {+ max_retries: 0,+ initial_backoff_ms: 1,+ max_backoff_ms: 1,+ },+ keepalive_interval: None,+ keepalive_timeout: None,+ num_channels: 4,},- keepalive_interval: None,- keepalive_timeout: None,- num_channels: 4,- })+ )}#[tokio::test]@@ -109,4 +139,9 @@ mod tests {let _ch1 = backend.channel();let _ch2 = backend.channel();}++ #[tokio::test]+ async fn dns_backend_always_has_endpoints() {+ assert!(make_backend().has_endpoints());+ }}diff --git a/rust/personhog-router/src/backend/mod.rs b/rust/personhog-router/src/backend/mod.rsindex 2224219774fd..8db3a9322077 100644--- a/rust/personhog-router/src/backend/mod.rs+++ b/rust/personhog-router/src/backend/mod.rs@@ -1,12 +1,12 @@+mod channel;pub mod discovery;mod leader;-mod replica;mod stash;+pub use channel::{ChannelBackend, DnsBackendConfig};pub(crate) use leader::counts_as_possibly_applied;pub use leader::{AddressResolver, BounceReason, ForwardDecision, ForwardPath, LeaderBackend, LeaderBackendConfig,};pub(crate) use leader::{BOUNCE_BACKOFF, MAX_CONSECUTIVE_BOUNCES};-pub use replica::{ReplicaBackend, ReplicaDnsConfig};pub use stash::{DrainSession, StashDecision, StashKey, StashTable, StashedRequest, TakenKeyRun};diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rsindex 34a8a0d527df..634e87675051 100644--- a/rust/personhog-router/src/config.rs+++ b/rust/personhog-router/src/config.rs@@ -8,31 +8,31 @@ use std::net::SocketAddr;use std::time::Duration;#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum ReplicaDiscoveryMode {+pub enum DiscoveryMode {/// DNS mode: static channels to ClusterIP URL.Dns,/// K8s mode: EndpointSlice watcher with client-side p2c balancing.K8s,}-impl fmt::Display for ReplicaDiscoveryMode {+impl fmt::Display for DiscoveryMode {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {match self {- ReplicaDiscoveryMode::Dns => write!(f, "dns"),- ReplicaDiscoveryMode::K8s => write!(f, "k8s"),+ DiscoveryMode::Dns => write!(f, "dns"),+ DiscoveryMode::K8s => write!(f, "k8s"),}}}-impl FromStr for ReplicaDiscoveryMode {+impl FromStr for DiscoveryMode {type Err = String;fn from_str(s: &str) -> Result<Self, Self::Err> {match s.to_lowercase().as_str() {- "dns" => Ok(ReplicaDiscoveryMode::Dns),- "k8s" => Ok(ReplicaDiscoveryMode::K8s),+ "dns" => Ok(DiscoveryMode::Dns),+ "k8s" => Ok(DiscoveryMode::K8s),other => Err(format!(- "unknown replica discovery mode '{other}', expected 'dns' or 'k8s'"+ "unknown discovery mode '{other}', expected 'dns' or 'k8s'")),}}@@ -91,7 +91,7 @@ pub struct Config {/// Discovery mode for replica endpoints: "dns" (default)/// or "k8s" (EndpointSlice watcher with client-side balancing)#[envconfig(default = "dns")]- pub replica_discovery_mode: ReplicaDiscoveryMode,+ pub replica_discovery_mode: DiscoveryMode,/// Kubernetes service name to watch for replica endpoints (k8s mode only)#[envconfig(default = "personhog-replica")]@@ -106,6 +106,41 @@ pub struct Config {#[envconfig(default = "50051")]pub replica_port: u16,+ /// Forward identity and lifecycle RPCs to personhog-identity. Off, the+ /// router answers those service names with UNIMPLEMENTED.+ #[envconfig(default = "false")]+ pub identity_enabled: bool,++ /// URL of the personhog-identity backend (DNS mode only)+ #[envconfig(default = "http://127.0.0.1:50055")]+ pub identity_url: String,++ /// Number of gRPC channels to open to the identity service (DNS mode only)+ #[envconfig(default = "4")]+ pub identity_channels: usize,++ /// Discovery mode for identity endpoints: "dns" (default) or "k8s"+ #[envconfig(default = "dns")]+ pub identity_discovery_mode: DiscoveryMode,++ /// Kubernetes service name to watch for identity endpoints (k8s mode only)+ #[envconfig(default = "personhog-identity")]+ pub identity_service_name: String,++ /// Kubernetes namespace for identity endpoint discovery (k8s mode only).+ /// If empty, reads from the service account mount.+ #[envconfig(default = "")]+ pub identity_service_namespace: String,++ /// gRPC port on identity pods (k8s mode only)+ #[envconfig(default = "50055")]+ pub identity_port: u16,++ /// Timeout for identity backend requests in milliseconds. Lifecycle RPCs+ /// run their saga inline, so this sits well above the replica timeout.+ #[envconfig(default = "30000")]+ pub identity_timeout_ms: u64,+/// Timeout for backend requests in milliseconds#[envconfig(default = "5000")]pub backend_timeout_ms: u64,@@ -582,20 +617,20 @@ mod tests {);}- // ── ReplicaDiscoveryMode ──────────────────────────────────────────────────+ // ── DiscoveryMode ──────────────────────────────────────────────────#[test]- fn replica_discovery_mode_from_str_valid_variants() {+ fn discovery_mode_from_str_valid_variants() {let cases = [- ("dns", ReplicaDiscoveryMode::Dns),- ("k8s", ReplicaDiscoveryMode::K8s),+ ("dns", DiscoveryMode::Dns),+ ("k8s", DiscoveryMode::K8s),// case-insensitive- ("DNS", ReplicaDiscoveryMode::Dns),- ("K8S", ReplicaDiscoveryMode::K8s),- ("Dns", ReplicaDiscoveryMode::Dns),+ ("DNS", DiscoveryMode::Dns),+ ("K8S", DiscoveryMode::K8s),+ ("Dns", DiscoveryMode::Dns),];for (input, expected) in cases {- let result: Result<ReplicaDiscoveryMode, _> = input.parse();+ let result: Result<DiscoveryMode, _> = input.parse();assert_eq!(result.unwrap(),expected,@@ -605,10 +640,10 @@ mod tests {}#[test]- fn replica_discovery_mode_from_str_invalid_returns_error() {+ fn discovery_mode_from_str_invalid_returns_error() {let invalid_inputs = ["endpoint", "", "replica", "kubernetes", "k8s1"];for input in invalid_inputs {- let result: Result<ReplicaDiscoveryMode, _> = input.parse();+ let result: Result<DiscoveryMode, _> = input.parse();assert!(result.is_err(), "'{input}' should be an error");let msg = result.unwrap_err();assert!(@@ -619,16 +654,16 @@ mod tests {}#[test]- fn replica_discovery_mode_display() {- assert_eq!(ReplicaDiscoveryMode::Dns.to_string(), "dns");- assert_eq!(ReplicaDiscoveryMode::K8s.to_string(), "k8s");+ fn discovery_mode_display() {+ assert_eq!(DiscoveryMode::Dns.to_string(), "dns");+ assert_eq!(DiscoveryMode::K8s.to_string(), "k8s");}#[test]- fn replica_discovery_mode_roundtrips() {- for mode in [ReplicaDiscoveryMode::Dns, ReplicaDiscoveryMode::K8s] {+ fn discovery_mode_roundtrips() {+ for mode in [DiscoveryMode::Dns, DiscoveryMode::K8s] {let s = mode.to_string();- let parsed: ReplicaDiscoveryMode = s.parse().unwrap();+ let parsed: DiscoveryMode = s.parse().unwrap();assert_eq!(parsed, mode,"Display → FromStr roundtrip failed for {mode:?}"@@ -689,6 +724,10 @@ impl Config {Duration::from_millis(self.backend_timeout_ms)}+ pub fn identity_timeout(&self) -> Duration {+ Duration::from_millis(self.identity_timeout_ms)+ }+pub fn backend_connect_timeout(&self) -> Duration {Duration::from_millis(self.backend_connect_timeout_ms)}@@ -966,29 +1005,30 @@ impl Config {/// Resolve the replica service namespace from config or the service account mount.pub fn resolve_replica_namespace(&self) -> Result<String, String> {- if !self.replica_service_namespace.is_empty() {- return Ok(self.replica_service_namespace.clone());- }- std::fs::read_to_string("/var/run/secrets/kubernetes.io/serviceaccount/namespace")- .map(|s| s.trim().to_string())- .map_err(|e| {- format!(- "replica_service_namespace not set and failed to read from service account: {e}"- )- })+ namespace_or_service_account(&self.replica_service_namespace, "replica_service_namespace")+ }++ /// Resolve the identity service namespace from config or the service account mount.+ pub fn resolve_identity_namespace(&self) -> Result<String, String> {+ namespace_or_service_account(+ &self.identity_service_namespace,+ "identity_service_namespace",+ )}/// Resolve the K8s namespace from config or the service account mount.pub fn resolve_k8s_namespace(&self) -> Result<String, String> {- if !self.k8s_namespace.is_empty() {- return Ok(self.k8s_namespace.clone());- }- std::fs::read_to_string("/var/run/secrets/kubernetes.io/serviceaccount/namespace")- .map(|s| s.trim().to_string())- .map_err(|e| {- format!("k8s_namespace not set and failed to read from service account: {e}")- })+ namespace_or_service_account(&self.k8s_namespace, "k8s_namespace")+ }+}++fn namespace_or_service_account(configured: &str, field: &str) -> Result<String, String> {+ if !configured.is_empty() {+ return Ok(configured.to_string());}+ std::fs::read_to_string("/var/run/secrets/kubernetes.io/serviceaccount/namespace")+ .map(|s| s.trim().to_string())+ .map_err(|e| format!("{field} not set and failed to read from service account: {e}"))}#[derive(Clone, Copy, Debug)]diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 471a4f69b139..2091b2df3a35 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -5,7 +5,7 @@ use assignment_coordination::store::{EtcdStore, StoreConfig};use axum::{routing::get, Router};use envconfig::Envconfig;use k8s_awareness::K8sAwareness;-use lifecycle::{ComponentOptions, Manager};+use lifecycle::{ComponentOptions, Handle, Manager};use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle};use personhog_common::grpc::{tracked_tcp_incoming, GrpcMetricsLayer};use personhog_common::metrics::WRITE_PATH_LATENCY_BUCKETS_MS;@@ -13,12 +13,12 @@ use personhog_coordination::coordinator::{Coordinator, CoordinatorConfig};use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};use personhog_coordination::store::PersonhogStore;use personhog_coordination::strategy::StickyBalancedStrategy;-use personhog_router::backend::discovery::{EndpointConfig, EndpointDiscovery};+use personhog_router::backend::discovery::{DiscoveryReadiness, EndpointConfig, EndpointDiscovery};use personhog_router::backend::{- LeaderBackend, LeaderBackendConfig, ReplicaBackend, ReplicaDnsConfig, StashTable,+ ChannelBackend, DnsBackendConfig, LeaderBackend, LeaderBackendConfig, StashTable,};-use personhog_router::config::{Config, ReplicaDiscoveryMode, RouterMode};-use personhog_router::proxy::RawProxyService;+use personhog_router::config::{Config, DiscoveryMode, RouterMode};+use personhog_router::proxy::{IdentityProxyService, LifecycleProxyService, RawProxyService};use personhog_router::stash_handler::RouterStashHandler;use tokio_util::sync::CancellationToken;use tonic::transport::Server;@@ -70,6 +70,22 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {tracing::info!("Replica discovery mode: {}", config.replica_discovery_mode);tracing::info!("Replica URL: {}", config.replica_url);tracing::info!("Backend timeout: {}ms", config.backend_timeout_ms);+ tracing::info!(+ "Identity proxy: {}",+ if config.identity_enabled {+ "enabled"+ } else {+ "disabled"+ }+ );+ if config.identity_enabled {+ tracing::info!(+ "Identity discovery mode: {}",+ config.identity_discovery_mode+ );+ tracing::info!("Identity URL: {}", config.identity_url);+ tracing::info!("Identity timeout: {}ms", config.identity_timeout_ms);+ }tracing::info!("Metrics port: {}", config.metrics_port);tracing::info!("Retry config: max_retries={}, initial_backoff={}ms, max_backoff={}ms",@@ -124,73 +140,61 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {(None, None)};- // Register discovery handle before monitor_background() consumes the manager- let discovery_handle = if config.replica_discovery_mode == ReplicaDiscoveryMode::K8s {- Some(- manager.register(- "replica-discovery",- ComponentOptions::new()- .with_graceful_shutdown(config.phase1_graceful_shutdown())- .with_shutdown_phase(1),- ),- )- } else {- None+ // Register discovery handles before monitor_background() consumes the manager+ let discovery_options = || {+ ComponentOptions::new()+ .with_graceful_shutdown(config.phase1_graceful_shutdown())+ .with_shutdown_phase(1)};+ let replica_discovery_handle = (config.replica_discovery_mode == DiscoveryMode::K8s)+ .then(|| manager.register("replica-discovery", discovery_options()));+ let identity_discovery_handle = (config.identity_enabled+ && config.identity_discovery_mode == DiscoveryMode::K8s)+ .then(|| manager.register("identity-discovery", discovery_options()));let readiness = manager.readiness_handler();let liveness = manager.liveness_handler();let monitor_guard = manager.monitor_background();- // Create backend connection(s) to personhog-replica- let (replica_backend, discovery_readiness) = match config.replica_discovery_mode {- ReplicaDiscoveryMode::Dns => (- Arc::new(ReplicaBackend::new_dns(ReplicaDnsConfig {- url: config.replica_url.clone(),- timeout: config.backend_timeout(),- retry_config: config.retry_config(),- keepalive_interval: config.backend_keepalive_interval(),- keepalive_timeout: config.backend_keepalive_timeout(),- num_channels: config.replica_channels,- })),- None,- ),- ReplicaDiscoveryMode::K8s => {- let kube_client = kube::Client::try_default()- .await- .expect("failed to create K8s client for replica discovery");- let namespace = config- .resolve_replica_namespace()- .expect("failed to resolve replica service namespace");-- let discovery_handle =- discovery_handle.expect("discovery handle must be registered in k8s mode");-- let (channel, disc_readiness, discovery) = EndpointDiscovery::new(- kube_client,- namespace,- config.replica_service_name.clone(),- config.replica_port,- EndpointConfig {- timeout: config.backend_timeout(),- connect_timeout: config.backend_connect_timeout(),- keepalive_interval: config.backend_keepalive_interval(),- keepalive_timeout: config.backend_keepalive_timeout(),- },- discovery_handle.shutdown_token(),- );-- tokio::spawn(async move {- let _guard = discovery_handle.process_scope();- discovery.run().await;- });-- (- Arc::new(ReplicaBackend::new_k8s(channel, config.retry_config())),- Some(disc_readiness),- )- }+ let (replica_backend, discovery_readiness) = build_channel_backend(+ BackendSpec {+ role: "replica",+ discovery_mode: config.replica_discovery_mode,+ url: config.replica_url.clone(),+ num_channels: config.replica_channels,+ service_name: config.replica_service_name.clone(),+ namespace: Config::resolve_replica_namespace,+ port: config.replica_port,+ timeout: config.backend_timeout(),+ },+ &config,+ replica_discovery_handle,+ )+ .await;++ // Identity readiness gates each identity request in the proxy rather+ // than the pod, so an identity outage never pulls a router out of the+ // write path.+ let identity_backend = if config.identity_enabled {+ let (backend, _readiness) = build_channel_backend(+ BackendSpec {+ role: "identity",+ discovery_mode: config.identity_discovery_mode,+ url: config.identity_url.clone(),+ num_channels: config.identity_channels,+ service_name: config.identity_service_name.clone(),+ namespace: Config::resolve_identity_namespace,+ port: config.identity_port,+ timeout: config.identity_timeout(),+ },+ &config,+ identity_discovery_handle,+ )+ .await;+ Some(backend)+ } else {+ None};// Metrics/health HTTP server (spawned after backend creation so it can@@ -405,6 +409,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let proxy = RawProxyService::new(replica_backend,+ identity_backend,leader_backend,retry_config,max_recv,@@ -414,7 +419,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {.http2_keepalive_interval(keepalive_interval).http2_keepalive_timeout(keepalive_timeout).layer(GrpcMetricsLayer::default())- .add_service(proxy)+ .add_service(proxy.clone())+ .add_service(IdentityProxyService(proxy.clone()))+ .add_service(LifecycleProxyService(proxy)).serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal()).await;@@ -427,6 +434,85 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {Ok(())}+/// What one channel backend needs to dial its pods in either discovery+/// mode; the replica and identity backends differ only in these values.+struct BackendSpec {+ role: &'static str,+ discovery_mode: DiscoveryMode,+ url: String,+ num_channels: usize,+ service_name: String,+ namespace: fn(&Config) -> Result<String, String>,+ port: u16,+ timeout: Duration,+}++/// Build a channel backend; in k8s mode this also starts its EndpointSlice+/// discovery task under `discovery_handle` and returns the readiness the+/// task drives.+async fn build_channel_backend(+ spec: BackendSpec,+ config: &Config,+ discovery_handle: Option<Handle>,+) -> (Arc<ChannelBackend>, Option<DiscoveryReadiness>) {+ let role = spec.role;+ match spec.discovery_mode {+ DiscoveryMode::Dns => (+ Arc::new(ChannelBackend::new_dns(+ role,+ DnsBackendConfig {+ url: spec.url,+ timeout: spec.timeout,+ retry_config: config.retry_config(),+ keepalive_interval: config.backend_keepalive_interval(),+ keepalive_timeout: config.backend_keepalive_timeout(),+ num_channels: spec.num_channels,+ },+ )),+ None,+ ),+ DiscoveryMode::K8s => {+ let kube_client = kube::Client::try_default().await.unwrap_or_else(|e| {+ panic!("failed to create K8s client for {role} discovery: {e}")+ });+ let namespace = (spec.namespace)(config)+ .unwrap_or_else(|e| panic!("failed to resolve {role} service namespace: {e}"));+ let discovery_handle = discovery_handle.unwrap_or_else(|| {+ panic!("{role} discovery handle must be registered in k8s mode")+ });++ let (channel, readiness, discovery) = EndpointDiscovery::new(+ kube_client,+ namespace,+ spec.service_name,+ spec.port,+ EndpointConfig {+ timeout: spec.timeout,+ connect_timeout: config.backend_connect_timeout(),+ keepalive_interval: config.backend_keepalive_interval(),+ keepalive_timeout: config.backend_keepalive_timeout(),+ },+ discovery_handle.shutdown_token(),+ );++ tokio::spawn(async move {+ let _guard = discovery_handle.process_scope();+ discovery.run().await;+ });++ (+ Arc::new(ChannelBackend::new_k8s(+ role,+ channel,+ config.retry_config(),+ readiness.clone(),+ )),+ Some(readiness),+ )+ }+ }+}+/// Must stay equal to `common_metrics::ETCD_PAYLOAD_SIZE_BUCKETS_BYTES`,/// which every binary on the shared recorder gets. This binary builds its/// own recorder and does not depend on that crate, but the store layerdiff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rsindex 1560eb054b1b..f091f69432f4 100644--- a/rust/personhog-router/src/proxy.rs+++ b/rust/personhog-router/src/proxy.rs@@ -17,12 +17,14 @@ use tonic::body::BoxBody;use tonic::Code;use tower::{Service, ServiceExt};-use crate::backend::{LeaderBackend, ReplicaBackend};+use crate::backend::{ChannelBackend, LeaderBackend};use crate::config::RetryConfig;use crate::grpc_http::{grpc_error_response, grpc_status_code, is_grpc_error_response};const SERVICE_PREFIX: &str = "/personhog.service.v1.PersonHogService/";const REPLICA_PREFIX: &str = "/personhog.replica.v1.PersonHogReplica/";+const IDENTITY_PREFIX: &str = "/personhog.identity.v1.PersonHogIdentity/";+const LIFECYCLE_PREFIX: &str = "/personhog.lifecycle.v1.PersonHogLifecycle/";pub const KNOWN_METHODS: &[&str] = &["CheckCohortMembership",@@ -70,8 +72,57 @@ pub const KNOWN_METHODS: &[&str] = &["UpsertHashKeyOverrides",];-fn is_known_method(name: &str) -> bool {- KNOWN_METHODS.binary_search(&name).is_ok()+/// Identity-server RPCs, forwarded verbatim; sorted for binary search.+pub const IDENTITY_METHODS: &[&str] = &[+ "GetDistinctIdsForPersons",+ "GetOrCreatePersonByDistinctId",+ "GetOrCreatePersonsByDistinctIds",+ "GetPersonsByDistinctIds",+ "MergePersons",+];++pub const LIFECYCLE_METHODS: &[&str] = &["DeletePersons"];++/// Where a request path lands: the service facade, whose methods split+/// between replica and leader, or one of the identity server's two services.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Target {+ Service,+ Identity,+ Lifecycle,+}++impl Target {+ fn methods(self) -> &'static [&'static str] {+ match self {+ Target::Service => KNOWN_METHODS,+ Target::Identity => IDENTITY_METHODS,+ Target::Lifecycle => LIFECYCLE_METHODS,+ }+ }+}++/// Split a path into its target and method. Paths outside the served+/// services or their method lists are refused, which keeps the method label+/// on every router metric bounded.+#[allow(clippy::result_large_err)]+fn resolve_target(path: &str) -> Result<(Target, &str), http::Response<BoxBody>> {+ let (target, method) = if let Some(method) = path.strip_prefix(SERVICE_PREFIX) {+ (Target::Service, method)+ } else if let Some(method) = path.strip_prefix(IDENTITY_PREFIX) {+ (Target::Identity, method)+ } else if let Some(method) = path.strip_prefix(LIFECYCLE_PREFIX) {+ (Target::Lifecycle, method)+ } else {+ return Err(grpc_error_response(Code::Unimplemented, "unknown service"));+ };+ if target.methods().binary_search(&method).is_err() {+ return Err(grpc_error_response(+ Code::Unimplemented,+ &format!("unknown method: {method}"),+ ));+ }+ Ok((target, method))}pub struct RawProxyService {@@ -79,7 +130,8 @@ pub struct RawProxyService {}struct RawProxyInner {- replica: Arc<ReplicaBackend>,+ replica: Arc<ChannelBackend>,+ identity: Option<Arc<ChannelBackend>>,leader: Option<Arc<LeaderBackend>>,retry_config: RetryConfig,max_recv_message_size: usize,@@ -88,7 +140,8 @@ struct RawProxyInner {impl RawProxyService {pub fn new(- replica: Arc<ReplicaBackend>,+ replica: Arc<ChannelBackend>,+ identity: Option<Arc<ChannelBackend>>,leader: Option<Arc<LeaderBackend>>,retry_config: RetryConfig,max_recv_message_size: usize,@@ -97,6 +150,7 @@ impl RawProxyService {Self {inner: Arc::new(RawProxyInner {replica,+ identity,leader,retry_config,max_recv_message_size,@@ -135,29 +189,62 @@ impl Service<http::Request<BoxBody>> for RawProxyService {}}+/// tonic routes each registration by its `NamedService::NAME`, so the+/// identity server's two services need their own registered types; both+/// delegate to the one proxy.+macro_rules! proxy_facet {+ ($name:ident, $service:literal) => {+ #[derive(Clone)]+ pub struct $name(pub RawProxyService);++ impl tonic::server::NamedService for $name {+ const NAME: &'static str = $service;+ }++ impl Service<http::Request<BoxBody>> for $name {+ type Response = http::Response<BoxBody>;+ type Error = Infallible;+ type Future = <RawProxyService as Service<http::Request<BoxBody>>>::Future;++ fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {+ self.0.poll_ready(cx)+ }++ fn call(&mut self, req: http::Request<BoxBody>) -> Self::Future {+ self.0.call(req)+ }+ }+ };+}++proxy_facet!(+ IdentityProxyService,+ "personhog.identity.v1.PersonHogIdentity"+);+proxy_facet!(+ LifecycleProxyService,+ "personhog.lifecycle.v1.PersonHogLifecycle"+);+impl RawProxyInner {async fn handle(&self, req: http::Request<BoxBody>) -> http::Response<BoxBody> {let path = req.uri().path().to_string();-- let method_name = match path.strip_prefix(SERVICE_PREFIX) {- Some(m) => m,- None => return grpc_error_response(Code::Unimplemented, "unknown service"),+ let (target, method_name) = match resolve_target(&path) {+ Ok(resolved) => resolved,+ Err(response) => return response,};- if !is_known_method(method_name) {- return grpc_error_response(- Code::Unimplemented,- &format!("unknown method: {method_name}"),- );- }-let method: Arc<str> = Arc::from(method_name);let client = current_client_name();let caller_tag = current_caller_tag();let start = Instant::now();- let (mut response, backend, channel_call_ms) = match method_name {- "UpdatePersonProperties" => {+ let (mut response, backend, channel_call_ms) = match (target, method_name) {+ (Target::Identity | Target::Lifecycle, _) => {+ let (resp, call_ms) = self.raw_proxy_to_identity(req, &path, method.clone()).await;+ (resp, "identity", call_ms)+ }+ (Target::Service, "UpdatePersonProperties") => {let (resp, call_ms) = self.raw_proxy_to_leader(req, "UpdatePersonProperties").await;@@ -165,21 +252,21 @@ impl RawProxyInner {}// Lifecycle fence RPCs: person writes, so they route to the// owning leader and share the handoff stash discipline.- "FencePerson" => {+ (Target::Service, "FencePerson") => {let (resp, call_ms) = self.raw_proxy_to_leader(req, "FencePerson").await;(resp, "leader", call_ms)}- "ReleaseFence" => {+ (Target::Service, "ReleaseFence") => {let (resp, call_ms) = self.raw_proxy_to_leader(req, "ReleaseFence").await;(resp, "leader", call_ms)}// The merge saga's document write: leader-routed like every// person write.- "FoldPersonDocument" => {+ (Target::Service, "FoldPersonDocument") => {let (resp, call_ms) = self.raw_proxy_to_leader(req, "FoldPersonDocument").await;(resp, "leader", call_ms)}- "GetPerson" => {+ (Target::Service, "GetPerson") => {let is_strong = req.headers().get("x-read-consistency")@@ -194,7 +281,7 @@ impl RawProxyInner {(resp, "replica", call_ms)}}- _ => {+ (Target::Service, _) => {let (resp, call_ms) = self.raw_proxy_to_replica(req, method.clone()).await;(resp, "replica", call_ms)}@@ -279,39 +366,90 @@ impl RawProxyInner {method: Arc<str>,) -> (http::Response<BoxBody>, Option<f64>) {let (parts, body) = req.into_parts();+ let body_bytes = match self.collect_body_timed(body, &method).await {+ Ok(b) => b,+ Err(resp) => return (resp, None),+ };+ let new_path = format!("{REPLICA_PREFIX}{method}");- let collect_start = Instant::now();- let body_bytes = match collect_body_limited(body, self.max_recv_message_size).await {+ let _in_flight = ClientInFlightGuard::new("replica");+ self.forward_with_retry(&self.replica, &parts, &body_bytes, &new_path, method)+ .await+ }++ /// Forward an identity-server request (identity or lifecycle service)+ /// verbatim: same path, same headers, no routing key. Identity pods are+ /// interchangeable, so the balanced channel picks one.+ async fn raw_proxy_to_identity(+ &self,+ req: http::Request<BoxBody>,+ path: &str,+ method: Arc<str>,+ ) -> (http::Response<BoxBody>, Option<f64>) {+ let identity = match &self.identity {+ Some(backend) => backend,+ None => {+ return (+ grpc_error_response(+ Code::Unimplemented,+ "identity backend not configured for this router",+ ),+ None,+ )+ }+ };+ // Fail fast rather than park the request on an empty balancer until+ // the client's deadline.+ if !identity.has_endpoints() {+ return (+ grpc_error_response(Code::Unavailable, "identity backend has no endpoints"),+ None,+ );+ }++ let (parts, body) = req.into_parts();+ let body_bytes = match self.collect_body_timed(body, &method).await {Ok(b) => b,Err(resp) => return (resp, None),};- let client = current_client_name();++ let _in_flight = ClientInFlightGuard::new("identity");+ self.forward_with_retry(identity, &parts, &body_bytes, path, method)+ .await+ }++ /// Buffer the request body under the receive cap, timing the wait. The+ /// forwarders need the whole body in hand to replay it on a retry.+ #[allow(clippy::result_large_err)]+ async fn collect_body_timed(+ &self,+ body: BoxBody,+ method: &Arc<str>,+ ) -> Result<Bytes, http::Response<BoxBody>> {+ let collect_start = Instant::now();+ let body_bytes = collect_body_limited(body, self.max_recv_message_size).await?;histogram!("personhog_router_body_collect_ms","method" => method.clone(),- "client" => client.clone(),+ "client" => current_client_name(),).record(collect_start.elapsed().as_secs_f64() * 1000.0);-- let new_path = format!("{REPLICA_PREFIX}{method}");-- let _in_flight = ClientInFlightGuard::new("replica");- self.forward_with_retry(&parts, &body_bytes, &new_path, method)- .await+ Ok(body_bytes)}async fn forward_with_retry(&self,+ backend: &ChannelBackend,parts: &http::request::Parts,body_bytes: &Bytes,- new_path: &str,+ path: &str,method: Arc<str>,) -> (http::Response<BoxBody>, Option<f64>) {let mut delay_ms = self.retry_config.initial_backoff_ms;let client = current_client_name();for attempt in 0..=self.retry_config.max_retries {- let mut channel = self.replica.channel();+ let mut channel = backend.channel();let ready_start = Instant::now();let ready_channel = match channel.ready().await {@@ -330,7 +468,7 @@ impl RawProxyInner {return (grpc_error_response(Code::Unavailable,- &format!("replica channel not ready: {e}"),+ &format!("{} channel not ready: {e}", backend.role()),),None,);@@ -352,10 +490,7 @@ impl RawProxyInner {let mut req = http::Request::new(body);*req.method_mut() = parts.method.clone();- *req.uri_mut() = http::Uri::builder()- .path_and_query(new_path)- .build()- .unwrap();+ *req.uri_mut() = http::Uri::builder().path_and_query(path).build().unwrap();*req.version_mut() = parts.version;*req.headers_mut() = parts.headers.clone();@@ -386,7 +521,7 @@ impl RawProxyInner {return (grpc_error_response(Code::Unavailable,- &format!("replica backend error: {e}"),+ &format!("{} backend error: {e}", backend.role()),),None,);@@ -444,17 +579,10 @@ impl RawProxyInner {};let (parts, body) = req.into_parts();- let collect_start = Instant::now();- let body_bytes = match collect_body_limited(body, self.max_recv_message_size).await {+ let body_bytes = match self.collect_body_timed(body, &Arc::from(method)).await {Ok(b) => b,Err(resp) => return (resp, None),};- histogram!(- "personhog_router_body_collect_ms",- "method" => method,- "client" => current_client_name(),- )- .record(collect_start.elapsed().as_secs_f64() * 1000.0);let partition = leader.partition_for_person(team_id, person_id);@@ -684,54 +812,121 @@ mod tests {use futures::stream;use http_body_util::{Empty, StreamBody};+ const METHOD_LISTS: [(&str, &[&str], &str); 3] = [+ ("KNOWN_METHODS", KNOWN_METHODS, "service/v1/service.proto"),+ (+ "IDENTITY_METHODS",+ IDENTITY_METHODS,+ "identity/v1/identity.proto",+ ),+ (+ "LIFECYCLE_METHODS",+ LIFECYCLE_METHODS,+ "lifecycle/v1/lifecycle.proto",+ ),+ ];++ fn proto_rpc_names(proto_path: &str) -> Vec<String> {+ let path = format!(+ "{}/../../proto/personhog/{proto_path}",+ env!("CARGO_MANIFEST_DIR")+ );+ let proto =+ std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("failed to read {path}: {e}"));+ let mut names: Vec<String> = proto+ .lines()+ .filter_map(|line| {+ line.trim()+ .strip_prefix("rpc ")+ .and_then(|rest| rest.split('(').next())+ .map(|name| name.trim().to_string())+ })+ .collect();+ names.sort();+ names+ }+#[test]- fn known_method_lookup() {- assert!(is_known_method("GetPerson"));- assert!(is_known_method("UpdatePersonProperties"));- assert!(is_known_method("ListGroups"));- assert!(is_known_method("CheckCohortMembership"));- assert!(!is_known_method("FakeMethod"));- assert!(!is_known_method(""));+ fn method_lists_are_sorted() {+ for (name, list, _) in METHOD_LISTS {+ for window in list.windows(2) {+ assert!(+ window[0] < window[1],+ "{name} is not sorted: {:?} should come after {:?}",+ window[0],+ window[1],+ );+ }+ }}#[test]- fn known_methods_is_sorted() {- for window in KNOWN_METHODS.windows(2) {- assert!(- window[0] < window[1],- "KNOWN_METHODS is not sorted: {:?} should come after {:?}",- window[0],- window[1],+ fn method_lists_match_their_protos() {+ for (name, list, proto_path) in METHOD_LISTS {+ assert_eq!(+ list.to_vec(),+ proto_rpc_names(proto_path),+ "{name} is out of sync with {proto_path}: add or remove entries to match");}}#[test]- fn known_methods_matches_service_proto() {- let proto = std::fs::read_to_string(concat!(- env!("CARGO_MANIFEST_DIR"),- "/../../proto/personhog/service/v1/service.proto"- ))- .expect("failed to read service.proto — is the proto directory present?");-- let mut proto_methods: Vec<&str> = proto- .lines()- .filter_map(|line| {- line.trim()- .strip_prefix("rpc ")- .and_then(|rest| rest.split('(').next())- .map(|name| name.trim())- })- .collect();- proto_methods.sort();-- let known: Vec<&str> = KNOWN_METHODS.to_vec();+ fn prefixes_match_registered_service_names() {+ use tonic::server::NamedService;+ assert_eq!(SERVICE_PREFIX, format!("/{}/", RawProxyService::NAME));+ assert_eq!(IDENTITY_PREFIX, format!("/{}/", IdentityProxyService::NAME));assert_eq!(- known, proto_methods,- "KNOWN_METHODS is out of sync with service.proto — add/remove entries to match"+ LIFECYCLE_PREFIX,+ format!("/{}/", LifecycleProxyService::NAME));}+ #[test]+ fn resolve_target_accepts_listed_methods_on_each_service() {+ let cases = [+ (+ "/personhog.service.v1.PersonHogService/GetPerson",+ Target::Service,+ "GetPerson",+ ),+ (+ "/personhog.identity.v1.PersonHogIdentity/GetOrCreatePersonsByDistinctIds",+ Target::Identity,+ "GetOrCreatePersonsByDistinctIds",+ ),+ (+ "/personhog.lifecycle.v1.PersonHogLifecycle/DeletePersons",+ Target::Lifecycle,+ "DeletePersons",+ ),+ ];+ for (path, target, method) in cases {+ assert_eq!(resolve_target(path).ok(), Some((target, method)), "{path}");+ }+ }++ /// A method is only known on its own service: the facade's methods do+ /// not leak onto the identity server and vice versa.+ #[test]+ fn resolve_target_refuses_unknown_services_and_methods() {+ let paths = [+ "/personhog.service.v1.PersonHogService/FakeMethod",+ "/personhog.service.v1.PersonHogService/",+ "/personhog.identity.v1.PersonHogIdentity/GetPerson",+ "/personhog.lifecycle.v1.PersonHogLifecycle/MergePersons",+ "/personhog.replica.v1.PersonHogReplica/GetPerson",+ ];+ for path in paths {+ let resp = resolve_target(path).expect_err(path);+ assert_eq!(+ resp.headers().get("grpc-status").unwrap(),+ &format!("{}", Code::Unimplemented as i32),+ "{path}"+ );+ }+ }+/// Well-formed routing-key headers yield the `(team_id, person_id)`/// pair the router hashes for partition placement.#[test]diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rsindex 20d9393c3703..b8bee2c9deef 100644--- a/rust/personhog-router/tests/common/mod.rs+++ b/rust/personhog-router/tests/common/mod.rs@@ -8,9 +8,17 @@ use std::time::Duration;use dashmap::DashMap;use personhog_common::async_gzip::{AsyncGzipConfig, AsyncGzipLayer};+use personhog_proto::personhog::identity::v1 as identity;+use personhog_proto::personhog::identity::v1::person_hog_identity_server::{+ PersonHogIdentity, PersonHogIdentityServer,+};use personhog_proto::personhog::leader::v1::person_hog_leader_server::{PersonHogLeader, PersonHogLeaderServer,};+use personhog_proto::personhog::lifecycle::v1 as lifecycle;+use personhog_proto::personhog::lifecycle::v1::person_hog_lifecycle_server::{+ PersonHogLifecycle, PersonHogLifecycleServer,+};use personhog_proto::personhog::replica::v1::person_hog_replica_server::{PersonHogReplica, PersonHogReplicaServer,};@@ -45,10 +53,10 @@ use personhog_proto::personhog::types::v1::{UpsertHashKeyOverridesRequest, UpsertHashKeyOverridesResponse,};use personhog_router::backend::{- LeaderBackend, LeaderBackendConfig, ReplicaBackend, ReplicaDnsConfig, StashTable,+ ChannelBackend, DnsBackendConfig, LeaderBackend, LeaderBackendConfig, StashTable,};use personhog_router::config::RetryConfig;-use personhog_router::proxy::RawProxyService;+use personhog_router::proxy::{IdentityProxyService, LifecycleProxyService, RawProxyService};use tokio::net::TcpListener;use tokio::sync::RwLock;use tonic::codec::CompressionEncoding;@@ -850,20 +858,23 @@ fn serve_test_leader(listener: TcpListener, service: TestLeaderService) {// Raw proxy test helpers// ============================================================-fn make_replica_backend(replica_addr: SocketAddr) -> Arc<ReplicaBackend> {+fn make_channel_backend(role: &'static str, addr: SocketAddr) -> Arc<ChannelBackend> {let retry_config = RetryConfig {max_retries: 1,initial_backoff_ms: 1,max_backoff_ms: 1,};- Arc::new(ReplicaBackend::new_dns(ReplicaDnsConfig {- url: format!("http://{}", replica_addr),- timeout: Duration::from_secs(5),- retry_config,- keepalive_interval: None,- keepalive_timeout: None,- num_channels: 1,- }))+ Arc::new(ChannelBackend::new_dns(+ role,+ DnsBackendConfig {+ url: format!("http://{}", addr),+ timeout: Duration::from_secs(5),+ retry_config,+ keepalive_interval: None,+ keepalive_timeout: None,+ num_channels: 1,+ },+ ))}fn make_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Arc<LeaderBackend> {@@ -918,6 +929,20 @@ fn make_dying_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Ar))}+/// Serve the proxy under every service name production registers, so a+/// test hits the proxy's own refusals rather than tonic's unknown-service one.+fn spawn_proxy_server(listener: TcpListener, proxy: RawProxyService) {+ tokio::spawn(async move {+ Server::builder()+ .add_service(proxy.clone())+ .add_service(IdentityProxyService(proxy.clone()))+ .add_service(LifecycleProxyService(proxy))+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))+ .await+ .unwrap();+ });+}+/// Raw proxy router whose leader answers one request and is then gone.pub async fn start_test_router_raw_with_dying_leader(replica_addr: SocketAddr,@@ -927,7 +952,8 @@ pub async fn start_test_router_raw_with_dying_leader(let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let addr = listener.local_addr().unwrap();let proxy = RawProxyService::new(- make_replica_backend(replica_addr),+ make_channel_backend("replica", replica_addr),+ None,Some(make_dying_leader_backend(leader_addr, num_partitions)),RetryConfig {max_retries: 1,@@ -937,13 +963,7 @@ pub async fn start_test_router_raw_with_dying_leader(4 * 1024 * 1024,0,);- tokio::spawn(async move {- Server::builder()- .add_service(proxy)- .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))- .await- .unwrap();- });+ spawn_proxy_server(listener, proxy);tokio::time::sleep(Duration::from_millis(10)).await;addr}@@ -961,21 +981,15 @@ pub async fn start_test_router_raw_with_max_recv(let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let addr = listener.local_addr().unwrap();- let replica = make_replica_backend(replica_addr);+ let replica = make_channel_backend("replica", replica_addr);let retry_config = RetryConfig {max_retries: 1,initial_backoff_ms: 1,max_backoff_ms: 1,};- let proxy = RawProxyService::new(replica, None, retry_config, max_recv_message_size, 0);+ let proxy = RawProxyService::new(replica, None, None, retry_config, max_recv_message_size, 0);- tokio::spawn(async move {- Server::builder()- .add_service(proxy)- .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))- .await- .unwrap();- });+ spawn_proxy_server(listener, proxy);tokio::time::sleep(Duration::from_millis(10)).await;addr@@ -1006,7 +1020,7 @@ pub async fn start_test_router_raw_with_leader_and_max_recv(let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let addr = listener.local_addr().unwrap();- let replica = make_replica_backend(replica_addr);+ let replica = make_channel_backend("replica", replica_addr);let leader = make_leader_backend(leader_addr, num_partitions);let retry_config = RetryConfig {max_retries: 1,@@ -1015,19 +1029,160 @@ pub async fn start_test_router_raw_with_leader_and_max_recv(};let proxy = RawProxyService::new(replica,+ None,Some(leader),retry_config,max_recv_message_size,0,);+ spawn_proxy_server(listener, proxy);++ tokio::time::sleep(Duration::from_millis(10)).await;+ addr+}++// ============================================================+// Identity server test doubles+// ============================================================++/// Identity server for the raw-proxy tests. Records the client name it+/// received and answers get-or-create with one created result per entry, so+/// a test can check that body and headers both survived the forward.+#[derive(Default)]+pub struct TestIdentityService {+ pub seen_client_name: Arc<Mutex<Option<String>>>,+}++fn record_client_name<T>(request: &Request<T>, into: &Mutex<Option<String>>) {+ *into.lock().unwrap() = request+ .metadata()+ .get("x-client-name")+ .and_then(|v| v.to_str().ok())+ .map(str::to_string);+}++#[tonic::async_trait]+impl PersonHogIdentity for TestIdentityService {+ async fn get_or_create_person_by_distinct_id(+ &self,+ _request: Request<identity::GetOrCreatePersonByDistinctIdRequest>,+ ) -> Result<Response<identity::GetOrCreatePersonByDistinctIdResponse>, Status> {+ Err(Status::unimplemented("not exercised by the proxy tests"))+ }++ async fn get_or_create_persons_by_distinct_ids(+ &self,+ request: Request<identity::GetOrCreatePersonsByDistinctIdsRequest>,+ ) -> Result<Response<identity::GetOrCreatePersonsByDistinctIdsResponse>, Status> {+ record_client_name(&request, &self.seen_client_name);+ let results = request+ .into_inner()+ .entries+ .into_iter()+ .map(|entry| identity::GetOrCreatePersonResult {+ team_id: entry.team_id,+ distinct_id: entry.distinct_id,+ person: None,+ created: true,+ error: None,+ })+ .collect();+ Ok(Response::new(+ identity::GetOrCreatePersonsByDistinctIdsResponse { results },+ ))+ }++ async fn get_persons_by_distinct_ids(+ &self,+ _request: Request<identity::GetPersonsByDistinctIdsRequest>,+ ) -> Result<Response<identity::GetPersonsByDistinctIdsResponse>, Status> {+ Err(Status::unimplemented("not exercised by the proxy tests"))+ }++ async fn get_distinct_ids_for_persons(+ &self,+ _request: Request<identity::GetDistinctIdsForPersonsRequest>,+ ) -> Result<Response<identity::GetDistinctIdsForPersonsResponse>, Status> {+ Err(Status::unimplemented("not exercised by the proxy tests"))+ }++ async fn merge_persons(+ &self,+ _request: Request<identity::MergePersonsRequest>,+ ) -> Result<Response<identity::MergePersonsResponse>, Status> {+ Err(Status::unimplemented("not exercised by the proxy tests"))+ }+}++/// Lifecycle server for the raw-proxy tests: echoes the op id and reports+/// every requested person as deleted.+#[derive(Default)]+pub struct TestLifecycleService;++#[tonic::async_trait]+impl PersonHogLifecycle for TestLifecycleService {+ async fn delete_persons(+ &self,+ request: Request<lifecycle::DeletePersonsRequest>,+ ) -> Result<Response<lifecycle::DeletePersonsResponse>, Status> {+ let request = request.into_inner();+ let results = request+ .person_ids+ .into_iter()+ .map(|person_id| lifecycle::DeletePersonResult {+ person_id,+ outcome: lifecycle::DeletePersonOutcome::Deleted as i32,+ })+ .collect();+ Ok(Response::new(lifecycle::DeletePersonsResponse {+ op_id: request.op_id,+ results,+ }))+ }+}++/// Serve both identity-server services on one port, as the identity binary does.+pub async fn start_test_identity(+ identity_service: TestIdentityService,+ lifecycle_service: TestLifecycleService,+) -> SocketAddr {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();tokio::spawn(async move {Server::builder()- .add_service(proxy)+ .add_service(PersonHogIdentityServer::new(identity_service))+ .add_service(PersonHogLifecycleServer::new(lifecycle_service)).serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)).await.unwrap();});+ tokio::time::sleep(Duration::from_millis(10)).await;+ addr+}++/// Start a raw proxy router with replica and identity backends, no leader.+pub async fn start_test_router_raw_with_identity(+ replica_addr: SocketAddr,+ identity_addr: SocketAddr,+) -> SocketAddr {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();++ let proxy = RawProxyService::new(+ make_channel_backend("replica", replica_addr),+ Some(make_channel_backend("identity", identity_addr)),+ None,+ RetryConfig {+ max_retries: 1,+ initial_backoff_ms: 1,+ max_backoff_ms: 1,+ },+ 4 * 1024 * 1024,+ 0,+ );++ spawn_proxy_server(listener, proxy);tokio::time::sleep(Duration::from_millis(10)).await;addrdiff --git a/rust/personhog-router/tests/raw_proxy_integration.rs b/rust/personhog-router/tests/raw_proxy_integration.rsindex 1f4fff06320b..a2a59c2c2028 100644--- a/rust/personhog-router/tests/raw_proxy_integration.rs+++ b/rust/personhog-router/tests/raw_proxy_integration.rs@@ -1,13 +1,22 @@mod common;+use std::sync::{Arc, Mutex};+use common::{create_client, create_compressed_client, create_test_person, raw_grpc_call_with_gzip_accept,- start_test_leader, start_test_replica, start_test_replica_with_async_gzip,+ start_test_identity, start_test_leader, start_test_replica, start_test_replica_with_async_gzip,start_test_replica_with_async_gzip_disabled, start_test_router_raw,- start_test_router_raw_with_dying_leader, start_test_router_raw_with_leader,- start_test_router_raw_with_leader_and_max_recv, start_test_router_raw_with_max_recv,- TestLeaderService, TestReplicaService,+ start_test_router_raw_with_dying_leader, start_test_router_raw_with_identity,+ start_test_router_raw_with_leader, start_test_router_raw_with_leader_and_max_recv,+ start_test_router_raw_with_max_recv, TestIdentityService, TestLeaderService,+ TestLifecycleService, TestReplicaService,+};+use personhog_proto::personhog::identity::v1::person_hog_identity_client::PersonHogIdentityClient;+use personhog_proto::personhog::identity::v1::{+ GetOrCreatePersonEntry, GetOrCreatePersonsByDistinctIdsRequest,};+use personhog_proto::personhog::lifecycle::v1::person_hog_lifecycle_client::PersonHogLifecycleClient;+use personhog_proto::personhog::lifecycle::v1::DeletePersonsRequest as LifecycleDeletePersonsRequest;use personhog_proto::personhog::types::v1::{CheckCohortMembershipRequest, CohortMembership, DeletePersonsRequest, GetGroupsRequest,GetPersonByDistinctIdRequest, GetPersonRequest, GetPersonResponse,@@ -920,3 +929,106 @@ async fn async_gzip_disabled_flag_skips_compression() {let response = <GetPersonResponse as prost::Message>::decode(payload).unwrap();assert_eq!(response.person.unwrap().id, 42);}++// ============================================================+// 4. Identity routing — verbatim forward to the identity server+// ============================================================++/// An identity RPC reaches the identity server with body and headers+/// intact: the results echo the request entries, and the server saw the+/// client name header.+#[tokio::test]+async fn raw_proxy_get_or_create_routes_to_identity() {+ let seen_client_name = Arc::new(Mutex::new(None));+ let identity_addr = start_test_identity(+ TestIdentityService {+ seen_client_name: seen_client_name.clone(),+ },+ TestLifecycleService,+ )+ .await;+ let replica_addr = start_test_replica(TestReplicaService::new()).await;+ let router_addr = start_test_router_raw_with_identity(replica_addr, identity_addr).await;++ let mut client = PersonHogIdentityClient::connect(format!("http://{router_addr}"))+ .await+ .unwrap();+ let mut request = Request::new(GetOrCreatePersonsByDistinctIdsRequest {+ entries: vec![GetOrCreatePersonEntry {+ team_id: 7,+ distinct_id: "user-7".to_string(),+ ..Default::default()+ }],+ });+ request+ .metadata_mut()+ .insert("x-client-name", "proxy-test".parse().unwrap());++ let results = client+ .get_or_create_persons_by_distinct_ids(request)+ .await+ .unwrap()+ .into_inner()+ .results;++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].team_id, 7);+ assert_eq!(results[0].distinct_id, "user-7");+ assert!(results[0].created);+ assert_eq!(+ seen_client_name.lock().unwrap().as_deref(),+ Some("proxy-test")+ );+}++/// The lifecycle service shares a method name with the service facade+/// (DeletePersons): the prefix decides the backend, not the method.+#[tokio::test]+async fn raw_proxy_lifecycle_delete_persons_routes_to_identity() {+ let identity_addr =+ start_test_identity(TestIdentityService::default(), TestLifecycleService).await;+ let replica_addr = start_test_replica(TestReplicaService::new()).await;+ let router_addr = start_test_router_raw_with_identity(replica_addr, identity_addr).await;++ let mut client = PersonHogLifecycleClient::connect(format!("http://{router_addr}"))+ .await+ .unwrap();+ let response = client+ .delete_persons(LifecycleDeletePersonsRequest {+ team_id: 7,+ person_ids: vec![1, 2],+ op_id: "op-1".to_string(),+ })+ .await+ .unwrap()+ .into_inner();++ assert_eq!(response.op_id, "op-1");+ let person_ids: Vec<i64> = response.results.iter().map(|r| r.person_id).collect();+ assert_eq!(person_ids, vec![1, 2]);+}++/// A router without an identity backend refuses the identity service names+/// outright instead of falling through to the replica.+#[tokio::test]+async fn raw_proxy_identity_without_backend_returns_unimplemented() {+ let replica_addr = start_test_replica(TestReplicaService::new()).await;+ let router_addr = start_test_router_raw(replica_addr).await;++ let mut client = PersonHogIdentityClient::connect(format!("http://{router_addr}"))+ .await+ .unwrap();+ let status = client+ .get_or_create_persons_by_distinct_ids(GetOrCreatePersonsByDistinctIdsRequest {+ entries: vec![],+ })+ .await+ .unwrap_err();++ assert_eq!(status.code(), tonic::Code::Unimplemented);+ assert!(+ status.message().contains("identity backend not configured"),+ "{}",+ status.message()+ );+}diff --git a/rust/personhog-test-harness/src/client.rs b/rust/personhog-test-harness/src/client.rsindex 888d296157ca..6687c48b6c0d 100644--- a/rust/personhog-test-harness/src/client.rs+++ b/rust/personhog-test-harness/src/client.rs@@ -135,8 +135,9 @@ impl HarnessClient {}}-/// Client for the personhog-identity service — the get-or-create entry-/// point. Called directly, not through the router, so no routing headers.+/// Client for the personhog-identity service, the get-or-create entry+/// point. No routing headers: identity pods are interchangeable, and the+/// router forwards these paths verbatim when it fronts the service.#[derive(Clone)]pub struct IdentityClient {inner: PersonHogIdentityClient<Channel>,diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rsindex cf0fb8bfa511..0e4bed9c0b7f 100644--- a/rust/personhog-test-harness/src/stack/mod.rs+++ b/rust/personhog-test-harness/src/stack/mod.rs@@ -91,7 +91,8 @@ pub struct Stack {store: PersonhogStore,topic: String,pub router_url: String,- /// Set when the stack spawned a personhog-identity service.+ /// Set when the stack spawned a personhog-identity service: the traffic+ /// router's URL, which proxies identity RPCs to it.pub identity_url: Option<String>,pub log_dir: PathBuf,}@@ -225,6 +226,12 @@ impl Stack {("ETCD_ENDPOINTS", config.etcd_endpoints.clone()),("ETCD_PREFIX", ETCD_PREFIX.to_string()),("BACKEND_TIMEOUT_MS", "5000".to_string()),+ // Identity RPCs enter through the router, as deployed.+ ("IDENTITY_ENABLED", config.spawn_identity.to_string()),+ (+ "IDENTITY_URL",+ format!("http://127.0.0.1:{IDENTITY_GRPC_PORT}"),+ ),("POD_NAME", name.clone()),("COORDINATOR_ENABLED", (!is_traffic_router).to_string()),(@@ -268,7 +275,7 @@ impl Stack {],&log_dir,)?);- Some(format!("http://127.0.0.1:{IDENTITY_GRPC_PORT}"))+ Some(router_url.clone())} else {None};