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.

5.7 KB
Raw Blame
from datetime import datetime
from typing import Any, cast

from requests import HTTPError, Response, Session

from products.warehouse_sources.sources.fieldpulse.settings import (
    AUTH_ERROR,
    BASE_URL,
    ENDPOINTS,
    ENDPOINTS_WITHOUT_DOCUMENTED_PAGING,
    PAGE_SIZE,
    PRIMARY_KEYS,
)
from products.warehouse_sources.sources.sdk import (
    APIKeyAuth,
    ClientConfig,
    Endpoint,
    EndpointResource,
    PageNumberPaginator,
    PaginatorConfig,
    RESTAPIConfig,
    RESTClient,
    ResumableSourceManager,
    SinglePagePaginator,
    SourceResponse,
    frozen,
    make_tracked_session,
    rest_api_resource,
    schema_for_resource,
)


@frozen
class FieldpulseResumeConfig:
    page: int
    lower_bound: str | None


REQUEST_TIMEOUT = (10.0, 60.0)


def _normalize_rate_limit_header(response: Response, *args: object, **kwargs: object) -> Response:
    if response.status_code == 429 and "RateLimit-Reset" in response.headers:
        # The shared client parses epoch resets under the X-RateLimit-Reset header.
        response.headers["X-RateLimit-Reset"] = response.headers["RateLimit-Reset"]
    return response


class RepeatedPagePaginator(PageNumberPaginator):
    """Stops when the API returns the same page again.

    An endpoint that ignores `page` returns its first page for each request, so the usual
    stop on an empty page never occurs.
    """

    def __init__(self) -> None:
        super().__init__(base_page=1, total_path=None)
        self._previous_page: list[Any] | None = None

    def update_state(self, response: Response, data: list[Any] | None = None) -> None:
        if data and data == self._previous_page:
            # The client yields this list after this call, so emptying it drops the duplicate rows.
            data.clear()
        else:
            self._previous_page = list(data) if data else None
        super().update_state(response, data)


def _session(api_key: str) -> Session:
    session = make_tracked_session(redact_values=(api_key,))
    session.hooks["response"].append(_normalize_rate_limit_header)
    return session


def validate_credentials(api_key: str) -> tuple[bool, str | None]:
    client = RESTClient(
        base_url=BASE_URL,
        auth=APIKeyAuth(name="x-api-key", api_key=api_key, location="header"),
        paginator=SinglePagePaginator(),
        allow_redirects=False,
        session=_session(api_key),
        request_timeout=REQUEST_TIMEOUT,
    )
    try:
        next(client.paginate("customers", params={"limit": 1}, data_selector="response", data_selector_required=True))
    except HTTPError as error:
        if error.response is not None and error.response.status_code in (401, 403, 422):
            return False, AUTH_ERROR
        raise
    return True, None


def fieldpulse_source(
    api_key: str,
    endpoint: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[FieldpulseResumeConfig],
    should_use_incremental_field: bool,
    db_incremental_field_last_value: str | datetime | None,
) -> SourceResponse:
    path = schema_for_resource(ENDPOINTS, endpoint)
    watermark = db_incremental_field_last_value if should_use_incremental_field else None
    lower_bound = watermark.isoformat() if isinstance(watermark, datetime) else watermark
    initial_state = None
    if resumable_source_manager.can_resume():
        saved = resumable_source_manager.load_state()
        if saved is not None:
            initial_state = {"page": saved.page}
            # Page offsets must use the original filter, even when the pipeline has advanced its watermark.
            lower_bound = saved.lower_bound if should_use_incremental_field else None

    params: dict[str, Any] = {
        "limit": PAGE_SIZE,
        "sort[0][attribute]": "updated_at" if should_use_incremental_field else "id",
        "sort[0][order]": "asc",
    }
    if should_use_incremental_field:
        params.update({"sort[1][attribute]": "id", "sort[1][order]": "asc"})
    if lower_bound is not None:
        params.update(
            {
                "filter[0][attribute]": "updated_at",
                "filter[0][operator]": ">=",
                "filter[0][class]": "date",
                "filter[0][value]": lower_bound,
            }
        )

    def save_checkpoint(state: dict[str, Any] | None) -> None:
        if state is not None:
            resumable_source_manager.save_state(
                FieldpulseResumeConfig(page=int(state["page"]), lower_bound=lower_bound)
            )
        resumable_source_manager.safe_point()

    paginator: PaginatorConfig = (
        RepeatedPagePaginator()
        if endpoint in ENDPOINTS_WITHOUT_DOCUMENTED_PAGING
        else cast(PaginatorConfig, {"type": "page_number", "base_page": 1, "total_path": None})
    )
    client_config: ClientConfig = {
        "base_url": BASE_URL,
        "auth": {"type": "api_key", "name": "x-api-key", "api_key": api_key, "location": "header"},
        "paginator": paginator,
        "allow_redirects": False,
        "session": _session(api_key),
        "request_timeout": REQUEST_TIMEOUT,
    }
    endpoint_config: Endpoint = {
        "path": path,
        "params": params,
        "data_selector": "response",
        "data_selector_required": True,
    }
    resource_config: EndpointResource = {"name": endpoint, "endpoint": endpoint_config}
    config: RESTAPIConfig = {"client": client_config, "resources": [resource_config]}
    resource = rest_api_resource(
        config,
        team_id,
        job_id,
        None,
        resume_hook=save_checkpoint,
        initial_paginator_state=initial_state,
    )
    return SourceResponse(
        name=endpoint,
        items=lambda: resource,
        primary_keys=PRIMARY_KEYS,
        sort_mode="asc" if should_use_incremental_field else None,
    )