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.

11.8 KB
Raw Blame
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from typing import Any, Optional, cast

from requests import Request, Response
from requests.exceptions import RequestException

from products.warehouse_sources.sources.fillout.settings import (
    ALLOWED_FILLOUT_API_BASE_URLS,
    DEFAULT_FILLOUT_API_BASE_URL,
    FILLOUT_ENDPOINTS,
    FilloutEndpointConfig,
)
from products.warehouse_sources.sources.sdk import (
    ClientConfig,
    Endpoint,
    EndpointResource,
    IncrementalConfig,
    OffsetPaginator,
    RESTAPIConfig,
    SinglePagePaginator,
    SourceResponse,
    build_dependent_resource,
    coerce_datetime_to_utc,
    make_tracked_session,
    rest_api_resource,
)


def _normalize_api_base_url(api_base_url: str | None) -> str:
    return (api_base_url or DEFAULT_FILLOUT_API_BASE_URL).rstrip("/")


def _validated_api_base_url(api_base_url: str | None) -> str:
    normalized_url = _normalize_api_base_url(api_base_url)
    if normalized_url not in ALLOWED_FILLOUT_API_BASE_URLS:
        raise ValueError(
            "API base URL must be one of https://api.fillout.com/v1/api or https://eu-api.fillout.com/v1/api."
        )
    return normalized_url


def _format_fillout_datetime(value: Any) -> str:
    """Format the incremental watermark for Fillout's `afterDate` filter.

    Truncates to whole milliseconds, matching the precision Fillout itself reports
    `submissionTime` at. Truncating rounds the lower bound *down* — so a sync
    re-fetches at most a few boundary rows (the merge dedupes them) rather than
    skipping any.
    """
    normalized_value = coerce_datetime_to_utc(value)
    if normalized_value is None:
        return str(value)
    return f"{normalized_value.strftime('%Y-%m-%dT%H:%M:%S')}.{normalized_value.microsecond // 1000:03d}Z"


def _fillout_incremental_window(cursor_path: str) -> IncrementalConfig:
    # `afterDate` is a genuine server-side filter on submission time, and Fillout reports the
    # filtered count in `totalResponses`, so the offset walk terminates at the watermark.
    return {
        "cursor_path": cursor_path,
        "start_param": "afterDate",
        "convert": _format_fillout_datetime,
    }


def _no_incremental_window(cursor_path: str) -> IncrementalConfig | None:
    # Fillout has no `afterDate` value meaning "since the beginning of time", and the endpoint
    # returns every submission when the param is absent. So a sync with no watermark yet sends
    # no `afterDate` at all rather than a sentinel date the API can reject.
    return None


def _incremental_window_factory(
    db_incremental_field_last_value: Optional[Any],
) -> Callable[[str], IncrementalConfig | None]:
    if db_incremental_field_last_value is None:
        return _no_incremental_window
    return _fillout_incremental_window


def _auth_headers(api_key: str) -> dict[str, str]:
    return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}


def _rest_api_client_config(base_api_url: str, api_key: str) -> ClientConfig:
    return {
        "base_url": base_api_url,
        "auth": {"type": "bearer", "token": api_key},
        "headers": {"Accept": "application/json"},
    }


class FilloutSubmissionsPaginator(OffsetPaginator):
    """Limit/offset paginator for `/forms/{formId}/submissions`.

    Pins `sort=asc`, oldest-first within one form. No `status`
    param: `finished` is already Fillout's default, so sending it only added a way for the
    request to be rejected. `totalResponses` reflects the `afterDate`-filtered count, so the
    walk stops at the watermark on incremental syncs rather than re-reading each form's full
    history.
    """

    def __init__(self, limit: int) -> None:
        super().__init__(
            limit=limit,
            total_path="totalResponses",
            offset_param="offset",
            limit_param="limit",
        )

    def init_request(self, request: Request) -> None:
        super().init_request(request)
        request.params.setdefault("sort", "asc")


@dataclass(frozen=True)
class _PerFormProbe:
    """A follow-up request against one form, confirming the key reaches a per-form endpoint."""

    path_suffix: str
    params: dict[str, Any]
    label: str


# Fillout answers the per-form probe with a 400 or 404 when it can't load that one form, which
# says nothing about the key. Later forms stand in for it, up to a cap that keeps validation
# quick on accounts with many forms.
_FORM_SPECIFIC_PROBE_STATUSES = (400, 404)
_MAX_FORMS_TO_PROBE = 5

_PER_FORM_PROBES: dict[str, _PerFormProbe] = {
    "submissions": _PerFormProbe(path_suffix="/submissions", params={"limit": 1}, label="submissions"),
    "form_metadata": _PerFormProbe(path_suffix="", params={}, label="form metadata"),
}


