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.5 KB
Raw Blame
import dataclasses
from typing import Any, Optional
from urllib.parse import urlparse

from requests import Response

from products.warehouse_sources.sources.launchdarkly.settings import LAUNCHDARKLY_ENDPOINTS, LaunchDarklyEndpointConfig
from products.warehouse_sources.sources.sdk import (
    BaseNextUrlPaginator,
    ClientConfig,
    EndpointResource,
    Resource,
    RESTAPIConfig,
    ResumableSourceManager,
    SourceResponse,
    make_tracked_session,
    rename_parent_fields,
    rest_api_resource,
    rest_api_resources,
    validate_via_probe,
)

API_HOST = "https://app.launchdarkly.com"
BASE_URL = f"{API_HOST}/api/v2"

# Parent resource name for fan-out endpoints. Named singular so include_from_parent injects the
# project key under `_project_key` (make_parent_key_name(name, "key") == f"_{name}_key"), matching
# the column the hand-rolled source emitted.
PROJECTS_PARENT_NAME = "project"
# Parent resource name for environment-scoped endpoints, injecting the environment key as `_environment_key`.
ENVIRONMENTS_PARENT_NAME = "environment"
# Parent resource name for team-scoped endpoints, injecting the team key as `_team_key`.
TEAMS_PARENT_NAME = "team"


@dataclasses.dataclass(frozen=False)
class LaunchDarklyResumeConfig:
    # Full URL of the next page to fetch for a top-level endpoint ("" once exhausted).
    next_url: str = ""
    # Retained for backwards compatibility with resume state saved by the previous
    # implementation; unused by the current code.
    project_key: str = ""
    # Framework fan-out resume state ({"completed": [...], "current": ..., "child_state": ...}).
    fanout_state: Optional[dict[str, Any]] = None


def _get_headers(access_token: str) -> dict[str, str]:
    # LaunchDarkly expects the raw access token in the Authorization header, with no
    # "Bearer" prefix (see https://apidocs.launchdarkly.com/#section/Overview/Authentication).
    return {
        "Authorization": access_token,
        "Accept": "application/json",
    }


def _resolve_url(href: str) -> str:
    # LaunchDarkly returns relative hrefs (e.g. "/api/v2/projects?limit=20&offset=20").
    if href.startswith("http"):
        return href
    return f"{API_HOST}{href}"


class LaunchDarklyLinkPaginator(BaseNextUrlPaginator):
    """Follows LaunchDarkly's ``_links.next.href`` pagination.

    The href is usually a relative path, so it's resolved against the API host before the next
    request is sent. Resume (``get_resume_state``/``set_resume_state`` on the next URL) is inherited
    from ``BaseNextUrlPaginator``.
    """

    def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
        try:
            body = response.json()
        except Exception:
            body = {}
        links = (body.get("_links") if isinstance(body, dict) else None) or {}
        next_link = links.get("next") or {}
        href = next_link.get("href")
        if href:
            self._next_url = _resolve_url(href)
            self._has_next_page = True
        else:
            self._has_next_page = False

    def __str__(self) -> str:
        return "LaunchDarklyLinkPaginator()"


def _endpoint_params(config: LaunchDarklyEndpointConfig) -> dict[str, Any]:
    params: dict[str, Any] = dict(config.extra_params)
    if config.page_size is not None:
        params["limit"] = config.page_size
    return params


def _with_flag_key(row: dict[str, Any]) -> dict[str, Any]:
    # A flag status row names its flag only in its links: /api/v2/flag-statuses/{project}/{environment}/{flag}.
    links = row.get("_links") or {}
    href = (links.get("self") or {}).get("href") or (links.get("parent") or {}).get("href") or ""
    row["_flag_key"] = urlparse(href).path.rstrip("/").rsplit("/", 1)[-1] or None
    return row


