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.

13.8 KB
Raw Blame
import dataclasses
from collections.abc import Callable, Iterator
from typing import Any, Optional
from urllib.parse import quote, urlparse

import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter

from products.warehouse_sources.sources.sdk import SourceResponse, frozen, make_tracked_session

# Scroll pages cap at 1000 docs to stay well under the pipeline's buffering thresholds.
PAGE_SIZE = 1000
# Scroll contexts are kept alive between page fetches for this long.
SCROLL_KEEPALIVE = "5m"
REQUEST_TIMEOUT_SECONDS = 120
MAX_RETRY_ATTEMPTS = 5

# Stable prefix for the non-JSON response error. Shared so source.py can match it in
# get_non_retryable_errors without the two strings silently drifting apart.
NON_JSON_RESPONSE_ERROR = "Elasticsearch returned a non-JSON response"

# Elasticsearch numeric types whose _source JSON alternates between whole (40) and fractional
# (40.5) representations across documents. Left alone, that makes a column infer as int64 on one
# scroll page and double on the next, which PyArrow/Delta refuse to merge ("incompatible types:
# int64 vs double"). Coercing these fields to float up front pins the type deterministically.
# Integer types (long/integer/short/byte) are excluded on purpose: they're always whole in JSON,
# and widening a large `long` id to float64 would silently lose precision past 2^53.
_ES_FLOAT_TYPES = frozenset({"float", "double", "half_float", "scaled_float"})


# Setup-time copy, one message per failure the root-info probe can tell apart. Collapsing them
# into one blames the credentials for a cluster that was never reached, so someone re-enters a
# key that was correct all along.
CREDENTIALS_REJECTED_ERROR = (
    "Elasticsearch rejected your credentials. Check the username and password, or the API key, then try again."
)
FORBIDDEN_ERROR = (
    "Your Elasticsearch credentials can't read this cluster. Grant the user or API key read access "
    "to the indices you want to sync, then try again."
)
UNREACHABLE_ERROR = (
    "Couldn't reach your Elasticsearch cluster. Check the cluster URL and port, and that the "
    "cluster accepts connections from PostHog's IP addresses."
)
TLS_ERROR = (
    "Couldn't open a secure connection to your Elasticsearch cluster. Check that the URL starts "
    "with https and that the cluster's TLS certificate is valid."
)
CLUSTER_UNAVAILABLE_ERROR = (
    "Your Elasticsearch cluster didn't answer the connection check. Check the cluster's health, then try again."
)
UNEXPECTED_RESPONSE_ERROR = (
    "Elasticsearch didn't accept the connection check. Check that the cluster URL points at the "
    "Elasticsearch HTTP API, not Kibana or a proxy in front of it."
)


class ElasticsearchRetryableError(Exception):
    pass


@frozen
class ElasticsearchAuth:
    username: Optional[str] = None
    password: Optional[str] = dataclasses.field(default=None, repr=False)
    api_key: Optional[str] = dataclasses.field(default=None, repr=False)


def normalize_host(host: str) -> str:
    """Normalize the cluster URL and reject anything that isn't plain http(s)."""
    host = host.strip()
    if not host:
        raise ValueError("Elasticsearch host is required")
    if "://" not in host:
        host = f"https://{host}"
    host = host.rstrip("/")
    parsed = urlparse(host)
    if parsed.scheme not in ("http", "https") or not parsed.hostname:
        raise ValueError(f"Invalid Elasticsearch host: {host}")
    return host


def hostname_of(host: str) -> str:
    return urlparse(normalize_host(host)).hostname or ""


def _get_session(auth: ElasticsearchAuth) -> requests.Session:
    secrets = tuple(value for value in (auth.password, auth.api_key) if value)
    session = make_tracked_session(redact_values=secrets, allow_redirects=False)
    if auth.api_key:
        session.headers["Authorization"] = f"ApiKey {auth.api_key}"
    elif auth.username is not None:
        session.auth = (auth.username, auth.password or "")
    return session


def validate_credentials(host: str, auth: ElasticsearchAuth) -> tuple[bool, str | None]:
    """Confirm the cluster is reachable and the credentials are valid via the root info endpoint."""
    try:
        response = _get_session(auth).get(f"{normalize_host(host)}/", timeout=10)
    except requests.exceptions.SSLError:
        return False, TLS_ERROR
    except Exception:
        return False, UNREACHABLE_ERROR

    if response.status_code == 200:
        return True, None
    if response.status_code == 401:
        return False, CREDENTIALS_REJECTED_ERROR
    if response.status_code == 403:
        return False, FORBIDDEN_ERROR
    # A 429 or 5xx means the cluster is busy or unhealthy, not that the URL or the credentials
    # are wrong, so neither is worth re-checking.
    if response.status_code == 429 or response.status_code >= 500:
        return False, CLUSTER_UNAVAILABLE_ERROR
    return False, UNEXPECTED_RESPONSE_ERROR


