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.3 KB
Raw Blame
import dataclasses
from typing import Any, Optional

from requests import Request, Response

from products.warehouse_sources.sources.codemagic.settings import (
    BASE_URL,
    CODEMAGIC_V1,
    CODEMAGIC_V3,
    ENDPOINTS,
    V3_BASE_URL,
    V3_ENDPOINTS,
    V3_PAGE_SIZE,
    V3_TEAMS_PATH,
)
from products.warehouse_sources.sources.sdk import (
    BasePaginator,
    ClientConfig,
    EndpointResource,
    JSONResponseCursorPaginator,
    PageNumberPaginator,
    RESTAPIConfig,
    ResumableSourceManager,
    SinglePagePaginator,
    SourceResponse,
    make_tracked_session,
    rest_api_resource,
    rest_api_resources,
)


@dataclasses.dataclass(frozen=True)
class CodemagicResumeConfig:
    # v1 Builds: offset of the next page.
    skip: Optional[int] = None
    # v3 Builds fan out per team: team build paths already synced, the one in progress, and its
    # cursor paginator state.
    completed: Optional[list[str]] = None
    current: Optional[str] = None
    child_state: Optional[dict[str, Any]] = None


class CodemagicBuildsPaginator(BasePaginator):
    """Skip-offset pagination for GET /builds.

    Codemagic doesn't document a page-size query param for this endpoint — only `skip` — so
    unlike `OffsetPaginator` we can't compare the page length against a declared limit to detect
    the last page (the vendor's actual fixed batch size isn't documented and could change without
    notice). Instead `skip` advances by however many rows the page actually returned, and
    pagination stops once a page comes back empty.
    """

    def __init__(self, skip: int = 0) -> None:
        super().__init__()
        self._skip = skip

    def init_request(self, request: Request) -> None:
        if request.params is None:
            request.params = {}
        request.params["skip"] = self._skip

    def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
        if not data:
            self._has_next_page = False
            return
        self._skip += len(data)
        self._has_next_page = True

    def update_request(self, request: Request) -> None:
        if request.params is None:
            request.params = {}
        request.params["skip"] = self._skip

    def get_resume_state(self) -> Optional[dict[str, Any]]:
        return {"skip": self._skip} if self._has_next_page else None

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


def get_resource(endpoint: str) -> EndpointResource:
    config = ENDPOINTS[endpoint]
    return {
        "name": config.name,
        "table_name": config.name.lower(),
        "write_disposition": "replace",
        "endpoint": {
            "data_selector": config.data_selector,
            "path": config.path,
        },
        "table_format": "delta",
    }


def codemagic_source(
    api_token: str,
    endpoint: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[CodemagicResumeConfig],
    api_version: str,
) -> SourceResponse:
    if api_version == CODEMAGIC_V1:
        return _v1_source(api_token, endpoint, team_id, job_id, resumable_source_manager)
    if api_version == CODEMAGIC_V3:
        return _v3_source(api_token, endpoint, team_id, job_id, resumable_source_manager)
    raise ValueError(f"Unsupported Codemagic API version: {api_version}")


def _v1_source(
    api_token: str,
    endpoint: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[CodemagicResumeConfig],
) -> SourceResponse:
    endpoint_config = ENDPOINTS[endpoint]
    is_builds = endpoint == "Builds"
    paginator: BasePaginator = CodemagicBuildsPaginator() if is_builds else SinglePagePaginator()

    rest_config: RESTAPIConfig = {
        "client": {
            "base_url": BASE_URL,
            "auth": {
                "type": "api_key",
                "api_key": api_token,
                "name": "x-auth-token",
                "location": "header",
            },
            "paginator": paginator,
            # The token rides in a custom header that `requests` preserves across cross-origin
            # redirects, so following a 3xx could replay it off-host. Pin to the base host.
            "allow_redirects": False,
        },
        "resource_defaults": {
            "write_disposition": "replace",
        },
        "resources": [get_resource(endpoint)],
    }

    initial_paginator_state: Optional[dict[str, Any]] = None
    if is_builds and resumable_source_manager.can_resume():
        resume_config = resumable_source_manager.load_state()
        if resume_config is not None and resume_config.skip is not None:
            initial_paginator_state = {"skip": resume_config.skip}

    def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
        # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on
        # completion. Saving happens after each page is yielded, so a crash re-fetches the last
        # page rather than skipping it.
        if state and state.get("skip") is not None:
            resumable_source_manager.save_state(CodemagicResumeConfig(skip=int(state["skip"])))

    resource = rest_api_resource(
        rest_config,
        team_id,
        job_id,
        db_incremental_field_last_value=None,
        resume_hook=save_checkpoint if is_builds else None,
        initial_paginator_state=initial_paginator_state,
    )

    return SourceResponse(
        name=endpoint_config.name.lower(),
        items=lambda: resource,
        primary_keys=["_id"],
        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,
        # Builds come back newest-first with no way to request ascending order; Applications is a
        # single unordered page where sort direction is moot.
        sort_mode="desc" if is_builds else "asc",
    )


