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.

8.8 KB
Raw Blame
use std::time::Duration;

use anyhow::{Context, Result};
use personhog_common::client::RouterClient;
use personhog_common::grpc::CLIENT_NAME_HEADER;
use personhog_proto::personhog::{
    identity::v1::{
        person_hog_identity_client::PersonHogIdentityClient, GetOrCreatePersonEntry,
        GetOrCreatePersonResult, GetOrCreatePersonsByDistinctIdsRequest, MergePersonsRequest,
        MergePersonsResponse, MergeSource,
    },
    lifecycle::v1::{
        person_hog_lifecycle_client::PersonHogLifecycleClient, DeletePersonOutcome,
        DeletePersonsRequest,
    },
    types::v1::{
        ConsistencyLevel, FencePersonRequest, FencePersonResponse, LifecycleOpType, Person,
        ReleaseFenceRequest, ReleaseOutcome, UpdatePersonPropertiesRequest,
        UpdatePersonPropertiesResponse,
    },
};
use tonic::metadata::MetadataValue;
use tonic::transport::Channel;
use tonic::Request;

const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
const HARNESS_CLIENT_NAME: &str = "personhog-test-harness";

fn with_client_name<T>(message: T) -> Request<T> {
    let mut request = Request::new(message);
    request.metadata_mut().insert(
        CLIENT_NAME_HEADER,
        MetadataValue::from_static(HARNESS_CLIENT_NAME),
    );
    request
}

/// Harness wrapper over the shared router client: same wire behavior,
/// anyhow-flavored results for scenario code.
#[derive(Clone)]
pub struct HarnessClient {
    inner: RouterClient,
}

impl HarnessClient {
    pub async fn connect(url: &str) -> Result<Self> {
        Self::connect_with_channels(url, 1).await
    }

    /// Connect over `channels` router connections, selected round-robin.
    /// Load-driving scenarios pass more than one so an instance spreads
    /// across router pods instead of pinning to whichever pod its single
    /// connection landed on.
    pub async fn connect_with_channels(url: &str, channels: usize) -> Result<Self> {
        let inner = RouterClient::with_channels(url, REQUEST_TIMEOUT, channels)
            .context("invalid router URL")?
            .with_client_name(HARNESS_CLIENT_NAME);
        Ok(Self { inner })
    }

    pub async fn get_person(
        &self,
        team_id: i64,
        person_id: i64,
        consistency: ConsistencyLevel,
    ) -> Result<Option<Person>> {
        self.inner
            .get_person(team_id, person_id, consistency)
            .await
            .context("GetPerson failed")
    }

    /// Fence a person for a delete op, returning the sealed version.
    pub async fn fence_person(
        &self,
        team_id: i64,
        person_id: i64,
        op_id: &uuid::Uuid,
    ) -> Result<FencePersonResponse> {
        self.inner
            .fence_person(FencePersonRequest {
                team_id,
                person_id,
                op_id: op_id.to_string(),
                op_type: LifecycleOpType::Delete.into(),
            })
            .await
            .context("FencePerson failed")
    }

    /// Release a fence with the aborted outcome: the person resumes life.
    pub async fn release_fence_aborted(
        &self,
        team_id: i64,
        person_id: i64,
        op_id: &uuid::Uuid,
    ) -> Result<()> {
        self.inner
            .release_fence(ReleaseFenceRequest {
                team_id,
                person_id,
                person_uuid: String::new(),
                op_id: op_id.to_string(),
                outcome: ReleaseOutcome::Aborted.into(),
                sealed_version: None,
                created_at: 0,
                tombstone_version: None,
            })
            .await
            .context("ReleaseFence failed")?;
        Ok(())
    }

    pub async fn update_properties(
        &self,
        team_id: i64,
        person_id: i64,
        set_properties: serde_json::Value,
        set_once_properties: serde_json::Value,
        unset_properties: Vec<String>,
    ) -> Result<UpdatePersonPropertiesResponse> {
        self.inner
            .update_person_properties(UpdatePersonPropertiesRequest {
                force_update: true,
                team_id,
                person_id,
                event_name: "$set".to_string(),
                set_properties: serde_json::to_vec(&set_properties)?,
                set_once_properties: serde_json::to_vec(&set_once_properties)?,
                unset_properties,
                is_identified: None,
                last_seen_at: None,
            })
            .await
            .context("UpdatePersonProperties failed")
    }
}