def list_indices(host: str, auth: ElasticsearchAuth) -> list[str]:
    """List non-system indices (system indices start with a dot)."""
    session = _get_session(auth)
    response = session.get(
        f"{normalize_host(host)}/_cat/indices?format=json&h=index",
        timeout=REQUEST_TIMEOUT_SECONDS,
    )
    response.raise_for_status()
    try:
        body = response.json()
    except requests.exceptions.JSONDecodeError:
        # A 2xx body that isn't JSON usually means the URL points at something other than
        # the Elasticsearch HTTP API (e.g. a browser/Kibana URL or a reverse proxy).
        raise ValueError(
            f"{NON_JSON_RESPONSE_ERROR}. Check that the cluster URL points "
            "at the Elasticsearch HTTP API, not a browser or Kibana URL."
        ) from None
    indices = [row.get("index", "") for row in body if isinstance(row, dict)]
    return sorted(index for index in indices if index and not index.startswith("."))


def list_data_streams(host: str, auth: ElasticsearchAuth) -> list[str]:
    """List non-hidden, non-system data streams.

    Their backing indices are hidden and dot-prefixed, so `list_indices` never returns them.
    Best-effort: clusters before 7.9 have no data stream API, and credentials without
    `view_index_metadata` can't list streams, so both yield no streams instead of failing discovery.
    """
    response = _get_session(auth).get(f"{normalize_host(host)}/_data_stream", timeout=REQUEST_TIMEOUT_SECONDS)
    if not response.ok:
        return []
    try:
        body = response.json()
    except requests.exceptions.JSONDecodeError:
        return []

    streams = body.get("data_streams") if isinstance(body, dict) else None
    names = [
        stream.get("name") or ""
        for stream in streams or []
        if isinstance(stream, dict) and not stream.get("hidden") and not stream.get("system")
    ]
    return sorted(name for name in names if name and not name.startswith("."))


def is_data_stream(session: requests.Session, base_url: str, name: str) -> bool:
    # A plain index answers 404 here, and a cluster without the data stream API answers 400 or 404.
    response = session.get(f"{base_url}/_data_stream/{quote(name)}", timeout=REQUEST_TIMEOUT_SECONDS)
    if not response.ok:
        return False
    try:
        body = response.json()
    except requests.exceptions.JSONDecodeError:
        return False
    streams = body.get("data_streams") if isinstance(body, dict) else None
    return any(isinstance(stream, dict) and stream.get("name") == name for stream in streams or [])


def _collect_float_paths(properties: dict[str, Any], prefix: str, paths: set[str]) -> None:
    """Walk an Elasticsearch mapping's `properties` tree, recording dotted paths of float-typed fields."""
    for name, spec in properties.items():
        if not isinstance(spec, dict):
            continue
        path = f"{prefix}{name}"
        if spec.get("type") in _ES_FLOAT_TYPES:
            paths.add(path)
        sub_properties = spec.get("properties")
        if isinstance(sub_properties, dict):
            _collect_float_paths(sub_properties, f"{path}.", paths)


def get_float_field_paths(session: requests.Session, base_url: str, index: str) -> set[str]:
    """Dotted paths of fields the index mapping types as floating point.

    Best-effort: a mapping we can't read (permissions, non-JSON body) yields no paths, so the sync
    behaves as before rather than failing on the mapping lookup alone.
    """
    try:
        response = session.get(f"{base_url}/{quote(index)}/_mapping", timeout=REQUEST_TIMEOUT_SECONDS)
        response.raise_for_status()
        body = response.json()
    except (requests.exceptions.RequestException, requests.exceptions.JSONDecodeError, ValueError):
        return set()

    paths: set[str] = set()
    # Shape: {"<index>": {"mappings": {"properties": {...}}}}. An alias resolves to several indices,
    # so union every block's float paths.
    if isinstance(body, dict):
        for index_block in body.values():
            properties = ((index_block or {}).get("mappings") or {}).get("properties")
            if isinstance(properties, dict):
                _collect_float_paths(properties, "", paths)
    return paths


