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): extract persons module and router client to common (#73254)

José Sequeirabadb24737f6e
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index d4cb1f8f8441..edccc86be448 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -7671,20 +7671,24 @@ name = "personhog-common"
version = "0.1.0"
dependencies = [
"bytes",
+ "chrono",
"flate2",
"futures",
"http 1.4.0",
"http-body 1.0.1",
"http-body-util",
"metrics",
+ "personhog-proto",
"pin-project",
"rstest",
"serde_json",
"sqlx",
+ "thiserror 2.0.18",
"tokio",
"tonic 0.12.3",
"tower 0.4.13",
"tracing",
+ "uuid",
]
[[package]]
@@ -7775,7 +7779,6 @@ dependencies = [
"rstest",
"serde_json",
"sqlx",
- "thiserror 2.0.18",
"tokio",
"tokio-stream",
"tonic 0.12.3",
diff --git a/rust/personhog-common/Cargo.toml b/rust/personhog-common/Cargo.toml
index 6aa874aedfd1..66b7f6d90b6a 100644
--- a/rust/personhog-common/Cargo.toml
+++ b/rust/personhog-common/Cargo.toml
@@ -5,7 +5,10 @@ edition = "2021"
publish = false
[dependencies]
+personhog-proto = { path = "../personhog-proto" }
+
bytes = { workspace = true }
+chrono = { workspace = true }
flate2 = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
@@ -18,7 +21,9 @@ sqlx = { workspace = true }
tokio = { workspace = true }
tonic = { workspace = true }
tower = { workspace = true }
+thiserror = { workspace = true }
tracing = { workspace = true }
+uuid = { workspace = true }
[dev-dependencies]
rstest = "0.26"
diff --git a/rust/personhog-common/src/client.rs b/rust/personhog-common/src/client.rs
new file mode 100644
index 000000000000..dfb966dac798
--- /dev/null
+++ b/rust/personhog-common/src/client.rs
@@ -0,0 +1,186 @@
+//! Shared client for the router's public PersonHogService.
+//!
+//! The router routes leader-bound calls by hashing the person routing
+//! headers — it never decodes request bodies — so every caller must stamp
+//! `x-team-id`/`x-person-id` on property writes and strong reads. This
+//! client owns that contract so callers cannot get it wrong.
+
+use std::time::Duration;
+
+use tonic::transport::{Channel, Endpoint};
+use tonic::{Request, Status};
+
+use personhog_proto::personhog::service::v1::person_hog_service_client::PersonHogServiceClient;
+use personhog_proto::personhog::types::v1::{
+ ConsistencyLevel, GetPersonRequest, Person, ReadOptions, UpdatePersonPropertiesRequest,
+ UpdatePersonPropertiesResponse,
+};
+
+/// Routing headers for leader-bound calls through the router.
+pub const TEAM_ID_HEADER: &str = "x-team-id";
+pub const PERSON_ID_HEADER: &str = "x-person-id";
+pub const READ_CONSISTENCY_HEADER: &str = "x-read-consistency";
+
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
+
+#[derive(Clone)]
+pub struct RouterClient {
+ inner: PersonHogServiceClient<Channel>,
+ request_timeout: Duration,
+}
+
+impl RouterClient {
+ /// Connect lazily to the router; the first RPC establishes the
+ /// connection.
+ pub fn new(
+ router_url: &str,
+ request_timeout: Duration,
+ ) -> Result<Self, tonic::transport::Error> {
+ let channel = Endpoint::from_shared(router_url.to_string())?
+ .connect_timeout(CONNECT_TIMEOUT)
+ .tcp_nodelay(true)
+ .connect_lazy();
+ Ok(Self {
+ inner: PersonHogServiceClient::new(channel),
+ request_timeout,
+ })
+ }
+
+ /// Leader-routed property write. The routing headers are stamped from
+ /// the request's own team_id/person_id.
+ pub async fn update_person_properties(
+ &self,
+ request: UpdatePersonPropertiesRequest,
+ ) -> Result<UpdatePersonPropertiesResponse, Status> {
+ let request = self.build_update_request(request);
+ self.inner
+ .clone()
+ .update_person_properties(request)
+ .await
+ .map(|response| response.into_inner())
+ }
+
+ /// Person read. Strong reads route to the owning leader and therefore
+ /// carry the routing headers plus the strong-consistency opt-in;
+ /// eventual reads go to the replica with no headers.
+ pub async fn get_person(
+ &self,
+ team_id: i64,
+ person_id: i64,
+ consistency: ConsistencyLevel,
+ ) -> Result<Option<Person>, Status> {
+ let request = self.build_get_person_request(team_id, person_id, consistency);
+ self.inner
+ .clone()
+ .get_person(request)
+ .await
+ .map(|response| response.into_inner().person)
+ }
+
+ fn build_update_request(
+ &self,
+ request: UpdatePersonPropertiesRequest,
+ ) -> Request<UpdatePersonPropertiesRequest> {
+ let (team_id, person_id) = (request.team_id, request.person_id);
+ let mut request = Request::new(request);
+ request.set_timeout(self.request_timeout);
+ stamp_person_routing_headers(&mut request, team_id, person_id);
+ request
+ }
+
+ fn build_get_person_request(
+ &self,
+ team_id: i64,
+ person_id: i64,
+ consistency: ConsistencyLevel,
+ ) -> Request<GetPersonRequest> {
+ let mut request = Request::new(GetPersonRequest {
+ team_id,
+ person_id,
+ read_options: Some(ReadOptions {
+ consistency: consistency.into(),
+ ..Default::default()
+ }),
+ });
+ request.set_timeout(self.request_timeout);
+ if consistency == ConsistencyLevel::Strong {
+ stamp_person_routing_headers(&mut request, team_id, person_id);
+ request.metadata_mut().insert(
+ READ_CONSISTENCY_HEADER,
+ tonic::metadata::MetadataValue::from_static("strong"),
+ );
+ }
+ request
+ }
+}
+
+/// Stamp the person routing headers the router hashes for leader routing.
+pub fn stamp_person_routing_headers<T>(request: &mut Request<T>, team_id: i64, person_id: i64) {
+ let metadata = request.metadata_mut();
+ metadata.insert(
+ TEAM_ID_HEADER,
+ team_id
+ .to_string()
+ .parse()
+ .expect("numeric header is valid metadata"),
+ );
+ metadata.insert(
+ PERSON_ID_HEADER,
+ person_id
+ .to_string()
+ .parse()
+ .expect("numeric header is valid metadata"),
+ );
+}
+
+/// The router fails leader-bound calls closed on missing headers and would
+/// misroute on wrong ones, so the header decisions per routing branch are
+/// pinned here: leader-bound requests (writes, strong reads) must carry the
+/// person routing headers, replica-bound reads must not.
+#[cfg(test)]
+mod tests {
+ use rstest::rstest;
+
+ use super::*;
+
+ fn client() -> RouterClient {
+ RouterClient::new("http://127.0.0.1:1", Duration::from_secs(1))
+ .expect("lazy client construction cannot fail on a valid url")
+ }
+
+ // Channel construction (even lazy) needs a Tokio reactor, hence async tests.
+ #[tokio::test]
+ async fn update_request_carries_the_routing_headers() {
+ let request = client().build_update_request(UpdatePersonPropertiesRequest {
+ team_id: 7,
+ person_id: 42,
+ ..Default::default()
+ });
+ let metadata = request.metadata();
+ assert_eq!(metadata.get(TEAM_ID_HEADER).unwrap(), "7");
+ assert_eq!(metadata.get(PERSON_ID_HEADER).unwrap(), "42");
+ assert!(metadata.get(READ_CONSISTENCY_HEADER).is_none());
+ }
+
+ #[rstest]
+ #[case::strong(ConsistencyLevel::Strong, true)]
+ #[case::eventual(ConsistencyLevel::Eventual, false)]
+ #[case::unspecified(ConsistencyLevel::Unspecified, false)]
+ #[tokio::test]
+ async fn get_person_request_headers_follow_the_routing_branch(
+ #[case] consistency: ConsistencyLevel,
+ #[case] leader_bound: bool,
+ ) {
+ let request = client().build_get_person_request(7, 42, consistency);
+ let metadata = request.metadata();
+ if leader_bound {
+ assert_eq!(metadata.get(TEAM_ID_HEADER).unwrap(), "7");
+ assert_eq!(metadata.get(PERSON_ID_HEADER).unwrap(), "42");
+ assert_eq!(metadata.get(READ_CONSISTENCY_HEADER).unwrap(), "strong");
+ } else {
+ assert!(metadata.get(TEAM_ID_HEADER).is_none());
+ assert!(metadata.get(PERSON_ID_HEADER).is_none());
+ assert!(metadata.get(READ_CONSISTENCY_HEADER).is_none());
+ }
+ }
+}
diff --git a/rust/personhog-common/src/lib.rs b/rust/personhog-common/src/lib.rs
index adb0ff7a9758..b8b2e722a22f 100644
--- a/rust/personhog-common/src/lib.rs
+++ b/rust/personhog-common/src/lib.rs
@@ -1,7 +1,10 @@
pub mod async_gzip;
+pub mod client;
pub mod grpc;
pub mod partitioning;
+pub mod persons;
mod pool_monitor;
pub mod properties;
+pub mod storage_error;
pub use pool_monitor::{spawn_pool_monitor, MonitoredPool};
diff --git a/rust/personhog-common/src/persons.rs b/rust/personhog-common/src/persons.rs
new file mode 100644
index 000000000000..0617f9af1704
--- /dev/null
+++ b/rust/personhog-common/src/persons.rs
@@ -0,0 +1,63 @@
+//! Shared person-storage primitives used by the personhog services that read
+//! or write person rows in Postgres (replica, identity). Each service keeps
+//! its own SQL; the row type and deterministic UUID scheme live here so the
+//! services cannot drift apart. Error classification lives in
+//! [`crate::storage_error`].
+
+use uuid::Uuid;
+
+/// Namespace for deterministic person UUIDs (uuidv5 of "team_id:distinct_id").
+/// Mirrors the Django/plugin-server convention.
+pub const PERSON_UUIDV5_NAMESPACE: Uuid = Uuid::from_bytes([
+ 0x93, 0x29, 0x79, 0xb4, 0x65, 0xc3, 0x44, 0x24, 0x84, 0x67, 0x0b, 0x66, 0xec, 0x27, 0xbc, 0x22,
+]);
+
+/// The deterministic person UUID for a (team_id, distinct_id) pair.
+pub fn person_uuid(team_id: i64, distinct_id: &str) -> Uuid {
+ Uuid::new_v5(
+ &PERSON_UUIDV5_NAMESPACE,
+ format!("{team_id}:{distinct_id}").as_bytes(),
+ )
+}
+
+#[derive(Debug, Clone)]
+pub struct Person {
+ pub id: i64,
+ pub uuid: Uuid,
+ pub team_id: i64,
+ pub properties: Option<String>,
+ pub properties_last_updated_at: Option<String>,
+ pub properties_last_operation: Option<String>,
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ pub version: Option<i64>,
+ pub is_identified: bool,
+ pub is_user_id: Option<bool>,
+ pub last_seen_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+impl From<Person> for personhog_proto::personhog::types::v1::Person {
+ fn from(person: Person) -> Self {
+ personhog_proto::personhog::types::v1::Person {
+ id: person.id,
+ uuid: person.uuid.to_string(),
+ team_id: person.team_id,
+ properties: person
+ .properties
+ .map(|v| v.into_bytes())
+ .unwrap_or_default(),
+ properties_last_updated_at: person
+ .properties_last_updated_at
+ .map(|v| v.into_bytes())
+ .unwrap_or_default(),
+ properties_last_operation: person
+ .properties_last_operation
+ .map(|v| v.into_bytes())
+ .unwrap_or_default(),
+ created_at: person.created_at.timestamp_millis(),
+ version: person.version.unwrap_or(0),
+ is_identified: person.is_identified,
+ is_user_id: person.is_user_id,
+ last_seen_at: person.last_seen_at.map(|t| t.timestamp_millis()),
+ }
+ }
+}
diff --git a/rust/personhog-common/src/storage_error.rs b/rust/personhog-common/src/storage_error.rs
new file mode 100644
index 000000000000..4fc9fe747365
--- /dev/null
+++ b/rust/personhog-common/src/storage_error.rs
@@ -0,0 +1,55 @@
+//! Shared storage-error classification for personhog services backed by the
+//! persons Postgres. The variants map 1:1 onto the gRPC status codes the
+//! services surface, so the classification lives here rather than per
+//! service.
+
+use thiserror::Error;
+
+#[derive(Error, Debug)]
+pub enum StorageError {
+ /// Connection-level errors (network, TLS, authentication)
+ #[error("Database connection error: {0}")]
+ Connection(String),
+
+ /// Query execution errors (SQL errors, constraint violations)
+ #[error("Database query error: {0}")]
+ Query(String),
+
+ /// Connection pool exhausted or closed
+ #[error("Database pool exhausted")]
+ PoolExhausted,
+
+ /// Resource not found (e.g. person, distinct_id)
+ #[error("Not found: {0}")]
+ NotFound(String),
+
+ /// Operation precondition violated (e.g. concurrent modification)
+ #[error("Failed precondition: {0}")]
+ FailedPrecondition(String),
+}
+
+impl Clone for StorageError {
+ fn clone(&self) -> Self {
+ match self {
+ Self::Connection(msg) => Self::Connection(msg.clone()),
+ Self::Query(msg) => Self::Query(msg.clone()),
+ Self::PoolExhausted => Self::PoolExhausted,
+ Self::NotFound(msg) => Self::NotFound(msg.clone()),
+ Self::FailedPrecondition(msg) => Self::FailedPrecondition(msg.clone()),
+ }
+ }
+}
+
+impl From<sqlx::Error> for StorageError {
+ fn from(err: sqlx::Error) -> Self {
+ match &err {
+ sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed => StorageError::PoolExhausted,
+
+ sqlx::Error::Io(_) | sqlx::Error::Tls(_) => StorageError::Connection(err.to_string()),
+
+ _ => StorageError::Query(err.to_string()),
+ }
+ }
+}
+
+pub type StorageResult<T> = Result<T, StorageError>;
diff --git a/rust/personhog-replica/Cargo.toml b/rust/personhog-replica/Cargo.toml
index 034dc6e393b5..bdb8d3723601 100644
--- a/rust/personhog-replica/Cargo.toml
+++ b/rust/personhog-replica/Cargo.toml
@@ -22,7 +22,6 @@ envconfig = { workspace = true }
rand = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
-thiserror = { workspace = true }
tokio = { workspace = true }
tonic = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/personhog-replica/src/service/types/mod.rs b/rust/personhog-replica/src/service/types/mod.rs
index 7e7fc9029c4c..3cf3067b07ed 100644
--- a/rust/personhog-replica/src/service/types/mod.rs
+++ b/rust/personhog-replica/src/service/types/mod.rs
@@ -1,2 +1 @@
mod group;
-mod person;
diff --git a/rust/personhog-replica/src/service/types/person.rs b/rust/personhog-replica/src/service/types/person.rs
deleted file mode 100644
index 99318a2a158a..000000000000
--- a/rust/personhog-replica/src/service/types/person.rs
+++ /dev/null
@@ -1,30 +0,0 @@
-use personhog_proto::personhog::types::v1::Person;
-
-use crate::storage;
-
-impl From<storage::Person> for Person {
- fn from(person: storage::Person) -> Self {
- Person {
- id: person.id,
- uuid: person.uuid.to_string(),
- team_id: person.team_id,
- properties: person
- .properties
- .map(|v| v.into_bytes())
- .unwrap_or_default(),
- properties_last_updated_at: person
- .properties_last_updated_at
- .map(|v| v.into_bytes())
- .unwrap_or_default(),
- properties_last_operation: person
- .properties_last_operation
- .map(|v| v.into_bytes())
- .unwrap_or_default(),
- created_at: person.created_at.timestamp_millis(),
- version: person.version.unwrap_or(0),
- is_identified: person.is_identified,
- is_user_id: person.is_user_id,
- last_seen_at: person.last_seen_at.map(|t| t.timestamp_millis()),
- }
- }
-}
diff --git a/rust/personhog-replica/src/storage/error.rs b/rust/personhog-replica/src/storage/error.rs
index 4522b6cf0e19..b4aa008dbc11 100644
--- a/rust/personhog-replica/src/storage/error.rs
+++ b/rust/personhog-replica/src/storage/error.rs
@@ -1,38 +1 @@
-use thiserror::Error;
-
-#[derive(Error, Debug)]
-pub enum StorageError {
- /// Connection-level errors (network, TLS, authentication)
- #[error("Database connection error: {0}")]
- Connection(String),
-
- /// Query execution errors (SQL errors, constraint violations)
- #[error("Database query error: {0}")]
- Query(String),
-
- /// Connection pool exhausted or closed
- #[error("Database pool exhausted")]
- PoolExhausted,
-
- /// Resource not found (e.g. person, distinct_id)
- #[error("Not found: {0}")]
- NotFound(String),
-
- /// Operation precondition violated (e.g. concurrent modification)
- #[error("Failed precondition: {0}")]
- FailedPrecondition(String),
-}
-
-impl Clone for StorageError {
- fn clone(&self) -> Self {
- match self {
- Self::Connection(msg) => Self::Connection(msg.clone()),
- Self::Query(msg) => Self::Query(msg.clone()),
- Self::PoolExhausted => Self::PoolExhausted,
- Self::NotFound(msg) => Self::NotFound(msg.clone()),
- Self::FailedPrecondition(msg) => Self::FailedPrecondition(msg.clone()),
- }
- }
-}
-
-pub type StorageResult<T> = Result<T, StorageError>;
+pub use personhog_common::storage_error::{StorageError, StorageResult};
diff --git a/rust/personhog-replica/src/storage/postgres/mod.rs b/rust/personhog-replica/src/storage/postgres/mod.rs
index 95370012cc29..9988eef6af28 100644
--- a/rust/personhog-replica/src/storage/postgres/mod.rs
+++ b/rust/personhog-replica/src/storage/postgres/mod.rs
@@ -136,15 +136,3 @@ impl PostgresStorage {
&self.replica_pool
}
}
-
-impl From<sqlx::Error> for StorageError {
- fn from(err: sqlx::Error) -> Self {
- match &err {
- sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed => StorageError::PoolExhausted,
-
- sqlx::Error::Io(_) | sqlx::Error::Tls(_) => StorageError::Connection(err.to_string()),
-
- _ => StorageError::Query(err.to_string()),
- }
- }
-}
diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rs
index 61ef1e1268bb..f213090a68fe 100644
--- a/rust/personhog-replica/src/storage/postgres/person.rs
+++ b/rust/personhog-replica/src/storage/postgres/person.rs
@@ -13,10 +13,6 @@ use crate::storage::error::{StorageError, StorageResult};
use crate::storage::traits::PersonLookup;
use crate::storage::types::{Person, SplitResult};
-const PERSON_UUIDV5_NAMESPACE: Uuid = Uuid::from_bytes([
- 0x93, 0x29, 0x79, 0xb4, 0x65, 0xc3, 0x44, 0x24, 0x84, 0x67, 0x0b, 0x66, 0xec, 0x27, 0xbc, 0x22,
-]);
-
/// Version offset for split person/PDI rows — mirrors the Django convention.
const SPLIT_VERSION_OFFSET: i64 = 101;
@@ -782,12 +778,7 @@ impl PersonLookup for PostgresStorage {
let dids: Vec<String> = distinct_ids_to_split.to_vec();
let new_uuids: Vec<Uuid> = dids
.iter()
- .map(|did| {
- Uuid::new_v5(
- &PERSON_UUIDV5_NAMESPACE,
- format!("{team_id}:{did}").as_bytes(),
- )
- })
+ .map(|did| personhog_common::persons::person_uuid(team_id, did))
.collect();
let pdi_versions: Vec<i64> = dids
.iter()
diff --git a/rust/personhog-replica/src/storage/types/person.rs b/rust/personhog-replica/src/storage/types/person.rs
index ae1e6e8229c9..96efe5276e67 100644
--- a/rust/personhog-replica/src/storage/types/person.rs
+++ b/rust/personhog-replica/src/storage/types/person.rs
@@ -1,19 +1,6 @@
use uuid::Uuid;
-#[derive(Debug, Clone)]
-pub struct Person {
- pub id: i64,
- pub uuid: Uuid,
- pub team_id: i64,
- pub properties: Option<String>,
- pub properties_last_updated_at: Option<String>,
- pub properties_last_operation: Option<String>,
- pub created_at: chrono::DateTime<chrono::Utc>,
- pub version: Option<i64>,
- pub is_identified: bool,
- pub is_user_id: Option<bool>,
- pub last_seen_at: Option<chrono::DateTime<chrono::Utc>>,
-}
+pub use personhog_common::persons::Person;
#[derive(Debug, Clone)]
pub struct DistinctIdMapping {