def _code_ref_statistic_rows(body: dict[str, Any]) -> list[dict[str, Any]]:
    # The statistics body maps each flag key to one statistic per repository that references the flag.
    flags = body.get("flags") or {}
    return [
        {**statistic, "_flag_key": flag_key, "_project_key": body.get("_project_key")}
        for flag_key, statistics in flags.items()
        for statistic in statistics or []
    ]


def _client_config(access_token: str, beta: bool = False) -> ClientConfig:
    # Only non-secret headers go here; the access token rides on the framework auth so it's
    # scrubbed from any raised error message.
    headers = {"Accept": "application/json"}
    if beta:
        headers["LD-API-Version"] = "beta"
    return {
        "base_url": BASE_URL,
        "headers": headers,
        "auth": {"type": "api_key", "api_key": access_token, "name": "Authorization", "location": "header"},
    }


def _build_toplevel_resource(
    config: LaunchDarklyEndpointConfig,
    access_token: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],
    resume: Optional[LaunchDarklyResumeConfig],
) -> Resource:
    rest_config: RESTAPIConfig = {
        "client": _client_config(access_token, beta=config.beta),
        "resources": [
            {
                "name": config.name,
                "endpoint": {
                    "path": config.path,
                    "params": _endpoint_params(config),
                    "data_selector": config.data_selector,
                    "paginator": LaunchDarklyLinkPaginator(),
                },
            }
        ],
    }

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

    def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
        # Save AFTER a page is yielded (only while a next page remains) so a crash re-fetches the
        # next page rather than re-emitting the one just yielded (merge dedupes regardless).
        if state and state.get("next_url"):
            resumable_source_manager.save_state(LaunchDarklyResumeConfig(next_url=state["next_url"]))

    return rest_api_resource(
        rest_config,
        team_id,
        job_id,
        None,
        resume_hook=save_checkpoint,
        initial_paginator_state=initial_paginator_state,
    )


def _fanout_config(config: LaunchDarklyEndpointConfig, access_token: str, team_id: int, job_id: str) -> RESTAPIConfig:
    if config.requires_team:
        parent_name, parent_endpoint, path_param = TEAMS_PARENT_NAME, LAUNCHDARKLY_ENDPOINTS["teams"], "team_key"
    else:
        parent_name, parent_endpoint, path_param = (
            PROJECTS_PARENT_NAME,
            LAUNCHDARKLY_ENDPOINTS["projects"],
            "project_key",
        )

    parent: EndpointResource = {
        "name": parent_name,
        "endpoint": {
            "path": parent_endpoint.path,
            "params": {"limit": parent_endpoint.page_size},
            "data_selector": "items",
            "paginator": LaunchDarklyLinkPaginator(),
        },
    }
    if config.beta:
        # One client serves both resources, so the GA parent is listed by its own client to keep the
        # beta header off its requests.
        parent_rows = rest_api_resource(
            {"client": _client_config(access_token), "resources": [parent]}, team_id, job_id, None
        )
        parent = {
            "name": parent_name,
            # The iterator supplies the rows; the path is never requested.
            "endpoint": {"path": parent_endpoint.path},
            "data_iterator": lambda: iter(parent_rows),
        }

    return {
        "client": _client_config(access_token, beta=config.beta),
        "resources": [
            parent,
            {
                "name": config.name,
                "endpoint": {
                    "path": config.path,
                    "params": {
                        path_param: {"type": "resolve", "resource": parent_name, "field": "key"},
                        **_endpoint_params(config),
                    },
                    "data_selector": config.data_selector,
                    "paginator": LaunchDarklyLinkPaginator(),
                },
                # Injects the parent's key into every child row as `_project_key` or `_team_key`.
                "include_from_parent": ["key"],
            },
        ],
    }


