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.2 KB
Raw Blame
import dataclasses
from collections.abc import Callable
from typing import Any, Optional, cast
from urllib.parse import urlencode

from requests import Request, Response

from products.warehouse_sources.sources.lattice.settings import LATTICE_ENDPOINTS, PAGE_SIZE
from products.warehouse_sources.sources.sdk import (
    BasePaginator,
    ClientConfig,
    Resource,
    RESTAPIConfig,
    ResumableSourceManager,
    SourceResponse,
    build_dependent_resource,
    make_tracked_session,
    rest_api_resource,
    validate_via_probe,
)

LATTICE_HOSTS = {
    "us": "https://api.latticehq.com",
    "emea": "https://api.emea.latticehq.com",
}


@dataclasses.dataclass(frozen=False)
class LatticeResumeConfig:
    # Lattice cursor pagination: pass the previous page's endingCursor as
    # startingAfter; static params are rebuilt deterministically on resume.
    starting_after: Optional[str] = None
    # Per-review-cycle endpoints checkpoint the shape `build_dependent_resource` emits:
    # which cycles finished and where the current one stopped.
    fanout_state: Optional[dict[str, Any]] = None


class LatticeCursorPaginator(BasePaginator):
    """Lattice cursor pagination: the next page's ``startingAfter`` is the previous
    page's ``endingCursor``. Pagination stops as soon as ``hasMore`` is false, the
    body carries no ``endingCursor``, or the page returned no rows — the last of
    which guards against a server that keeps advertising more with an empty page.

    ``/v1/goals/updates`` reports the same cursor as ``pageInfo.endCursor`` and
    ``pageInfo.hasNextPage`` instead."""

    def __init__(self, cursor_param: str = "startingAfter") -> None:
        super().__init__()
        self.cursor_param = cursor_param
        self._cursor_value: Optional[str] = None

    def _apply_cursor(self, request: Request) -> None:
        if self._cursor_value is not None:
            if request.params is None:
                request.params = {}
            request.params[self.cursor_param] = self._cursor_value

    def init_request(self, request: Request) -> None:
        # Seed a resumed run's first request with the saved cursor.
        self._apply_cursor(request)

    def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
        try:
            body = response.json()
        except Exception:
            body = None
        if not isinstance(body, dict):
            body = {}
        page_info = body.get("pageInfo")
        if not isinstance(page_info, dict):
            page_info = {}
        ending_cursor = body.get("endingCursor") or page_info.get("endCursor")
        has_more = body["hasMore"] if "hasMore" in body else page_info.get("hasNextPage")
        if data and has_more and ending_cursor:
            self._cursor_value = ending_cursor
            self._has_next_page = True
        else:
            self._has_next_page = False

    def update_request(self, request: Request) -> None:
        self._apply_cursor(request)

    def get_resume_state(self) -> Optional[dict[str, Any]]:
        return {"cursor": self._cursor_value} if self._has_next_page and self._cursor_value is not None else None

    def set_resume_state(self, state: dict[str, Any]) -> None:
        cursor = state.get("cursor")
        if cursor is not None:
            self._cursor_value = cursor
            self._has_next_page = True


def _nested_id(value: Any) -> Optional[str]:
    return value.get("id") if isinstance(value, dict) else None


def _lift_custom_attribute_ids(row: dict[str, Any]) -> dict[str, Any]:
    return {
        **row,
        "custom_attribute_id": _nested_id(row.get("customAttribute")),
        "custom_attribute_value_id": _nested_id(row.get("customAttributeValue")),
    }


ROW_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
    "user_custom_attributes": _lift_custom_attribute_ids,
}


def _base_url(region: str) -> str:
    host = LATTICE_HOSTS.get(region)
    if host is None:
        raise ValueError(f"Invalid Lattice region: {region}")
    return host


def validate_credentials(region: str, api_key: str) -> tuple[bool, str | None]:
    """Confirm the API key is valid with a cheap one-user probe.

    Keys inherit the creating user's privileges, so a key may lack access to a
    specific stream (403); only 401 means the key itself is bad."""
    try:
        base_url = _base_url(region)
    except ValueError as e:
        return False, str(e)

    _ok, status = validate_via_probe(
        lambda: make_tracked_session(redact_values=(api_key,)),
        f"{base_url}/v1/users?{urlencode({'limit': 1})}",
        headers={"Authorization": f"Bearer {api_key}"},
    )

    if status is None:
        # Transport failures (timeouts, connection resets) are not auth failures;
        # don't mislabel the key as invalid.
        return False, "Could not reach Lattice"
    if status == 401:
        return False, "Invalid Lattice API key"
    return True, None


def lattice_source(
    region: str,
    api_key: str,
    endpoint: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[LatticeResumeConfig],
    db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
    config = LATTICE_ENDPOINTS[endpoint]
    client_config: ClientConfig = {
        "base_url": _base_url(region),
        # Auth is supplied via the framework auth config so its value is redacted from logs.
        "auth": {"type": "bearer", "token": api_key},
        "paginator": LatticeCursorPaginator(),
    }

    resume: Optional[LatticeResumeConfig] = None
    if resumable_source_manager.can_resume():
        resume = resumable_source_manager.load_state()

    if config.fanout is not None:

        def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:
            if state:
                resumable_source_manager.save_state(LatticeResumeConfig(fanout_state=state))

        child = build_dependent_resource(
            endpoint_configs=LATTICE_ENDPOINTS,
            child_endpoint=endpoint,
            fanout=config.fanout,
            client_config=client_config,
            parent_endpoint_extra={"data_selector": "data"},
            child_endpoint_extra={"data_selector": "data"},
            path_format_values={},
            team_id=team_id,
            job_id=job_id,
            db_incremental_field_last_value=db_incremental_field_last_value,
            resume_hook=save_fanout_checkpoint,
            initial_paginator_state=resume.fanout_state if resume else None,
        )
        row_map = ROW_MAPS.get(endpoint)
        if row_map is not None:
            child = cast(Resource, child).add_map(row_map)
        return SourceResponse(
            name=endpoint,
            items=lambda: child,
            primary_keys=config.primary_keys,
            partition_count=1,
            partition_size=1,
            sort_mode="asc",
        )

    rest_config: RESTAPIConfig = {
        "client": client_config,
        "resource_defaults": {},
        "resources": [
            {
                "name": endpoint,
                "endpoint": {
                    "path": config.path,
                    "params": {"limit": PAGE_SIZE},
                    "data_selector": "data",
                },
            }
        ],
    }

    initial_paginator_state: Optional[dict[str, Any]] = None
    if resume is not None and resume.starting_after is not None:
        initial_paginator_state = {"cursor": resume.starting_after}

    def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
        # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields
        # the last page (merge dedupes on primary key) rather than skipping it.
        if state and state.get("cursor") is not None:
            resumable_source_manager.save_state(LatticeResumeConfig(starting_after=str(state["cursor"])))

    resource = rest_api_resource(
        rest_config,
        team_id,
        job_id,
        db_incremental_field_last_value,
        resume_hook=save_checkpoint,
        initial_paginator_state=initial_paginator_state,
    )

    return SourceResponse(
        name=endpoint,
        items=lambda: resource,
        primary_keys=config.primary_keys,
        partition_count=1,
        partition_size=1,
        sort_mode="asc",
    )