/// Client for the personhog-identity service, the get-or-create entry
/// point. No routing headers: identity pods are interchangeable, and the
/// router forwards these paths verbatim when it fronts the service.
#[derive(Clone)]
pub struct IdentityClient {
    inner: PersonHogIdentityClient<Channel>,
}

impl IdentityClient {
    pub async fn connect(url: &str) -> Result<Self> {
        let channel = Channel::from_shared(url.to_string())
            .context("invalid identity URL")?
            .timeout(REQUEST_TIMEOUT)
            .connect_timeout(Duration::from_secs(5))
            .tcp_nodelay(true)
            .connect_lazy();

        Ok(Self {
            inner: PersonHogIdentityClient::new(channel),
        })
    }

    pub async fn get_or_create_persons(
        &self,
        entries: Vec<GetOrCreatePersonEntry>,
    ) -> Result<Vec<GetOrCreatePersonResult>> {
        let resp = self
            .inner
            .clone()
            .get_or_create_persons_by_distinct_ids(with_client_name(
                GetOrCreatePersonsByDistinctIdsRequest { entries },
            ))
            .await
            .context("GetOrCreatePersonsByDistinctIds failed")?;
        Ok(resp.into_inner().results)
    }

    /// Merge `source_distinct_ids` into the person that
    /// `target_distinct_id` resolves to. A retry with the same op id
    /// returns the recorded outcome and does not merge again. The
    /// creator must stay stable across those retries, so the caller
    /// mints it once per merge alongside the op id.
    #[allow(clippy::too_many_arguments)]
    pub async fn merge_persons(
        &self,
        team_id: i64,
        target_distinct_id: &str,
        source_distinct_ids: &[String],
        event_set: serde_json::Value,
        event_set_once: serde_json::Value,
        op_id: &uuid::Uuid,
        creator_event_uuid: &uuid::Uuid,
        allow_identified_sources: bool,
        move_limit: i64,
    ) -> Result<MergePersonsResponse> {
        let resp = self
            .inner
            .clone()
            .merge_persons(with_client_name(MergePersonsRequest {
                team_id,
                target_distinct_id: target_distinct_id.to_string(),
                sources: source_distinct_ids
                    .iter()
                    .map(|did| MergeSource {
                        source_distinct_id: did.clone(),
                        event_uuid: uuid::Uuid::new_v4().to_string(),
                    })
                    .collect(),
                event_set: serde_json::to_vec(&event_set)?,
                event_set_once: serde_json::to_vec(&event_set_once)?,
                op_id: op_id.to_string(),
                allow_identified_sources,
                move_limit: Some(move_limit),
                created_at: 0,
                creator_event_uuid: creator_event_uuid.to_string(),
            }))
            .await
            .context("MergePersons failed")?;
        Ok(resp.into_inner())
    }
}

/// Client for the lifecycle saga service, co-served on the identity
/// server's address.
#[derive(Clone)]
pub struct LifecycleClient {
    inner: PersonHogLifecycleClient<Channel>,
}

impl LifecycleClient {
    pub async fn connect(url: &str) -> Result<Self> {
        let channel = Channel::from_shared(url.to_string())
            .context("invalid lifecycle URL")?
            .timeout(REQUEST_TIMEOUT)
            .connect_timeout(Duration::from_secs(5))
            .tcp_nodelay(true)
            .connect_lazy();

        Ok(Self {
            inner: PersonHogLifecycleClient::new(channel),
        })
    }

    /// Destroy persons through the durable delete saga, returning each
    /// person's outcome. The op id is scoped to this attempt — never
    /// derived from the rows, which revive with the same id.
    pub async fn delete_persons(
        &self,
        team_id: i64,
        person_ids: Vec<i64>,
        op_id: &uuid::Uuid,
    ) -> Result<Vec<(i64, DeletePersonOutcome)>> {
        let resp = self
            .inner
            .clone()
            .delete_persons(with_client_name(DeletePersonsRequest {
                team_id,
                person_ids,
                op_id: op_id.to_string(),
            }))
            .await
            .context("DeletePersons failed")?;
        Ok(resp
            .into_inner()
            .results
            .into_iter()
            .map(|result| (result.person_id, result.outcome()))
            .collect())
    }
}