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.

6.1 KB
Raw Blame
use async_trait::async_trait;
use uuid::Uuid;

use crate::storage::error::StorageResult;
use crate::storage::types::{
    DeletePersonsOutcome, Person, PersonListEntry, PersonTombstoneQueueEntry,
    PersonVersionFloorResult, SplitResult, TombstoneTarget, TombstonedDeleteOutcome,
    TombstonedPerson,
};

/// Person lookup operations by ID, UUID, and distinct ID
#[async_trait]
pub trait PersonLookup: Send + Sync {
    // Lookups by ID/UUID

    async fn get_person_by_id(&self, team_id: i64, person_id: i64)
        -> StorageResult<Option<Person>>;

    async fn get_person_by_uuid(&self, team_id: i64, uuid: Uuid) -> StorageResult<Option<Person>>;

    async fn get_persons_by_ids(
        &self,
        team_id: i64,
        person_ids: &[i64],
        include_properties: bool,
    ) -> StorageResult<Vec<Person>>;

    async fn get_persons_by_uuids(
        &self,
        team_id: i64,
        uuids: &[Uuid],
        include_properties: bool,
    ) -> StorageResult<Vec<Person>>;

    // Lookups by distinct ID

    async fn get_person_by_distinct_id(
        &self,
        team_id: i64,
        distinct_id: &str,
    ) -> StorageResult<Option<Person>>;

    async fn get_persons_by_distinct_ids_in_team(
        &self,
        team_id: i64,
        distinct_ids: &[String],
        include_properties: bool,
    ) -> StorageResult<Vec<(String, Option<Person>)>>;

    async fn get_persons_by_distinct_ids_cross_team(
        &self,
        team_distinct_ids: &[(i64, String)],
        include_properties: bool,
    ) -> StorageResult<Vec<((i64, String), Option<Person>)>>;

    // Deletes

    /// Tombstones the persons and reports the versions written for the ClickHouse tombstones.
    async fn delete_persons(
        &self,
        team_id: i64,
        uuids: &[Uuid],
    ) -> StorageResult<DeletePersonsOutcome>;

    /// Delete persons that are still tombstoned, at most `max_rows` dependent rows per call:
    /// persons that fit the budget go whole, the first that does not is trimmed with the leftover
    /// and returned pending, the rest are returned pending untouched. A revival either wins the
    /// row lock first and is skipped, or lands afterwards on a fresh row. Idempotent.
    ///
    /// A person is deleted only while its version is at or below its target's `max_version`,
    /// checked under the same row lock. A uuid listed twice keeps its lowest bound.
    async fn delete_tombstoned_persons(
        &self,
        team_id: i64,
        targets: &[TombstoneTarget],
        max_rows: i64,
    ) -> StorageResult<TombstonedDeleteOutcome>;

    async fn get_person_tombstones(
        &self,
        team_id: i64,
        uuids: &[Uuid],
    ) -> StorageResult<Vec<TombstonedPerson>>;

    async fn ack_person_tombstones(
        &self,
        team_id: i64,
        acked: &[(Uuid, i64)],
    ) -> StorageResult<i64>;

    async fn list_person_tombstone_queue(
        &self,
        after: (i64, Uuid),
        team_id: Option<i64>,
        limit: i64,
    ) -> StorageResult<Vec<PersonTombstoneQueueEntry>>;

    /// Delete up to `batch_size` persons for a team. Selects person IDs with
    /// FOR UPDATE SKIP LOCKED, then splits them into fixed-size chunks and
    /// deletes concurrently. Each chunk deletes distinct_ids first (FK is
    /// NO ACTION) then persons (feature flag hash key overrides cascade at
    /// the DB level). Returns the number of deleted person records; 0 means
    /// no more persons to delete.
    async fn delete_persons_batch_for_team(
        &self,
        team_id: i64,
        batch_size: i64,
    ) -> StorageResult<i64>;

    /// Atomically split distinct_ids off a person onto new persons.
    ///
    /// Within a single transaction (constant statement count, set-based):
    /// 1. Locks the specified PersonDistinctId rows with SELECT FOR UPDATE and
    ///    validates ownership under the lock
    /// 2. Creates new persons via one bulk upsert (deterministic UUIDv5,
    ///    version = original person version + 101). A live person at that
    ///    UUID is never reused: the distinct_id gets a random UUID instead.
    /// 3. Reassigns PDIs to new persons in one bulk update
    ///    (version = original PDI version + 101)
    ///
    /// Returns StorageError::NotFound if the person doesn't exist or any
    /// distinct_id doesn't belong to it.
    async fn split_person(
        &self,
        team_id: i64,
        person_id: i64,
        distinct_ids_to_split: &[String],
    ) -> StorageResult<Vec<SplitResult>>;

    // Undelete repair

    /// Bump a person_distinct_id row's version to `min_version`, but only when the stored
    /// version is lower (the update never lowers a version). Returns the person the
    /// distinct_id maps to whenever it exists — even if the guard left the version
    /// unchanged — and None when the distinct_id does not exist (it has not been re-used
    /// yet). Used by the undelete repair flow to revive a soft-deleted distinct_id.
    async fn set_person_distinct_id_version_floor(
        &self,
        team_id: i64,
        distinct_id: &str,
        min_version: i64,
    ) -> StorageResult<Option<Person>>;

    /// Bump a person's version to `min_version`, but only when the stored version is
    /// lower (the update never lowers a version). Returns whether a row was updated.
    async fn set_person_version_floor(
        &self,
        team_id: i64,
        person_id: i64,
        min_version: i64,
    ) -> StorageResult<bool>;

    /// Raise each person tombstone to at least its min version in one primary transaction, inserting a
    /// tombstone for a missing person and leaving a live row unchanged; `floors` must not repeat a uuid.
    async fn ensure_person_version_floors(
        &self,
        team_id: i64,
        floors: &[(Uuid, i64)],
    ) -> StorageResult<Vec<PersonVersionFloorResult>>;

    /// One page of a team's persons, live and tombstoned, with id above `after_person_id` and below
    /// `before_person_id` when given, in id order.
    async fn list_persons_for_team(
        &self,
        team_id: i64,
        after_person_id: i64,
        before_person_id: Option<i64>,
        limit: i64,
    ) -> StorageResult<Vec<PersonListEntry>>;
}