def _to_float(value: Any) -> Any:
    # bool is an int subclass but never a numeric field value here — leave it untouched.
    if isinstance(value, bool):
        return value
    if isinstance(value, int):
        return float(value)
    if isinstance(value, list):
        return [_to_float(item) for item in value]
    return value


def _coerce_path(obj: Any, parts: list[str]) -> None:
    key = parts[0]
    if isinstance(obj, list):
        for item in obj:
            _coerce_path(item, parts)
        return
    if not isinstance(obj, dict) or key not in obj:
        return
    if len(parts) == 1:
        obj[key] = _to_float(obj[key])
    else:
        _coerce_path(obj[key], parts[1:])


def coerce_float_fields(doc: dict[str, Any], float_paths: set[str]) -> None:
    """Rewrite whole-number values under float-typed fields to float, in place."""
    for path in float_paths:
        _coerce_path(doc, path.split("."))


def _build_post_fn(
    session: requests.Session, logger: FilteringBoundLogger
) -> Callable[[str, dict[str, Any]], dict[str, Any]]:
    @retry(
        retry=retry_if_exception_type((ElasticsearchRetryableError, requests.ReadTimeout, requests.ConnectionError)),
        stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
        wait=wait_exponential_jitter(initial=1, max=60),
        reraise=True,
    )
    def post(url: str, body: dict[str, Any]) -> dict[str, Any]:
        response = session.post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS)

        if response.status_code == 429 or response.status_code >= 500:
            raise ElasticsearchRetryableError(
                f"Elasticsearch error (retryable): status={response.status_code}, url={url}"
            )

        if not response.ok:
            logger.error(f"Elasticsearch error: status={response.status_code}, body={response.text}, url={url}")
            response.raise_for_status()

        return response.json()

    return post


def _page_items(
    data: dict[str, Any], float_paths: set[str], include_index: bool = False
) -> tuple[list, list[dict[str, Any]]]:
    """Split a scroll response into its raw hits and the coerced `_source` rows."""
    hits = ((data.get("hits") or {}).get("hits")) or []
    items = [{**(hit.get("_source") or {}), "_id": hit["_id"]} for hit in hits]
    if include_index:
        for item, hit in zip(items, hits):
            item["_index"] = hit.get("_index")
    if float_paths:
        for item in items:
            coerce_float_fields(item, float_paths)
    return hits, items


def _clear_scroll(session: requests.Session, base_url: str, scroll_id: str) -> None:
    # Best-effort: free the server-side scroll context early.
    try:
        session.delete(f"{base_url}/_search/scroll", json={"scroll_id": [scroll_id]}, timeout=10)
    except Exception:
        pass


def get_rows(
    host: str,
    auth: ElasticsearchAuth,
    index: str,
    logger: FilteringBoundLogger,
    include_index: bool = False,
) -> Iterator[list[dict[str, Any]]]:
    session = _get_session(auth)
    base_url = normalize_host(host)
    float_paths = get_float_field_paths(session, base_url, index)
    post = _build_post_fn(session, logger)

    # The scroll API gives a stable snapshot of the index for the duration of
    # the walk; scroll ids expire after SCROLL_KEEPALIVE of inactivity, so the
    # walk restarts from scratch on retry rather than persisting state.
    data = post(
        f"{base_url}/{quote(index)}/_search?scroll={SCROLL_KEEPALIVE}",
        {"size": PAGE_SIZE, "sort": ["_doc"], "query": {"match_all": {}}},
    )
    scroll_id: Optional[str] = data.get("_scroll_id")

    try:
        while True:
            hits, items = _page_items(data, float_paths, include_index)

            if items:
                yield items

            if len(hits) < PAGE_SIZE or not scroll_id:
                break

            data = post(f"{base_url}/_search/scroll", {"scroll": SCROLL_KEEPALIVE, "scroll_id": scroll_id})
            scroll_id = data.get("_scroll_id", scroll_id)
    finally:
        if scroll_id:
            _clear_scroll(session, base_url, scroll_id)


def elasticsearch_source(
    host: str,
    auth: ElasticsearchAuth,
    index: str,
    logger: FilteringBoundLogger,
) -> SourceResponse:
    # A data stream only keeps `_id` unique within one backing index, so its rows carry the
    # backing index and key on both.
    data_stream = is_data_stream(_get_session(auth), normalize_host(host), index)
    return SourceResponse(
        name=index,
        items=lambda: get_rows(
            host=host,
            auth=auth,
            index=index,
            logger=logger,
            include_index=data_stream,
        ),
        primary_keys=["_index", "_id"] if data_stream else ["_id"],
        partition_count=1,
        partition_size=1,
        sort_mode="asc",
    )