def validate_credentials(
    api_key: str, api_base_url: str | None = None, schema_name: str | None = None
) -> tuple[bool, str | None]:
    try:
        base_url = _validated_api_base_url(api_base_url)
    except ValueError as exc:
        return False, str(exc)

    headers = _auth_headers(api_key)
    errors: list[str] = []

    # `/forms` is the only endpoint the `forms` schema reads, so it needs no follow-up. At
    # source-create time (no schema yet) the submissions probe stands in for every per-form
    # endpoint — Fillout issues one key with no per-endpoint scopes.
    probe = _PER_FORM_PROBES.get(schema_name or "submissions")

    def _parse_error_description(response: Response) -> str:
        try:
            payload = response.json()
            if isinstance(payload, dict):
                for key in ("message", "error", "description"):
                    value = payload.get(key)
                    if isinstance(value, str) and value:
                        return value
        except Exception:
            pass
        return response.text

    forms_response: Response | None = None
    try:
        forms_response = make_tracked_session().get(f"{base_url}/forms", headers=headers, timeout=10)
        if forms_response.status_code == 401:
            errors.append("Invalid Fillout API key")
        elif forms_response.status_code == 403:
            errors.append("Fillout API key is missing permission to list forms")
        elif forms_response.status_code != 200:
            errors.append(f"/forms endpoint failed: {_parse_error_description(forms_response)}")
    except RequestException as exc:
        errors.append(f"/forms request failed: {exc}")

    if probe and forms_response and forms_response.status_code == 200:
        forms_items = forms_response.json()

        # With no forms there's nothing to probe against; that shouldn't block validation.
        if isinstance(forms_items, list) and forms_items:
            for form in forms_items[:_MAX_FORMS_TO_PROBE]:
                form_id = form.get("formId") if isinstance(form, dict) else None
                if not isinstance(form_id, str) or not form_id:
                    errors.append(f"Fillout returned an invalid form id while validating {probe.label} access.")
                    break
                try:
                    probe_response = make_tracked_session().get(
                        f"{base_url}/forms/{form_id}{probe.path_suffix}",
                        headers=headers,
                        params=probe.params,
                        timeout=10,
                    )
                except RequestException as exc:
                    errors.append(f"Fillout {probe.label} request failed: {exc}")
                    break
                if probe_response.status_code in _FORM_SPECIFIC_PROBE_STATUSES:
                    continue
                if probe_response.status_code == 401:
                    errors.append("Invalid Fillout API key")
                elif probe_response.status_code == 403:
                    errors.append(f"Fillout API key is missing permission to read {probe.label}")
                elif probe_response.status_code != 200:
                    errors.append(f"Fillout {probe.label} endpoint failed: {_parse_error_description(probe_response)}")
                break

    if errors:
        return False, "; ".join(errors)
    return True, None


def get_resource(endpoint: str) -> EndpointResource:
    config = FILLOUT_ENDPOINTS[endpoint]
    if config.fanout:
        raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")

    endpoint_config: Endpoint = {
        "path": config.path,
        "params": {},
        "data_selector": config.data_selector,
        "paginator": SinglePagePaginator(),
    }

    return {
        "name": config.name,
        "table_name": config.name,
        "write_disposition": "replace",
        "endpoint": endpoint_config,
        "table_format": "delta",
    }


def _child_endpoint_extra(endpoint_config: FilloutEndpointConfig) -> Endpoint:
    if endpoint_config.paginated:
        return {
            "paginator": FilloutSubmissionsPaginator(limit=endpoint_config.page_size),
            "data_selector": endpoint_config.data_selector,
        }
    # `/forms/{formId}` returns the form's whole metadata object in one response, so there is
    # nothing to page through and the object itself is the single row.
    return {
        "paginator": SinglePagePaginator(),
        "data_selector": endpoint_config.data_selector,
    }


def _make_source_response(endpoint_config: FilloutEndpointConfig, items_fn) -> SourceResponse:
    return SourceResponse(
        name=endpoint_config.name,
        items=items_fn,
        primary_keys=endpoint_config.primary_key
        if isinstance(endpoint_config.primary_key, list)
        else [endpoint_config.primary_key],
        sort_mode=endpoint_config.sort_mode,
        partition_count=1,
        partition_size=1,
        partition_mode="datetime" if endpoint_config.partition_key else None,
        partition_format="week" if endpoint_config.partition_key else None,
        partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
    )


def fillout_source(
    api_key: str,
    api_base_url: str | None,
    endpoint: str,
    team_id: int,
    job_id: str,
    should_use_incremental_field: bool = False,
    db_incremental_field_last_value: Optional[Any] = None,
    incremental_field: str | None = None,
) -> SourceResponse:
    endpoint_config = FILLOUT_ENDPOINTS[endpoint]
    base_api_url = _validated_api_base_url(api_base_url)

    if endpoint_config.fanout:
        parent_config = FILLOUT_ENDPOINTS[endpoint_config.fanout.parent_name]
        dependent_resource = cast(
            Iterable[Any],
            build_dependent_resource(
                endpoint_configs=FILLOUT_ENDPOINTS,
                child_endpoint=endpoint,
                fanout=endpoint_config.fanout,
                client_config=_rest_api_client_config(base_api_url, api_key),
                path_format_values={},
                team_id=team_id,
                job_id=job_id,
                db_incremental_field_last_value=db_incremental_field_last_value,
                should_use_incremental_field=should_use_incremental_field,
                incremental_field=incremental_field,
                incremental_config_factory=_incremental_window_factory(db_incremental_field_last_value),
                page_size_param="limit" if endpoint_config.paginated else None,
                parent_endpoint_extra={
                    "paginator": SinglePagePaginator(),
                    "data_selector": parent_config.data_selector,
                },
                child_endpoint_extra=_child_endpoint_extra(endpoint_config),
            ),
        )
        return _make_source_response(endpoint_config, lambda: dependent_resource)

    config: RESTAPIConfig = {
        "client": _rest_api_client_config(base_api_url, api_key),
        "resource_defaults": {"write_disposition": "replace"},
        "resources": [get_resource(endpoint=endpoint)],
    }

    resource = rest_api_resource(config, team_id, job_id, db_incremental_field_last_value)
    return _make_source_response(endpoint_config, lambda: resource)