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(personhog): router replica pod discovery (#61460)

Nick Best9a7f89ffa245
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index a235312c88a6..86c58e4353a2 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -6823,6 +6823,7 @@ dependencies = [
"http-body 1.0.1",
"http-body-util",
"k8s-awareness",
+ "k8s-openapi",
"kube",
"lifecycle",
"metrics",
diff --git a/rust/personhog-router/Cargo.toml b/rust/personhog-router/Cargo.toml
index f5157950e81c..52cacedbac2a 100644
--- a/rust/personhog-router/Cargo.toml
+++ b/rust/personhog-router/Cargo.toml
@@ -13,7 +13,8 @@ k8s-awareness = { path = "../common/k8s-awareness" }
common-alloc = { path = "../common/alloc" }
metrics-exporter-prometheus = { workspace = true }
lifecycle = { path = "../common/lifecycle" }
-kube = { version = "0.98", features = ["client"] }
+k8s-openapi = { version = "0.24", features = ["latest"] }
+kube = { version = "0.98", features = ["client", "runtime"] }
async-trait = { workspace = true }
axum = { workspace = true }
diff --git a/rust/personhog-router/src/backend/discovery.rs b/rust/personhog-router/src/backend/discovery.rs
new file mode 100644
index 000000000000..1e7728c198ca
--- /dev/null
+++ b/rust/personhog-router/src/backend/discovery.rs
@@ -0,0 +1,979 @@
+use std::collections::{HashMap, HashSet};
+use std::net::{IpAddr, SocketAddr};
+use std::time::Duration;
+
+use futures::StreamExt;
+use k8s_openapi::api::discovery::v1::EndpointSlice;
+use kube::api::Api;
+use kube::runtime::watcher::{self, Config as WatcherConfig, Event};
+use kube::Client;
+use tokio::sync::mpsc::Sender;
+use tokio::sync::watch;
+use tokio_util::sync::CancellationToken;
+use tonic::transport::{Channel, Endpoint};
+use tower::discover::Change;
+use tracing::{info, warn};
+
+const DISCOVERY_CHANNEL_BUFFER: usize = 64;
+
+pub struct EndpointConfig {
+ pub timeout: Duration,
+ pub connect_timeout: Duration,
+ pub keepalive_interval: Option<Duration>,
+ pub keepalive_timeout: Option<Duration>,
+}
+
+pub struct EndpointDiscovery {
+ client: Client,
+ namespace: String,
+ service_name: String,
+ port: u16,
+ endpoint_config: EndpointConfig,
+ tx: Sender<Change<SocketAddr, Endpoint>>,
+ ready_tx: watch::Sender<bool>,
+ cancel: CancellationToken,
+}
+
+/// Handle for callers to check whether discovery has completed its initial
+/// list and has at least one endpoint available.
+#[derive(Clone)]
+pub struct DiscoveryReadiness {
+ rx: watch::Receiver<bool>,
+}
+
+impl DiscoveryReadiness {
+ pub fn is_ready(&self) -> bool {
+ *self.rx.borrow()
+ }
+
+ pub async fn wait_until_ready(&mut self) {
+ while !*self.rx.borrow_and_update() {
+ if self.rx.changed().await.is_err() {
+ break;
+ }
+ }
+ }
+}
+
+/// Parses an EndpointSlice and returns the set of ready socket addresses.
+///
+/// An endpoint is considered ready when `conditions.ready` is `true` or when
+/// `conditions` is absent entirely (the K8s spec treats a nil ready field as
+/// "assume ready"). Endpoints with `ready = false` are skipped. Address
+/// strings that fail IP parsing are also skipped silently.
+pub fn extract_ready_addrs(slice: &EndpointSlice, port: u16) -> HashSet<SocketAddr> {
+ let mut addrs = HashSet::new();
+ for endpoint in slice.endpoints.iter() {
+ let ready = endpoint
+ .conditions
+ .as_ref()
+ .and_then(|c| c.ready)
+ .unwrap_or(true);
+ if !ready {
+ continue;
+ }
+
+ for addr_str in &endpoint.addresses {
+ if let Ok(ip) = addr_str.parse::<IpAddr>() {
+ addrs.insert(SocketAddr::new(ip, port));
+ }
+ }
+ }
+ addrs
+}
+
+impl EndpointDiscovery {
+ pub fn new(
+ client: Client,
+ namespace: String,
+ service_name: String,
+ port: u16,
+ endpoint_config: EndpointConfig,
+ cancel: CancellationToken,
+ ) -> (Channel, DiscoveryReadiness, Self) {
+ let (channel, tx) = Channel::balance_channel::<SocketAddr>(DISCOVERY_CHANNEL_BUFFER);
+ let (ready_tx, ready_rx) = watch::channel(false);
+
+ let discovery = Self {
+ client,
+ namespace,
+ service_name,
+ port,
+ endpoint_config,
+ tx,
+ ready_tx,
+ cancel,
+ };
+
+ (channel, DiscoveryReadiness { rx: ready_rx }, discovery)
+ }
+
+ /// Constructor for unit tests: accepts a pre-built sender so tests can
+ /// observe the change stream without needing a real K8s client or tonic
+ /// balance channel.
+ #[cfg(test)]
+ pub(crate) fn new_for_test(
+ port: u16,
+ tx: Sender<Change<SocketAddr, Endpoint>>,
+ ) -> (Self, DiscoveryReadiness) {
+ let (ready_tx, ready_rx) = watch::channel(false);
+ let discovery = Self {
+ // Safety: this client is never used in tests — `run()` is not
+ // called. The dummy URL keeps construction from panicking.
+ client: kube::Client::try_from(kube::Config::new(
+ "http://localhost:8080".parse().expect("valid test URL"),
+ ))
+ .expect("kube client"),
+ namespace: "test".to_string(),
+ service_name: "test-service".to_string(),
+ port,
+ endpoint_config: EndpointConfig {
+ timeout: Duration::from_secs(5),
+ connect_timeout: Duration::from_secs(2),
+ keepalive_interval: None,
+ keepalive_timeout: None,
+ },
+ tx,
+ ready_tx,
+ cancel: CancellationToken::new(),
+ };
+ (discovery, DiscoveryReadiness { rx: ready_rx })
+ }
+
+ pub async fn run(self) {
+ let api: Api<EndpointSlice> = Api::namespaced(self.client.clone(), &self.namespace);
+ let label_selector = format!("kubernetes.io/service-name={}", self.service_name);
+ let config = WatcherConfig::default().labels(&label_selector);
+
+ info!(
+ service = %self.service_name,
+ namespace = %self.namespace,
+ port = self.port,
+ "starting EndpointSlice discovery"
+ );
+
+ let stream = watcher::watcher(api, config);
+ tokio::pin!(stream);
+
+ // Track addrs per slice name so we can correctly reconcile when one
+ // slice changes without clobbering addrs from other slices.
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ let mut active_addrs: HashSet<SocketAddr> = HashSet::new();
+
+ loop {
+ tokio::select! {
+ _ = self.cancel.cancelled() => {
+ info!("endpoint discovery cancelled");
+ break;
+ }
+ item = stream.next() => {
+ match item {
+ Some(Ok(event)) => {
+ self.handle_event(event, &mut slices, &mut active_addrs).await;
+ }
+ Some(Err(e)) => {
+ warn!(error = %e, "EndpointSlice watcher error, stream will retry");
+ metrics::counter!("personhog_router_discovery_errors_total").increment(1);
+ }
+ None => {
+ warn!("EndpointSlice watcher stream ended unexpectedly");
+ metrics::counter!("personhog_router_discovery_stream_terminated_total").increment(1);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ async fn handle_event(
+ &self,
+ event: Event<EndpointSlice>,
+ slices: &mut HashMap<String, HashSet<SocketAddr>>,
+ active_addrs: &mut HashSet<SocketAddr>,
+ ) {
+ match event {
+ Event::Apply(slice) | Event::InitApply(slice) => {
+ let slice_key = slice
+ .metadata
+ .name
+ .clone()
+ .or_else(|| slice.metadata.uid.clone())
+ .unwrap_or_else(|| "unknown".to_string());
+ let new_addrs = extract_ready_addrs(&slice, self.port);
+ slices.insert(slice_key, new_addrs);
+ self.sync_active(slices, active_addrs).await;
+ }
+ Event::Delete(slice) => {
+ let slice_key = slice
+ .metadata
+ .name
+ .or_else(|| slice.metadata.uid.clone())
+ .unwrap_or_else(|| "unknown".to_string());
+ slices.remove(&slice_key);
+ self.sync_active(slices, active_addrs).await;
+ }
+ Event::Init => {
+ // Clear the slice map but keep active_addrs intact so the
+ // balancer continues serving on stale endpoints during the
+ // re-list. InitApply events will rebuild `slices`, and
+ // InitDone will reconcile against `active_addrs`.
+ slices.clear();
+ }
+ Event::InitDone => {
+ self.sync_active(slices, active_addrs).await;
+ }
+ }
+ }
+
+ async fn sync_active(
+ &self,
+ slices: &HashMap<String, HashSet<SocketAddr>>,
+ active_addrs: &mut HashSet<SocketAddr>,
+ ) {
+ let desired: HashSet<SocketAddr> = slices.values().flatten().copied().collect();
+
+ for addr in desired.difference(active_addrs) {
+ let endpoint = self.build_endpoint(*addr);
+ if self.tx.send(Change::Insert(*addr, endpoint)).await.is_ok() {
+ metrics::counter!("personhog_router_discovery_updates_total", "action" => "insert")
+ .increment(1);
+ }
+ }
+
+ for addr in active_addrs.difference(&desired) {
+ if self.tx.send(Change::Remove(*addr)).await.is_ok() {
+ metrics::counter!("personhog_router_discovery_updates_total", "action" => "remove")
+ .increment(1);
+ }
+ }
+
+ *active_addrs = desired;
+ let count = active_addrs.len();
+ metrics::gauge!("personhog_router_discovery_endpoints_active").set(count as f64);
+ let _ = self.ready_tx.send(count > 0);
+ }
+
+ fn build_endpoint(&self, addr: SocketAddr) -> Endpoint {
+ let mut ep = Endpoint::from_shared(format!("http://{addr}"))
+ .expect("valid endpoint URL")
+ .timeout(self.endpoint_config.timeout)
+ .connect_timeout(self.endpoint_config.connect_timeout)
+ .tcp_nodelay(true);
+
+ if let Some(interval) = self.endpoint_config.keepalive_interval {
+ ep = ep
+ .http2_keep_alive_interval(interval)
+ .keep_alive_while_idle(true);
+ }
+ if let Some(timeout) = self.endpoint_config.keepalive_timeout {
+ ep = ep.keep_alive_timeout(timeout);
+ }
+
+ ep
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::{HashMap, HashSet};
+ use std::net::SocketAddr;
+
+ use k8s_openapi::api::discovery::v1::EndpointSlice;
+ use k8s_openapi::api::discovery::v1::{Endpoint as K8sEndpoint, EndpointConditions};
+ use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
+ use kube::runtime::watcher::Event;
+ use tokio::sync::mpsc;
+ use tonic::transport::Endpoint;
+ use tower::discover::Change;
+
+ use super::{extract_ready_addrs, EndpointDiscovery};
+
+ // ── helpers ──────────────────────────────────────────────────────────────
+
+ fn make_endpoint_with_conditions(addresses: Vec<&str>, ready: Option<bool>) -> K8sEndpoint {
+ K8sEndpoint {
+ addresses: addresses.into_iter().map(str::to_string).collect(),
+ conditions: ready.map(|r| EndpointConditions {
+ ready: Some(r),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+ }
+
+ fn make_endpoint_no_conditions(addresses: Vec<&str>) -> K8sEndpoint {
+ K8sEndpoint {
+ addresses: addresses.into_iter().map(str::to_string).collect(),
+ conditions: None,
+ ..Default::default()
+ }
+ }
+
+ fn make_slice(name: &str, endpoints: Vec<K8sEndpoint>) -> EndpointSlice {
+ EndpointSlice {
+ metadata: ObjectMeta {
+ name: Some(name.to_string()),
+ ..Default::default()
+ },
+ address_type: "IPv4".to_string(),
+ endpoints,
+ ports: None,
+ }
+ }
+
+ fn addr(ip: &str, port: u16) -> SocketAddr {
+ format!("{ip}:{port}").parse().unwrap()
+ }
+
+ /// Drain all pending messages from the receiver without blocking.
+ fn drain_changes(
+ rx: &mut mpsc::Receiver<Change<SocketAddr, Endpoint>>,
+ ) -> Vec<Change<SocketAddr, Endpoint>> {
+ let mut out = Vec::new();
+ while let Ok(msg) = rx.try_recv() {
+ out.push(msg);
+ }
+ out
+ }
+
+ fn inserted_addrs(changes: &[Change<SocketAddr, Endpoint>]) -> HashSet<SocketAddr> {
+ changes
+ .iter()
+ .filter_map(|c| match c {
+ Change::Insert(addr, _) => Some(*addr),
+ Change::Remove(_) => None,
+ })
+ .collect()
+ }
+
+ fn removed_addrs(changes: &[Change<SocketAddr, Endpoint>]) -> HashSet<SocketAddr> {
+ changes
+ .iter()
+ .filter_map(|c| match c {
+ Change::Remove(addr) => Some(*addr),
+ Change::Insert(_, _) => None,
+ })
+ .collect()
+ }
+
+ // ── extract_ready_addrs ───────────────────────────────────────────────────
+
+ #[test]
+ fn extract_ready_addrs_returns_empty_for_empty_slice() {
+ let slice = make_slice("s1", vec![]);
+ let result = extract_ready_addrs(&slice, 50051);
+ assert!(
+ result.is_empty(),
+ "expected empty set for empty EndpointSlice"
+ );
+ }
+
+ #[test]
+ fn extract_ready_addrs_includes_endpoint_with_ready_true() {
+ let slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
+ );
+ let result = extract_ready_addrs(&slice, 50051);
+ assert_eq!(result, HashSet::from([addr("10.0.0.1", 50051)]));
+ }
+
+ #[test]
+ fn extract_ready_addrs_excludes_endpoint_with_ready_false() {
+ let slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(false))],
+ );
+ let result = extract_ready_addrs(&slice, 50051);
+ assert!(
+ result.is_empty(),
+ "ready=false endpoint must not be included"
+ );
+ }
+
+ #[test]
+ fn extract_ready_addrs_includes_endpoint_with_no_conditions() {
+ // Absent conditions field defaults to ready=true per K8s spec.
+ let slice = make_slice("s1", vec![make_endpoint_no_conditions(vec!["10.0.0.2"])]);
+ let result = extract_ready_addrs(&slice, 50051);
+ assert_eq!(result, HashSet::from([addr("10.0.0.2", 50051)]));
+ }
+
+ #[test]
+ fn extract_ready_addrs_includes_endpoint_with_conditions_but_nil_ready() {
+ // Conditions present but ready field is None — also defaults to true.
+ let slice = make_slice(
+ "s1",
+ vec![K8sEndpoint {
+ addresses: vec!["10.0.0.3".to_string()],
+ conditions: Some(EndpointConditions {
+ ready: None,
+ ..Default::default()
+ }),
+ ..Default::default()
+ }],
+ );
+ let result = extract_ready_addrs(&slice, 50051);
+ assert_eq!(result, HashSet::from([addr("10.0.0.3", 50051)]));
+ }
+
+ #[test]
+ fn extract_ready_addrs_uses_provided_port() {
+ let slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
+ );
+ assert_eq!(
+ extract_ready_addrs(&slice, 9090),
+ HashSet::from([addr("10.0.0.1", 9090)]),
+ );
+ assert_eq!(
+ extract_ready_addrs(&slice, 1234),
+ HashSet::from([addr("10.0.0.1", 1234)]),
+ );
+ }
+
+ #[test]
+ fn extract_ready_addrs_skips_unparseable_address() {
+ let slice = make_slice(
+ "s1",
+ vec![K8sEndpoint {
+ addresses: vec!["not-an-ip".to_string(), "10.0.0.5".to_string()],
+ conditions: None,
+ ..Default::default()
+ }],
+ );
+ let result = extract_ready_addrs(&slice, 50051);
+ // The valid address is included; the bad one is silently skipped.
+ assert_eq!(result, HashSet::from([addr("10.0.0.5", 50051)]));
+ }
+
+ #[test]
+ fn extract_ready_addrs_handles_mixed_ready_and_not_ready_endpoints() {
+ let slice = make_slice(
+ "s1",
+ vec![
+ make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true)),
+ make_endpoint_with_conditions(vec!["10.0.0.2"], Some(false)),
+ make_endpoint_no_conditions(vec!["10.0.0.3"]),
+ ],
+ );
+ let result = extract_ready_addrs(&slice, 50051);
+ assert_eq!(
+ result,
+ HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.3", 50051)]),
+ );
+ }
+
+ #[test]
+ fn extract_ready_addrs_handles_multiple_addresses_per_endpoint() {
+ let slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(
+ vec!["10.0.0.1", "10.0.0.2"],
+ Some(true),
+ )],
+ );
+ let result = extract_ready_addrs(&slice, 50051);
+ assert_eq!(
+ result,
+ HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
+ );
+ }
+
+ #[test]
+ fn extract_ready_addrs_handles_ipv6_address() {
+ let slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(vec!["::1"], Some(true))],
+ );
+ let result = extract_ready_addrs(&slice, 50051);
+ assert_eq!(
+ result,
+ HashSet::from(["[::1]:50051".parse::<SocketAddr>().unwrap()])
+ );
+ }
+
+ // ── sync_active ───────────────────────────────────────────────────────────
+
+ #[tokio::test]
+ async fn sync_active_sends_insert_for_new_addr() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
+ let mut active: HashSet<SocketAddr> = HashSet::new();
+
+ discovery.sync_active(&slices, &mut active).await;
+
+ let changes = drain_changes(&mut rx);
+ assert_eq!(
+ inserted_addrs(&changes),
+ HashSet::from([addr("10.0.0.1", 50051)]),
+ "should insert the new addr",
+ );
+ assert!(removed_addrs(&changes).is_empty(), "no removes expected");
+ assert_eq!(active, HashSet::from([addr("10.0.0.1", 50051)]));
+ }
+
+ #[tokio::test]
+ async fn sync_active_sends_remove_for_gone_addr() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
+
+ discovery.sync_active(&slices, &mut active).await;
+
+ let changes = drain_changes(&mut rx);
+ assert!(inserted_addrs(&changes).is_empty(), "no inserts expected");
+ assert_eq!(
+ removed_addrs(&changes),
+ HashSet::from([addr("10.0.0.1", 50051)]),
+ "should remove the addr that disappeared from desired",
+ );
+ assert!(active.is_empty());
+ }
+
+ #[tokio::test]
+ async fn sync_active_noop_when_sets_are_equal() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
+ let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
+
+ discovery.sync_active(&slices, &mut active).await;
+
+ let changes = drain_changes(&mut rx);
+ assert!(
+ changes.is_empty(),
+ "no changes expected when desired == active"
+ );
+ }
+
+ #[tokio::test]
+ async fn sync_active_updates_active_to_desired() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ // Desired: {.1, .2}; Active: {.1, .3}
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert(
+ "s1".to_string(),
+ HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
+ );
+ let mut active: HashSet<SocketAddr> =
+ HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.3", 50051)]);
+
+ discovery.sync_active(&slices, &mut active).await;
+
+ let changes = drain_changes(&mut rx);
+ assert_eq!(
+ inserted_addrs(&changes),
+ HashSet::from([addr("10.0.0.2", 50051)]),
+ "only the new addr is inserted",
+ );
+ assert_eq!(
+ removed_addrs(&changes),
+ HashSet::from([addr("10.0.0.3", 50051)]),
+ "only the gone addr is removed",
+ );
+ assert_eq!(
+ active,
+ HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
+ );
+ }
+
+ #[tokio::test]
+ async fn sync_active_aggregates_addrs_across_slices() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
+ slices.insert("s2".to_string(), HashSet::from([addr("10.0.0.2", 50051)]));
+ let mut active: HashSet<SocketAddr> = HashSet::new();
+
+ discovery.sync_active(&slices, &mut active).await;
+
+ let changes = drain_changes(&mut rx);
+ assert_eq!(
+ inserted_addrs(&changes),
+ HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
+ );
+ }
+
+ // ── handle_event ─────────────────────────────────────────────────────────
+
+ #[tokio::test]
+ async fn handle_event_apply_inserts_ready_addrs() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices = HashMap::new();
+ let mut active = HashSet::new();
+
+ let slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
+ );
+ discovery
+ .handle_event(Event::Apply(slice), &mut slices, &mut active)
+ .await;
+
+ let changes = drain_changes(&mut rx);
+ assert_eq!(
+ inserted_addrs(&changes),
+ HashSet::from([addr("10.0.0.1", 50051)]),
+ );
+ assert_eq!(active, HashSet::from([addr("10.0.0.1", 50051)]));
+ }
+
+ #[tokio::test]
+ async fn handle_event_init_apply_inserts_ready_addrs() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices = HashMap::new();
+ let mut active = HashSet::new();
+
+ let slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(vec!["10.0.0.2"], Some(true))],
+ );
+ discovery
+ .handle_event(Event::InitApply(slice), &mut slices, &mut active)
+ .await;
+
+ let changes = drain_changes(&mut rx);
+ assert_eq!(
+ inserted_addrs(&changes),
+ HashSet::from([addr("10.0.0.2", 50051)]),
+ );
+ }
+
+ #[tokio::test]
+ async fn handle_event_delete_removes_slice_addrs_and_syncs() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
+ let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
+
+ let slice = make_slice("s1", vec![]);
+ discovery
+ .handle_event(Event::Delete(slice), &mut slices, &mut active)
+ .await;
+
+ let changes = drain_changes(&mut rx);
+ assert_eq!(
+ removed_addrs(&changes),
+ HashSet::from([addr("10.0.0.1", 50051)]),
+ "delete should trigger removal of the slice's addrs",
+ );
+ assert!(active.is_empty());
+ assert!(!slices.contains_key("s1"), "slice entry should be gone");
+ }
+
+ #[tokio::test]
+ async fn handle_event_delete_one_slice_does_not_remove_other_slice_addrs() {
+ // Critical multi-slice test: deleting s1 must not touch s2's addrs.
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
+ slices.insert("s2".to_string(), HashSet::from([addr("10.0.0.2", 50051)]));
+ let mut active: HashSet<SocketAddr> =
+ HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]);
+
+ let slice = make_slice("s1", vec![]);
+ discovery
+ .handle_event(Event::Delete(slice), &mut slices, &mut active)
+ .await;
+
+ let changes = drain_changes(&mut rx);
+ assert_eq!(
+ removed_addrs(&changes),
+ HashSet::from([addr("10.0.0.1", 50051)]),
+ "only s1's addr is removed",
+ );
+ assert!(
+ inserted_addrs(&changes).is_empty(),
+ "s2's addr is still active and must not be re-inserted",
+ );
+ assert_eq!(
+ active,
+ HashSet::from([addr("10.0.0.2", 50051)]),
+ "s2's addr must remain in the active set",
+ );
+ }
+
+ #[tokio::test]
+ async fn handle_event_init_clears_slices_but_preserves_active_addrs() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
+ let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
+
+ discovery
+ .handle_event(Event::Init, &mut slices, &mut active)
+ .await;
+
+ let changes = drain_changes(&mut rx);
+ assert!(
+ changes.is_empty(),
+ "Init must not send any changes — stale endpoints stay in the balancer during re-list",
+ );
+ assert_eq!(
+ active,
+ HashSet::from([addr("10.0.0.1", 50051)]),
+ "active_addrs must be preserved so the balancer keeps serving during re-list",
+ );
+ assert!(slices.is_empty(), "slices map must be cleared for re-list");
+ }
+
+ #[tokio::test]
+ async fn handle_event_init_noop_when_no_active_addrs() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices = HashMap::new();
+ let mut active: HashSet<SocketAddr> = HashSet::new();
+
+ discovery
+ .handle_event(Event::Init, &mut slices, &mut active)
+ .await;
+
+ let changes = drain_changes(&mut rx);
+ assert!(
+ changes.is_empty(),
+ "Init with no active addrs sends nothing"
+ );
+ }
+
+ #[tokio::test]
+ async fn handle_event_init_done_reconciles_active_with_slices() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ // Simulate post-re-list state: slices has the fresh set, active_addrs
+ // still has stale endpoints from before Init.
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.2", 50051)]));
+ let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
+
+ discovery
+ .handle_event(Event::InitDone, &mut slices, &mut active)
+ .await;
+
+ let changes = drain_changes(&mut rx);
+ assert_eq!(
+ inserted_addrs(&changes),
+ HashSet::from([addr("10.0.0.2", 50051)]),
+ "new addr from re-listed slice is inserted",
+ );
+ assert_eq!(
+ removed_addrs(&changes),
+ HashSet::from([addr("10.0.0.1", 50051)]),
+ "stale addr not in re-listed slices is removed",
+ );
+ assert_eq!(
+ active,
+ HashSet::from([addr("10.0.0.2", 50051)]),
+ "active matches the re-listed state",
+ );
+ }
+
+ #[tokio::test]
+ async fn handle_event_init_done_noop_when_active_matches_slices() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
+ let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
+
+ discovery
+ .handle_event(Event::InitDone, &mut slices, &mut active)
+ .await;
+
+ let changes = drain_changes(&mut rx);
+ assert!(
+ changes.is_empty(),
+ "no changes when active already matches re-listed slices",
+ );
+ }
+
+ #[tokio::test]
+ async fn handle_event_apply_updates_existing_slice_addrs() {
+ // Simulates a pod being replaced: the same slice name gets new addrs.
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
+ let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
+
+ let updated_slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(vec!["10.0.0.9"], Some(true))],
+ );
+ discovery
+ .handle_event(Event::Apply(updated_slice), &mut slices, &mut active)
+ .await;
+
+ let changes = drain_changes(&mut rx);
+ assert_eq!(
+ inserted_addrs(&changes),
+ HashSet::from([addr("10.0.0.9", 50051)]),
+ "new addr is inserted",
+ );
+ assert_eq!(
+ removed_addrs(&changes),
+ HashSet::from([addr("10.0.0.1", 50051)]),
+ "old addr is removed",
+ );
+ assert_eq!(active, HashSet::from([addr("10.0.0.9", 50051)]));
+ }
+
+ #[tokio::test]
+ async fn handle_event_apply_slice_without_name_falls_back_to_uid() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices = HashMap::new();
+ let mut active = HashSet::new();
+
+ let mut slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
+ );
+ slice.metadata.name = None;
+ slice.metadata.uid = Some("abc-123".to_string());
+
+ discovery
+ .handle_event(Event::Apply(slice), &mut slices, &mut active)
+ .await;
+
+ assert!(
+ slices.contains_key("abc-123"),
+ "unnamed slice stored under UID key"
+ );
+ let changes = drain_changes(&mut rx);
+ assert!(
+ !inserted_addrs(&changes).is_empty(),
+ "addr is still inserted"
+ );
+ }
+
+ #[tokio::test]
+ async fn handle_event_apply_slice_without_name_or_uid_uses_unknown() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices = HashMap::new();
+ let mut active = HashSet::new();
+
+ let mut slice = make_slice(
+ "s1",
+ vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
+ );
+ slice.metadata.name = None;
+ slice.metadata.uid = None;
+
+ discovery
+ .handle_event(Event::Apply(slice), &mut slices, &mut active)
+ .await;
+
+ assert!(
+ slices.contains_key("unknown"),
+ "slice with no name or UID stored under 'unknown' key"
+ );
+ let changes = drain_changes(&mut rx);
+ assert!(
+ !inserted_addrs(&changes).is_empty(),
+ "addr is still inserted"
+ );
+ }
+
+ // ── Init → re-list → InitDone full flow ─────────────────────────────────
+
+ #[tokio::test]
+ async fn relist_flow_preserves_endpoints_and_reconciles_on_init_done() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+
+ let mut slices = HashMap::new();
+ let mut active = HashSet::new();
+
+ // Initial state: two pods discovered.
+ let slice = make_slice(
+ "s1",
+ vec![
+ make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true)),
+ make_endpoint_with_conditions(vec!["10.0.0.2"], Some(true)),
+ ],
+ );
+ discovery
+ .handle_event(Event::Apply(slice), &mut slices, &mut active)
+ .await;
+ drain_changes(&mut rx);
+
+ // API server drops the watch — Init fires.
+ discovery
+ .handle_event(Event::Init, &mut slices, &mut active)
+ .await;
+ let changes = drain_changes(&mut rx);
+ assert!(
+ changes.is_empty(),
+ "Init must not send any removes — stale endpoints stay in the balancer",
+ );
+ assert_eq!(
+ active,
+ HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
+ "active_addrs preserved during re-list",
+ );
+
+ // Re-list: pod .2 is gone, pod .3 is new.
+ let relisted_slice = make_slice(
+ "s1",
+ vec![
+ make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true)),
+ make_endpoint_with_conditions(vec!["10.0.0.3"], Some(true)),
+ ],
+ );
+ discovery
+ .handle_event(Event::InitApply(relisted_slice), &mut slices, &mut active)
+ .await;
+ // InitApply calls sync_active, but we want to verify the full flow
+ // through InitDone, so drain these intermediate changes.
+ drain_changes(&mut rx);
+
+ // InitDone signals re-list is complete.
+ discovery
+ .handle_event(Event::InitDone, &mut slices, &mut active)
+ .await;
+ let final_changes = drain_changes(&mut rx);
+
+ // At this point active should exactly match the re-listed state.
+ assert_eq!(
+ active,
+ HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.3", 50051)]),
+ "active reflects re-listed endpoints",
+ );
+ // InitDone sync_active is a no-op here because InitApply already reconciled.
+ assert!(
+ final_changes.is_empty(),
+ "InitDone is a no-op when InitApply already reconciled",
+ );
+ }
+}
diff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rs
index 1771e3d5605d..131cde02556d 100644
--- a/rust/personhog-router/src/backend/leader.rs
+++ b/rust/personhog-router/src/backend/leader.rs
@@ -24,9 +24,8 @@ use crate::config::RetryConfig;
pub type AddressResolver = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
-/// Static configuration for `LeaderBackend`. Mirrors `ReplicaBackendConfig`
-/// in the same crate; bundles the knobs that come from `Config` so the
-/// constructor stays narrow as we add fields.
+/// Static configuration for `LeaderBackend`. Bundles the knobs that come
+/// from `Config` so the constructor stays narrow as we add fields.
pub struct LeaderBackendConfig {
pub num_partitions: u32,
pub timeout: Duration,
diff --git a/rust/personhog-router/src/backend/mod.rs b/rust/personhog-router/src/backend/mod.rs
index 9fe6ce13c405..47568c35ea4a 100644
--- a/rust/personhog-router/src/backend/mod.rs
+++ b/rust/personhog-router/src/backend/mod.rs
@@ -1,10 +1,11 @@
+pub mod discovery;
mod leader;
mod replica;
mod retry;
mod stash;
pub use leader::{AddressResolver, LeaderBackend, LeaderBackendConfig};
-pub use replica::{ReplicaBackend, ReplicaBackendConfig};
+pub use replica::{ReplicaBackend, ReplicaDnsConfig};
pub use stash::{StashDecision, StashTable, StashedRequest};
use async_trait::async_trait;
diff --git a/rust/personhog-router/src/backend/replica.rs b/rust/personhog-router/src/backend/replica.rs
index 1e181fa84f79..7d94f1afa6f6 100644
--- a/rust/personhog-router/src/backend/replica.rs
+++ b/rust/personhog-router/src/backend/replica.rs
@@ -1,3 +1,5 @@
+use std::sync::atomic::{AtomicUsize, Ordering};
+
use async_trait::async_trait;
use personhog_proto::personhog::replica::v1::person_hog_replica_client::PersonHogReplicaClient;
use personhog_proto::personhog::types::v1::{
@@ -26,7 +28,6 @@ use personhog_proto::personhog::types::v1::{
UpdateGroupRequest, UpdateGroupResponse, UpdateGroupTypeMappingRequest,
UpdateGroupTypeMappingResponse, UpsertHashKeyOverridesRequest, UpsertHashKeyOverridesResponse,
};
-use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use tonic::codec::CompressionEncoding;
use tonic::transport::{Channel, Endpoint};
@@ -39,30 +40,15 @@ use super::retry::with_retry;
use super::PersonHogBackend;
use crate::config::RetryConfig;
-/// Backend implementation that forwards requests to a personhog-replica service
-/// using separate heavy/light gRPC channel pools with round-robin selection.
-///
-/// Heavy channels carry RPCs that return Person/Group objects with large JSON
-/// property blobs. Light channels carry everything else (group type mappings,
-/// cohort checks, scalar responses). This isolation prevents TCP head-of-line
-/// blocking from large responses stalling small ones on shared HTTP/2 connections.
-///
-/// Connection lifecycle is managed server-side via `max_connection_age` on the
-/// replica's gRPC server, which sends GOAWAY to trigger transparent client
-/// reconnects — no client-side recycling needed.
pub struct ReplicaBackend {
- heavy_clients: Vec<PersonHogReplicaClient<Channel>>,
- heavy_raw_channels: Vec<Channel>,
- heavy_next_idx: AtomicUsize,
- light_clients: Vec<PersonHogReplicaClient<Channel>>,
- light_raw_channels: Vec<Channel>,
- light_next_idx: AtomicUsize,
+ clients: Vec<PersonHogReplicaClient<Channel>>,
+ channels: Vec<Channel>,
+ next_idx: AtomicUsize,
retry_config: RetryConfig,
}
-/// Configuration for creating replica backend channels.
#[derive(Clone)]
-pub struct ReplicaBackendConfig {
+pub struct ReplicaDnsConfig {
pub url: String,
pub timeout: Duration,
pub retry_config: RetryConfig,
@@ -71,48 +57,9 @@ pub struct ReplicaBackendConfig {
pub max_send_message_size: usize,
pub max_recv_message_size: usize,
pub num_channels: usize,
- pub num_light_channels: usize,
}
-/// RPCs whose responses contain only small/scalar data (no Person/Group objects
-/// with JSON property blobs). These are routed to dedicated light channels to
-/// isolate them from TCP head-of-line blocking caused by large responses.
-///
-/// Must be sorted — used with binary_search.
-const LIGHT_METHODS: &[&str] = &[
- "CheckCohortMembership",
- "CountCohortMembers",
- "CountGroupTypeMappings",
- "DeleteCohortMember",
- "DeleteCohortMembersBulk",
- "DeleteGroupTypeMapping",
- "DeleteGroupTypeMappingsBatchForTeam",
- "DeleteGroupsBatchForTeam",
- "DeleteHashKeyOverridesByTeams",
- "DeletePersons",
- "DeletePersonsBatchForTeam",
- "GetDistinctIdsForPerson",
- "GetGroupTypeMappingByDashboardId",
- "GetGroupTypeMappingsByProjectId",
- "GetGroupTypeMappingsByProjectIds",
- "GetGroupTypeMappingsByTeamId",
- "GetGroupTypeMappingsByTeamIds",
- "GetHashKeyOverrideContext",
- "InsertCohortMembers",
- "UpdateGroupTypeMapping",
- "UpsertHashKeyOverrides",
-];
-
-pub fn is_light_method(method: &str) -> bool {
- LIGHT_METHODS.binary_search(&method).is_ok()
-}
-
-/// RPCs that bypass the replica channel pools entirely (routed to leader via
-/// typed proxy in proxy.rs). Excluded from the retry_call! coverage check.
-#[cfg(test)]
-const LEADER_ONLY_METHODS: &[&str] = &["UpdatePersonProperties"];
-
-fn build_endpoint(config: &ReplicaBackendConfig) -> Endpoint {
+fn build_dns_endpoint(config: &ReplicaDnsConfig) -> Endpoint {
let mut endpoint = Channel::from_shared(config.url.clone())
.unwrap_or_else(|e| panic!("invalid replica URL '{}': {e}", config.url))
.timeout(config.timeout)
@@ -128,88 +75,81 @@ fn build_endpoint(config: &ReplicaBackendConfig) -> Endpoint {
endpoint
}
-fn create_channels(config: &ReplicaBackendConfig) -> Vec<Channel> {
- (0..config.num_channels)
- .map(|_| build_endpoint(config).connect_lazy())
- .collect()
-}
-
-fn wrap_clients(
- channels: &[Channel],
- config: &ReplicaBackendConfig,
-) -> Vec<PersonHogReplicaClient<Channel>> {
- channels
- .iter()
- .map(|channel| {
- PersonHogReplicaClient::new(channel.clone())
- .max_encoding_message_size(config.max_send_message_size)
- .max_decoding_message_size(config.max_recv_message_size)
- .send_compressed(CompressionEncoding::Zstd)
- .accept_compressed(CompressionEncoding::Zstd)
- })
- .collect()
+fn wrap_client(
+ channel: &Channel,
+ max_send_message_size: usize,
+ max_recv_message_size: usize,
+) -> PersonHogReplicaClient<Channel> {
+ PersonHogReplicaClient::new(channel.clone())
+ .max_encoding_message_size(max_send_message_size)
+ .max_decoding_message_size(max_recv_message_size)
+ .send_compressed(CompressionEncoding::Zstd)
+ .accept_compressed(CompressionEncoding::Zstd)
}
impl ReplicaBackend {
- pub fn new(config: ReplicaBackendConfig) -> Self {
- let retry_config = config.retry_config;
- let num_heavy = config.num_channels.max(1);
- let num_light = config.num_light_channels.max(1);
-
- let heavy_config = ReplicaBackendConfig {
- num_channels: num_heavy,
- ..config.clone()
- };
- let light_config = ReplicaBackendConfig {
- num_channels: num_light,
- ..config
- };
-
- let heavy_raw_channels = create_channels(&heavy_config);
- let heavy_clients = wrap_clients(&heavy_raw_channels, &heavy_config);
-
- let light_raw_channels = create_channels(&light_config);
- let light_clients = wrap_clients(&light_raw_channels, &light_config);
+ /// DNS discovery: opens multiple lazy channels to the ClusterIP service URL
+ /// with round-robin selection across them.
+ pub fn new_dns(config: ReplicaDnsConfig) -> Self {
+ let num = config.num_channels.max(1);
+ let channels: Vec<Channel> = (0..num)
+ .map(|_| build_dns_endpoint(&config).connect_lazy())
+ .collect();
+ let clients: Vec<_> = channels
+ .iter()
+ .map(|ch| {
+ wrap_client(
+ ch,
+ config.max_send_message_size,
+ config.max_recv_message_size,
+ )
+ })
+ .collect();
info!(
- num_heavy,
- num_light,
- url = heavy_config.url,
- "created replica backend channels"
+ url = config.url,
+ num_channels = num,
+ mode = "dns",
+ "created replica backend"
);
Self {
- heavy_clients,
- heavy_raw_channels,
- heavy_next_idx: AtomicUsize::new(0),
- light_clients,
- light_raw_channels,
- light_next_idx: AtomicUsize::new(0),
- retry_config,
+ clients,
+ channels,
+ next_idx: AtomicUsize::new(0),
+ retry_config: config.retry_config,
}
}
- fn next_heavy_client(&self) -> PersonHogReplicaClient<Channel> {
- let idx = self.heavy_next_idx.fetch_add(1, Ordering::Relaxed) % self.heavy_clients.len();
- self.heavy_clients[idx].clone()
+ /// 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,
+ max_send_message_size: usize,
+ max_recv_message_size: usize,
+ ) -> Self {
+ let client = wrap_client(&channel, max_send_message_size, max_recv_message_size);
+
+ info!(mode = "k8s", "created replica backend");
+
+ Self {
+ clients: vec![client],
+ channels: vec![channel],
+ next_idx: AtomicUsize::new(0),
+ retry_config,
+ }
}
- fn next_light_client(&self) -> PersonHogReplicaClient<Channel> {
- let idx = self.light_next_idx.fetch_add(1, Ordering::Relaxed) % self.light_clients.len();
- self.light_clients[idx].clone()
+ fn client(&self) -> PersonHogReplicaClient<Channel> {
+ let idx = self.next_idx.fetch_add(1, Ordering::Relaxed) % self.clients.len();
+ self.clients[idx].clone()
}
- /// Get the next raw channel for byte-level proxying, routed by method weight.
- pub fn next_raw_channel_for(&self, method: &str) -> Channel {
- if is_light_method(method) {
- let idx =
- self.light_next_idx.fetch_add(1, Ordering::Relaxed) % self.light_raw_channels.len();
- self.light_raw_channels[idx].clone()
- } else {
- let idx =
- self.heavy_next_idx.fetch_add(1, Ordering::Relaxed) % self.heavy_raw_channels.len();
- self.heavy_raw_channels[idx].clone()
- }
+ pub fn channel(&self) -> Channel {
+ let idx = self.next_idx.fetch_add(1, Ordering::Relaxed) % self.channels.len();
+ self.channels[idx].clone()
}
pub fn retry_config(&self) -> &RetryConfig {
@@ -217,17 +157,10 @@ impl ReplicaBackend {
}
}
-/// Wraps a gRPC call with retry logic. Clones the request for each attempt.
-/// Forwards `x-client-name` and `x-caller-tag` headers so the downstream
-/// service can attribute metrics to the originating client and code path.
-///
-/// The `$client_fn` parameter selects the channel pool: `next_heavy_client`
-/// for RPCs returning large Person/Group payloads, `next_light_client` for
-/// small/scalar responses.
macro_rules! retry_call {
- ($self:expr, $client_fn:ident, $method:ident, $request:expr) => {{
+ ($self:expr, $method:ident, $request:expr) => {{
with_retry(&$self.retry_config, stringify!($method), || {
- let mut client = $self.$client_fn();
+ let mut client = $self.client();
let req = $request.clone();
let client_name = current_client_name();
let caller_tag = current_caller_tag();
@@ -246,337 +179,248 @@ macro_rules! retry_call {
}};
}
+/// RPCs that bypass the replica channel pools entirely (routed to leader via
+/// typed proxy in proxy.rs). Excluded from the retry_call! coverage check.
+#[cfg(test)]
+const LEADER_ONLY_METHODS: &[&str] = &["UpdatePersonProperties"];
+
#[async_trait]
impl PersonHogBackend for ReplicaBackend {
- // ── Heavy: Person lookups (return Person objects with properties) ───
-
async fn get_person(&self, request: GetPersonRequest) -> Result<GetPersonResponse, Status> {
- retry_call!(self, next_heavy_client, get_person, request)
+ retry_call!(self, get_person, request)
}
async fn get_persons(&self, request: GetPersonsRequest) -> Result<PersonsResponse, Status> {
- retry_call!(self, next_heavy_client, get_persons, request)
+ retry_call!(self, get_persons, request)
}
async fn get_person_by_uuid(
&self,
request: GetPersonByUuidRequest,
) -> Result<GetPersonResponse, Status> {
- retry_call!(self, next_heavy_client, get_person_by_uuid, request)
+ retry_call!(self, get_person_by_uuid, request)
}
async fn get_persons_by_uuids(
&self,
request: GetPersonsByUuidsRequest,
) -> Result<PersonsResponse, Status> {
- retry_call!(self, next_heavy_client, get_persons_by_uuids, request)
+ retry_call!(self, get_persons_by_uuids, request)
}
async fn get_person_by_distinct_id(
&self,
request: GetPersonByDistinctIdRequest,
) -> Result<GetPersonResponse, Status> {
- retry_call!(self, next_heavy_client, get_person_by_distinct_id, request)
+ retry_call!(self, get_person_by_distinct_id, request)
}
async fn get_persons_by_distinct_ids_in_team(
&self,
request: GetPersonsByDistinctIdsInTeamRequest,
) -> Result<PersonsByDistinctIdsInTeamResponse, Status> {
- retry_call!(
- self,
- next_heavy_client,
- get_persons_by_distinct_ids_in_team,
- request
- )
+ retry_call!(self, get_persons_by_distinct_ids_in_team, request)
}
async fn get_persons_by_distinct_ids(
&self,
request: GetPersonsByDistinctIdsRequest,
) -> Result<PersonsByDistinctIdsResponse, Status> {
- retry_call!(
- self,
- next_heavy_client,
- get_persons_by_distinct_ids,
- request
- )
+ retry_call!(self, get_persons_by_distinct_ids, request)
}
- // ── Light: Distinct ID for single person (bounded string list) ───
-
async fn get_distinct_ids_for_person(
&self,
request: GetDistinctIdsForPersonRequest,
) -> Result<GetDistinctIdsForPersonResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- get_distinct_ids_for_person,
- request
- )
+ retry_call!(self, get_distinct_ids_for_person, request)
}
- // ── Heavy: Distinct IDs for multiple persons (p99: 540 rows EU) ──
-
async fn get_distinct_ids_for_persons(
&self,
request: GetDistinctIdsForPersonsRequest,
) -> Result<GetDistinctIdsForPersonsResponse, Status> {
- retry_call!(
- self,
- next_heavy_client,
- get_distinct_ids_for_persons,
- request
- )
+ retry_call!(self, get_distinct_ids_for_persons, request)
}
- // ── Light: Feature flag hash key overrides (small structs/scalars) ─
-
async fn get_hash_key_override_context(
&self,
request: GetHashKeyOverrideContextRequest,
) -> Result<GetHashKeyOverrideContextResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- get_hash_key_override_context,
- request
- )
+ retry_call!(self, get_hash_key_override_context, request)
}
async fn upsert_hash_key_overrides(
&self,
request: UpsertHashKeyOverridesRequest,
) -> Result<UpsertHashKeyOverridesResponse, Status> {
- retry_call!(self, next_light_client, upsert_hash_key_overrides, request)
+ retry_call!(self, upsert_hash_key_overrides, request)
}
async fn delete_hash_key_overrides_by_teams(
&self,
request: DeleteHashKeyOverridesByTeamsRequest,
) -> Result<DeleteHashKeyOverridesByTeamsResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- delete_hash_key_overrides_by_teams,
- request
- )
+ retry_call!(self, delete_hash_key_overrides_by_teams, request)
}
- // ── Light: Person deletes (scalar responses) ─────────────────────
-
async fn delete_persons(
&self,
request: DeletePersonsRequest,
) -> Result<DeletePersonsResponse, Status> {
- retry_call!(self, next_light_client, delete_persons, request)
+ retry_call!(self, delete_persons, request)
}
async fn delete_persons_batch_for_team(
&self,
request: DeletePersonsBatchForTeamRequest,
) -> Result<DeletePersonsBatchForTeamResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- delete_persons_batch_for_team,
- request
- )
+ retry_call!(self, delete_persons_batch_for_team, request)
}
- // ── Light: Cohort membership (small/scalar responses) ────────────
-
async fn check_cohort_membership(
&self,
request: CheckCohortMembershipRequest,
) -> Result<CohortMembershipResponse, Status> {
- retry_call!(self, next_light_client, check_cohort_membership, request)
+ retry_call!(self, check_cohort_membership, request)
}
async fn count_cohort_members(
&self,
request: CountCohortMembersRequest,
) -> Result<CountCohortMembersResponse, Status> {
- retry_call!(self, next_light_client, count_cohort_members, request)
+ retry_call!(self, count_cohort_members, request)
}
async fn delete_cohort_member(
&self,
request: DeleteCohortMemberRequest,
) -> Result<DeleteCohortMemberResponse, Status> {
- retry_call!(self, next_light_client, delete_cohort_member, request)
+ retry_call!(self, delete_cohort_member, request)
}
async fn delete_cohort_members_bulk(
&self,
request: DeleteCohortMembersBulkRequest,
) -> Result<DeleteCohortMembersBulkResponse, Status> {
- retry_call!(self, next_light_client, delete_cohort_members_bulk, request)
+ retry_call!(self, delete_cohort_members_bulk, request)
}
async fn insert_cohort_members(
&self,
request: InsertCohortMembersRequest,
) -> Result<InsertCohortMembersResponse, Status> {
- retry_call!(self, next_light_client, insert_cohort_members, request)
+ retry_call!(self, insert_cohort_members, request)
}
- // ── Heavy: ListCohortMemberIds (unbounded repeated int64) ────────
-
async fn list_cohort_member_ids(
&self,
request: ListCohortMemberIdsRequest,
) -> Result<ListCohortMemberIdsResponse, Status> {
- retry_call!(self, next_heavy_client, list_cohort_member_ids, request)
+ retry_call!(self, list_cohort_member_ids, request)
}
- // ── Heavy: Group reads (return Group objects with properties) ─────
-
async fn get_group(&self, request: GetGroupRequest) -> Result<GetGroupResponse, Status> {
- retry_call!(self, next_heavy_client, get_group, request)
+ retry_call!(self, get_group, request)
}
async fn get_groups(&self, request: GetGroupsRequest) -> Result<GroupsResponse, Status> {
- retry_call!(self, next_heavy_client, get_groups, request)
+ retry_call!(self, get_groups, request)
}
async fn get_groups_batch(
&self,
request: GetGroupsBatchRequest,
) -> Result<GetGroupsBatchResponse, Status> {
- retry_call!(self, next_heavy_client, get_groups_batch, request)
+ retry_call!(self, get_groups_batch, request)
}
async fn list_groups(&self, request: ListGroupsRequest) -> Result<ListGroupsResponse, Status> {
- retry_call!(self, next_heavy_client, list_groups, request)
+ retry_call!(self, list_groups, request)
}
- // ── Light: Group type mappings (small struct rows, no JSON blobs) ─
-
async fn get_group_type_mappings_by_team_id(
&self,
request: GetGroupTypeMappingsByTeamIdRequest,
) -> Result<GroupTypeMappingsResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- get_group_type_mappings_by_team_id,
- request
- )
+ retry_call!(self, get_group_type_mappings_by_team_id, request)
}
async fn get_group_type_mappings_by_team_ids(
&self,
request: GetGroupTypeMappingsByTeamIdsRequest,
) -> Result<GroupTypeMappingsBatchResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- get_group_type_mappings_by_team_ids,
- request
- )
+ retry_call!(self, get_group_type_mappings_by_team_ids, request)
}
async fn get_group_type_mappings_by_project_id(
&self,
request: GetGroupTypeMappingsByProjectIdRequest,
) -> Result<GroupTypeMappingsResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- get_group_type_mappings_by_project_id,
- request
- )
+ retry_call!(self, get_group_type_mappings_by_project_id, request)
}
async fn get_group_type_mappings_by_project_ids(
&self,
request: GetGroupTypeMappingsByProjectIdsRequest,
) -> Result<GroupTypeMappingsBatchResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- get_group_type_mappings_by_project_ids,
- request
- )
+ retry_call!(self, get_group_type_mappings_by_project_ids, request)
}
async fn count_group_type_mappings(
&self,
request: CountGroupTypeMappingsRequest,
) -> Result<CountGroupTypeMappingsResponse, Status> {
- retry_call!(self, next_light_client, count_group_type_mappings, request)
+ retry_call!(self, count_group_type_mappings, request)
}
async fn get_group_type_mapping_by_dashboard_id(
&self,
request: GetGroupTypeMappingByDashboardIdRequest,
) -> Result<GetGroupTypeMappingByDashboardIdResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- get_group_type_mapping_by_dashboard_id,
- request
- )
+ retry_call!(self, get_group_type_mapping_by_dashboard_id, request)
}
- // ── Heavy: Group writes (return Group objects with properties) ────
-
async fn create_group(
&self,
request: CreateGroupRequest,
) -> Result<CreateGroupResponse, Status> {
- retry_call!(self, next_heavy_client, create_group, request)
+ retry_call!(self, create_group, request)
}
async fn update_group(
&self,
request: UpdateGroupRequest,
) -> Result<UpdateGroupResponse, Status> {
- retry_call!(self, next_heavy_client, update_group, request)
+ retry_call!(self, update_group, request)
}
- // ── Light: Group batch delete (scalar response) ──────────────────
-
async fn delete_groups_batch_for_team(
&self,
request: DeleteGroupsBatchForTeamRequest,
) -> Result<DeleteGroupsBatchForTeamResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- delete_groups_batch_for_team,
- request
- )
+ retry_call!(self, delete_groups_batch_for_team, request)
}
- // ── Light: Group type mapping writes (small struct/scalar) ───────
-
async fn update_group_type_mapping(
&self,
request: UpdateGroupTypeMappingRequest,
) -> Result<UpdateGroupTypeMappingResponse, Status> {
- retry_call!(self, next_light_client, update_group_type_mapping, request)
+ retry_call!(self, update_group_type_mapping, request)
}
async fn delete_group_type_mapping(
&self,
request: DeleteGroupTypeMappingRequest,
) -> Result<DeleteGroupTypeMappingResponse, Status> {
- retry_call!(self, next_light_client, delete_group_type_mapping, request)
+ retry_call!(self, delete_group_type_mapping, request)
}
async fn delete_group_type_mappings_batch_for_team(
&self,
request: DeleteGroupTypeMappingsBatchForTeamRequest,
) -> Result<DeleteGroupTypeMappingsBatchForTeamResponse, Status> {
- retry_call!(
- self,
- next_light_client,
- delete_group_type_mappings_batch_for_team,
- request
- )
+ retry_call!(self, delete_group_type_mappings_batch_for_team, request)
}
}
@@ -585,8 +429,8 @@ mod tests {
use super::*;
use crate::proxy::KNOWN_METHODS;
- fn make_backend(num_heavy: usize, num_light: usize) -> ReplicaBackend {
- ReplicaBackend::new(ReplicaBackendConfig {
+ fn make_backend() -> ReplicaBackend {
+ ReplicaBackend::new_dns(ReplicaDnsConfig {
url: "http://localhost:50051".to_string(),
timeout: Duration::from_secs(1),
retry_config: RetryConfig {
@@ -598,119 +442,15 @@ mod tests {
keepalive_timeout: None,
max_send_message_size: 4 * 1024 * 1024,
max_recv_message_size: 4 * 1024 * 1024,
- num_channels: num_heavy,
- num_light_channels: num_light,
+ num_channels: 4,
})
}
#[tokio::test]
- async fn heavy_client_round_robins_across_channels() {
- let backend = make_backend(4, 2);
- for round in 0..3u64 {
- for ch in 0..4u64 {
- backend.next_heavy_client();
- let expected = round * 4 + ch + 1;
- assert_eq!(
- backend.heavy_next_idx.load(Ordering::Relaxed),
- expected as usize
- );
- }
- }
- }
-
- #[tokio::test]
- async fn light_client_round_robins_across_channels() {
- let backend = make_backend(4, 2);
- for round in 0..3u64 {
- for ch in 0..2u64 {
- backend.next_light_client();
- let expected = round * 2 + ch + 1;
- assert_eq!(
- backend.light_next_idx.load(Ordering::Relaxed),
- expected as usize
- );
- }
- }
- }
-
- #[tokio::test]
- async fn heavy_and_light_pools_are_independent() {
- let backend = make_backend(4, 2);
- for _ in 0..5 {
- backend.next_heavy_client();
- }
- assert_eq!(backend.heavy_next_idx.load(Ordering::Relaxed), 5);
- assert_eq!(backend.light_next_idx.load(Ordering::Relaxed), 0);
-
- for _ in 0..3 {
- backend.next_light_client();
- }
- assert_eq!(backend.heavy_next_idx.load(Ordering::Relaxed), 5);
- assert_eq!(backend.light_next_idx.load(Ordering::Relaxed), 3);
- }
-
- #[tokio::test]
- async fn heavy_client_wraps_around() {
- let backend = make_backend(3, 2);
- for _ in 0..3 {
- backend.next_heavy_client();
- }
- let idx_before = backend.heavy_next_idx.load(Ordering::Relaxed);
- backend.next_heavy_client();
- assert_eq!(idx_before % backend.heavy_clients.len(), 0);
- }
-
- #[tokio::test]
- async fn num_channels_floors_to_one() {
- let backend = make_backend(0, 0);
- assert_eq!(backend.heavy_clients.len(), 1);
- assert_eq!(backend.light_clients.len(), 1);
- }
-
- #[test]
- fn light_methods_is_sorted() {
- for window in LIGHT_METHODS.windows(2) {
- assert!(
- window[0] < window[1],
- "LIGHT_METHODS is not sorted: {:?} should come after {:?}",
- window[0],
- window[1],
- );
- }
- }
-
- #[test]
- fn light_methods_are_all_known() {
- for method in LIGHT_METHODS {
- assert!(
- KNOWN_METHODS.contains(method),
- "LIGHT_METHODS contains unknown method: {method}"
- );
- }
- }
-
- #[test]
- fn classification_correctness() {
- // Light methods
- assert!(is_light_method("GetGroupTypeMappingsByProjectIds"));
- assert!(is_light_method("GetGroupTypeMappingsByTeamIds"));
- assert!(is_light_method("CheckCohortMembership"));
- assert!(is_light_method("GetHashKeyOverrideContext"));
- assert!(is_light_method("DeletePersons"));
- assert!(is_light_method("GetDistinctIdsForPerson"));
-
- // Heavy methods
- assert!(!is_light_method("GetPerson"));
- assert!(!is_light_method("GetPersonsByDistinctIds"));
- assert!(!is_light_method("GetGroupsBatch"));
- assert!(!is_light_method("GetGroups"));
- assert!(!is_light_method("GetDistinctIdsForPersons"));
- assert!(!is_light_method("ListCohortMemberIds"));
- assert!(!is_light_method("CreateGroup"));
-
- // Unknown methods default to heavy
- assert!(!is_light_method("FakeMethod"));
- assert!(!is_light_method(""));
+ async fn channel_is_cloneable() {
+ let backend = make_backend();
+ let _ch1 = backend.channel();
+ let _ch2 = backend.channel();
}
fn snake_to_pascal(s: &str) -> String {
@@ -726,18 +466,15 @@ mod tests {
}
#[test]
- fn typed_proxy_annotations_match_light_methods() {
+ fn retry_call_annotations_cover_all_known_methods() {
let source = std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/backend/replica.rs"
))
.expect("failed to read replica.rs");
- let mut typed_light: Vec<String> = Vec::new();
- let mut typed_heavy: Vec<String> = Vec::new();
+ let mut typed_methods: Vec<String> = Vec::new();
- // Collect retry_call! invocations spanning multiple lines by accumulating
- // text between `retry_call!(` and the closing `)`.
let mut in_macro = false;
let mut macro_buf = String::new();
@@ -764,80 +501,27 @@ mod tests {
}
let args: Vec<&str> = macro_buf.split(',').collect();
- if args.len() >= 3 {
- let client_fn = args[1].trim();
- let method_snake = args[2].trim();
- let method = snake_to_pascal(method_snake);
- match client_fn {
- "next_light_client" => typed_light.push(method),
- "next_heavy_client" => typed_heavy.push(method),
- _ => {}
- }
+ if args.len() >= 2 {
+ let method_snake = args[1].trim();
+ typed_methods.push(snake_to_pascal(method_snake));
}
macro_buf.clear();
}
- typed_light.sort();
- typed_heavy.sort();
+ typed_methods.sort();
assert!(
- !typed_light.is_empty() && !typed_heavy.is_empty(),
+ !typed_methods.is_empty(),
"parser found no retry_call! invocations — source formatting may have changed"
);
- for method in &typed_light {
- assert!(
- is_light_method(method),
- "retry_call! uses next_light_client for '{method}' but it's not in LIGHT_METHODS"
- );
- }
-
- for method in &typed_heavy {
- assert!(
- !is_light_method(method),
- "retry_call! uses next_heavy_client for '{method}' but it IS in LIGHT_METHODS"
- );
- }
-
- let mut all_typed: Vec<&str> = typed_light
- .iter()
- .chain(typed_heavy.iter())
- .map(|s| s.as_str())
- .collect();
- all_typed.sort();
-
let mut all_known: Vec<&str> = KNOWN_METHODS.to_vec();
all_known.retain(|m| !LEADER_ONLY_METHODS.contains(m));
all_known.sort();
assert_eq!(
- all_typed, all_known,
+ typed_methods, all_known,
"retry_call! annotations don't cover all known methods (minus leader-only ones)"
);
-
- assert_eq!(
- typed_light.len(),
- LIGHT_METHODS.len(),
- "number of next_light_client annotations ({}) doesn't match LIGHT_METHODS ({})",
- typed_light.len(),
- LIGHT_METHODS.len(),
- );
- }
-
- #[tokio::test]
- async fn raw_channel_routes_by_method() {
- let backend = make_backend(4, 2);
-
- backend.next_raw_channel_for("GetGroupTypeMappingsByProjectIds");
- assert_eq!(backend.light_next_idx.load(Ordering::Relaxed), 1);
- assert_eq!(backend.heavy_next_idx.load(Ordering::Relaxed), 0);
-
- backend.next_raw_channel_for("GetGroupsBatch");
- assert_eq!(backend.light_next_idx.load(Ordering::Relaxed), 1);
- assert_eq!(backend.heavy_next_idx.load(Ordering::Relaxed), 1);
-
- backend.next_raw_channel_for("UnknownMethod");
- assert_eq!(backend.light_next_idx.load(Ordering::Relaxed), 1);
- assert_eq!(backend.heavy_next_idx.load(Ordering::Relaxed), 2);
}
}
diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rs
index f17dc463044d..097d8b6ee800 100644
--- a/rust/personhog-router/src/config.rs
+++ b/rust/personhog-router/src/config.rs
@@ -5,6 +5,37 @@ use envconfig::Envconfig;
use std::net::SocketAddr;
use std::time::Duration;
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ReplicaDiscoveryMode {
+ /// DNS mode: static channels to ClusterIP URL.
+ Dns,
+ /// K8s mode: EndpointSlice watcher with client-side p2c balancing.
+ K8s,
+}
+
+impl fmt::Display for ReplicaDiscoveryMode {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ ReplicaDiscoveryMode::Dns => write!(f, "dns"),
+ ReplicaDiscoveryMode::K8s => write!(f, "k8s"),
+ }
+ }
+}
+
+impl FromStr for ReplicaDiscoveryMode {
+ 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),
+ other => Err(format!(
+ "unknown replica discovery mode '{other}', expected 'dns' or 'k8s'"
+ )),
+ }
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RouterMode {
/// Replica-only mode: all requests go to personhog-replica.
@@ -84,27 +115,41 @@ pub struct Config {
#[envconfig(default = "typed")]
pub proxy_mode: ProxyMode,
- /// URL of the personhog-replica backend
+ /// URL of the personhog-replica backend (DNS mode only)
#[envconfig(default = "http://127.0.0.1:50051")]
pub replica_url: String,
- /// Number of gRPC channels (HTTP/2 connections) to open to the replica backend
- /// for heavy RPCs (Person/Group lookups with large JSON property blobs).
+ /// Number of gRPC channels to open to the replica service (DNS mode only).
/// Multiple channels distribute requests across K8s service endpoints.
#[envconfig(default = "4")]
pub replica_channels: usize,
- /// Number of dedicated gRPC channels for light RPCs (group type mappings,
- /// cohort checks, scalar responses). Isolates small responses from TCP
- /// head-of-line blocking caused by large Person/Group payloads on the
- /// heavy channels.
- #[envconfig(default = "2")]
- pub replica_light_channels: usize,
+ /// Discovery mode for replica endpoints: "dns" (default)
+ /// or "k8s" (EndpointSlice watcher with client-side balancing)
+ #[envconfig(default = "dns")]
+ pub replica_discovery_mode: ReplicaDiscoveryMode,
+
+ /// Kubernetes service name to watch for replica endpoints (k8s mode only)
+ #[envconfig(default = "personhog-replica")]
+ pub replica_service_name: String,
+
+ /// Kubernetes namespace for replica endpoint discovery (k8s mode only).
+ /// If empty, reads from the service account mount.
+ #[envconfig(default = "")]
+ pub replica_service_namespace: String,
+
+ /// gRPC port on replica pods (k8s mode only)
+ #[envconfig(default = "50051")]
+ pub replica_port: u16,
/// Timeout for backend requests in milliseconds
#[envconfig(default = "5000")]
pub backend_timeout_ms: u64,
+ /// Connect timeout for backend connections in milliseconds (k8s mode only)
+ #[envconfig(default = "2000")]
+ pub backend_connect_timeout_ms: u64,
+
#[envconfig(default = "9101")]
pub metrics_port: u16,
@@ -235,11 +280,168 @@ pub struct Config {
pub k8s_namespace: String,
}
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ── ReplicaDiscoveryMode ──────────────────────────────────────────────────
+
+ #[test]
+ fn replica_discovery_mode_from_str_valid_variants() {
+ let cases = [
+ ("dns", ReplicaDiscoveryMode::Dns),
+ ("k8s", ReplicaDiscoveryMode::K8s),
+ // case-insensitive
+ ("DNS", ReplicaDiscoveryMode::Dns),
+ ("K8S", ReplicaDiscoveryMode::K8s),
+ ("Dns", ReplicaDiscoveryMode::Dns),
+ ];
+ for (input, expected) in cases {
+ let result: Result<ReplicaDiscoveryMode, _> = input.parse();
+ assert_eq!(
+ result.unwrap(),
+ expected,
+ "'{input}' should parse to {expected:?}",
+ );
+ }
+ }
+
+ #[test]
+ fn replica_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();
+ assert!(result.is_err(), "'{input}' should be an error");
+ let msg = result.unwrap_err();
+ assert!(
+ msg.contains(input) || msg.contains("expected"),
+ "error message should mention the bad input or expected values, got: {msg}",
+ );
+ }
+ }
+
+ #[test]
+ fn replica_discovery_mode_display() {
+ assert_eq!(ReplicaDiscoveryMode::Dns.to_string(), "dns");
+ assert_eq!(ReplicaDiscoveryMode::K8s.to_string(), "k8s");
+ }
+
+ #[test]
+ fn replica_discovery_mode_roundtrips() {
+ for mode in [ReplicaDiscoveryMode::Dns, ReplicaDiscoveryMode::K8s] {
+ let s = mode.to_string();
+ let parsed: ReplicaDiscoveryMode = s.parse().unwrap();
+ assert_eq!(
+ parsed, mode,
+ "Display → FromStr roundtrip failed for {mode:?}"
+ );
+ }
+ }
+
+ // ── RouterMode ───────────────────────────────────────────────────────────
+
+ #[test]
+ fn router_mode_from_str_valid_variants() {
+ let cases = [
+ ("replica", RouterMode::Replica),
+ ("leader", RouterMode::Leader),
+ ("REPLICA", RouterMode::Replica),
+ ("LEADER", RouterMode::Leader),
+ ];
+ for (input, expected) in cases {
+ let result: Result<RouterMode, _> = input.parse();
+ assert_eq!(
+ result.unwrap(),
+ expected,
+ "'{input}' should parse to {expected:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn router_mode_from_str_invalid_returns_error() {
+ let invalid_inputs = ["dns", "", "follow", "primary"];
+ for input in invalid_inputs {
+ let result: Result<RouterMode, _> = input.parse();
+ assert!(result.is_err(), "'{input}' should be an error");
+ }
+ }
+
+ #[test]
+ fn router_mode_display() {
+ assert_eq!(RouterMode::Replica.to_string(), "replica");
+ assert_eq!(RouterMode::Leader.to_string(), "leader");
+ }
+
+ #[test]
+ fn router_mode_roundtrips() {
+ for mode in [RouterMode::Replica, RouterMode::Leader] {
+ let s = mode.to_string();
+ let parsed: RouterMode = s.parse().unwrap();
+ assert_eq!(
+ parsed, mode,
+ "Display → FromStr roundtrip failed for {mode:?}"
+ );
+ }
+ }
+
+ // ── ProxyMode ─────────────────────────────────────────────────────────────
+
+ #[test]
+ fn proxy_mode_from_str_valid_variants() {
+ let cases = [
+ ("typed", ProxyMode::Typed),
+ ("raw", ProxyMode::Raw),
+ ("TYPED", ProxyMode::Typed),
+ ("RAW", ProxyMode::Raw),
+ ];
+ for (input, expected) in cases {
+ let result: Result<ProxyMode, _> = input.parse();
+ assert_eq!(
+ result.unwrap(),
+ expected,
+ "'{input}' should parse to {expected:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn proxy_mode_from_str_invalid_returns_error() {
+ let invalid_inputs = ["byte", "", "proxy", "passthrough"];
+ for input in invalid_inputs {
+ let result: Result<ProxyMode, _> = input.parse();
+ assert!(result.is_err(), "'{input}' should be an error");
+ }
+ }
+
+ #[test]
+ fn proxy_mode_display() {
+ assert_eq!(ProxyMode::Typed.to_string(), "typed");
+ assert_eq!(ProxyMode::Raw.to_string(), "raw");
+ }
+
+ #[test]
+ fn proxy_mode_roundtrips() {
+ for mode in [ProxyMode::Typed, ProxyMode::Raw] {
+ let s = mode.to_string();
+ let parsed: ProxyMode = s.parse().unwrap();
+ assert_eq!(
+ parsed, mode,
+ "Display → FromStr roundtrip failed for {mode:?}"
+ );
+ }
+ }
+}
+
impl Config {
pub fn backend_timeout(&self) -> Duration {
Duration::from_millis(self.backend_timeout_ms)
}
+ pub fn backend_connect_timeout(&self) -> Duration {
+ Duration::from_millis(self.backend_connect_timeout_ms)
+ }
+
pub fn grpc_keepalive_interval(&self) -> Option<Duration> {
if self.grpc_keepalive_interval_secs == 0 {
None
@@ -308,6 +510,20 @@ impl Config {
Duration::from_millis(self.stash_max_wait_ms)
}
+ /// 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}"
+ )
+ })
+ }
+
/// 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() {
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index 72945a565415..cfb97331ea46 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -13,10 +13,11 @@ use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, St
use personhog_coordination::store::PersonhogStore;
use personhog_coordination::strategy::StickyBalancedStrategy;
use personhog_proto::personhog::service::v1::person_hog_service_server::PersonHogServiceServer;
+use personhog_router::backend::discovery::{EndpointConfig, EndpointDiscovery};
use personhog_router::backend::{
- LeaderBackend, LeaderBackendConfig, ReplicaBackend, ReplicaBackendConfig, StashTable,
+ LeaderBackend, LeaderBackendConfig, ReplicaBackend, ReplicaDnsConfig, StashTable,
};
-use personhog_router::config::{Config, ProxyMode, RouterMode};
+use personhog_router::config::{Config, ProxyMode, ReplicaDiscoveryMode, RouterMode};
use personhog_router::proxy::RawProxyService;
use personhog_router::router::PersonHogRouter;
use personhog_router::service::PersonHogRouterService;
@@ -58,12 +59,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing::info!("Router mode: {}", config.router_mode);
tracing::info!("Proxy mode: {}", config.proxy_mode);
tracing::info!("gRPC address: {}", config.grpc_address);
+ tracing::info!("Replica discovery mode: {}", config.replica_discovery_mode);
tracing::info!("Replica URL: {}", config.replica_url);
- tracing::info!(
- "Replica channels: {} heavy, {} light",
- config.replica_channels,
- config.replica_light_channels
- );
tracing::info!("Backend timeout: {}ms", config.backend_timeout_ms);
tracing::info!("Metrics port: {}", config.metrics_port);
tracing::info!(
@@ -101,12 +98,80 @@ 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(Duration::from_secs(5)),
+ ))
+ } else {
+ None
+ };
+
let readiness = manager.readiness_handler();
let liveness = manager.liveness_handler();
let monitor_guard = manager.monitor_background();
- // Metrics/health HTTP server (observability handle — stays alive during standard drain)
+ // 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(),
+ max_send_message_size: config.grpc_max_send_message_size,
+ max_recv_message_size: config.grpc_max_recv_message_size,
+ 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(),
+ config.grpc_max_send_message_size,
+ config.grpc_max_recv_message_size,
+ )),
+ Some(disc_readiness),
+ )
+ }
+ };
+
+ // Metrics/health HTTP server (spawned after backend creation so it can
+ // include discovery readiness in the health check)
let metrics_port = config.metrics_port;
tokio::spawn(async move {
let _guard = metrics_handle.process_scope();
@@ -137,7 +202,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"/_readiness",
get(move || {
let r = readiness.clone();
- async move { r.check().await }
+ let dr = discovery_readiness.clone();
+ async move {
+ if let Some(ref dr) = dr {
+ if !dr.is_ready() {
+ return axum::http::StatusCode::SERVICE_UNAVAILABLE;
+ }
+ }
+ r.check().await
+ }
}),
)
.route("/_liveness", get(move || async move { liveness.check() }))
@@ -157,19 +230,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.expect("Metrics server error");
});
- // Create backend connection(s) to personhog-replica
- let replica_backend = Arc::new(ReplicaBackend::new(ReplicaBackendConfig {
- 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(),
- max_send_message_size: config.grpc_max_send_message_size,
- max_recv_message_size: config.grpc_max_recv_message_size,
- num_channels: config.replica_channels,
- num_light_channels: config.replica_light_channels,
- }));
-
// In leader mode, wire up etcd coordination and the leader backend
// for person writes / strong reads.
let leader_backend: Option<Arc<LeaderBackend>> = if config.router_mode == RouterMode::Leader {
diff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rs
index 25921c7010dc..7717617ff176 100644
--- a/rust/personhog-router/src/proxy.rs
+++ b/rust/personhog-router/src/proxy.rs
@@ -288,7 +288,7 @@ impl RawProxyInner {
let client = current_client_name();
for attempt in 0..=self.retry_config.max_retries {
- let mut channel = self.replica.next_raw_channel_for(&method);
+ let mut channel = self.replica.channel();
let ready_start = Instant::now();
let ready_channel = match channel.ready().await {
diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rs
index fea663d42d6e..a53e8e92c0de 100644
--- a/rust/personhog-router/tests/common/mod.rs
+++ b/rust/personhog-router/tests/common/mod.rs
@@ -44,7 +44,7 @@ use personhog_proto::personhog::types::v1::{
UpsertHashKeyOverridesRequest, UpsertHashKeyOverridesResponse,
};
use personhog_router::backend::{
- LeaderBackend, LeaderBackendConfig, ReplicaBackend, ReplicaBackendConfig, StashTable,
+ LeaderBackend, LeaderBackendConfig, ReplicaBackend, ReplicaDnsConfig, StashTable,
};
use personhog_router::config::RetryConfig;
use personhog_router::proxy::RawProxyService;
@@ -537,7 +537,7 @@ pub async fn start_test_router(replica_addr: SocketAddr) -> SocketAddr {
initial_backoff_ms: 1,
max_backoff_ms: 1,
};
- let backend = ReplicaBackend::new(ReplicaBackendConfig {
+ let backend = ReplicaBackend::new_dns(ReplicaDnsConfig {
url: replica_url,
timeout: Duration::from_secs(5),
retry_config,
@@ -546,7 +546,6 @@ pub async fn start_test_router(replica_addr: SocketAddr) -> SocketAddr {
max_send_message_size: 4 * 1024 * 1024,
max_recv_message_size: 4 * 1024 * 1024,
num_channels: 1,
- num_light_channels: 1,
});
let router = PersonHogRouter::new(Arc::new(backend));
let service = PersonHogRouterService::new(Arc::new(router));
@@ -781,7 +780,7 @@ pub async fn start_test_router_with_leader(
// Replica backend
let replica_url = format!("http://{}", replica_addr);
- let replica = ReplicaBackend::new(ReplicaBackendConfig {
+ let replica = ReplicaBackend::new_dns(ReplicaDnsConfig {
url: replica_url,
timeout: Duration::from_secs(5),
retry_config,
@@ -790,7 +789,6 @@ pub async fn start_test_router_with_leader(
max_send_message_size: 4 * 1024 * 1024,
max_recv_message_size: 4 * 1024 * 1024,
num_channels: 1,
- num_light_channels: 1,
});
// Leader backend: all partitions → "leader-0", resolver → leader_addr
@@ -841,7 +839,7 @@ fn make_replica_backend(replica_addr: SocketAddr) -> Arc<ReplicaBackend> {
initial_backoff_ms: 1,
max_backoff_ms: 1,
};
- Arc::new(ReplicaBackend::new(ReplicaBackendConfig {
+ Arc::new(ReplicaBackend::new_dns(ReplicaDnsConfig {
url: format!("http://{}", replica_addr),
timeout: Duration::from_secs(5),
retry_config,
@@ -850,7 +848,6 @@ fn make_replica_backend(replica_addr: SocketAddr) -> Arc<ReplicaBackend> {
max_send_message_size: 4 * 1024 * 1024,
max_recv_message_size: 4 * 1024 * 1024,
num_channels: 1,
- num_light_channels: 1,
}))
}