def _v3_client_config(api_token: str) -> ClientConfig:
    return {
        "base_url": V3_BASE_URL,
        "auth": {
            "type": "api_key",
            "api_key": api_token,
            "name": "x-auth-token",
            "location": "header",
        },
        "allow_redirects": False,
    }


def _v3_page_number_paginator() -> PageNumberPaginator:
    return PageNumberPaginator(base_page=1, total_path="total_pages")


def _v3_source(
    api_token: str,
    endpoint: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[CodemagicResumeConfig],
) -> SourceResponse:
    endpoint_config = V3_ENDPOINTS[endpoint]
    table_name = endpoint_config.name.lower()
    is_builds = endpoint == "Builds"

    if not is_builds:
        resource = rest_api_resource(
            {
                "client": _v3_client_config(api_token),
                "resources": [
                    {
                        "name": table_name,
                        "table_name": table_name,
                        "write_disposition": "replace",
                        "endpoint": {
                            "path": endpoint_config.path,
                            "params": {"page_size": V3_PAGE_SIZE},
                            "data_selector": endpoint_config.data_selector,
                            "paginator": _v3_page_number_paginator(),
                        },
                        "table_format": "delta",
                    }
                ],
            },
            team_id,
            job_id,
            db_incremental_field_last_value=None,
        )
    else:
        initial_state: Optional[dict[str, Any]] = None
        if resumable_source_manager.can_resume():
            resume_config = resumable_source_manager.load_state()
            if resume_config is not None and (resume_config.completed or resume_config.current):
                initial_state = {
                    "completed": resume_config.completed or [],
                    "current": resume_config.current,
                    "child_state": resume_config.child_state,
                }

        def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
            if state is not None:
                resumable_source_manager.save_state(
                    CodemagicResumeConfig(
                        completed=state.get("completed"),
                        current=state.get("current"),
                        child_state=state.get("child_state"),
                    )
                )

        resources = rest_api_resources(
            {
                "client": _v3_client_config(api_token),
                "resources": [
                    {
                        "name": "teams",
                        "endpoint": {
                            "path": V3_TEAMS_PATH,
                            "params": {"page_size": V3_PAGE_SIZE},
                            "data_selector": "data",
                            "paginator": _v3_page_number_paginator(),
                        },
                    },
                    {
                        "name": table_name,
                        "table_name": table_name,
                        "write_disposition": "replace",
                        "endpoint": {
                            "path": endpoint_config.path,
                            "params": {
                                "team_id": {"type": "resolve", "resource": "teams", "field": "id"},
                                "page_size": V3_PAGE_SIZE,
                            },
                            "data_selector": endpoint_config.data_selector,
                            "paginator": JSONResponseCursorPaginator(
                                cursor_path="cursor", cursor_param="cursor", raise_on_repeated_cursor=True
                            ),
                        },
                        "table_format": "delta",
                    },
                ],
            },
            team_id,
            job_id,
            db_incremental_field_last_value=None,
            resume_hook=save_checkpoint,
            initial_paginator_state=initial_state,
        )
        resource = next(r for r in resources if getattr(r, "name", None) == table_name)

    return SourceResponse(
        name=table_name,
        items=lambda: resource,
        primary_keys=["id"],
        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 validate_credentials(api_token: str, api_version: str) -> tuple[bool, str | None]:
    if api_version == CODEMAGIC_V1:
        url = f"{BASE_URL}/apps"
    elif api_version == CODEMAGIC_V3:
        url = f"{V3_BASE_URL}{V3_ENDPOINTS['Applications'].path}"
    else:
        raise ValueError(f"Unsupported Codemagic API version: {api_version}")
    response = make_tracked_session(redact_values=(api_token,), allow_redirects=False).get(
        url,
        headers={"x-auth-token": api_token},
    )
    if response.status_code == 200:
        return True, None
    return False, "Invalid Codemagic API token"