def _build_fanout_resource(
    config: LaunchDarklyEndpointConfig,
    access_token: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],
    resume: Optional[LaunchDarklyResumeConfig],
) -> Resource:
    initial_paginator_state: Optional[dict[str, Any]] = None
    if resume is not None and resume.fanout_state:
        initial_paginator_state = resume.fanout_state

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

    resources = rest_api_resources(
        _fanout_config(config, access_token, team_id, job_id),
        team_id,
        job_id,
        None,
        resume_hook=save_checkpoint,
        initial_paginator_state=initial_paginator_state,
    )
    resource = next(resource for resource in resources if resource.name == config.name)
    if config.name == "code_ref_statistics":
        resource.add_map(_code_ref_statistic_rows)
    return resource


def _build_environment_fanout_resource(
    config: LaunchDarklyEndpointConfig,
    access_token: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],
    resume: Optional[LaunchDarklyResumeConfig],
) -> Resource:
    # The framework resumes only one dependent level, so the project -> environment walk feeds the
    # child as a plain iterator and the per-environment child progress is what gets checkpointed.
    environments_config = LAUNCHDARKLY_ENDPOINTS["environments"]
    environments = next(
        resource
        for resource in rest_api_resources(
            _fanout_config(environments_config, access_token, team_id, job_id), team_id, job_id, None
        )
        if resource.name == environments_config.name
    )

    rest_config: RESTAPIConfig = {
        "client": _client_config(access_token),
        "resources": [
            {
                "name": ENVIRONMENTS_PARENT_NAME,
                # The iterator supplies the rows; the path is never requested.
                "endpoint": {"path": "/projects"},
                "data_iterator": lambda: iter(environments),
            },
            {
                "name": config.name,
                "endpoint": {
                    "path": config.path,
                    "params": {
                        "project_key": {
                            "type": "resolve",
                            "resource": ENVIRONMENTS_PARENT_NAME,
                            "field": "_project_key",
                        },
                        "environment_key": {"type": "resolve", "resource": ENVIRONMENTS_PARENT_NAME, "field": "key"},
                        **_endpoint_params(config),
                    },
                    "data_selector": "items",
                    "paginator": LaunchDarklyLinkPaginator(),
                },
                "include_from_parent": ["key", "_project_key"],
            },
        ],
    }

    initial_paginator_state: Optional[dict[str, Any]] = None
    if resume is not None and resume.fanout_state:
        initial_paginator_state = resume.fanout_state

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

    resources = rest_api_resources(
        rest_config,
        team_id,
        job_id,
        None,
        resume_hook=save_checkpoint,
        initial_paginator_state=initial_paginator_state,
    )
    resource = next(resource for resource in resources if resource.name == config.name)
    resource.add_map(rename_parent_fields(ENVIRONMENTS_PARENT_NAME, {"_project_key": "_project_key"}))
    if config.name == "flag_statuses":
        resource.add_map(_with_flag_key)
    return resource


def launchdarkly_source(
    access_token: str,
    endpoint: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],
) -> SourceResponse:
    config = LAUNCHDARKLY_ENDPOINTS[endpoint]

    resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None

    if config.requires_environment:
        resource = _build_environment_fanout_resource(
            config, access_token, team_id, job_id, resumable_source_manager, resume
        )
    elif config.requires_project or config.requires_team:
        resource = _build_fanout_resource(config, access_token, team_id, job_id, resumable_source_manager, resume)
    else:
        resource = _build_toplevel_resource(config, access_token, team_id, job_id, resumable_source_manager, resume)

    return SourceResponse(
        name=endpoint,
        items=lambda: resource,
        primary_keys=config.primary_key,
        # LaunchDarkly timestamps are epoch-millisecond integers and the datetime
        # partitioner expects epoch-seconds, so partitioning is intentionally left off to
        # avoid mis-bucketing rows far into the future.
        partition_mode=None,
        partition_keys=None,
    )


def validate_credentials(access_token: str, path: str = "/caller-identity") -> int | None:
    """Probe an endpoint and return the HTTP status code (or None on transport failure)."""
    _ok, status = validate_via_probe(
        lambda: make_tracked_session(redact_values=(access_token,)),
        f"{BASE_URL}{path}",
        headers=_get_headers(access_token),
    )
    return status