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.

chore(personhog): remove typed proxy (#62511)

Zach Brown269e457f937e
diff --git a/rust/personhog-router/src/backend/mod.rs b/rust/personhog-router/src/backend/mod.rs
index 6b9cad6eb0c3..94a2cd3b885f 100644
--- a/rust/personhog-router/src/backend/mod.rs
+++ b/rust/personhog-router/src/backend/mod.rs
@@ -10,34 +10,8 @@ pub use stash::{StashDecision, StashTable, StashedRequest};
use async_trait::async_trait;
use personhog_proto::personhog::types::v1::{
- CheckCohortMembershipRequest, CohortMembershipResponse, CountCohortMembersRequest,
- CountCohortMembersResponse, CountGroupTypeMappingsRequest, CountGroupTypeMappingsResponse,
- CreateGroupRequest, CreateGroupResponse, DeleteCohortMemberRequest, DeleteCohortMemberResponse,
- DeleteCohortMembersBulkRequest, DeleteCohortMembersBulkResponse, DeleteGroupTypeMappingRequest,
- DeleteGroupTypeMappingResponse, DeleteGroupTypeMappingsBatchForTeamRequest,
- DeleteGroupTypeMappingsBatchForTeamResponse, DeleteGroupsBatchForTeamRequest,
- DeleteGroupsBatchForTeamResponse, DeleteHashKeyOverridesByTeamsRequest,
- DeleteHashKeyOverridesByTeamsResponse, DeletePersonlessDistinctIdsBatchForTeamRequest,
- DeletePersonlessDistinctIdsBatchForTeamResponse, DeletePersonsBatchForTeamRequest,
- DeletePersonsBatchForTeamResponse, DeletePersonsRequest, DeletePersonsResponse,
- GetDistinctIdsForPersonRequest, GetDistinctIdsForPersonResponse,
- GetDistinctIdsForPersonsRequest, GetDistinctIdsForPersonsResponse, GetGroupRequest,
- GetGroupResponse, GetGroupTypeMappingByDashboardIdRequest,
- GetGroupTypeMappingByDashboardIdResponse, GetGroupTypeMappingsByProjectIdRequest,
- GetGroupTypeMappingsByProjectIdsRequest, GetGroupTypeMappingsByTeamIdRequest,
- GetGroupTypeMappingsByTeamIdsRequest, GetGroupsBatchRequest, GetGroupsBatchResponse,
- GetGroupsRequest, GetHashKeyOverrideContextRequest, GetHashKeyOverrideContextResponse,
- GetPersonByDistinctIdRequest, GetPersonByUuidRequest, GetPersonRequest, GetPersonResponse,
- GetPersonsByDistinctIdsInTeamRequest, GetPersonsByDistinctIdsRequest, GetPersonsByUuidsRequest,
- GetPersonsRequest, GroupTypeMappingsBatchResponse, GroupTypeMappingsResponse, GroupsResponse,
- InsertCohortMembersRequest, InsertCohortMembersResponse, ListCohortMemberIdsRequest,
- ListCohortMemberIdsResponse, ListGroupsRequest, ListGroupsResponse,
- PersonsByDistinctIdsInTeamResponse, PersonsByDistinctIdsResponse, PersonsResponse,
- SetPersonDistinctIdVersionFloorRequest, SetPersonDistinctIdVersionFloorResponse,
- SetPersonVersionFloorRequest, SetPersonVersionFloorResponse, SplitPersonRequest,
- SplitPersonResponse, UpdateGroupRequest, UpdateGroupResponse, UpdateGroupTypeMappingRequest,
- UpdateGroupTypeMappingResponse, UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
- UpsertHashKeyOverridesRequest, UpsertHashKeyOverridesResponse,
+ GetPersonRequest, GetPersonResponse, UpdatePersonPropertiesRequest,
+ UpdatePersonPropertiesResponse,
};
use tonic::Status;
@@ -51,179 +25,3 @@ pub trait LeaderOps: Send + Sync {
request: UpdatePersonPropertiesRequest,
) -> Result<UpdatePersonPropertiesResponse, Status>;
}
-
-/// Trait defining the replica backend interface for read operations.
-/// The replica serves eventual-consistency reads from Postgres replicas.
-#[async_trait]
-pub trait PersonHogBackend: Send + Sync {
- // Person lookups by ID
- async fn get_person(&self, request: GetPersonRequest) -> Result<GetPersonResponse, Status>;
- async fn get_persons(&self, request: GetPersonsRequest) -> Result<PersonsResponse, Status>;
- async fn get_person_by_uuid(
- &self,
- request: GetPersonByUuidRequest,
- ) -> Result<GetPersonResponse, Status>;
- async fn get_persons_by_uuids(
- &self,
- request: GetPersonsByUuidsRequest,
- ) -> Result<PersonsResponse, Status>;
-
- // Person lookups by distinct ID
- async fn get_person_by_distinct_id(
- &self,
- request: GetPersonByDistinctIdRequest,
- ) -> Result<GetPersonResponse, Status>;
- async fn get_persons_by_distinct_ids_in_team(
- &self,
- request: GetPersonsByDistinctIdsInTeamRequest,
- ) -> Result<PersonsByDistinctIdsInTeamResponse, Status>;
- async fn get_persons_by_distinct_ids(
- &self,
- request: GetPersonsByDistinctIdsRequest,
- ) -> Result<PersonsByDistinctIdsResponse, Status>;
-
- // Distinct ID operations
- async fn get_distinct_ids_for_person(
- &self,
- request: GetDistinctIdsForPersonRequest,
- ) -> Result<GetDistinctIdsForPersonResponse, Status>;
- async fn get_distinct_ids_for_persons(
- &self,
- request: GetDistinctIdsForPersonsRequest,
- ) -> Result<GetDistinctIdsForPersonsResponse, Status>;
-
- // Feature flag hash key override support
- async fn get_hash_key_override_context(
- &self,
- request: GetHashKeyOverrideContextRequest,
- ) -> Result<GetHashKeyOverrideContextResponse, Status>;
- async fn upsert_hash_key_overrides(
- &self,
- request: UpsertHashKeyOverridesRequest,
- ) -> Result<UpsertHashKeyOverridesResponse, Status>;
- async fn delete_hash_key_overrides_by_teams(
- &self,
- request: DeleteHashKeyOverridesByTeamsRequest,
- ) -> Result<DeleteHashKeyOverridesByTeamsResponse, Status>;
-
- // Person deletes
- async fn delete_persons(
- &self,
- request: DeletePersonsRequest,
- ) -> Result<DeletePersonsResponse, Status>;
- async fn delete_persons_batch_for_team(
- &self,
- request: DeletePersonsBatchForTeamRequest,
- ) -> Result<DeletePersonsBatchForTeamResponse, Status>;
- async fn delete_personless_distinct_ids_batch_for_team(
- &self,
- request: DeletePersonlessDistinctIdsBatchForTeamRequest,
- ) -> Result<DeletePersonlessDistinctIdsBatchForTeamResponse, Status>;
-
- // Person split
- async fn split_person(
- &self,
- request: SplitPersonRequest,
- ) -> Result<SplitPersonResponse, Status>;
-
- // Undelete repair version resets
- async fn set_person_distinct_id_version_floor(
- &self,
- request: SetPersonDistinctIdVersionFloorRequest,
- ) -> Result<SetPersonDistinctIdVersionFloorResponse, Status>;
- async fn set_person_version_floor(
- &self,
- request: SetPersonVersionFloorRequest,
- ) -> Result<SetPersonVersionFloorResponse, Status>;
-
- // Cohort membership
- async fn check_cohort_membership(
- &self,
- request: CheckCohortMembershipRequest,
- ) -> Result<CohortMembershipResponse, Status>;
- async fn count_cohort_members(
- &self,
- request: CountCohortMembersRequest,
- ) -> Result<CountCohortMembersResponse, Status>;
- async fn delete_cohort_member(
- &self,
- request: DeleteCohortMemberRequest,
- ) -> Result<DeleteCohortMemberResponse, Status>;
- async fn delete_cohort_members_bulk(
- &self,
- request: DeleteCohortMembersBulkRequest,
- ) -> Result<DeleteCohortMembersBulkResponse, Status>;
- async fn insert_cohort_members(
- &self,
- request: InsertCohortMembersRequest,
- ) -> Result<InsertCohortMembersResponse, Status>;
- async fn list_cohort_member_ids(
- &self,
- request: ListCohortMemberIdsRequest,
- ) -> Result<ListCohortMemberIdsResponse, Status>;
-
- // Groups
- async fn get_group(&self, request: GetGroupRequest) -> Result<GetGroupResponse, Status>;
- async fn get_groups(&self, request: GetGroupsRequest) -> Result<GroupsResponse, Status>;
- async fn get_groups_batch(
- &self,
- request: GetGroupsBatchRequest,
- ) -> Result<GetGroupsBatchResponse, Status>;
- async fn list_groups(&self, request: ListGroupsRequest) -> Result<ListGroupsResponse, Status>;
-
- // Group type mappings
- async fn get_group_type_mappings_by_team_id(
- &self,
- request: GetGroupTypeMappingsByTeamIdRequest,
- ) -> Result<GroupTypeMappingsResponse, Status>;
- async fn get_group_type_mappings_by_team_ids(
- &self,
- request: GetGroupTypeMappingsByTeamIdsRequest,
- ) -> Result<GroupTypeMappingsBatchResponse, Status>;
- async fn get_group_type_mappings_by_project_id(
- &self,
- request: GetGroupTypeMappingsByProjectIdRequest,
- ) -> Result<GroupTypeMappingsResponse, Status>;
- async fn get_group_type_mappings_by_project_ids(
- &self,
- request: GetGroupTypeMappingsByProjectIdsRequest,
- ) -> Result<GroupTypeMappingsBatchResponse, Status>;
- async fn count_group_type_mappings(
- &self,
- request: CountGroupTypeMappingsRequest,
- ) -> Result<CountGroupTypeMappingsResponse, Status>;
-
- // Group type mapping lookups (additional)
- async fn get_group_type_mapping_by_dashboard_id(
- &self,
- request: GetGroupTypeMappingByDashboardIdRequest,
- ) -> Result<GetGroupTypeMappingByDashboardIdResponse, Status>;
-
- // Group writes
- async fn create_group(
- &self,
- request: CreateGroupRequest,
- ) -> Result<CreateGroupResponse, Status>;
- async fn update_group(
- &self,
- request: UpdateGroupRequest,
- ) -> Result<UpdateGroupResponse, Status>;
- async fn delete_groups_batch_for_team(
- &self,
- request: DeleteGroupsBatchForTeamRequest,
- ) -> Result<DeleteGroupsBatchForTeamResponse, Status>;
-
- // Group type mapping writes
- async fn update_group_type_mapping(
- &self,
- request: UpdateGroupTypeMappingRequest,
- ) -> Result<UpdateGroupTypeMappingResponse, Status>;
- async fn delete_group_type_mapping(
- &self,
- request: DeleteGroupTypeMappingRequest,
- ) -> Result<DeleteGroupTypeMappingResponse, Status>;
- async fn delete_group_type_mappings_batch_for_team(
- &self,
- request: DeleteGroupTypeMappingsBatchForTeamRequest,
- ) -> Result<DeleteGroupTypeMappingsBatchForTeamResponse, Status>;
-}
diff --git a/rust/personhog-router/src/backend/replica.rs b/rust/personhog-router/src/backend/replica.rs
index a2b00b8b311c..be27ba870eec 100644
--- a/rust/personhog-router/src/backend/replica.rs
+++ b/rust/personhog-router/src/backend/replica.rs
@@ -1,50 +1,12 @@
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::{
- CheckCohortMembershipRequest, CohortMembershipResponse, CountCohortMembersRequest,
- CountCohortMembersResponse, CountGroupTypeMappingsRequest, CountGroupTypeMappingsResponse,
- CreateGroupRequest, CreateGroupResponse, DeleteCohortMemberRequest, DeleteCohortMemberResponse,
- DeleteCohortMembersBulkRequest, DeleteCohortMembersBulkResponse, DeleteGroupTypeMappingRequest,
- DeleteGroupTypeMappingResponse, DeleteGroupTypeMappingsBatchForTeamRequest,
- DeleteGroupTypeMappingsBatchForTeamResponse, DeleteGroupsBatchForTeamRequest,
- DeleteGroupsBatchForTeamResponse, DeleteHashKeyOverridesByTeamsRequest,
- DeleteHashKeyOverridesByTeamsResponse, DeletePersonlessDistinctIdsBatchForTeamRequest,
- DeletePersonlessDistinctIdsBatchForTeamResponse, DeletePersonsBatchForTeamRequest,
- DeletePersonsBatchForTeamResponse, DeletePersonsRequest, DeletePersonsResponse,
- GetDistinctIdsForPersonRequest, GetDistinctIdsForPersonResponse,
- GetDistinctIdsForPersonsRequest, GetDistinctIdsForPersonsResponse, GetGroupRequest,
- GetGroupResponse, GetGroupTypeMappingByDashboardIdRequest,
- GetGroupTypeMappingByDashboardIdResponse, GetGroupTypeMappingsByProjectIdRequest,
- GetGroupTypeMappingsByProjectIdsRequest, GetGroupTypeMappingsByTeamIdRequest,
- GetGroupTypeMappingsByTeamIdsRequest, GetGroupsBatchRequest, GetGroupsBatchResponse,
- GetGroupsRequest, GetHashKeyOverrideContextRequest, GetHashKeyOverrideContextResponse,
- GetPersonByDistinctIdRequest, GetPersonByUuidRequest, GetPersonRequest, GetPersonResponse,
- GetPersonsByDistinctIdsInTeamRequest, GetPersonsByDistinctIdsRequest, GetPersonsByUuidsRequest,
- GetPersonsRequest, GroupTypeMappingsBatchResponse, GroupTypeMappingsResponse, GroupsResponse,
- InsertCohortMembersRequest, InsertCohortMembersResponse, ListCohortMemberIdsRequest,
- ListCohortMemberIdsResponse, ListGroupsRequest, ListGroupsResponse,
- PersonsByDistinctIdsInTeamResponse, PersonsByDistinctIdsResponse, PersonsResponse,
- SetPersonDistinctIdVersionFloorRequest, SetPersonDistinctIdVersionFloorResponse,
- SetPersonVersionFloorRequest, SetPersonVersionFloorResponse, SplitPersonRequest,
- SplitPersonResponse, UpdateGroupRequest, UpdateGroupResponse, UpdateGroupTypeMappingRequest,
- UpdateGroupTypeMappingResponse, UpsertHashKeyOverridesRequest, UpsertHashKeyOverridesResponse,
-};
use std::time::Duration;
-use tonic::codec::CompressionEncoding;
+
use tonic::transport::{Channel, Endpoint};
-use tonic::{Request, Status};
use tracing::info;
-use personhog_common::grpc::{current_caller_tag, current_client_name};
-
-use super::retry::with_retry;
-use super::PersonHogBackend;
use crate::config::RetryConfig;
pub struct ReplicaBackend {
- clients: Vec<PersonHogReplicaClient<Channel>>,
channels: Vec<Channel>,
next_idx: AtomicUsize,
retry_config: RetryConfig,
@@ -57,8 +19,6 @@ pub struct ReplicaDnsConfig {
pub retry_config: RetryConfig,
pub keepalive_interval: Option<Duration>,
pub keepalive_timeout: Option<Duration>,
- pub max_send_message_size: usize,
- pub max_recv_message_size: usize,
pub num_channels: usize,
}
@@ -78,18 +38,6 @@ fn build_dns_endpoint(config: &ReplicaDnsConfig) -> Endpoint {
endpoint
}
-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 {
/// DNS discovery: opens multiple lazy channels to the ClusterIP service URL
/// with round-robin selection across them.
@@ -98,16 +46,6 @@ impl ReplicaBackend {
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!(
url = config.url,
@@ -117,7 +55,6 @@ impl ReplicaBackend {
);
Self {
- clients,
channels,
next_idx: AtomicUsize::new(0),
retry_config: config.retry_config,
@@ -127,29 +64,16 @@ impl ReplicaBackend {
/// 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);
-
+ pub fn new_k8s(channel: Channel, retry_config: RetryConfig) -> Self {
info!(mode = "k8s", "created replica backend");
Self {
- clients: vec![client],
channels: vec![channel],
next_idx: AtomicUsize::new(0),
retry_config,
}
}
- fn client(&self) -> PersonHogReplicaClient<Channel> {
- let idx = self.next_idx.fetch_add(1, Ordering::Relaxed) % self.clients.len();
- self.clients[idx].clone()
- }
-
pub fn channel(&self) -> Channel {
let idx = self.next_idx.fetch_add(1, Ordering::Relaxed) % self.channels.len();
self.channels[idx].clone()
@@ -160,305 +84,9 @@ impl ReplicaBackend {
}
}
-macro_rules! retry_call {
- ($self:expr, $method:ident, $request:expr) => {{
- with_retry(&$self.retry_config, stringify!($method), || {
- let mut client = $self.client();
- let req = $request.clone();
- let client_name = current_client_name();
- let caller_tag = current_caller_tag();
- async move {
- let mut request = Request::new(req);
- if let Ok(val) = client_name.parse() {
- request.metadata_mut().insert("x-client-name", val);
- }
- if let Ok(val) = caller_tag.parse() {
- request.metadata_mut().insert("x-caller-tag", val);
- }
- client.$method(request).await.map(|r| r.into_inner())
- }
- })
- .await
- }};
-}
-
-/// 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 {
- async fn get_person(&self, request: GetPersonRequest) -> Result<GetPersonResponse, Status> {
- retry_call!(self, get_person, request)
- }
-
- async fn get_persons(&self, request: GetPersonsRequest) -> Result<PersonsResponse, Status> {
- retry_call!(self, get_persons, request)
- }
-
- async fn get_person_by_uuid(
- &self,
- request: GetPersonByUuidRequest,
- ) -> Result<GetPersonResponse, Status> {
- retry_call!(self, get_person_by_uuid, request)
- }
-
- async fn get_persons_by_uuids(
- &self,
- request: GetPersonsByUuidsRequest,
- ) -> Result<PersonsResponse, Status> {
- retry_call!(self, get_persons_by_uuids, request)
- }
-
- async fn get_person_by_distinct_id(
- &self,
- request: GetPersonByDistinctIdRequest,
- ) -> Result<GetPersonResponse, Status> {
- 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, get_persons_by_distinct_ids_in_team, request)
- }
-
- async fn get_persons_by_distinct_ids(
- &self,
- request: GetPersonsByDistinctIdsRequest,
- ) -> Result<PersonsByDistinctIdsResponse, Status> {
- retry_call!(self, get_persons_by_distinct_ids, request)
- }
-
- async fn get_distinct_ids_for_person(
- &self,
- request: GetDistinctIdsForPersonRequest,
- ) -> Result<GetDistinctIdsForPersonResponse, Status> {
- retry_call!(self, get_distinct_ids_for_person, request)
- }
-
- async fn get_distinct_ids_for_persons(
- &self,
- request: GetDistinctIdsForPersonsRequest,
- ) -> Result<GetDistinctIdsForPersonsResponse, Status> {
- retry_call!(self, get_distinct_ids_for_persons, request)
- }
-
- async fn get_hash_key_override_context(
- &self,
- request: GetHashKeyOverrideContextRequest,
- ) -> Result<GetHashKeyOverrideContextResponse, Status> {
- retry_call!(self, get_hash_key_override_context, request)
- }
-
- async fn upsert_hash_key_overrides(
- &self,
- request: UpsertHashKeyOverridesRequest,
- ) -> Result<UpsertHashKeyOverridesResponse, Status> {
- 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, delete_hash_key_overrides_by_teams, request)
- }
-
- async fn delete_persons(
- &self,
- request: DeletePersonsRequest,
- ) -> Result<DeletePersonsResponse, Status> {
- retry_call!(self, delete_persons, request)
- }
-
- async fn delete_persons_batch_for_team(
- &self,
- request: DeletePersonsBatchForTeamRequest,
- ) -> Result<DeletePersonsBatchForTeamResponse, Status> {
- retry_call!(self, delete_persons_batch_for_team, request)
- }
-
- async fn delete_personless_distinct_ids_batch_for_team(
- &self,
- request: DeletePersonlessDistinctIdsBatchForTeamRequest,
- ) -> Result<DeletePersonlessDistinctIdsBatchForTeamResponse, Status> {
- retry_call!(self, delete_personless_distinct_ids_batch_for_team, request)
- }
-
- async fn split_person(
- &self,
- request: SplitPersonRequest,
- ) -> Result<SplitPersonResponse, Status> {
- retry_call!(self, split_person, request)
- }
-
- async fn set_person_distinct_id_version_floor(
- &self,
- request: SetPersonDistinctIdVersionFloorRequest,
- ) -> Result<SetPersonDistinctIdVersionFloorResponse, Status> {
- retry_call!(self, set_person_distinct_id_version_floor, request)
- }
-
- async fn set_person_version_floor(
- &self,
- request: SetPersonVersionFloorRequest,
- ) -> Result<SetPersonVersionFloorResponse, Status> {
- retry_call!(self, set_person_version_floor, request)
- }
-
- async fn check_cohort_membership(
- &self,
- request: CheckCohortMembershipRequest,
- ) -> Result<CohortMembershipResponse, Status> {
- retry_call!(self, check_cohort_membership, request)
- }
-
- async fn count_cohort_members(
- &self,
- request: CountCohortMembersRequest,
- ) -> Result<CountCohortMembersResponse, Status> {
- retry_call!(self, count_cohort_members, request)
- }
-
- async fn delete_cohort_member(
- &self,
- request: DeleteCohortMemberRequest,
- ) -> Result<DeleteCohortMemberResponse, Status> {
- retry_call!(self, delete_cohort_member, request)
- }
-
- async fn delete_cohort_members_bulk(
- &self,
- request: DeleteCohortMembersBulkRequest,
- ) -> Result<DeleteCohortMembersBulkResponse, Status> {
- retry_call!(self, delete_cohort_members_bulk, request)
- }
-
- async fn insert_cohort_members(
- &self,
- request: InsertCohortMembersRequest,
- ) -> Result<InsertCohortMembersResponse, Status> {
- retry_call!(self, insert_cohort_members, request)
- }
-
- async fn list_cohort_member_ids(
- &self,
- request: ListCohortMemberIdsRequest,
- ) -> Result<ListCohortMemberIdsResponse, Status> {
- retry_call!(self, list_cohort_member_ids, request)
- }
-
- async fn get_group(&self, request: GetGroupRequest) -> Result<GetGroupResponse, Status> {
- retry_call!(self, get_group, request)
- }
-
- async fn get_groups(&self, request: GetGroupsRequest) -> Result<GroupsResponse, Status> {
- retry_call!(self, get_groups, request)
- }
-
- async fn get_groups_batch(
- &self,
- request: GetGroupsBatchRequest,
- ) -> Result<GetGroupsBatchResponse, Status> {
- retry_call!(self, get_groups_batch, request)
- }
-
- async fn list_groups(&self, request: ListGroupsRequest) -> Result<ListGroupsResponse, Status> {
- retry_call!(self, list_groups, request)
- }
-
- async fn get_group_type_mappings_by_team_id(
- &self,
- request: GetGroupTypeMappingsByTeamIdRequest,
- ) -> Result<GroupTypeMappingsResponse, Status> {
- 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, 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, 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, get_group_type_mappings_by_project_ids, request)
- }
-
- async fn count_group_type_mappings(
- &self,
- request: CountGroupTypeMappingsRequest,
- ) -> Result<CountGroupTypeMappingsResponse, Status> {
- 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, get_group_type_mapping_by_dashboard_id, request)
- }
-
- async fn create_group(
- &self,
- request: CreateGroupRequest,
- ) -> Result<CreateGroupResponse, Status> {
- retry_call!(self, create_group, request)
- }
-
- async fn update_group(
- &self,
- request: UpdateGroupRequest,
- ) -> Result<UpdateGroupResponse, Status> {
- retry_call!(self, update_group, request)
- }
-
- async fn delete_groups_batch_for_team(
- &self,
- request: DeleteGroupsBatchForTeamRequest,
- ) -> Result<DeleteGroupsBatchForTeamResponse, Status> {
- retry_call!(self, delete_groups_batch_for_team, request)
- }
-
- async fn update_group_type_mapping(
- &self,
- request: UpdateGroupTypeMappingRequest,
- ) -> Result<UpdateGroupTypeMappingResponse, Status> {
- retry_call!(self, update_group_type_mapping, request)
- }
-
- async fn delete_group_type_mapping(
- &self,
- request: DeleteGroupTypeMappingRequest,
- ) -> Result<DeleteGroupTypeMappingResponse, Status> {
- 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, delete_group_type_mappings_batch_for_team, request)
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
- use crate::proxy::KNOWN_METHODS;
fn make_backend() -> ReplicaBackend {
ReplicaBackend::new_dns(ReplicaDnsConfig {
@@ -471,8 +99,6 @@ mod tests {
},
keepalive_interval: None,
keepalive_timeout: None,
- max_send_message_size: 4 * 1024 * 1024,
- max_recv_message_size: 4 * 1024 * 1024,
num_channels: 4,
})
}
@@ -483,76 +109,4 @@ mod tests {
let _ch1 = backend.channel();
let _ch2 = backend.channel();
}
-
- fn snake_to_pascal(s: &str) -> String {
- s.split('_')
- .map(|part| {
- let mut chars = part.chars();
- match chars.next() {
- Some(c) => c.to_uppercase().to_string() + chars.as_str(),
- None => String::new(),
- }
- })
- .collect()
- }
-
- #[test]
- 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_methods: Vec<String> = Vec::new();
-
- let mut in_macro = false;
- let mut macro_buf = String::new();
-
- for line in source.lines() {
- let trimmed = line.trim();
- if !in_macro {
- if let Some(rest) = trimmed.strip_prefix("retry_call!(") {
- if rest.ends_with(')') {
- macro_buf = rest.trim_end_matches(')').to_string();
- } else {
- macro_buf = rest.to_string();
- in_macro = true;
- continue;
- }
- } else {
- continue;
- }
- } else if trimmed == ")" {
- in_macro = false;
- } else {
- macro_buf.push(' ');
- macro_buf.push_str(trimmed);
- continue;
- }
-
- let args: Vec<&str> = macro_buf.split(',').collect();
- if args.len() >= 2 {
- let method_snake = args[1].trim();
- typed_methods.push(snake_to_pascal(method_snake));
- }
- macro_buf.clear();
- }
-
- typed_methods.sort();
-
- assert!(
- !typed_methods.is_empty(),
- "parser found no retry_call! invocations — source formatting may have changed"
- );
-
- let mut all_known: Vec<&str> = KNOWN_METHODS.to_vec();
- all_known.retain(|m| !LEADER_ONLY_METHODS.contains(m));
- all_known.sort();
-
- assert_eq!(
- typed_methods, all_known,
- "retry_call! annotations don't cover all known methods (minus leader-only ones)"
- );
- }
}
diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rs
index 097d8b6ee800..6c88ee894b5e 100644
--- a/rust/personhog-router/src/config.rs
+++ b/rust/personhog-router/src/config.rs
@@ -45,15 +45,6 @@ pub enum RouterMode {
Leader,
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum ProxyMode {
- /// Typed mode: deserialize/serialize every request through the PersonHogService trait.
- Typed,
- /// Raw mode: proxy raw bytes to replica for most methods, only deserialize
- /// for GetPerson (STRONG) and UpdatePersonProperties which need leader routing.
- Raw,
-}
-
impl fmt::Display for RouterMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@@ -77,29 +68,6 @@ impl FromStr for RouterMode {
}
}
-impl fmt::Display for ProxyMode {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- ProxyMode::Typed => write!(f, "typed"),
- ProxyMode::Raw => write!(f, "raw"),
- }
- }
-}
-
-impl FromStr for ProxyMode {
- type Err = String;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match s.to_lowercase().as_str() {
- "typed" => Ok(ProxyMode::Typed),
- "raw" => Ok(ProxyMode::Raw),
- other => Err(format!(
- "unknown proxy mode '{other}', expected 'typed' or 'raw'"
- )),
- }
- }
-}
-
#[derive(Envconfig, Clone, Debug)]
pub struct Config {
#[envconfig(default = "127.0.0.1:50052")]
@@ -109,12 +77,6 @@ pub struct Config {
#[envconfig(default = "replica")]
pub router_mode: RouterMode,
- /// Proxy mode: "typed" (default) or "raw"
- /// Typed: full deserialization through PersonHogService trait
- /// Raw: byte-level proxying for most methods, only typed for leader paths
- #[envconfig(default = "typed")]
- pub proxy_mode: ProxyMode,
-
/// URL of the personhog-replica backend (DNS mode only)
#[envconfig(default = "http://127.0.0.1:50051")]
pub replica_url: String,
@@ -384,53 +346,6 @@ mod tests {
);
}
}
-
- // ── 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 {
diff --git a/rust/personhog-router/src/lib.rs b/rust/personhog-router/src/lib.rs
index 1cad0823a9a6..55984716370f 100644
--- a/rust/personhog-router/src/lib.rs
+++ b/rust/personhog-router/src/lib.rs
@@ -1,6 +1,4 @@
pub mod backend;
pub mod config;
pub mod proxy;
-pub mod router;
-pub mod service;
pub mod stash_handler;
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index cfb97331ea46..cf46b65ddd28 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -12,15 +12,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_proto::personhog::service::v1::person_hog_service_server::PersonHogServiceServer;
use personhog_router::backend::discovery::{EndpointConfig, EndpointDiscovery};
use personhog_router::backend::{
LeaderBackend, LeaderBackendConfig, ReplicaBackend, ReplicaDnsConfig, StashTable,
};
-use personhog_router::config::{Config, ProxyMode, ReplicaDiscoveryMode, RouterMode};
+use personhog_router::config::{Config, ReplicaDiscoveryMode, RouterMode};
use personhog_router::proxy::RawProxyService;
-use personhog_router::router::PersonHogRouter;
-use personhog_router::service::PersonHogRouterService;
use personhog_router::stash_handler::RouterStashHandler;
use tokio_util::sync::CancellationToken;
use tonic::transport::Server;
@@ -57,7 +54,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing::info!("Starting personhog-router service");
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);
@@ -122,8 +118,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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,
@@ -159,12 +153,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
});
(
- Arc::new(ReplicaBackend::new_k8s(
- channel,
- config.retry_config(),
- config.grpc_max_send_message_size,
- config.grpc_max_recv_message_size,
- )),
+ Arc::new(ReplicaBackend::new_k8s(channel, config.retry_config())),
Some(disc_readiness),
)
}
@@ -357,9 +346,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let grpc_addr = config.grpc_address;
let keepalive_interval = config.grpc_keepalive_interval();
let keepalive_timeout = config.grpc_keepalive_timeout();
- let max_send = config.grpc_max_send_message_size;
let max_recv = config.grpc_max_recv_message_size;
- let proxy_mode = config.proxy_mode;
let retry_config = config.retry_config();
tracing::info!("Starting gRPC server on {}", grpc_addr);
@@ -374,40 +361,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
};
let incoming = tracked_tcp_incoming(listener);
- let result = if proxy_mode == ProxyMode::Raw {
- let proxy = RawProxyService::new(
- replica_backend,
- leader_backend,
- retry_config,
- max_recv,
- config.response_size_warn_bytes,
- );
- Server::builder()
- .http2_keepalive_interval(keepalive_interval)
- .http2_keepalive_timeout(keepalive_timeout)
- .layer(GrpcMetricsLayer::default())
- .add_service(proxy)
- .serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal())
- .await
- } else {
- let replica_dyn: Arc<dyn personhog_router::backend::PersonHogBackend> = replica_backend;
- let mut router = PersonHogRouter::new(replica_dyn);
- if let Some(leader) = leader_backend {
- router = router.with_leader(leader);
- }
- let service = PersonHogRouterService::new(Arc::new(router));
- Server::builder()
- .http2_keepalive_interval(keepalive_interval)
- .http2_keepalive_timeout(keepalive_timeout)
- .layer(GrpcMetricsLayer::default())
- .add_service(
- PersonHogServiceServer::new(service)
- .max_encoding_message_size(max_send)
- .max_decoding_message_size(max_recv),
- )
- .serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal())
- .await
- };
+ let proxy = RawProxyService::new(
+ replica_backend,
+ leader_backend,
+ retry_config,
+ max_recv,
+ config.response_size_warn_bytes,
+ );
+ let result = Server::builder()
+ .http2_keepalive_interval(keepalive_interval)
+ .http2_keepalive_timeout(keepalive_timeout)
+ .layer(GrpcMetricsLayer::default())
+ .add_service(proxy)
+ .serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal())
+ .await;
if let Err(e) = result {
grpc_handle.signal_failure(format!("gRPC server error: {e}"));
diff --git a/rust/personhog-router/src/router/mod.rs b/rust/personhog-router/src/router/mod.rs
deleted file mode 100644
index cc78c85ca015..000000000000
--- a/rust/personhog-router/src/router/mod.rs
+++ /dev/null
@@ -1,689 +0,0 @@
-mod routing;
-
-pub use routing::{DataCategory, OperationType, RouteDecision};
-
-use std::sync::Arc;
-use std::time::Instant;
-
-use metrics::{counter, histogram};
-use personhog_common::grpc::{current_client_name, ClientInFlightGuard};
-use personhog_proto::personhog::types::v1::{
- CheckCohortMembershipRequest, CohortMembershipResponse, CountCohortMembersRequest,
- CountCohortMembersResponse, CountGroupTypeMappingsRequest, CountGroupTypeMappingsResponse,
- CreateGroupRequest, CreateGroupResponse, DeleteCohortMemberRequest, DeleteCohortMemberResponse,
- DeleteCohortMembersBulkRequest, DeleteCohortMembersBulkResponse, DeleteGroupTypeMappingRequest,
- DeleteGroupTypeMappingResponse, DeleteGroupTypeMappingsBatchForTeamRequest,
- DeleteGroupTypeMappingsBatchForTeamResponse, DeleteGroupsBatchForTeamRequest,
- DeleteGroupsBatchForTeamResponse, DeleteHashKeyOverridesByTeamsRequest,
- DeleteHashKeyOverridesByTeamsResponse, DeletePersonlessDistinctIdsBatchForTeamRequest,
- DeletePersonlessDistinctIdsBatchForTeamResponse, DeletePersonsBatchForTeamRequest,
- DeletePersonsBatchForTeamResponse, DeletePersonsRequest, DeletePersonsResponse,
- GetDistinctIdsForPersonRequest, GetDistinctIdsForPersonResponse,
- GetDistinctIdsForPersonsRequest, GetDistinctIdsForPersonsResponse, GetGroupRequest,
- GetGroupResponse, GetGroupTypeMappingByDashboardIdRequest,
- GetGroupTypeMappingByDashboardIdResponse, GetGroupTypeMappingsByProjectIdRequest,
- GetGroupTypeMappingsByProjectIdsRequest, GetGroupTypeMappingsByTeamIdRequest,
- GetGroupTypeMappingsByTeamIdsRequest, GetGroupsBatchRequest, GetGroupsBatchResponse,
- GetGroupsRequest, GetHashKeyOverrideContextRequest, GetHashKeyOverrideContextResponse,
- GetPersonByDistinctIdRequest, GetPersonByUuidRequest, GetPersonRequest, GetPersonResponse,
- GetPersonsByDistinctIdsInTeamRequest, GetPersonsByDistinctIdsRequest, GetPersonsByUuidsRequest,
- GetPersonsRequest, GroupTypeMappingsBatchResponse, GroupTypeMappingsResponse, GroupsResponse,
- InsertCohortMembersRequest, InsertCohortMembersResponse, ListCohortMemberIdsRequest,
- ListCohortMemberIdsResponse, ListGroupsRequest, ListGroupsResponse,
- PersonsByDistinctIdsInTeamResponse, PersonsByDistinctIdsResponse, PersonsResponse,
- SetPersonDistinctIdVersionFloorRequest, SetPersonDistinctIdVersionFloorResponse,
- SetPersonVersionFloorRequest, SetPersonVersionFloorResponse, SplitPersonRequest,
- SplitPersonResponse, UpdateGroupRequest, UpdateGroupResponse, UpdateGroupTypeMappingRequest,
- UpdateGroupTypeMappingResponse, UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
- UpsertHashKeyOverridesRequest, UpsertHashKeyOverridesResponse,
-};
-use tonic::metadata::MetadataMap;
-use tonic::Status;
-
-use crate::backend::{LeaderOps, PersonHogBackend};
-use routing::{resolve_consistency, route_request};
-
-/// Calls a replica backend method with timing instrumentation.
-macro_rules! call_backend {
- ($self:expr, $method_name:expr, $method:ident, $request:expr) => {{
- let client = current_client_name();
- counter!(
- "personhog_router_backend_requests_total",
- "method" => $method_name,
- "backend" => "replica",
- "client" => client.clone()
- )
- .increment(1);
-
- let _in_flight = ClientInFlightGuard::new("replica");
-
- let start = Instant::now();
- let result = $self.replica_backend.$method($request).await;
- let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
-
- histogram!(
- "personhog_router_backend_duration_ms",
- "method" => $method_name,
- "backend" => "replica",
- "client" => client.clone()
- )
- .record(duration_ms);
-
- if result.is_err() {
- counter!(
- "personhog_router_backend_errors_total",
- "method" => $method_name,
- "backend" => "replica",
- "client" => client.clone()
- )
- .increment(1);
- }
-
- result
- }};
-}
-
-/// Macro to call a leader operation with timing instrumentation.
-macro_rules! call_leader {
- ($self:expr, $method_name:expr, $method:ident, $request:expr) => {{
- let leader = $self.leader_ops.as_ref().ok_or_else(|| {
- Status::unimplemented("leader backend not configured for this router")
- })?;
-
- let client = current_client_name();
- counter!(
- "personhog_router_backend_requests_total",
- "method" => $method_name,
- "backend" => "leader",
- "client" => client.clone()
- )
- .increment(1);
-
- let start = Instant::now();
- let result = leader.$method($request).await;
- let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
-
- histogram!(
- "personhog_router_backend_duration_ms",
- "method" => $method_name,
- "backend" => "leader",
- "client" => client.clone()
- )
- .record(duration_ms);
-
- if result.is_err() {
- counter!(
- "personhog_router_backend_errors_total",
- "method" => $method_name,
- "backend" => "leader",
- "client" => client.clone()
- )
- .increment(1);
- }
-
- result
- }};
-}
-
-/// PersonHogRouter coordinates routing requests to the appropriate backend.
-///
-/// # Routing Logic
-///
-/// | Data Type | Operation | Consistency | Target Backend |
-/// |-----------------|-----------|-------------|--------------------------|
-/// | Person data | Read | EVENTUAL | personhog-replica |
-/// | Person data | Read | STRONG | personhog-leader (Phase 2) |
-/// | Person data | Write | - | personhog-leader (Phase 2) |
-/// | Non-person data | Read | EVENTUAL | personhog-replica |
-/// | Non-person data | Read | STRONG | personhog-replica (primary) |
-/// | Non-person data | Write | - | personhog-replica |
-///
-/// Non-person data includes: hash key overrides, cohort membership, groups, group type mappings
-///
-/// # Metrics
-///
-/// Records backend-specific metrics:
-/// - `personhog_router_backend_requests_total` - counter by method and backend
-/// - `personhog_router_backend_duration_ms` - histogram by method and backend
-/// - `personhog_router_backend_errors_total` - counter by method and backend
-pub struct PersonHogRouter {
- replica_backend: Arc<dyn PersonHogBackend>,
- leader_ops: Option<Arc<dyn LeaderOps>>,
-}
-
-impl PersonHogRouter {
- pub fn new(replica_backend: Arc<dyn PersonHogBackend>) -> Self {
- Self {
- replica_backend,
- leader_ops: None,
- }
- }
-
- pub fn with_leader(mut self, leader_ops: Arc<dyn LeaderOps>) -> Self {
- self.leader_ops = Some(leader_ops);
- self
- }
-
- /// Validate that a read request routes to replica (not leader).
- /// Person data reads with STRONG consistency require the leader, but only
- /// `get_person` supports that. All other person data reads must use EVENTUAL.
- #[allow(clippy::result_large_err)]
- fn require_replica(
- &self,
- category: DataCategory,
- metadata: &MetadataMap,
- read_options: &Option<personhog_proto::personhog::types::v1::ReadOptions>,
- ) -> Result<(), Status> {
- let decision = route_request(
- category,
- OperationType::Read,
- resolve_consistency(metadata, read_options),
- )?;
- if decision == RouteDecision::Leader {
- return Err(Status::unimplemented(
- "strong consistency reads are only supported for get_person",
- ));
- }
- Ok(())
- }
-
- // ============================================================
- // Person lookups by ID - Person data, read operations
- // ============================================================
-
- pub async fn get_person(
- &self,
- metadata: &MetadataMap,
- request: GetPersonRequest,
- ) -> Result<GetPersonResponse, Status> {
- let decision = route_request(
- DataCategory::PersonData,
- OperationType::Read,
- resolve_consistency(metadata, &request.read_options),
- )?;
- match decision {
- RouteDecision::Leader => call_leader!(self, "GetPerson", get_person, request),
- RouteDecision::Replica => {
- call_backend!(self, "GetPerson", get_person, request)
- }
- }
- }
-
- pub async fn get_persons(
- &self,
- metadata: &MetadataMap,
- request: GetPersonsRequest,
- ) -> Result<PersonsResponse, Status> {
- self.require_replica(DataCategory::PersonData, metadata, &request.read_options)?;
- call_backend!(self, "GetPersons", get_persons, request)
- }
-
- pub async fn get_person_by_uuid(
- &self,
- metadata: &MetadataMap,
- request: GetPersonByUuidRequest,
- ) -> Result<GetPersonResponse, Status> {
- self.require_replica(DataCategory::PersonData, metadata, &request.read_options)?;
- call_backend!(self, "GetPersonByUuid", get_person_by_uuid, request)
- }
-
- pub async fn get_persons_by_uuids(
- &self,
- metadata: &MetadataMap,
- request: GetPersonsByUuidsRequest,
- ) -> Result<PersonsResponse, Status> {
- self.require_replica(DataCategory::PersonData, metadata, &request.read_options)?;
- call_backend!(self, "GetPersonsByUuids", get_persons_by_uuids, request)
- }
-
- // ============================================================
- // Person lookups by distinct ID - Person data, read operations
- // ============================================================
-
- pub async fn get_person_by_distinct_id(
- &self,
- metadata: &MetadataMap,
- request: GetPersonByDistinctIdRequest,
- ) -> Result<GetPersonResponse, Status> {
- self.require_replica(DataCategory::PersonData, metadata, &request.read_options)?;
- call_backend!(
- self,
- "GetPersonByDistinctId",
- get_person_by_distinct_id,
- request
- )
- }
-
- pub async fn get_persons_by_distinct_ids_in_team(
- &self,
- metadata: &MetadataMap,
- request: GetPersonsByDistinctIdsInTeamRequest,
- ) -> Result<PersonsByDistinctIdsInTeamResponse, Status> {
- self.require_replica(DataCategory::PersonData, metadata, &request.read_options)?;
- call_backend!(
- self,
- "GetPersonsByDistinctIdsInTeam",
- get_persons_by_distinct_ids_in_team,
- request
- )
- }
-
- pub async fn get_persons_by_distinct_ids(
- &self,
- metadata: &MetadataMap,
- request: GetPersonsByDistinctIdsRequest,
- ) -> Result<PersonsByDistinctIdsResponse, Status> {
- self.require_replica(DataCategory::PersonData, metadata, &request.read_options)?;
- call_backend!(
- self,
- "GetPersonsByDistinctIds",
- get_persons_by_distinct_ids,
- request
- )
- }
-
- // ============================================================
- // Distinct ID operations - Person data, read operations
- // ============================================================
-
- pub async fn get_distinct_ids_for_person(
- &self,
- metadata: &MetadataMap,
- request: GetDistinctIdsForPersonRequest,
- ) -> Result<GetDistinctIdsForPersonResponse, Status> {
- self.require_replica(DataCategory::PersonData, metadata, &request.read_options)?;
- call_backend!(
- self,
- "GetDistinctIdsForPerson",
- get_distinct_ids_for_person,
- request
- )
- }
-
- pub async fn get_distinct_ids_for_persons(
- &self,
- metadata: &MetadataMap,
- request: GetDistinctIdsForPersonsRequest,
- ) -> Result<GetDistinctIdsForPersonsResponse, Status> {
- self.require_replica(DataCategory::PersonData, metadata, &request.read_options)?;
- call_backend!(
- self,
- "GetDistinctIdsForPersons",
- get_distinct_ids_for_persons,
- request
- )
- }
-
- // ============================================================
- // Feature flag hash key overrides - Non-person data
- // ============================================================
-
- pub async fn get_hash_key_override_context(
- &self,
- request: GetHashKeyOverrideContextRequest,
- ) -> Result<GetHashKeyOverrideContextResponse, Status> {
- call_backend!(
- self,
- "GetHashKeyOverrideContext",
- get_hash_key_override_context,
- request
- )
- }
-
- pub async fn upsert_hash_key_overrides(
- &self,
- request: UpsertHashKeyOverridesRequest,
- ) -> Result<UpsertHashKeyOverridesResponse, Status> {
- call_backend!(
- self,
- "UpsertHashKeyOverrides",
- upsert_hash_key_overrides,
- request
- )
- }
-
- pub async fn delete_hash_key_overrides_by_teams(
- &self,
- request: DeleteHashKeyOverridesByTeamsRequest,
- ) -> Result<DeleteHashKeyOverridesByTeamsResponse, Status> {
- call_backend!(
- self,
- "DeleteHashKeyOverridesByTeams",
- delete_hash_key_overrides_by_teams,
- request
- )
- }
-
- // ============================================================
- // Cohort membership - Non-person data
- // ============================================================
-
- pub async fn check_cohort_membership(
- &self,
- request: CheckCohortMembershipRequest,
- ) -> Result<CohortMembershipResponse, Status> {
- call_backend!(
- self,
- "CheckCohortMembership",
- check_cohort_membership,
- request
- )
- }
-
- pub async fn count_cohort_members(
- &self,
- request: CountCohortMembersRequest,
- ) -> Result<CountCohortMembersResponse, Status> {
- call_backend!(self, "CountCohortMembers", count_cohort_members, request)
- }
-
- pub async fn delete_cohort_member(
- &self,
- request: DeleteCohortMemberRequest,
- ) -> Result<DeleteCohortMemberResponse, Status> {
- call_backend!(self, "DeleteCohortMember", delete_cohort_member, request)
- }
-
- pub async fn delete_cohort_members_bulk(
- &self,
- request: DeleteCohortMembersBulkRequest,
- ) -> Result<DeleteCohortMembersBulkResponse, Status> {
- call_backend!(
- self,
- "DeleteCohortMembersBulk",
- delete_cohort_members_bulk,
- request
- )
- }
-
- pub async fn insert_cohort_members(
- &self,
- request: InsertCohortMembersRequest,
- ) -> Result<InsertCohortMembersResponse, Status> {
- call_backend!(self, "InsertCohortMembers", insert_cohort_members, request)
- }
-
- pub async fn list_cohort_member_ids(
- &self,
- request: ListCohortMemberIdsRequest,
- ) -> Result<ListCohortMemberIdsResponse, Status> {
- call_backend!(self, "ListCohortMemberIds", list_cohort_member_ids, request)
- }
-
- // ============================================================
- // Groups - Non-person data
- // ============================================================
-
- pub async fn get_group(&self, request: GetGroupRequest) -> Result<GetGroupResponse, Status> {
- call_backend!(self, "GetGroup", get_group, request)
- }
-
- pub async fn get_groups(&self, request: GetGroupsRequest) -> Result<GroupsResponse, Status> {
- call_backend!(self, "GetGroups", get_groups, request)
- }
-
- pub async fn get_groups_batch(
- &self,
- request: GetGroupsBatchRequest,
- ) -> Result<GetGroupsBatchResponse, Status> {
- call_backend!(self, "GetGroupsBatch", get_groups_batch, request)
- }
-
- pub async fn list_groups(
- &self,
- request: ListGroupsRequest,
- ) -> Result<ListGroupsResponse, Status> {
- call_backend!(self, "ListGroups", list_groups, request)
- }
-
- // ============================================================
- // Group type mappings - Non-person data
- // ============================================================
-
- pub async fn get_group_type_mappings_by_team_id(
- &self,
- request: GetGroupTypeMappingsByTeamIdRequest,
- ) -> Result<GroupTypeMappingsResponse, Status> {
- call_backend!(
- self,
- "GetGroupTypeMappingsByTeamId",
- get_group_type_mappings_by_team_id,
- request
- )
- }
-
- pub async fn get_group_type_mappings_by_team_ids(
- &self,
- request: GetGroupTypeMappingsByTeamIdsRequest,
- ) -> Result<GroupTypeMappingsBatchResponse, Status> {
- call_backend!(
- self,
- "GetGroupTypeMappingsByTeamIds",
- get_group_type_mappings_by_team_ids,
- request
- )
- }
-
- pub async fn get_group_type_mappings_by_project_id(
- &self,
- request: GetGroupTypeMappingsByProjectIdRequest,
- ) -> Result<GroupTypeMappingsResponse, Status> {
- call_backend!(
- self,
- "GetGroupTypeMappingsByProjectId",
- get_group_type_mappings_by_project_id,
- request
- )
- }
-
- pub async fn get_group_type_mappings_by_project_ids(
- &self,
- request: GetGroupTypeMappingsByProjectIdsRequest,
- ) -> Result<GroupTypeMappingsBatchResponse, Status> {
- call_backend!(
- self,
- "GetGroupTypeMappingsByProjectIds",
- get_group_type_mappings_by_project_ids,
- request
- )
- }
-
- pub async fn count_group_type_mappings(
- &self,
- request: CountGroupTypeMappingsRequest,
- ) -> Result<CountGroupTypeMappingsResponse, Status> {
- call_backend!(
- self,
- "CountGroupTypeMappings",
- count_group_type_mappings,
- request
- )
- }
-
- pub async fn get_group_type_mapping_by_dashboard_id(
- &self,
- request: GetGroupTypeMappingByDashboardIdRequest,
- ) -> Result<GetGroupTypeMappingByDashboardIdResponse, Status> {
- call_backend!(
- self,
- "GetGroupTypeMappingByDashboardId",
- get_group_type_mapping_by_dashboard_id,
- request
- )
- }
-
- // ============================================================
- // Group writes - Non-person data
- // ============================================================
-
- pub async fn create_group(
- &self,
- request: CreateGroupRequest,
- ) -> Result<CreateGroupResponse, Status> {
- call_backend!(self, "CreateGroup", create_group, request)
- }
-
- pub async fn update_group(
- &self,
- request: UpdateGroupRequest,
- ) -> Result<UpdateGroupResponse, Status> {
- call_backend!(self, "UpdateGroup", update_group, request)
- }
-
- pub async fn delete_groups_batch_for_team(
- &self,
- request: DeleteGroupsBatchForTeamRequest,
- ) -> Result<DeleteGroupsBatchForTeamResponse, Status> {
- call_backend!(
- self,
- "DeleteGroupsBatchForTeam",
- delete_groups_batch_for_team,
- request
- )
- }
-
- // ============================================================
- // Group type mapping writes - Non-person data
- // ============================================================
-
- pub async fn update_group_type_mapping(
- &self,
- request: UpdateGroupTypeMappingRequest,
- ) -> Result<UpdateGroupTypeMappingResponse, Status> {
- call_backend!(
- self,
- "UpdateGroupTypeMapping",
- update_group_type_mapping,
- request
- )
- }
-
- pub async fn delete_group_type_mapping(
- &self,
- request: DeleteGroupTypeMappingRequest,
- ) -> Result<DeleteGroupTypeMappingResponse, Status> {
- call_backend!(
- self,
- "DeleteGroupTypeMapping",
- delete_group_type_mapping,
- request
- )
- }
-
- pub async fn delete_group_type_mappings_batch_for_team(
- &self,
- request: DeleteGroupTypeMappingsBatchForTeamRequest,
- ) -> Result<DeleteGroupTypeMappingsBatchForTeamResponse, Status> {
- call_backend!(
- self,
- "DeleteGroupTypeMappingsBatchForTeam",
- delete_group_type_mappings_batch_for_team,
- request
- )
- }
-
- // ============================================================
- // Person deletes - Person data, write operations
- // ============================================================
-
- /// Delete persons from Postgres.
- ///
- /// WARNING: This is a write operation on person data. Per routing rules, it should
- /// use call_leader! once personhog-leader supports deletes. Currently routed through
- /// the replica (which uses the primary Postgres pool) as a temporary measure.
- /// TODO: Migrate to call_leader! before personhog-leader goes live.
- pub async fn delete_persons(
- &self,
- request: DeletePersonsRequest,
- ) -> Result<DeletePersonsResponse, Status> {
- call_backend!(self, "DeletePersons", delete_persons, request)
- }
-
- /// Delete up to batch_size persons for a team from Postgres.
- ///
- /// WARNING: Same routing caveat as delete_persons above.
- pub async fn delete_persons_batch_for_team(
- &self,
- request: DeletePersonsBatchForTeamRequest,
- ) -> Result<DeletePersonsBatchForTeamResponse, Status> {
- call_backend!(
- self,
- "DeletePersonsBatchForTeam",
- delete_persons_batch_for_team,
- request
- )
- }
-
- /// Delete a batch of personless distinct IDs for a team.
- ///
- /// WARNING: Same routing caveat as delete_persons above.
- pub async fn delete_personless_distinct_ids_batch_for_team(
- &self,
- request: DeletePersonlessDistinctIdsBatchForTeamRequest,
- ) -> Result<DeletePersonlessDistinctIdsBatchForTeamResponse, Status> {
- call_backend!(
- self,
- "DeletePersonlessDistinctIdsBatchForTeam",
- delete_personless_distinct_ids_batch_for_team,
- request
- )
- }
-
- /// Split distinct_ids off a person onto new persons.
- ///
- /// WARNING: Same routing caveat as delete_persons above — write operation on
- /// person data routed through replica (primary pool) until leader supports
- /// transactional writes.
- pub async fn split_person(
- &self,
- request: SplitPersonRequest,
- ) -> Result<SplitPersonResponse, Status> {
- call_backend!(self, "SplitPerson", split_person, request)
- }
-
- /// Set a person_distinct_id's version (undelete repair).
- ///
- /// WARNING: Same routing caveat as split_person above.
- pub async fn set_person_distinct_id_version_floor(
- &self,
- request: SetPersonDistinctIdVersionFloorRequest,
- ) -> Result<SetPersonDistinctIdVersionFloorResponse, Status> {
- call_backend!(
- self,
- "SetPersonDistinctIdVersionFloor",
- set_person_distinct_id_version_floor,
- request
- )
- }
-
- /// Bump a person's version (undelete repair).
- ///
- /// WARNING: Same routing caveat as split_person above.
- pub async fn set_person_version_floor(
- &self,
- request: SetPersonVersionFloorRequest,
- ) -> Result<SetPersonVersionFloorResponse, Status> {
- call_backend!(
- self,
- "SetPersonVersionFloor",
- set_person_version_floor,
- request
- )
- }
-
- // ============================================================
- // Person property updates - Person data, write operations
- // ============================================================
-
- pub async fn update_person_properties(
- &self,
- request: UpdatePersonPropertiesRequest,
- ) -> Result<UpdatePersonPropertiesResponse, Status> {
- call_leader!(
- self,
- "UpdatePersonProperties",
- update_person_properties,
- request
- )
- }
-}
diff --git a/rust/personhog-router/src/router/routing.rs b/rust/personhog-router/src/router/routing.rs
deleted file mode 100644
index 0dfc5e1a7d9d..000000000000
--- a/rust/personhog-router/src/router/routing.rs
+++ /dev/null
@@ -1,241 +0,0 @@
-use metrics::counter;
-use personhog_proto::personhog::types::v1::{ConsistencyLevel, ReadOptions};
-use tonic::metadata::MetadataMap;
-use tonic::Status;
-
-/// Categories of data for routing decisions.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum DataCategory {
- /// Person table data (person, persondistinctid)
- /// - Reads with EVENTUAL consistency → replica
- /// - Reads with STRONG consistency → leader
- /// - Writes → leader
- PersonData,
-
- /// Non-person data (hash key overrides, cohorts, groups, group type mappings)
- /// - All reads → replica (any consistency level)
- /// - All writes → replica
- NonPersonData,
-}
-
-/// Type of operation being performed.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum OperationType {
- Read,
- Write,
-}
-
-/// The target backend for a routed request.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum RouteDecision {
- /// Route to personhog-replica (Postgres replicas, or primary for strong consistency on non-person data)
- Replica,
- /// Route to personhog-leader (Kafka-backed cache)
- Leader,
-}
-
-/// Determine which backend should handle this request.
-///
-/// # Routing Rules
-///
-/// ## Person Data (person, persondistinctid tables)
-/// - EVENTUAL consistency reads → Replica
-/// - STRONG consistency reads → Leader
-/// - Writes → Leader
-///
-/// ## Non-Person Data (hash_key_overrides, cohort_membership, groups, group_type_mappings)
-/// - All reads → Replica (consistency is handled internally by replica)
-/// - All writes → Replica
-#[allow(clippy::unnecessary_wraps, clippy::result_large_err)]
-pub fn route_request(
- category: DataCategory,
- operation: OperationType,
- consistency: Option<ConsistencyLevel>,
-) -> Result<RouteDecision, Status> {
- match (category, operation) {
- // Person data routing
- (DataCategory::PersonData, OperationType::Read) => {
- let consistency = consistency.unwrap_or(ConsistencyLevel::Eventual);
- match consistency {
- ConsistencyLevel::Unspecified | ConsistencyLevel::Eventual => {
- Ok(RouteDecision::Replica)
- }
- ConsistencyLevel::Strong => Ok(RouteDecision::Leader),
- }
- }
- (DataCategory::PersonData, OperationType::Write) => Ok(RouteDecision::Leader),
-
- // Non-person data always goes to replica
- // The replica handles consistency internally (primary vs replica pool)
- (DataCategory::NonPersonData, OperationType::Read) => Ok(RouteDecision::Replica),
- (DataCategory::NonPersonData, OperationType::Write) => Ok(RouteDecision::Replica),
- }
-}
-
-/// Extract consistency level from optional ReadOptions.
-pub fn get_consistency(read_options: &Option<ReadOptions>) -> Option<ConsistencyLevel> {
- read_options.as_ref().map(|opts| opts.consistency())
-}
-
-/// Extract consistency level from the `x-read-consistency` gRPC metadata header.
-pub fn get_consistency_from_header(metadata: &MetadataMap) -> Option<ConsistencyLevel> {
- metadata
- .get("x-read-consistency")
- .and_then(|v| match v.to_str().ok()? {
- "strong" => Some(ConsistencyLevel::Strong),
- "eventual" => Some(ConsistencyLevel::Eventual),
- _ => None,
- })
-}
-
-/// Resolve consistency level: prefer the gRPC metadata header, fall back to body read_options.
-pub fn resolve_consistency(
- metadata: &MetadataMap,
- read_options: &Option<ReadOptions>,
-) -> Option<ConsistencyLevel> {
- if let Some(level) = get_consistency_from_header(metadata) {
- counter!("personhog_router_consistency_source", "source" => "header").increment(1);
- return Some(level);
- }
- let level = get_consistency(read_options);
- if level.is_some() {
- counter!("personhog_router_consistency_source", "source" => "body").increment(1);
- } else {
- counter!("personhog_router_consistency_source", "source" => "none").increment(1);
- }
- level
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_get_consistency_from_header_strong() {
- let mut metadata = MetadataMap::new();
- metadata.insert("x-read-consistency", "strong".parse().unwrap());
- assert_eq!(
- get_consistency_from_header(&metadata),
- Some(ConsistencyLevel::Strong)
- );
- }
-
- #[test]
- fn test_get_consistency_from_header_eventual() {
- let mut metadata = MetadataMap::new();
- metadata.insert("x-read-consistency", "eventual".parse().unwrap());
- assert_eq!(
- get_consistency_from_header(&metadata),
- Some(ConsistencyLevel::Eventual)
- );
- }
-
- #[test]
- fn test_get_consistency_from_header_missing() {
- let metadata = MetadataMap::new();
- assert_eq!(get_consistency_from_header(&metadata), None);
- }
-
- #[test]
- fn test_get_consistency_from_header_unknown_value() {
- let mut metadata = MetadataMap::new();
- metadata.insert("x-read-consistency", "bogus".parse().unwrap());
- assert_eq!(get_consistency_from_header(&metadata), None);
- }
-
- #[test]
- fn test_resolve_consistency_header_takes_precedence() {
- let mut metadata = MetadataMap::new();
- metadata.insert("x-read-consistency", "strong".parse().unwrap());
- let body_options = Some(ReadOptions {
- consistency: ConsistencyLevel::Eventual.into(),
- ..Default::default()
- });
- assert_eq!(
- resolve_consistency(&metadata, &body_options),
- Some(ConsistencyLevel::Strong)
- );
- }
-
- #[test]
- fn test_resolve_consistency_falls_back_to_body() {
- let metadata = MetadataMap::new();
- let body_options = Some(ReadOptions {
- consistency: ConsistencyLevel::Strong.into(),
- ..Default::default()
- });
- assert_eq!(
- resolve_consistency(&metadata, &body_options),
- Some(ConsistencyLevel::Strong)
- );
- }
-
- #[test]
- fn test_person_data_eventual_routes_to_replica() {
- let result = route_request(
- DataCategory::PersonData,
- OperationType::Read,
- Some(ConsistencyLevel::Eventual),
- );
- assert_eq!(result.unwrap(), RouteDecision::Replica);
- }
-
- #[test]
- fn test_person_data_unspecified_routes_to_replica() {
- let result = route_request(
- DataCategory::PersonData,
- OperationType::Read,
- Some(ConsistencyLevel::Unspecified),
- );
- assert_eq!(result.unwrap(), RouteDecision::Replica);
- }
-
- #[test]
- fn test_person_data_none_consistency_routes_to_replica() {
- let result = route_request(DataCategory::PersonData, OperationType::Read, None);
- assert_eq!(result.unwrap(), RouteDecision::Replica);
- }
-
- #[test]
- fn test_person_data_strong_routes_to_leader() {
- let result = route_request(
- DataCategory::PersonData,
- OperationType::Read,
- Some(ConsistencyLevel::Strong),
- );
- assert_eq!(result.unwrap(), RouteDecision::Leader);
- }
-
- #[test]
- fn test_person_data_write_routes_to_leader() {
- let result = route_request(DataCategory::PersonData, OperationType::Write, None);
- assert_eq!(result.unwrap(), RouteDecision::Leader);
- }
-
- #[test]
- fn test_non_person_data_read_eventual_routes_to_replica() {
- let result = route_request(
- DataCategory::NonPersonData,
- OperationType::Read,
- Some(ConsistencyLevel::Eventual),
- );
- assert_eq!(result.unwrap(), RouteDecision::Replica);
- }
-
- #[test]
- fn test_non_person_data_read_strong_routes_to_replica() {
- // Non-person data strong consistency is handled internally by replica
- let result = route_request(
- DataCategory::NonPersonData,
- OperationType::Read,
- Some(ConsistencyLevel::Strong),
- );
- assert_eq!(result.unwrap(), RouteDecision::Replica);
- }
-
- #[test]
- fn test_non_person_data_write_routes_to_replica() {
- let result = route_request(DataCategory::NonPersonData, OperationType::Write, None);
- assert_eq!(result.unwrap(), RouteDecision::Replica);
- }
-}
diff --git a/rust/personhog-router/src/service/mod.rs b/rust/personhog-router/src/service/mod.rs
deleted file mode 100644
index d36568868880..000000000000
--- a/rust/personhog-router/src/service/mod.rs
+++ /dev/null
@@ -1,382 +0,0 @@
-#[cfg(test)]
-mod tests;
-
-use std::sync::Arc;
-
-use personhog_proto::personhog::service::v1::person_hog_service_server::PersonHogService;
-use personhog_proto::personhog::types::v1::{
- CheckCohortMembershipRequest, CohortMembershipResponse, CountCohortMembersRequest,
- CountCohortMembersResponse, CountGroupTypeMappingsRequest, CountGroupTypeMappingsResponse,
- CreateGroupRequest, CreateGroupResponse, DeleteCohortMemberRequest, DeleteCohortMemberResponse,
- DeleteCohortMembersBulkRequest, DeleteCohortMembersBulkResponse, DeleteGroupTypeMappingRequest,
- DeleteGroupTypeMappingResponse, DeleteGroupTypeMappingsBatchForTeamRequest,
- DeleteGroupTypeMappingsBatchForTeamResponse, DeleteGroupsBatchForTeamRequest,
- DeleteGroupsBatchForTeamResponse, DeleteHashKeyOverridesByTeamsRequest,
- DeleteHashKeyOverridesByTeamsResponse, DeletePersonlessDistinctIdsBatchForTeamRequest,
- DeletePersonlessDistinctIdsBatchForTeamResponse, DeletePersonsBatchForTeamRequest,
- DeletePersonsBatchForTeamResponse, DeletePersonsRequest, DeletePersonsResponse,
- GetDistinctIdsForPersonRequest, GetDistinctIdsForPersonResponse,
- GetDistinctIdsForPersonsRequest, GetDistinctIdsForPersonsResponse, GetGroupRequest,
- GetGroupResponse, GetGroupTypeMappingByDashboardIdRequest,
- GetGroupTypeMappingByDashboardIdResponse, GetGroupTypeMappingsByProjectIdRequest,
- GetGroupTypeMappingsByProjectIdsRequest, GetGroupTypeMappingsByTeamIdRequest,
- GetGroupTypeMappingsByTeamIdsRequest, GetGroupsBatchRequest, GetGroupsBatchResponse,
- GetGroupsRequest, GetHashKeyOverrideContextRequest, GetHashKeyOverrideContextResponse,
- GetPersonByDistinctIdRequest, GetPersonByUuidRequest, GetPersonRequest, GetPersonResponse,
- GetPersonsByDistinctIdsInTeamRequest, GetPersonsByDistinctIdsRequest, GetPersonsByUuidsRequest,
- GetPersonsRequest, GroupTypeMappingsBatchResponse, GroupTypeMappingsResponse, GroupsResponse,
- InsertCohortMembersRequest, InsertCohortMembersResponse, ListCohortMemberIdsRequest,
- ListCohortMemberIdsResponse, ListGroupsRequest, ListGroupsResponse,
- PersonsByDistinctIdsInTeamResponse, PersonsByDistinctIdsResponse, PersonsResponse,
- SetPersonDistinctIdVersionFloorRequest, SetPersonDistinctIdVersionFloorResponse,
- SetPersonVersionFloorRequest, SetPersonVersionFloorResponse, SplitPersonRequest,
- SplitPersonResponse, UpdateGroupRequest, UpdateGroupResponse, UpdateGroupTypeMappingRequest,
- UpdateGroupTypeMappingResponse, UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
- UpsertHashKeyOverridesRequest, UpsertHashKeyOverridesResponse,
-};
-use tonic::{Request, Response, Status};
-
-use crate::router::PersonHogRouter;
-
-pub struct PersonHogRouterService {
- router: Arc<PersonHogRouter>,
-}
-
-impl PersonHogRouterService {
- pub fn new(router: Arc<PersonHogRouter>) -> Self {
- Self { router }
- }
-}
-
-macro_rules! route_request {
- ($self:expr, $method:ident, $request:expr) => {{
- match $self.router.$method($request.into_inner()).await {
- Ok(response) => Ok(Response::new(response)),
- Err(status) => Err(status),
- }
- }};
-}
-
-macro_rules! route_with_metadata {
- ($self:expr, $method:ident, $request:expr) => {{
- let metadata = $request.metadata().clone();
- match $self.router.$method(&metadata, $request.into_inner()).await {
- Ok(response) => Ok(Response::new(response)),
- Err(status) => Err(status),
- }
- }};
-}
-
-#[tonic::async_trait]
-impl PersonHogService for PersonHogRouterService {
- // Person lookups by ID
-
- async fn get_person(
- &self,
- request: Request<GetPersonRequest>,
- ) -> Result<Response<GetPersonResponse>, Status> {
- route_with_metadata!(self, get_person, request)
- }
-
- async fn get_persons(
- &self,
- request: Request<GetPersonsRequest>,
- ) -> Result<Response<PersonsResponse>, Status> {
- route_with_metadata!(self, get_persons, request)
- }
-
- async fn get_person_by_uuid(
- &self,
- request: Request<GetPersonByUuidRequest>,
- ) -> Result<Response<GetPersonResponse>, Status> {
- route_with_metadata!(self, get_person_by_uuid, request)
- }
-
- async fn get_persons_by_uuids(
- &self,
- request: Request<GetPersonsByUuidsRequest>,
- ) -> Result<Response<PersonsResponse>, Status> {
- route_with_metadata!(self, get_persons_by_uuids, request)
- }
-
- // Person lookups by distinct ID
-
- async fn get_person_by_distinct_id(
- &self,
- request: Request<GetPersonByDistinctIdRequest>,
- ) -> Result<Response<GetPersonResponse>, Status> {
- route_with_metadata!(self, get_person_by_distinct_id, request)
- }
-
- async fn get_persons_by_distinct_ids_in_team(
- &self,
- request: Request<GetPersonsByDistinctIdsInTeamRequest>,
- ) -> Result<Response<PersonsByDistinctIdsInTeamResponse>, Status> {
- route_with_metadata!(self, get_persons_by_distinct_ids_in_team, request)
- }
-
- async fn get_persons_by_distinct_ids(
- &self,
- request: Request<GetPersonsByDistinctIdsRequest>,
- ) -> Result<Response<PersonsByDistinctIdsResponse>, Status> {
- route_with_metadata!(self, get_persons_by_distinct_ids, request)
- }
-
- // Distinct ID operations
-
- async fn get_distinct_ids_for_person(
- &self,
- request: Request<GetDistinctIdsForPersonRequest>,
- ) -> Result<Response<GetDistinctIdsForPersonResponse>, Status> {
- route_with_metadata!(self, get_distinct_ids_for_person, request)
- }
-
- async fn get_distinct_ids_for_persons(
- &self,
- request: Request<GetDistinctIdsForPersonsRequest>,
- ) -> Result<Response<GetDistinctIdsForPersonsResponse>, Status> {
- route_with_metadata!(self, get_distinct_ids_for_persons, request)
- }
-
- // Feature flag hash key override support
-
- async fn get_hash_key_override_context(
- &self,
- request: Request<GetHashKeyOverrideContextRequest>,
- ) -> Result<Response<GetHashKeyOverrideContextResponse>, Status> {
- route_request!(self, get_hash_key_override_context, request)
- }
-
- async fn upsert_hash_key_overrides(
- &self,
- request: Request<UpsertHashKeyOverridesRequest>,
- ) -> Result<Response<UpsertHashKeyOverridesResponse>, Status> {
- route_request!(self, upsert_hash_key_overrides, request)
- }
-
- async fn delete_hash_key_overrides_by_teams(
- &self,
- request: Request<DeleteHashKeyOverridesByTeamsRequest>,
- ) -> Result<Response<DeleteHashKeyOverridesByTeamsResponse>, Status> {
- route_request!(self, delete_hash_key_overrides_by_teams, request)
- }
-
- // Cohort membership
-
- async fn check_cohort_membership(
- &self,
- request: Request<CheckCohortMembershipRequest>,
- ) -> Result<Response<CohortMembershipResponse>, Status> {
- route_request!(self, check_cohort_membership, request)
- }
-
- async fn count_cohort_members(
- &self,
- request: Request<CountCohortMembersRequest>,
- ) -> Result<Response<CountCohortMembersResponse>, Status> {
- route_request!(self, count_cohort_members, request)
- }
-
- async fn delete_cohort_member(
- &self,
- request: Request<DeleteCohortMemberRequest>,
- ) -> Result<Response<DeleteCohortMemberResponse>, Status> {
- route_request!(self, delete_cohort_member, request)
- }
-
- async fn delete_cohort_members_bulk(
- &self,
- request: Request<DeleteCohortMembersBulkRequest>,
- ) -> Result<Response<DeleteCohortMembersBulkResponse>, Status> {
- route_request!(self, delete_cohort_members_bulk, request)
- }
-
- async fn insert_cohort_members(
- &self,
- request: Request<InsertCohortMembersRequest>,
- ) -> Result<Response<InsertCohortMembersResponse>, Status> {
- route_request!(self, insert_cohort_members, request)
- }
-
- async fn list_cohort_member_ids(
- &self,
- request: Request<ListCohortMemberIdsRequest>,
- ) -> Result<Response<ListCohortMemberIdsResponse>, Status> {
- route_request!(self, list_cohort_member_ids, request)
- }
-
- // Groups
-
- async fn get_group(
- &self,
- request: Request<GetGroupRequest>,
- ) -> Result<Response<GetGroupResponse>, Status> {
- route_request!(self, get_group, request)
- }
-
- async fn get_groups(
- &self,
- request: Request<GetGroupsRequest>,
- ) -> Result<Response<GroupsResponse>, Status> {
- route_request!(self, get_groups, request)
- }
-
- async fn get_groups_batch(
- &self,
- request: Request<GetGroupsBatchRequest>,
- ) -> Result<Response<GetGroupsBatchResponse>, Status> {
- route_request!(self, get_groups_batch, request)
- }
-
- async fn list_groups(
- &self,
- request: Request<ListGroupsRequest>,
- ) -> Result<Response<ListGroupsResponse>, Status> {
- route_request!(self, list_groups, request)
- }
-
- // Group type mappings
-
- async fn get_group_type_mappings_by_team_id(
- &self,
- request: Request<GetGroupTypeMappingsByTeamIdRequest>,
- ) -> Result<Response<GroupTypeMappingsResponse>, Status> {
- route_request!(self, get_group_type_mappings_by_team_id, request)
- }
-
- async fn get_group_type_mappings_by_team_ids(
- &self,
- request: Request<GetGroupTypeMappingsByTeamIdsRequest>,
- ) -> Result<Response<GroupTypeMappingsBatchResponse>, Status> {
- route_request!(self, get_group_type_mappings_by_team_ids, request)
- }
-
- async fn get_group_type_mappings_by_project_id(
- &self,
- request: Request<GetGroupTypeMappingsByProjectIdRequest>,
- ) -> Result<Response<GroupTypeMappingsResponse>, Status> {
- route_request!(self, get_group_type_mappings_by_project_id, request)
- }
-
- async fn get_group_type_mappings_by_project_ids(
- &self,
- request: Request<GetGroupTypeMappingsByProjectIdsRequest>,
- ) -> Result<Response<GroupTypeMappingsBatchResponse>, Status> {
- route_request!(self, get_group_type_mappings_by_project_ids, request)
- }
-
- async fn count_group_type_mappings(
- &self,
- request: Request<CountGroupTypeMappingsRequest>,
- ) -> Result<Response<CountGroupTypeMappingsResponse>, Status> {
- route_request!(self, count_group_type_mappings, request)
- }
-
- async fn get_group_type_mapping_by_dashboard_id(
- &self,
- request: Request<GetGroupTypeMappingByDashboardIdRequest>,
- ) -> Result<Response<GetGroupTypeMappingByDashboardIdResponse>, Status> {
- route_request!(self, get_group_type_mapping_by_dashboard_id, request)
- }
-
- // Group writes
-
- async fn create_group(
- &self,
- request: Request<CreateGroupRequest>,
- ) -> Result<Response<CreateGroupResponse>, Status> {
- route_request!(self, create_group, request)
- }
-
- async fn update_group(
- &self,
- request: Request<UpdateGroupRequest>,
- ) -> Result<Response<UpdateGroupResponse>, Status> {
- route_request!(self, update_group, request)
- }
-
- async fn delete_groups_batch_for_team(
- &self,
- request: Request<DeleteGroupsBatchForTeamRequest>,
- ) -> Result<Response<DeleteGroupsBatchForTeamResponse>, Status> {
- route_request!(self, delete_groups_batch_for_team, request)
- }
-
- // Group type mapping writes
-
- async fn update_group_type_mapping(
- &self,
- request: Request<UpdateGroupTypeMappingRequest>,
- ) -> Result<Response<UpdateGroupTypeMappingResponse>, Status> {
- route_request!(self, update_group_type_mapping, request)
- }
-
- async fn delete_group_type_mapping(
- &self,
- request: Request<DeleteGroupTypeMappingRequest>,
- ) -> Result<Response<DeleteGroupTypeMappingResponse>, Status> {
- route_request!(self, delete_group_type_mapping, request)
- }
-
- async fn delete_group_type_mappings_batch_for_team(
- &self,
- request: Request<DeleteGroupTypeMappingsBatchForTeamRequest>,
- ) -> Result<Response<DeleteGroupTypeMappingsBatchForTeamResponse>, Status> {
- route_request!(self, delete_group_type_mappings_batch_for_team, request)
- }
-
- // Person deletes
-
- async fn delete_persons(
- &self,
- request: Request<DeletePersonsRequest>,
- ) -> Result<Response<DeletePersonsResponse>, Status> {
- route_request!(self, delete_persons, request)
- }
-
- async fn delete_persons_batch_for_team(
- &self,
- request: Request<DeletePersonsBatchForTeamRequest>,
- ) -> Result<Response<DeletePersonsBatchForTeamResponse>, Status> {
- route_request!(self, delete_persons_batch_for_team, request)
- }
-
- async fn delete_personless_distinct_ids_batch_for_team(
- &self,
- request: Request<DeletePersonlessDistinctIdsBatchForTeamRequest>,
- ) -> Result<Response<DeletePersonlessDistinctIdsBatchForTeamResponse>, Status> {
- route_request!(self, delete_personless_distinct_ids_batch_for_team, request)
- }
-
- // Person split
-
- async fn split_person(
- &self,
- request: Request<SplitPersonRequest>,
- ) -> Result<Response<SplitPersonResponse>, Status> {
- route_request!(self, split_person, request)
- }
-
- async fn set_person_distinct_id_version_floor(
- &self,
- request: Request<SetPersonDistinctIdVersionFloorRequest>,
- ) -> Result<Response<SetPersonDistinctIdVersionFloorResponse>, Status> {
- route_request!(self, set_person_distinct_id_version_floor, request)
- }
-
- async fn set_person_version_floor(
- &self,
- request: Request<SetPersonVersionFloorRequest>,
- ) -> Result<Response<SetPersonVersionFloorResponse>, Status> {
- route_request!(self, set_person_version_floor, request)
- }
-
- // Person property updates (routed to leader)
-
- async fn update_person_properties(
- &self,
- request: Request<UpdatePersonPropertiesRequest>,
- ) -> Result<Response<UpdatePersonPropertiesResponse>, Status> {
- route_request!(self, update_person_properties, request)
- }
-}
diff --git a/rust/personhog-router/src/service/tests/mocks.rs b/rust/personhog-router/src/service/tests/mocks.rs
deleted file mode 100644
index 57285905303e..000000000000
--- a/rust/personhog-router/src/service/tests/mocks.rs
+++ /dev/null
@@ -1,402 +0,0 @@
-use async_trait::async_trait;
-use personhog_proto::personhog::types::v1::{
- CheckCohortMembershipRequest, CohortMembershipResponse, CountCohortMembersRequest,
- CountCohortMembersResponse, CountGroupTypeMappingsRequest, CountGroupTypeMappingsResponse,
- CreateGroupRequest, CreateGroupResponse, DeleteCohortMemberRequest, DeleteCohortMemberResponse,
- DeleteCohortMembersBulkRequest, DeleteCohortMembersBulkResponse, DeleteGroupTypeMappingRequest,
- DeleteGroupTypeMappingResponse, DeleteGroupTypeMappingsBatchForTeamRequest,
- DeleteGroupTypeMappingsBatchForTeamResponse, DeleteGroupsBatchForTeamRequest,
- DeleteGroupsBatchForTeamResponse, DeleteHashKeyOverridesByTeamsRequest,
- DeleteHashKeyOverridesByTeamsResponse, DeletePersonlessDistinctIdsBatchForTeamRequest,
- DeletePersonlessDistinctIdsBatchForTeamResponse, DeletePersonsBatchForTeamRequest,
- DeletePersonsBatchForTeamResponse, DeletePersonsRequest, DeletePersonsResponse,
- GetDistinctIdsForPersonRequest, GetDistinctIdsForPersonResponse,
- GetDistinctIdsForPersonsRequest, GetDistinctIdsForPersonsResponse, GetGroupRequest,
- GetGroupResponse, GetGroupTypeMappingByDashboardIdRequest,
- GetGroupTypeMappingByDashboardIdResponse, GetGroupTypeMappingsByProjectIdRequest,
- GetGroupTypeMappingsByProjectIdsRequest, GetGroupTypeMappingsByTeamIdRequest,
- GetGroupTypeMappingsByTeamIdsRequest, GetGroupsBatchRequest, GetGroupsBatchResponse,
- GetGroupsRequest, GetHashKeyOverrideContextRequest, GetHashKeyOverrideContextResponse,
- GetPersonByDistinctIdRequest, GetPersonByUuidRequest, GetPersonRequest, GetPersonResponse,
- GetPersonsByDistinctIdsInTeamRequest, GetPersonsByDistinctIdsRequest, GetPersonsByUuidsRequest,
- GetPersonsRequest, GroupTypeMappingsBatchResponse, GroupTypeMappingsResponse, GroupsResponse,
- InsertCohortMembersRequest, InsertCohortMembersResponse, ListCohortMemberIdsRequest,
- ListCohortMemberIdsResponse, ListGroupsRequest, ListGroupsResponse, Person,
- PersonsByDistinctIdsInTeamResponse, PersonsByDistinctIdsResponse, PersonsResponse,
- SetPersonDistinctIdVersionFloorRequest, SetPersonDistinctIdVersionFloorResponse,
- SetPersonVersionFloorRequest, SetPersonVersionFloorResponse, SplitPersonRequest,
- SplitPersonResponse, UpdateGroupRequest, UpdateGroupResponse, UpdateGroupTypeMappingRequest,
- UpdateGroupTypeMappingResponse, UpsertHashKeyOverridesRequest, UpsertHashKeyOverridesResponse,
-};
-use std::sync::Mutex;
-use tonic::Status;
-
-use crate::backend::PersonHogBackend;
-
-pub struct MockBackend {
- person_response: Mutex<Option<Person>>,
- error: Mutex<Option<Status>>,
-}
-
-impl MockBackend {
- pub fn new() -> Self {
- Self {
- person_response: Mutex::new(None),
- error: Mutex::new(None),
- }
- }
-
- pub fn set_person_response(&self, person: Option<Person>) {
- *self.person_response.lock().unwrap() = person;
- }
-
- pub fn set_error(&self, status: Status) {
- *self.error.lock().unwrap() = Some(status);
- }
-
- #[allow(clippy::result_large_err)] // tonic::Status is large but we can't change it
- fn check_error(&self) -> Result<(), Status> {
- if let Some(status) = self.error.lock().unwrap().clone() {
- return Err(status);
- }
- Ok(())
- }
-}
-
-#[async_trait]
-impl PersonHogBackend for MockBackend {
- async fn get_person(&self, _request: GetPersonRequest) -> Result<GetPersonResponse, Status> {
- self.check_error()?;
- Ok(GetPersonResponse {
- person: self.person_response.lock().unwrap().clone(),
- })
- }
-
- async fn get_persons(&self, _request: GetPersonsRequest) -> Result<PersonsResponse, Status> {
- self.check_error()?;
- Ok(PersonsResponse {
- persons: vec![],
- missing_ids: vec![],
- })
- }
-
- async fn get_person_by_uuid(
- &self,
- _request: GetPersonByUuidRequest,
- ) -> Result<GetPersonResponse, Status> {
- self.check_error()?;
- Ok(GetPersonResponse {
- person: self.person_response.lock().unwrap().clone(),
- })
- }
-
- async fn get_persons_by_uuids(
- &self,
- _request: GetPersonsByUuidsRequest,
- ) -> Result<PersonsResponse, Status> {
- self.check_error()?;
- Ok(PersonsResponse {
- persons: vec![],
- missing_ids: vec![],
- })
- }
-
- async fn get_person_by_distinct_id(
- &self,
- _request: GetPersonByDistinctIdRequest,
- ) -> Result<GetPersonResponse, Status> {
- self.check_error()?;
- Ok(GetPersonResponse {
- person: self.person_response.lock().unwrap().clone(),
- })
- }
-
- async fn get_persons_by_distinct_ids_in_team(
- &self,
- _request: GetPersonsByDistinctIdsInTeamRequest,
- ) -> Result<PersonsByDistinctIdsInTeamResponse, Status> {
- self.check_error()?;
- Ok(PersonsByDistinctIdsInTeamResponse { results: vec![] })
- }
-
- async fn get_persons_by_distinct_ids(
- &self,
- _request: GetPersonsByDistinctIdsRequest,
- ) -> Result<PersonsByDistinctIdsResponse, Status> {
- self.check_error()?;
- Ok(PersonsByDistinctIdsResponse { results: vec![] })
- }
-
- async fn get_distinct_ids_for_person(
- &self,
- _request: GetDistinctIdsForPersonRequest,
- ) -> Result<GetDistinctIdsForPersonResponse, Status> {
- self.check_error()?;
- Ok(GetDistinctIdsForPersonResponse {
- distinct_ids: vec![],
- })
- }
-
- async fn get_distinct_ids_for_persons(
- &self,
- _request: GetDistinctIdsForPersonsRequest,
- ) -> Result<GetDistinctIdsForPersonsResponse, Status> {
- self.check_error()?;
- Ok(GetDistinctIdsForPersonsResponse {
- person_distinct_ids: vec![],
- })
- }
-
- async fn get_hash_key_override_context(
- &self,
- _request: GetHashKeyOverrideContextRequest,
- ) -> Result<GetHashKeyOverrideContextResponse, Status> {
- self.check_error()?;
- Ok(GetHashKeyOverrideContextResponse { results: vec![] })
- }
-
- async fn upsert_hash_key_overrides(
- &self,
- _request: UpsertHashKeyOverridesRequest,
- ) -> Result<UpsertHashKeyOverridesResponse, Status> {
- self.check_error()?;
- Ok(UpsertHashKeyOverridesResponse { inserted_count: 0 })
- }
-
- async fn delete_hash_key_overrides_by_teams(
- &self,
- _request: DeleteHashKeyOverridesByTeamsRequest,
- ) -> Result<DeleteHashKeyOverridesByTeamsResponse, Status> {
- self.check_error()?;
- Ok(DeleteHashKeyOverridesByTeamsResponse { deleted_count: 0 })
- }
-
- async fn delete_persons(
- &self,
- _request: DeletePersonsRequest,
- ) -> Result<DeletePersonsResponse, Status> {
- self.check_error()?;
- Ok(DeletePersonsResponse { deleted_count: 0 })
- }
-
- async fn delete_persons_batch_for_team(
- &self,
- _request: DeletePersonsBatchForTeamRequest,
- ) -> Result<DeletePersonsBatchForTeamResponse, Status> {
- self.check_error()?;
- Ok(DeletePersonsBatchForTeamResponse { deleted_count: 0 })
- }
-
- async fn delete_personless_distinct_ids_batch_for_team(
- &self,
- _request: DeletePersonlessDistinctIdsBatchForTeamRequest,
- ) -> Result<DeletePersonlessDistinctIdsBatchForTeamResponse, Status> {
- self.check_error()?;
- Ok(DeletePersonlessDistinctIdsBatchForTeamResponse { deleted_count: 0 })
- }
-
- async fn check_cohort_membership(
- &self,
- _request: CheckCohortMembershipRequest,
- ) -> Result<CohortMembershipResponse, Status> {
- self.check_error()?;
- Ok(CohortMembershipResponse {
- memberships: vec![],
- })
- }
-
- async fn count_cohort_members(
- &self,
- _request: CountCohortMembersRequest,
- ) -> Result<CountCohortMembersResponse, Status> {
- self.check_error()?;
- Ok(CountCohortMembersResponse { count: 0 })
- }
-
- async fn delete_cohort_member(
- &self,
- _request: DeleteCohortMemberRequest,
- ) -> Result<DeleteCohortMemberResponse, Status> {
- self.check_error()?;
- Ok(DeleteCohortMemberResponse { deleted: false })
- }
-
- async fn delete_cohort_members_bulk(
- &self,
- _request: DeleteCohortMembersBulkRequest,
- ) -> Result<DeleteCohortMembersBulkResponse, Status> {
- self.check_error()?;
- Ok(DeleteCohortMembersBulkResponse { deleted_count: 0 })
- }
-
- async fn insert_cohort_members(
- &self,
- _request: InsertCohortMembersRequest,
- ) -> Result<InsertCohortMembersResponse, Status> {
- self.check_error()?;
- Ok(InsertCohortMembersResponse { inserted_count: 0 })
- }
-
- async fn list_cohort_member_ids(
- &self,
- _request: ListCohortMemberIdsRequest,
- ) -> Result<ListCohortMemberIdsResponse, Status> {
- self.check_error()?;
- Ok(ListCohortMemberIdsResponse {
- person_ids: vec![],
- next_cursor: 0,
- })
- }
-
- async fn get_group(&self, _request: GetGroupRequest) -> Result<GetGroupResponse, Status> {
- self.check_error()?;
- Ok(GetGroupResponse { group: None })
- }
-
- async fn get_groups(&self, _request: GetGroupsRequest) -> Result<GroupsResponse, Status> {
- self.check_error()?;
- Ok(GroupsResponse {
- groups: vec![],
- missing_groups: vec![],
- })
- }
-
- async fn get_groups_batch(
- &self,
- _request: GetGroupsBatchRequest,
- ) -> Result<GetGroupsBatchResponse, Status> {
- self.check_error()?;
- Ok(GetGroupsBatchResponse { results: vec![] })
- }
-
- async fn list_groups(&self, _request: ListGroupsRequest) -> Result<ListGroupsResponse, Status> {
- self.check_error()?;
- Ok(ListGroupsResponse {
- groups: vec![],
- has_more: false,
- })
- }
-
- async fn get_group_type_mappings_by_team_id(
- &self,
- _request: GetGroupTypeMappingsByTeamIdRequest,
- ) -> Result<GroupTypeMappingsResponse, Status> {
- self.check_error()?;
- Ok(GroupTypeMappingsResponse { mappings: vec![] })
- }
-
- async fn get_group_type_mappings_by_team_ids(
- &self,
- _request: GetGroupTypeMappingsByTeamIdsRequest,
- ) -> Result<GroupTypeMappingsBatchResponse, Status> {
- self.check_error()?;
- Ok(GroupTypeMappingsBatchResponse { results: vec![] })
- }
-
- async fn get_group_type_mappings_by_project_id(
- &self,
- _request: GetGroupTypeMappingsByProjectIdRequest,
- ) -> Result<GroupTypeMappingsResponse, Status> {
- self.check_error()?;
- Ok(GroupTypeMappingsResponse { mappings: vec![] })
- }
-
- async fn get_group_type_mappings_by_project_ids(
- &self,
- _request: GetGroupTypeMappingsByProjectIdsRequest,
- ) -> Result<GroupTypeMappingsBatchResponse, Status> {
- self.check_error()?;
- Ok(GroupTypeMappingsBatchResponse { results: vec![] })
- }
-
- async fn count_group_type_mappings(
- &self,
- _request: CountGroupTypeMappingsRequest,
- ) -> Result<CountGroupTypeMappingsResponse, Status> {
- self.check_error()?;
- Ok(CountGroupTypeMappingsResponse { counts: vec![] })
- }
-
- async fn get_group_type_mapping_by_dashboard_id(
- &self,
- _request: GetGroupTypeMappingByDashboardIdRequest,
- ) -> Result<GetGroupTypeMappingByDashboardIdResponse, Status> {
- self.check_error()?;
- Ok(GetGroupTypeMappingByDashboardIdResponse { mapping: None })
- }
-
- async fn create_group(
- &self,
- _request: CreateGroupRequest,
- ) -> Result<CreateGroupResponse, Status> {
- self.check_error()?;
- Ok(CreateGroupResponse { group: None })
- }
-
- async fn update_group(
- &self,
- _request: UpdateGroupRequest,
- ) -> Result<UpdateGroupResponse, Status> {
- self.check_error()?;
- Ok(UpdateGroupResponse {
- group: None,
- updated: false,
- })
- }
-
- async fn delete_groups_batch_for_team(
- &self,
- _request: DeleteGroupsBatchForTeamRequest,
- ) -> Result<DeleteGroupsBatchForTeamResponse, Status> {
- self.check_error()?;
- Ok(DeleteGroupsBatchForTeamResponse { deleted_count: 0 })
- }
-
- async fn update_group_type_mapping(
- &self,
- _request: UpdateGroupTypeMappingRequest,
- ) -> Result<UpdateGroupTypeMappingResponse, Status> {
- self.check_error()?;
- Ok(UpdateGroupTypeMappingResponse { mapping: None })
- }
-
- async fn delete_group_type_mapping(
- &self,
- _request: DeleteGroupTypeMappingRequest,
- ) -> Result<DeleteGroupTypeMappingResponse, Status> {
- self.check_error()?;
- Ok(DeleteGroupTypeMappingResponse { deleted: false })
- }
-
- async fn delete_group_type_mappings_batch_for_team(
- &self,
- _request: DeleteGroupTypeMappingsBatchForTeamRequest,
- ) -> Result<DeleteGroupTypeMappingsBatchForTeamResponse, Status> {
- self.check_error()?;
- Ok(DeleteGroupTypeMappingsBatchForTeamResponse { deleted_count: 0 })
- }
-
- async fn split_person(
- &self,
- _request: SplitPersonRequest,
- ) -> Result<SplitPersonResponse, Status> {
- self.check_error()?;
- Ok(SplitPersonResponse { splits: vec![] })
- }
-
- async fn set_person_distinct_id_version_floor(
- &self,
- _request: SetPersonDistinctIdVersionFloorRequest,
- ) -> Result<SetPersonDistinctIdVersionFloorResponse, Status> {
- self.check_error()?;
- Ok(SetPersonDistinctIdVersionFloorResponse { person: None })
- }
-
- async fn set_person_version_floor(
- &self,
- _request: SetPersonVersionFloorRequest,
- ) -> Result<SetPersonVersionFloorResponse, Status> {
- self.check_error()?;
- Ok(SetPersonVersionFloorResponse { updated: false })
- }
-}
diff --git a/rust/personhog-router/src/service/tests/mod.rs b/rust/personhog-router/src/service/tests/mod.rs
deleted file mode 100644
index 889038831d99..000000000000
--- a/rust/personhog-router/src/service/tests/mod.rs
+++ /dev/null
@@ -1,427 +0,0 @@
-mod mocks;
-
-use std::sync::Arc;
-
-use mocks::MockBackend;
-use personhog_proto::personhog::service::v1::person_hog_service_server::PersonHogService;
-use personhog_proto::personhog::types::v1::{
- ConsistencyLevel, CreateGroupRequest, DeleteGroupTypeMappingRequest,
- DeleteGroupTypeMappingsBatchForTeamRequest, DeleteGroupsBatchForTeamRequest,
- DeletePersonsRequest, GetPersonByDistinctIdRequest, GetPersonRequest, Person, ReadOptions,
- UpdateGroupRequest, UpdateGroupTypeMappingRequest,
-};
-use tonic::{Request, Status};
-
-use crate::router::PersonHogRouter;
-
-use super::PersonHogRouterService;
-
-fn create_test_person() -> Person {
- Person {
- id: 1,
- team_id: 1,
- uuid: "00000000-0000-0000-0000-000000000001".to_string(),
- properties: b"{}".to_vec(),
- properties_last_updated_at: vec![],
- properties_last_operation: vec![],
- created_at: 0,
- version: 1,
- is_identified: true,
- is_user_id: None,
- last_seen_at: None,
- }
-}
-
-fn create_service_with_mock(mock: MockBackend) -> PersonHogRouterService {
- let router = PersonHogRouter::new(Arc::new(mock));
- PersonHogRouterService::new(Arc::new(router))
-}
-
-#[tokio::test]
-async fn test_get_person_routes_to_replica_with_eventual_consistency() {
- let mock = MockBackend::new();
- mock.set_person_response(Some(create_test_person()));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(GetPersonRequest {
- team_id: 1,
- person_id: 1,
- read_options: None, // Defaults to EVENTUAL
- });
-
- let response = service.get_person(request).await.unwrap();
- assert!(response.get_ref().person.is_some());
- assert_eq!(response.get_ref().person.as_ref().unwrap().id, 1);
-}
-
-#[tokio::test]
-async fn test_get_person_returns_none_when_not_found() {
- let mock = MockBackend::new();
- mock.set_person_response(None);
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(GetPersonRequest {
- team_id: 1,
- person_id: 999,
- read_options: None,
- });
-
- let response = service.get_person(request).await.unwrap();
- assert!(response.get_ref().person.is_none());
-}
-
-#[tokio::test]
-async fn test_get_person_by_distinct_id_routes_to_replica() {
- let mock = MockBackend::new();
- mock.set_person_response(Some(create_test_person()));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(GetPersonByDistinctIdRequest {
- team_id: 1,
- distinct_id: "user-123".to_string(),
- read_options: None,
- });
-
- let response = service.get_person_by_distinct_id(request).await.unwrap();
- assert!(response.get_ref().person.is_some());
-}
-
-#[tokio::test]
-async fn test_backend_error_passthrough() {
- let mock = MockBackend::new();
- mock.set_error(Status::unavailable("backend unavailable"));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(GetPersonRequest {
- team_id: 1,
- person_id: 1,
- read_options: None,
- });
-
- let result = service.get_person(request).await;
- assert!(result.is_err());
- let status = result.unwrap_err();
- assert_eq!(status.code(), tonic::Code::Unavailable);
-}
-
-#[tokio::test]
-async fn test_get_person_with_strong_consistency_returns_unimplemented() {
- let mock = MockBackend::new();
- mock.set_person_response(Some(create_test_person()));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(GetPersonRequest {
- team_id: 1,
- person_id: 1,
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Strong.into(),
- ..Default::default()
- }),
- });
-
- let result = service.get_person(request).await;
- assert!(result.is_err());
- let status = result.unwrap_err();
- assert_eq!(status.code(), tonic::Code::Unimplemented);
- assert!(status.message().contains("leader"));
-}
-
-#[tokio::test]
-async fn test_get_person_with_explicit_eventual_consistency_succeeds() {
- let mock = MockBackend::new();
- mock.set_person_response(Some(create_test_person()));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(GetPersonRequest {
- team_id: 1,
- person_id: 1,
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Eventual.into(),
- ..Default::default()
- }),
- });
-
- let response = service.get_person(request).await.unwrap();
- assert!(response.get_ref().person.is_some());
-}
-
-// ============================================================
-// DeletePersons tests
-// ============================================================
-
-#[tokio::test]
-async fn test_delete_persons_routes_to_replica() {
- let mock = MockBackend::new();
- let service = create_service_with_mock(mock);
-
- let request = Request::new(DeletePersonsRequest {
- team_id: 1,
- person_uuids: vec!["00000000-0000-0000-0000-000000000001".to_string()],
- });
-
- let response = service.delete_persons(request).await.unwrap();
- assert_eq!(response.get_ref().deleted_count, 0);
-}
-
-#[tokio::test]
-async fn test_delete_persons_error_passthrough() {
- let mock = MockBackend::new();
- mock.set_error(Status::unavailable("backend unavailable"));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(DeletePersonsRequest {
- team_id: 1,
- person_uuids: vec!["00000000-0000-0000-0000-000000000001".to_string()],
- });
-
- let result = service.delete_persons(request).await;
- assert!(result.is_err());
- let status = result.unwrap_err();
- assert_eq!(status.code(), tonic::Code::Unavailable);
-}
-
-// ============================================================
-// CreateGroup tests
-// ============================================================
-
-#[tokio::test]
-async fn test_create_group_routes_to_replica() {
- let mock = MockBackend::new();
- let service = create_service_with_mock(mock);
-
- let request = Request::new(CreateGroupRequest {
- team_id: 1,
- group_type_index: 0,
- group_key: "test-group".to_string(),
- group_properties: b"{}".to_vec(),
- created_at: Some(1700000000000),
- });
-
- let response = service.create_group(request).await.unwrap();
- assert!(response.get_ref().group.is_none());
-}
-
-#[tokio::test]
-async fn test_create_group_error_passthrough() {
- let mock = MockBackend::new();
- mock.set_error(Status::unavailable("backend unavailable"));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(CreateGroupRequest {
- team_id: 1,
- group_type_index: 0,
- group_key: "test-group".to_string(),
- group_properties: b"{}".to_vec(),
- created_at: Some(1700000000000),
- });
-
- let result = service.create_group(request).await;
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);
-}
-
-// ============================================================
-// UpdateGroup tests
-// ============================================================
-
-#[tokio::test]
-async fn test_update_group_routes_to_replica() {
- let mock = MockBackend::new();
- let service = create_service_with_mock(mock);
-
- let request = Request::new(UpdateGroupRequest {
- team_id: 1,
- group_type_index: 0,
- group_key: "test-group".to_string(),
- update_mask: vec!["group_properties".to_string()],
- group_properties: Some(b"{}".to_vec()),
- ..Default::default()
- });
-
- let response = service.update_group(request).await.unwrap();
- assert!(!response.get_ref().updated);
-}
-
-#[tokio::test]
-async fn test_update_group_error_passthrough() {
- let mock = MockBackend::new();
- mock.set_error(Status::unavailable("backend unavailable"));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(UpdateGroupRequest {
- team_id: 1,
- group_type_index: 0,
- group_key: "test-group".to_string(),
- update_mask: vec!["group_properties".to_string()],
- group_properties: Some(b"{}".to_vec()),
- ..Default::default()
- });
-
- let result = service.update_group(request).await;
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);
-}
-
-// ============================================================
-// DeleteGroupsBatchForTeam tests
-// ============================================================
-
-#[tokio::test]
-async fn test_delete_groups_batch_for_team_routes_to_replica() {
- let mock = MockBackend::new();
- let service = create_service_with_mock(mock);
-
- let request = Request::new(DeleteGroupsBatchForTeamRequest {
- team_id: 1,
- batch_size: 1000,
- });
-
- let response = service.delete_groups_batch_for_team(request).await.unwrap();
- assert_eq!(response.get_ref().deleted_count, 0);
-}
-
-#[tokio::test]
-async fn test_delete_groups_batch_for_team_error_passthrough() {
- let mock = MockBackend::new();
- mock.set_error(Status::unavailable("backend unavailable"));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(DeleteGroupsBatchForTeamRequest {
- team_id: 1,
- batch_size: 1000,
- });
-
- let result = service.delete_groups_batch_for_team(request).await;
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);
-}
-
-// ============================================================
-// UpdateGroupTypeMapping tests
-// ============================================================
-
-#[tokio::test]
-async fn test_update_group_type_mapping_routes_to_replica() {
- let mock = MockBackend::new();
- let service = create_service_with_mock(mock);
-
- let request = Request::new(UpdateGroupTypeMappingRequest {
- project_id: 1,
- group_type_index: 0,
- update_mask: vec!["name_singular".to_string()],
- name_singular: Some("Company".to_string()),
- name_plural: None,
- detail_dashboard_id: None,
- default_columns: None,
- });
-
- let response = service.update_group_type_mapping(request).await.unwrap();
- assert!(response.get_ref().mapping.is_none());
-}
-
-#[tokio::test]
-async fn test_update_group_type_mapping_error_passthrough() {
- let mock = MockBackend::new();
- mock.set_error(Status::unavailable("backend unavailable"));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(UpdateGroupTypeMappingRequest {
- project_id: 1,
- group_type_index: 0,
- update_mask: vec!["name_singular".to_string()],
- name_singular: Some("Company".to_string()),
- name_plural: None,
- detail_dashboard_id: None,
- default_columns: None,
- });
-
- let result = service.update_group_type_mapping(request).await;
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);
-}
-
-// ============================================================
-// DeleteGroupTypeMapping tests
-// ============================================================
-
-#[tokio::test]
-async fn test_delete_group_type_mapping_routes_to_replica() {
- let mock = MockBackend::new();
- let service = create_service_with_mock(mock);
-
- let request = Request::new(DeleteGroupTypeMappingRequest {
- project_id: 1,
- group_type_index: 0,
- });
-
- let response = service.delete_group_type_mapping(request).await.unwrap();
- assert!(!response.get_ref().deleted);
-}
-
-#[tokio::test]
-async fn test_delete_group_type_mapping_error_passthrough() {
- let mock = MockBackend::new();
- mock.set_error(Status::unavailable("backend unavailable"));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(DeleteGroupTypeMappingRequest {
- project_id: 1,
- group_type_index: 0,
- });
-
- let result = service.delete_group_type_mapping(request).await;
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);
-}
-
-// ============================================================
-// DeleteGroupTypeMappingsBatchForTeam tests
-// ============================================================
-
-#[tokio::test]
-async fn test_delete_group_type_mappings_batch_for_team_routes_to_replica() {
- let mock = MockBackend::new();
- let service = create_service_with_mock(mock);
-
- let request = Request::new(DeleteGroupTypeMappingsBatchForTeamRequest {
- team_id: 1,
- batch_size: 1000,
- });
-
- let response = service
- .delete_group_type_mappings_batch_for_team(request)
- .await
- .unwrap();
- assert_eq!(response.get_ref().deleted_count, 0);
-}
-
-#[tokio::test]
-async fn test_delete_group_type_mappings_batch_for_team_error_passthrough() {
- let mock = MockBackend::new();
- mock.set_error(Status::unavailable("backend unavailable"));
-
- let service = create_service_with_mock(mock);
-
- let request = Request::new(DeleteGroupTypeMappingsBatchForTeamRequest {
- team_id: 1,
- batch_size: 1000,
- });
-
- let result = service
- .delete_group_type_mappings_batch_for_team(request)
- .await;
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);
-}
diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rs
index 0a4c7d6baf22..0a4a47ae16f6 100644
--- a/rust/personhog-router/tests/common/mod.rs
+++ b/rust/personhog-router/tests/common/mod.rs
@@ -15,7 +15,6 @@ use personhog_proto::personhog::replica::v1::person_hog_replica_server::{
PersonHogReplica, PersonHogReplicaServer,
};
use personhog_proto::personhog::service::v1::person_hog_service_client::PersonHogServiceClient;
-use personhog_proto::personhog::service::v1::person_hog_service_server::PersonHogServiceServer;
use personhog_proto::personhog::types::v1::{
CheckCohortMembershipRequest, CohortMembershipResponse, CountCohortMembersRequest,
CountCohortMembersResponse, CountGroupTypeMappingsRequest, CountGroupTypeMappingsResponse,
@@ -51,8 +50,6 @@ use personhog_router::backend::{
};
use personhog_router::config::RetryConfig;
use personhog_router::proxy::RawProxyService;
-use personhog_router::router::PersonHogRouter;
-use personhog_router::service::PersonHogRouterService;
use tokio::net::TcpListener;
use tokio::sync::RwLock;
use tonic::codec::CompressionEncoding;
@@ -563,44 +560,6 @@ pub async fn start_test_replica_with_async_gzip_disabled(
addr
}
-/// Start a test router server connected to the given replica address
-pub async fn start_test_router(replica_addr: SocketAddr) -> SocketAddr {
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
-
- let replica_url = format!("http://{}", replica_addr);
- let retry_config = RetryConfig {
- max_retries: 1,
- initial_backoff_ms: 1,
- max_backoff_ms: 1,
- };
- let backend = ReplicaBackend::new_dns(ReplicaDnsConfig {
- url: replica_url,
- timeout: Duration::from_secs(5),
- retry_config,
- keepalive_interval: None,
- keepalive_timeout: None,
- max_send_message_size: 4 * 1024 * 1024,
- max_recv_message_size: 4 * 1024 * 1024,
- num_channels: 1,
- });
- let router = PersonHogRouter::new(Arc::new(backend));
- let service = PersonHogRouterService::new(Arc::new(router));
-
- tokio::spawn(async move {
- Server::builder()
- .add_service(PersonHogServiceServer::new(service))
- .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
- .await
- .unwrap();
- });
-
- // Give the server a moment to start
- tokio::time::sleep(Duration::from_millis(10)).await;
-
- addr
-}
-
/// Create a client connected to the router
pub async fn create_client(router_addr: SocketAddr) -> PersonHogServiceClient<Channel> {
let url = format!("http://{}", router_addr);
@@ -799,73 +758,6 @@ pub async fn start_test_leader(service: TestLeaderService) -> SocketAddr {
addr
}
-/// Start a test router with both replica and leader backends.
-/// All partitions are mapped to the given leader address.
-pub async fn start_test_router_with_leader(
- replica_addr: SocketAddr,
- leader_addr: SocketAddr,
- num_partitions: u32,
-) -> SocketAddr {
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
-
- let retry_config = RetryConfig {
- max_retries: 1,
- initial_backoff_ms: 1,
- max_backoff_ms: 1,
- };
-
- // Replica backend
- let replica_url = format!("http://{}", replica_addr);
- let replica = ReplicaBackend::new_dns(ReplicaDnsConfig {
- url: replica_url,
- timeout: Duration::from_secs(5),
- retry_config,
- keepalive_interval: None,
- keepalive_timeout: None,
- max_send_message_size: 4 * 1024 * 1024,
- max_recv_message_size: 4 * 1024 * 1024,
- num_channels: 1,
- });
-
- // Leader backend: all partitions → "leader-0", resolver → leader_addr
- let mut routing = HashMap::new();
- for p in 0..num_partitions {
- routing.insert(p, "leader-0".to_string());
- }
- let routing_table = Arc::new(RwLock::new(routing));
- let leader_url = format!("http://{}", leader_addr);
- let address_resolver: Arc<dyn Fn(&str) -> Option<String> + Send + Sync> =
- Arc::new(move |_pod_name| Some(leader_url.clone()));
- let leader = LeaderBackend::new(
- routing_table,
- address_resolver,
- LeaderBackendConfig {
- num_partitions,
- timeout: Duration::from_secs(5),
- retry_config,
- max_send_message_size: 4 * 1024 * 1024,
- max_recv_message_size: 4 * 1024 * 1024,
- },
- StashTable::with_bounds(usize::MAX, usize::MAX),
- );
-
- let router = PersonHogRouter::new(Arc::new(replica)).with_leader(Arc::new(leader));
- let service = PersonHogRouterService::new(Arc::new(router));
-
- tokio::spawn(async move {
- Server::builder()
- .add_service(PersonHogServiceServer::new(service))
- .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
- .await
- .unwrap();
- });
-
- tokio::time::sleep(Duration::from_millis(10)).await;
-
- addr
-}
-
// ============================================================
// Raw proxy test helpers
// ============================================================
@@ -882,8 +774,6 @@ fn make_replica_backend(replica_addr: SocketAddr) -> Arc<ReplicaBackend> {
retry_config,
keepalive_interval: None,
keepalive_timeout: None,
- max_send_message_size: 4 * 1024 * 1024,
- max_recv_message_size: 4 * 1024 * 1024,
num_channels: 1,
}))
}
diff --git a/rust/personhog-router/tests/integration.rs b/rust/personhog-router/tests/integration.rs
deleted file mode 100644
index be76af759953..000000000000
--- a/rust/personhog-router/tests/integration.rs
+++ /dev/null
@@ -1,503 +0,0 @@
-mod common;
-
-use common::{
- create_client, create_test_person, start_test_replica, start_test_router, TestReplicaService,
-};
-use personhog_proto::personhog::types::v1::{
- CheckCohortMembershipRequest, CohortMembership, ConsistencyLevel,
- GetGroupTypeMappingsByProjectIdRequest, GetGroupTypeMappingsByTeamIdRequest, GetGroupsRequest,
- GetHashKeyOverrideContextRequest, GetPersonByDistinctIdRequest, GetPersonRequest,
- GetPersonsByDistinctIdsInTeamRequest, Group, GroupIdentifier, GroupTypeMapping,
- HashKeyOverride, HashKeyOverrideContext, Person, PersonWithDistinctIds, ReadOptions,
- UpsertHashKeyOverridesRequest,
-};
-
-#[tokio::test]
-async fn test_get_person_roundtrip() {
- let test_person = create_test_person();
- let replica_service = TestReplicaService::with_person(test_person.clone());
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_person(GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: None,
- })
- .await
- .unwrap();
-
- let person = response.into_inner().person;
- assert!(person.is_some());
- let person = person.unwrap();
- assert_eq!(person.id, test_person.id);
- assert_eq!(person.team_id, test_person.team_id);
- assert_eq!(person.uuid, test_person.uuid);
-}
-
-#[tokio::test]
-async fn test_get_person_by_distinct_id_roundtrip() {
- let test_person = create_test_person();
- let replica_service = TestReplicaService::with_person(test_person.clone());
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_person_by_distinct_id(GetPersonByDistinctIdRequest {
- team_id: 1,
- distinct_id: "[email protected]".to_string(),
- read_options: None,
- })
- .await
- .unwrap();
-
- let person = response.into_inner().person;
- assert!(person.is_some());
- let person = person.unwrap();
- assert_eq!(person.id, test_person.id);
-}
-
-#[tokio::test]
-async fn test_get_person_not_found() {
- let replica_service = TestReplicaService::new();
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_person(GetPersonRequest {
- team_id: 1,
- person_id: 999,
- read_options: None,
- })
- .await
- .unwrap();
-
- let person = response.into_inner().person;
- assert!(person.is_none());
-}
-
-// ============================================================
-// Feature-flags behavior pattern tests
-// ============================================================
-
-/// Tests batch person lookup by distinct IDs within a team.
-/// Feature-flags uses this to resolve multiple distinct IDs to persons in a single call.
-#[tokio::test]
-async fn test_get_persons_by_distinct_ids_in_team() {
- let test_person = Person {
- id: 42,
- team_id: 1,
- uuid: "00000000-0000-0000-0000-000000000042".to_string(),
- properties: b"{}".to_vec(),
- properties_last_updated_at: vec![],
- properties_last_operation: vec![],
- created_at: 0,
- version: 1,
- is_identified: true,
- is_user_id: None,
- last_seen_at: None,
- };
-
- // Each PersonWithDistinctIds maps one distinct_id to one person
- let person_with_distinct_id = PersonWithDistinctIds {
- distinct_id: "[email protected]".to_string(),
- person: Some(test_person),
- };
-
- let replica_service =
- TestReplicaService::new().with_persons_by_distinct_id(vec![person_with_distinct_id]);
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_persons_by_distinct_ids_in_team(GetPersonsByDistinctIdsInTeamRequest {
- team_id: 1,
- distinct_ids: vec!["[email protected]".to_string()],
- read_options: None,
- })
- .await
- .unwrap();
-
- let results = response.into_inner().results;
- assert_eq!(results.len(), 1);
- assert_eq!(results[0].distinct_id, "[email protected]");
- assert!(results[0].person.is_some());
- assert_eq!(results[0].person.as_ref().unwrap().id, 42);
-}
-
-/// Tests cohort membership check - a batch operation that checks if a person
-/// belongs to multiple cohorts at once.
-/// Feature-flags uses this for cohort-based targeting.
-#[tokio::test]
-async fn test_check_cohort_membership() {
- let memberships = vec![
- CohortMembership {
- cohort_id: 100,
- is_member: true,
- },
- CohortMembership {
- cohort_id: 200,
- is_member: false,
- },
- CohortMembership {
- cohort_id: 300,
- is_member: true,
- },
- ];
-
- let replica_service = TestReplicaService::new().with_cohort_memberships(memberships);
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .check_cohort_membership(CheckCohortMembershipRequest {
- person_id: 42,
- cohort_ids: vec![100, 200, 300],
- read_options: None,
- })
- .await
- .unwrap();
-
- let result = response.into_inner();
- assert_eq!(result.memberships.len(), 3);
-
- // Verify specific membership results
- let cohort_100 = result.memberships.iter().find(|m| m.cohort_id == 100);
- assert!(cohort_100.is_some());
- assert!(cohort_100.unwrap().is_member);
-
- let cohort_200 = result.memberships.iter().find(|m| m.cohort_id == 200);
- assert!(cohort_200.is_some());
- assert!(!cohort_200.unwrap().is_member);
-}
-
-/// Tests cohort membership for non-existent person returns empty (not error).
-/// Feature-flags expects this behavior for graceful degradation.
-#[tokio::test]
-async fn test_check_cohort_membership_empty() {
- let replica_service = TestReplicaService::new(); // No memberships configured
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .check_cohort_membership(CheckCohortMembershipRequest {
- person_id: 999, // Non-existent person
- cohort_ids: vec![100, 200],
- read_options: None,
- })
- .await
- .unwrap();
-
- // Should succeed with empty memberships, not error
- let result = response.into_inner();
- assert!(result.memberships.is_empty());
-}
-
-/// Tests hash key override context lookup for experience continuity.
-/// Feature-flags uses this to maintain consistent flag experiences across distinct IDs.
-#[tokio::test]
-async fn test_get_hash_key_override_context() {
- let contexts = vec![HashKeyOverrideContext {
- person_id: 42,
- distinct_id: "[email protected]".to_string(),
- overrides: vec![
- HashKeyOverride {
- feature_flag_key: "beta-feature".to_string(),
- hash_key: "consistent-hash-key".to_string(),
- },
- HashKeyOverride {
- feature_flag_key: "experiment-1".to_string(),
- hash_key: "experiment-hash".to_string(),
- },
- ],
- existing_feature_flag_keys: vec!["beta-feature".to_string(), "experiment-1".to_string()],
- }];
-
- let replica_service = TestReplicaService::new().with_hash_key_override_contexts(contexts);
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_hash_key_override_context(GetHashKeyOverrideContextRequest {
- team_id: 1,
- distinct_ids: vec!["[email protected]".to_string()],
- check_person_exists: false,
- read_options: None,
- })
- .await
- .unwrap();
-
- let results = response.into_inner().results;
- assert_eq!(results.len(), 1);
- assert_eq!(results[0].distinct_id, "[email protected]");
- assert_eq!(results[0].person_id, 42);
- assert_eq!(results[0].overrides.len(), 2);
-}
-
-/// Tests upsert hash key overrides - a write operation for experience continuity.
-/// Returns the count of newly inserted overrides (ON CONFLICT DO NOTHING behavior).
-#[tokio::test]
-async fn test_upsert_hash_key_overrides() {
- let replica_service = TestReplicaService::new().with_upsert_inserted_count(3);
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .upsert_hash_key_overrides(UpsertHashKeyOverridesRequest {
- team_id: 1,
- distinct_ids: vec!["[email protected]".to_string()],
- hash_key: "consistent-hash".to_string(),
- feature_flag_keys: vec![
- "flag-1".to_string(),
- "flag-2".to_string(),
- "flag-3".to_string(),
- ],
- })
- .await
- .unwrap();
-
- let result = response.into_inner();
- assert_eq!(result.inserted_count, 3);
-}
-
-/// Tests batch group lookup.
-/// Feature-flags uses this to resolve group properties for group-based targeting.
-#[tokio::test]
-async fn test_get_groups() {
- let groups = vec![
- Group {
- id: 1,
- team_id: 1,
- group_type_index: 0,
- group_key: "company-abc".to_string(),
- group_properties: b"{\"name\": \"Acme Corp\", \"plan\": \"enterprise\"}".to_vec(),
- properties_last_updated_at: vec![],
- properties_last_operation: vec![],
- created_at: 0,
- version: 1,
- },
- Group {
- id: 2,
- team_id: 1,
- group_type_index: 1,
- group_key: "project-xyz".to_string(),
- group_properties: b"{\"name\": \"Secret Project\"}".to_vec(),
- properties_last_updated_at: vec![],
- properties_last_operation: vec![],
- created_at: 0,
- version: 1,
- },
- ];
-
- let replica_service = TestReplicaService::new().with_groups(groups);
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_groups(GetGroupsRequest {
- team_id: 1,
- group_identifiers: vec![
- GroupIdentifier {
- group_type_index: 0,
- group_key: "company-abc".to_string(),
- },
- GroupIdentifier {
- group_type_index: 1,
- group_key: "project-xyz".to_string(),
- },
- ],
- read_options: None,
- })
- .await
- .unwrap();
-
- let result = response.into_inner();
- assert_eq!(result.groups.len(), 2);
- assert!(result.missing_groups.is_empty());
-
- // Verify group data
- let company = result.groups.iter().find(|g| g.group_key == "company-abc");
- assert!(company.is_some());
- assert_eq!(company.unwrap().group_type_index, 0);
-}
-
-/// Tests group lookup when groups are not found returns empty (not error).
-#[tokio::test]
-async fn test_get_groups_not_found() {
- let replica_service = TestReplicaService::new(); // No groups configured
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_groups(GetGroupsRequest {
- team_id: 1,
- group_identifiers: vec![GroupIdentifier {
- group_type_index: 0,
- group_key: "nonexistent".to_string(),
- }],
- read_options: None,
- })
- .await
- .unwrap();
-
- // Should succeed with empty groups, not error
- let result = response.into_inner();
- assert!(result.groups.is_empty());
-}
-
-/// Tests group type mappings lookup by team ID.
-/// Feature-flags uses this to map group type names to indices.
-#[tokio::test]
-async fn test_get_group_type_mappings_by_team_id() {
- let mappings = vec![
- GroupTypeMapping {
- id: 1,
- team_id: 1,
- project_id: 1,
- group_type: "company".to_string(),
- group_type_index: 0,
- name_singular: Some("company".to_string()),
- name_plural: Some("companies".to_string()),
- default_columns: None,
- detail_dashboard_id: None,
- created_at: None,
- },
- GroupTypeMapping {
- id: 2,
- team_id: 1,
- project_id: 1,
- group_type: "project".to_string(),
- group_type_index: 1,
- name_singular: Some("project".to_string()),
- name_plural: Some("projects".to_string()),
- default_columns: None,
- detail_dashboard_id: None,
- created_at: None,
- },
- ];
-
- let replica_service = TestReplicaService::new().with_group_type_mappings(mappings);
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_group_type_mappings_by_team_id(GetGroupTypeMappingsByTeamIdRequest {
- team_id: 1,
- read_options: None,
- })
- .await
- .unwrap();
-
- let result = response.into_inner();
- assert_eq!(result.mappings.len(), 2);
-
- let company_mapping = result.mappings.iter().find(|m| m.group_type == "company");
- assert!(company_mapping.is_some());
- assert_eq!(company_mapping.unwrap().group_type_index, 0);
-}
-
-/// Tests that Unspecified consistency level routes to replica (same as Eventual).
-#[tokio::test]
-async fn test_get_person_with_unspecified_consistency() {
- let test_person = create_test_person();
- let replica_service = TestReplicaService::with_person(test_person.clone());
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_person(GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Unspecified.into(),
- ..Default::default()
- }),
- })
- .await
- .unwrap();
-
- let person = response.into_inner().person;
- assert!(person.is_some());
- assert_eq!(person.unwrap().id, test_person.id);
-}
-
-/// Tests group type mappings lookup by project ID.
-#[tokio::test]
-async fn test_get_group_type_mappings_by_project_id() {
- let mappings = vec![
- GroupTypeMapping {
- id: 1,
- team_id: 1,
- project_id: 100,
- group_type: "organization".to_string(),
- group_type_index: 0,
- name_singular: Some("organization".to_string()),
- name_plural: Some("organizations".to_string()),
- default_columns: None,
- detail_dashboard_id: None,
- created_at: None,
- },
- GroupTypeMapping {
- id: 2,
- team_id: 1,
- project_id: 100,
- group_type: "workspace".to_string(),
- group_type_index: 1,
- name_singular: Some("workspace".to_string()),
- name_plural: Some("workspaces".to_string()),
- default_columns: None,
- detail_dashboard_id: None,
- created_at: None,
- },
- ];
-
- let replica_service = TestReplicaService::new().with_group_type_mappings(mappings);
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .get_group_type_mappings_by_project_id(GetGroupTypeMappingsByProjectIdRequest {
- project_id: 100,
- read_options: None,
- })
- .await
- .unwrap();
-
- let result = response.into_inner();
- assert_eq!(result.mappings.len(), 2);
-
- let org_mapping = result
- .mappings
- .iter()
- .find(|m| m.group_type == "organization");
- assert!(org_mapping.is_some());
- assert_eq!(org_mapping.unwrap().group_type_index, 0);
- assert_eq!(org_mapping.unwrap().project_id, 100);
-}
diff --git a/rust/personhog-router/tests/leader_integration.rs b/rust/personhog-router/tests/leader_integration.rs
deleted file mode 100644
index 9b08c14471b0..000000000000
--- a/rust/personhog-router/tests/leader_integration.rs
+++ /dev/null
@@ -1,277 +0,0 @@
-mod common;
-
-use common::{
- create_client, create_test_person, start_test_leader, start_test_replica, start_test_router,
- start_test_router_with_leader, TestLeaderService, TestReplicaService,
-};
-use personhog_proto::personhog::types::v1::{
- ConsistencyLevel, GetGroupsRequest, GetPersonRequest, GroupIdentifier, ReadOptions,
- UpdatePersonPropertiesRequest,
-};
-
-const NUM_PARTITIONS: u32 = 8;
-
-// ============================================================
-// Routing behavior tests
-// ============================================================
-
-#[tokio::test]
-async fn eventual_read_routes_to_replica_not_leader() {
- let test_person = create_test_person();
- let replica_service = TestReplicaService::with_person(test_person.clone());
- let leader_service = TestLeaderService::new(); // empty
-
- let replica_addr = start_test_replica(replica_service).await;
- let leader_addr = start_test_leader(leader_service).await;
- let router_addr =
- start_test_router_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let mut client = create_client(router_addr).await;
-
- // Default read (EVENTUAL) should go to replica
- let response = client
- .get_person(GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: None,
- })
- .await
- .unwrap();
-
- let person = response.into_inner().person.unwrap();
- assert_eq!(person.id, test_person.id);
-}
-
-#[tokio::test]
-async fn strong_read_routes_to_leader() {
- let test_person = create_test_person();
- let replica_service = TestReplicaService::new(); // empty
- let leader_service = TestLeaderService::new().with_person(test_person.clone());
-
- let replica_addr = start_test_replica(replica_service).await;
- let leader_addr = start_test_leader(leader_service).await;
- let router_addr =
- start_test_router_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let mut client = create_client(router_addr).await;
-
- // Strong consistency read should go to leader
- let response = client
- .get_person(GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Strong.into(),
- ..Default::default()
- }),
- })
- .await
- .unwrap();
-
- let person = response.into_inner().person.unwrap();
- assert_eq!(person.id, test_person.id);
-}
-
-#[tokio::test]
-async fn write_routes_to_leader() {
- let test_person = create_test_person();
- let leader_service = TestLeaderService::new().with_person(test_person.clone());
- let replica_service = TestReplicaService::new();
-
- let replica_addr = start_test_replica(replica_service).await;
- let leader_addr = start_test_leader(leader_service).await;
- let router_addr =
- start_test_router_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let mut client = create_client(router_addr).await;
-
- let response = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"name": "Test User"})).unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0, // will be overwritten by router
- })
- .await
- .unwrap();
-
- let result = response.into_inner();
- assert!(result.updated);
- let person = result.person.unwrap();
- assert_eq!(person.version, test_person.version + 1);
-}
-
-#[tokio::test]
-async fn write_then_strong_read_roundtrip() {
- let test_person = create_test_person();
- let leader_service = TestLeaderService::new().with_person(test_person.clone());
- let replica_service = TestReplicaService::new();
-
- let replica_addr = start_test_replica(replica_service).await;
- let leader_addr = start_test_leader(leader_service).await;
- let router_addr =
- start_test_router_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let mut client = create_client(router_addr).await;
-
- // Write
- client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"email": "[email protected]"}))
- .unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
- .await
- .unwrap();
-
- // Strong read should see the update
- let response = client
- .get_person(GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Strong.into(),
- ..Default::default()
- }),
- })
- .await
- .unwrap();
-
- let person = response.into_inner().person.unwrap();
- assert_eq!(person.version, test_person.version + 1);
-
- let props: serde_json::Value = serde_json::from_slice(&person.properties).unwrap();
- assert_eq!(props["email"], "[email protected]");
-}
-
-// ============================================================
-// Error cases: no leader configured
-// ============================================================
-
-#[tokio::test]
-async fn write_fails_when_no_leader_configured() {
- let replica_service = TestReplicaService::new();
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await; // no leader
- let mut client = create_client(router_addr).await;
-
- let result = client
- .update_person_properties(UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: vec![],
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- })
- .await;
-
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::Unimplemented);
-}
-
-#[tokio::test]
-async fn strong_read_fails_when_no_leader_configured() {
- let replica_service = TestReplicaService::new();
-
- let replica_addr = start_test_replica(replica_service).await;
- let router_addr = start_test_router(replica_addr).await; // no leader
- let mut client = create_client(router_addr).await;
-
- let result = client
- .get_person(GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Strong.into(),
- ..Default::default()
- }),
- })
- .await;
-
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::Unimplemented);
-}
-
-// ============================================================
-// Non-person data always routes to replica
-// ============================================================
-
-#[tokio::test]
-async fn non_person_data_always_routes_to_replica() {
- let groups = vec![personhog_proto::personhog::types::v1::Group {
- id: 1,
- team_id: 1,
- group_type_index: 0,
- group_key: "company-abc".to_string(),
- group_properties: b"{}".to_vec(),
- properties_last_updated_at: vec![],
- properties_last_operation: vec![],
- created_at: 0,
- version: 1,
- }];
- let replica_service = TestReplicaService::new().with_groups(groups);
- let leader_service = TestLeaderService::new(); // empty
-
- let replica_addr = start_test_replica(replica_service).await;
- let leader_addr = start_test_leader(leader_service).await;
- let router_addr =
- start_test_router_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let mut client = create_client(router_addr).await;
-
- // Even with Strong consistency, groups go to replica
- let response = client
- .get_groups(GetGroupsRequest {
- team_id: 1,
- group_identifiers: vec![GroupIdentifier {
- group_type_index: 0,
- group_key: "company-abc".to_string(),
- }],
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Strong.into(),
- ..Default::default()
- }),
- })
- .await
- .unwrap();
-
- let result = response.into_inner();
- assert_eq!(result.groups.len(), 1);
- assert_eq!(result.groups[0].group_key, "company-abc");
-}
-
-// ============================================================
-// Leader NotFound
-// ============================================================
-
-#[tokio::test]
-async fn leader_person_not_found_returns_not_found() {
- let replica_service = TestReplicaService::new();
- let leader_service = TestLeaderService::new(); // empty
-
- let replica_addr = start_test_replica(replica_service).await;
- let leader_addr = start_test_leader(leader_service).await;
- let router_addr =
- start_test_router_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let mut client = create_client(router_addr).await;
-
- let result = client
- .get_person(GetPersonRequest {
- team_id: 1,
- person_id: 999,
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Strong.into(),
- ..Default::default()
- }),
- })
- .await;
-
- assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::NotFound);
-}
diff --git a/rust/personhog-router/tests/raw_proxy_integration.rs b/rust/personhog-router/tests/raw_proxy_integration.rs
index 6e9f5d7efa77..ac9b9c0224be 100644
--- a/rust/personhog-router/tests/raw_proxy_integration.rs
+++ b/rust/personhog-router/tests/raw_proxy_integration.rs
@@ -7,16 +7,12 @@ use common::{
start_test_router_raw_with_leader, start_test_router_raw_with_leader_and_max_recv,
start_test_router_raw_with_max_recv, TestLeaderService, TestReplicaService,
};
-use personhog_proto::personhog::service::v1::person_hog_service_client::PersonHogServiceClient;
use personhog_proto::personhog::types::v1::{
- CheckCohortMembershipRequest, CohortMembership, ConsistencyLevel, DeletePersonsRequest,
- GetGroupTypeMappingsByTeamIdRequest, GetGroupsRequest, GetHashKeyOverrideContextRequest,
- GetPersonByDistinctIdRequest, GetPersonByUuidRequest, GetPersonRequest, GetPersonResponse,
- GetPersonsByDistinctIdsInTeamRequest, Group, GroupIdentifier, GroupTypeMapping,
- HashKeyOverride, HashKeyOverrideContext, Person, PersonWithDistinctIds, ReadOptions,
+ CheckCohortMembershipRequest, CohortMembership, DeletePersonsRequest, GetGroupsRequest,
+ GetPersonByDistinctIdRequest, GetPersonRequest, GetPersonResponse,
+ GetPersonsByDistinctIdsInTeamRequest, Group, GroupIdentifier, Person, PersonWithDistinctIds,
UpdatePersonPropertiesRequest,
};
-use tonic::transport::Channel;
use tonic::Request;
const NUM_PARTITIONS: u32 = 8;
@@ -354,475 +350,7 @@ async fn raw_proxy_update_person_properties_no_leader_returns_unimplemented() {
}
// ============================================================
-// 4. Behavioral parity with typed path — replica
-// ============================================================
-
-/// Shared fixture: starts a replica with rich test data and both router types.
-/// Returns (typed_client, raw_client).
-async fn parity_replica_fixture(
- replica_service: TestReplicaService,
-) -> (
- PersonHogServiceClient<Channel>,
- PersonHogServiceClient<Channel>,
-) {
- let replica_addr = start_test_replica(replica_service).await;
- let typed_addr = common::start_test_router(replica_addr).await;
- let raw_addr = start_test_router_raw(replica_addr).await;
- (
- create_client(typed_addr).await,
- create_client(raw_addr).await,
- )
-}
-
-fn complex_properties() -> Vec<u8> {
- serde_json::to_vec(&serde_json::json!({
- "email": "[email protected]",
- "nested": {"deeply": {"value": 42}},
- "unicode": "日本語テスト",
- "special_chars": "quotes\"and\\backslashes",
- "empty_string": "",
- "null_value": null,
- "array": [1, "two", true],
- }))
- .unwrap()
-}
-
-#[tokio::test]
-async fn parity_get_person_with_complex_properties() {
- let person = Person {
- properties: complex_properties(),
- properties_last_updated_at: br#"{"email":1700000000,"nested":1700000001}"#.to_vec(),
- properties_last_operation: br#"{"email":"$set"}"#.to_vec(),
- ..create_test_person()
- };
- let (mut typed, mut raw) =
- parity_replica_fixture(TestReplicaService::with_person(person)).await;
-
- let req = || GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: None,
- };
-
- let t = typed.get_person(req()).await.unwrap().into_inner();
- let r = raw.get_person(req()).await.unwrap().into_inner();
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_get_person_not_found() {
- let (mut typed, mut raw) = parity_replica_fixture(TestReplicaService::new()).await;
-
- let req = || GetPersonRequest {
- team_id: 1,
- person_id: 999,
- read_options: None,
- };
-
- let t = typed.get_person(req()).await.unwrap().into_inner();
- let r = raw.get_person(req()).await.unwrap().into_inner();
- assert!(t.person.is_none());
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_get_person_by_distinct_id() {
- let person = Person {
- properties: complex_properties(),
- ..create_test_person()
- };
- let (mut typed, mut raw) =
- parity_replica_fixture(TestReplicaService::with_person(person)).await;
-
- let req = || GetPersonByDistinctIdRequest {
- team_id: 1,
- distinct_id: "user-abc".to_string(),
- read_options: None,
- };
-
- let t = typed
- .get_person_by_distinct_id(req())
- .await
- .unwrap()
- .into_inner();
- let r = raw
- .get_person_by_distinct_id(req())
- .await
- .unwrap()
- .into_inner();
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_get_person_by_uuid() {
- let (mut typed, mut raw) =
- parity_replica_fixture(TestReplicaService::with_person(create_test_person())).await;
-
- let req = || GetPersonByUuidRequest {
- team_id: 1,
- uuid: "00000000-0000-0000-0000-000000000042".to_string(),
- read_options: None,
- };
-
- let t = typed.get_person_by_uuid(req()).await.unwrap().into_inner();
- let r = raw.get_person_by_uuid(req()).await.unwrap().into_inner();
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_get_persons_by_distinct_ids_in_team() {
- let persons = vec![
- PersonWithDistinctIds {
- distinct_id: "user-1".to_string(),
- person: Some(create_test_person()),
- },
- PersonWithDistinctIds {
- distinct_id: "user-2".to_string(),
- person: None,
- },
- ];
- let (mut typed, mut raw) =
- parity_replica_fixture(TestReplicaService::new().with_persons_by_distinct_id(persons))
- .await;
-
- let req = || GetPersonsByDistinctIdsInTeamRequest {
- team_id: 1,
- distinct_ids: vec!["user-1".to_string(), "user-2".to_string()],
- read_options: None,
- };
-
- let t = typed
- .get_persons_by_distinct_ids_in_team(req())
- .await
- .unwrap()
- .into_inner();
- let r = raw
- .get_persons_by_distinct_ids_in_team(req())
- .await
- .unwrap()
- .into_inner();
- assert_eq!(t.results.len(), 2);
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_get_groups_multiple() {
- let groups = vec![
- Group {
- id: 1,
- team_id: 1,
- group_type_index: 0,
- group_key: "company-abc".to_string(),
- group_properties: complex_properties(),
- properties_last_updated_at: vec![],
- properties_last_operation: vec![],
- created_at: 1700000000,
- version: 3,
- },
- Group {
- id: 2,
- team_id: 1,
- group_type_index: 1,
- group_key: "project-xyz".to_string(),
- group_properties: b"{}".to_vec(),
- properties_last_updated_at: vec![],
- properties_last_operation: vec![],
- created_at: 1700000001,
- version: 1,
- },
- ];
- let (mut typed, mut raw) =
- parity_replica_fixture(TestReplicaService::new().with_groups(groups)).await;
-
- let req = || GetGroupsRequest {
- team_id: 1,
- group_identifiers: vec![
- GroupIdentifier {
- group_type_index: 0,
- group_key: "company-abc".to_string(),
- },
- GroupIdentifier {
- group_type_index: 1,
- group_key: "project-xyz".to_string(),
- },
- ],
- read_options: None,
- };
-
- let t = typed.get_groups(req()).await.unwrap().into_inner();
- let r = raw.get_groups(req()).await.unwrap().into_inner();
- assert_eq!(t.groups.len(), 2);
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_get_group_type_mappings_by_team_id() {
- let mappings = vec![
- GroupTypeMapping {
- id: 1,
- team_id: 1,
- project_id: 100,
- group_type: "company".to_string(),
- group_type_index: 0,
- name_singular: Some("Company".to_string()),
- name_plural: Some("Companies".to_string()),
- default_columns: None,
- detail_dashboard_id: Some(42),
- created_at: Some(1700000000),
- },
- GroupTypeMapping {
- id: 2,
- team_id: 1,
- project_id: 100,
- group_type: "project".to_string(),
- group_type_index: 1,
- name_singular: None,
- name_plural: None,
- default_columns: Some(b"[\"name\"]".to_vec()),
- detail_dashboard_id: None,
- created_at: None,
- },
- ];
- let (mut typed, mut raw) =
- parity_replica_fixture(TestReplicaService::new().with_group_type_mappings(mappings)).await;
-
- let req = || GetGroupTypeMappingsByTeamIdRequest {
- team_id: 1,
- read_options: None,
- };
-
- let t = typed
- .get_group_type_mappings_by_team_id(req())
- .await
- .unwrap()
- .into_inner();
- let r = raw
- .get_group_type_mappings_by_team_id(req())
- .await
- .unwrap()
- .into_inner();
- assert_eq!(t.mappings.len(), 2);
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_check_cohort_membership_multiple() {
- let memberships = vec![
- CohortMembership {
- cohort_id: 1,
- is_member: true,
- },
- CohortMembership {
- cohort_id: 2,
- is_member: false,
- },
- CohortMembership {
- cohort_id: 3,
- is_member: true,
- },
- ];
- let (mut typed, mut raw) =
- parity_replica_fixture(TestReplicaService::new().with_cohort_memberships(memberships))
- .await;
-
- let req = || CheckCohortMembershipRequest {
- person_id: 42,
- cohort_ids: vec![1, 2, 3],
- read_options: None,
- };
-
- let t = typed
- .check_cohort_membership(req())
- .await
- .unwrap()
- .into_inner();
- let r = raw
- .check_cohort_membership(req())
- .await
- .unwrap()
- .into_inner();
- assert_eq!(t.memberships.len(), 3);
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_get_hash_key_override_context() {
- let contexts = vec![HashKeyOverrideContext {
- person_id: 42,
- distinct_id: "user-abc".to_string(),
- overrides: vec![HashKeyOverride {
- feature_flag_key: "flag-1".to_string(),
- hash_key: "override-key".to_string(),
- }],
- existing_feature_flag_keys: vec!["flag-1".to_string(), "flag-2".to_string()],
- }];
- let (mut typed, mut raw) =
- parity_replica_fixture(TestReplicaService::new().with_hash_key_override_contexts(contexts))
- .await;
-
- let req = || GetHashKeyOverrideContextRequest {
- team_id: 1,
- distinct_ids: vec!["user-abc".to_string()],
- check_person_exists: false,
- read_options: None,
- };
-
- let t = typed
- .get_hash_key_override_context(req())
- .await
- .unwrap()
- .into_inner();
- let r = raw
- .get_hash_key_override_context(req())
- .await
- .unwrap()
- .into_inner();
- assert_eq!(t.results.len(), 1);
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_delete_persons() {
- let (mut typed, mut raw) = parity_replica_fixture(TestReplicaService::new()).await;
-
- let req = || DeletePersonsRequest {
- team_id: 1,
- person_uuids: vec!["00000000-0000-0000-0000-000000000042".to_string()],
- };
-
- let t = typed.delete_persons(req()).await.unwrap().into_inner();
- let r = raw.delete_persons(req()).await.unwrap().into_inner();
- assert_eq!(t, r);
-}
-
-// ============================================================
-// 5. Behavioral parity with typed path — leader
-// ============================================================
-
-#[tokio::test]
-async fn parity_leader_strong_get_person() {
- let person = Person {
- properties: complex_properties(),
- ..create_test_person()
- };
- let leader_service = TestLeaderService::new().with_person(person);
- let replica_service = TestReplicaService::new();
-
- let replica_addr = start_test_replica(replica_service).await;
- let leader_addr = start_test_leader(leader_service).await;
- let typed_addr =
- common::start_test_router_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let raw_addr =
- start_test_router_raw_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let mut typed = create_client(typed_addr).await;
- let mut raw = create_client(raw_addr).await;
-
- let typed_req = GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Strong.into(),
- ..Default::default()
- }),
- };
- let raw_req = with_consistency(
- GetPersonRequest {
- team_id: 1,
- person_id: 42,
- read_options: None,
- },
- "strong",
- );
-
- let t = typed.get_person(typed_req).await.unwrap().into_inner();
- let r = raw.get_person(raw_req).await.unwrap().into_inner();
- assert_eq!(t, r);
-}
-
-#[tokio::test]
-async fn parity_leader_update_person_properties() {
- let leader_service = TestLeaderService::new().with_person(create_test_person());
- let replica_service = TestReplicaService::new();
-
- let replica_addr = start_test_replica(replica_service).await;
- let leader_addr = start_test_leader(leader_service).await;
- let typed_addr =
- common::start_test_router_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let raw_addr =
- start_test_router_raw_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let mut typed = create_client(typed_addr).await;
- let mut raw = create_client(raw_addr).await;
-
- let req = || UpdatePersonPropertiesRequest {
- team_id: 1,
- person_id: 42,
- event_name: "$set".to_string(),
- set_properties: serde_json::to_vec(&serde_json::json!({"name": "Test"})).unwrap(),
- set_once_properties: vec![],
- unset_properties: vec![],
- partition: 0,
- };
-
- let t = typed
- .update_person_properties(req())
- .await
- .unwrap()
- .into_inner();
- let r = raw
- .update_person_properties(req())
- .await
- .unwrap()
- .into_inner();
- assert!(t.updated);
- assert!(r.updated);
- // Both should have version 2 (incremented from 1), but they hit the same
- // leader so the second call sees version 2 and produces version 3.
- // Compare structure: both should have person with updated=true.
- assert_eq!(t.updated, r.updated);
- assert!(t.person.is_some());
- assert!(r.person.is_some());
-}
-
-#[tokio::test]
-async fn parity_leader_person_not_found() {
- let leader_service = TestLeaderService::new();
- let replica_service = TestReplicaService::new();
-
- let replica_addr = start_test_replica(replica_service).await;
- let leader_addr = start_test_leader(leader_service).await;
- let typed_addr =
- common::start_test_router_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let raw_addr =
- start_test_router_raw_with_leader(replica_addr, leader_addr, NUM_PARTITIONS).await;
- let mut typed = create_client(typed_addr).await;
- let mut raw = create_client(raw_addr).await;
-
- let typed_req = GetPersonRequest {
- team_id: 1,
- person_id: 999,
- read_options: Some(ReadOptions {
- consistency: ConsistencyLevel::Strong.into(),
- ..Default::default()
- }),
- };
- let raw_req = with_consistency(
- GetPersonRequest {
- team_id: 1,
- person_id: 999,
- read_options: None,
- },
- "strong",
- );
-
- let t = typed.get_person(typed_req).await;
- let r = raw.get_person(raw_req).await;
- assert!(t.is_err());
- assert!(r.is_err());
- assert_eq!(t.unwrap_err().code(), r.unwrap_err().code());
-}
-
-// ============================================================
-// 6. Request body size limits
+// 4. Request body size limits
// ============================================================
#[tokio::test]
@@ -899,9 +427,22 @@ async fn raw_proxy_accepts_request_within_limit() {
}
// ============================================================
-// 7. Compression through raw proxy
+// 5. Compression through raw proxy
// ============================================================
+fn complex_properties() -> Vec<u8> {
+ serde_json::to_vec(&serde_json::json!({
+ "email": "[email protected]",
+ "nested": {"deeply": {"value": 42}},
+ "unicode": "日本語テスト",
+ "special_chars": "quotes\"and\\backslashes",
+ "empty_string": "",
+ "null_value": null,
+ "array": [1, "two", true],
+ }))
+ .unwrap()
+}
+
#[tokio::test]
async fn raw_proxy_compressed_request_matches_uncompressed() {
let person = Person {
@@ -965,7 +506,7 @@ async fn raw_proxy_compressed_get_persons_by_distinct_ids() {
}
// ============================================================
-// 8. Async gzip compression
+// 6. Async gzip compression
//
// These tests verify the AsyncGzipLayer by making raw gRPC requests with
// `grpc-accept-encoding: gzip` and inspecting the wire format. We bypass