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.6 KB
Raw Blame
import json
import dataclasses
from collections.abc import Callable, Iterable, Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional, cast

from requests.exceptions import HTTPError

from products.warehouse_sources.sources.linode.settings import (
    LINODE_ENDPOINTS,
    LINODE_MONTHLY_TRANSFER,
    MONTHLY_TRANSFER_LOOKBACK_MONTHS,
    PAGE_SIZE,
    LinodeEndpointConfig,
)
from products.warehouse_sources.sources.sdk import (
    ClientConfig,
    Endpoint,
    PageNumberPaginator,
    RESTAPIConfig,
    RESTClient,
    ResumableSourceManager,
    SinglePagePaginator,
    SourceResponse,
    build_dependent_resource,
    create_auth,
    make_tracked_session,
    parse_datetime_value,
    rest_api_resource,
    validate_via_probe,
)

LINODE_BASE_URL = "https://api.linode.com/v4"


@dataclasses.dataclass(frozen=False)
class LinodeResumeConfig:
    # Next page (1-indexed) to fetch. The X-Filter header (built from the run's fixed watermark) and
    # page_size are constant across a run, so the page number alone is enough to resume.
    next_page: int


def _accept_headers() -> dict[str, str]:
    # The Bearer token is supplied via the framework auth config so its value is redacted from logs
    # and raised errors; only the non-secret Accept header is set here.
    return {"Accept": "application/json"}


def _format_filter_value(value: Any) -> Any:
    """Format an incremental cursor value for a Linode X-Filter comparison.

    Integer cursors (event id) pass through unchanged. Datetime/date cursors are rendered as the
    `YYYY-MM-DDTHH:MM:SS` form Linode uses for its own timestamp fields (no timezone offset)."""
    if isinstance(value, datetime):
        return value.strftime("%Y-%m-%dT%H:%M:%S")
    if isinstance(value, date):
        return value.strftime("%Y-%m-%dT%H:%M:%S")
    return value


def _build_x_filter(field: str, value: Any) -> dict[str, Any]:
    """Build the JSON X-Filter body. Always orders ascending on the cursor field so pages arrive in
    the order SourceResponse.sort_mode ("asc") promises; adds a `+gte` bound when a watermark exists.

    The watermark is fixed for the whole run, so the header is built once and sent identically on
    every page request — the server applies the filter and order to the full result set, and
    pagination naturally terminates at the watermark (no client-side stop needed)."""
    x_filter: dict[str, Any] = {"+order_by": field, "+order": "asc"}
    if value is not None:
        x_filter[field] = {"+gte": _format_filter_value(value)}
    return x_filter


def validate_credentials(api_token: str) -> tuple[bool, str | None]:
    """Confirm the token is genuine by hitting /profile, which any valid token can read regardless of
    its granted scopes — so a token that only has scopes for some endpoints still validates."""
    ok, status = validate_via_probe(
        lambda: make_tracked_session(redact_values=(api_token,)),
        f"{LINODE_BASE_URL}/profile",
        headers={"Authorization": f"Bearer {api_token}", **_accept_headers()},
    )
    if ok:
        return True, None
    if status == 401:
        return False, "Invalid Linode API token"
    if status is None:
        return False, "Could not reach the Linode API"
    # Don't surface the raw response body: Linode error bodies can echo account/resource details, and
    # this message is persisted on the source. The status code alone is enough to diagnose.
    return False, f"Linode API returned {status}"


def linode_source(
    api_token: str,
    endpoint: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[LinodeResumeConfig],
    should_use_incremental_field: bool = False,
    db_incremental_field_last_value: Optional[Any] = None,
    incremental_field: str | None = None,
) -> SourceResponse:
    config = LINODE_ENDPOINTS[endpoint]

    if endpoint == LINODE_MONTHLY_TRANSFER:
        return _monthly_transfer_source(
            api_token,
            config,
            resumable_source_manager,
            db_incremental_field_last_value if should_use_incremental_field else None,
        )

    headers = _accept_headers()
    # Attach the X-Filter header for incremental/append endpoints. Honor the user's chosen cursor
    # field, falling back to the endpoint's declared filterable field. On the first sync the watermark
    # is None, so we send only the ordering (no +gte bound) and pull the full available window.
    if config.incremental_field is not None and should_use_incremental_field:
        cursor_field = incremental_field or config.incremental_field
        headers["X-Filter"] = json.dumps(_build_x_filter(cursor_field, db_incremental_field_last_value))

    client_config: ClientConfig = {
        "base_url": LINODE_BASE_URL,
        "headers": headers,
        "auth": {"type": "bearer", "token": api_token},
        # Linode returns {data, page, pages, results}; `pages` is the total page count, so the
        # paginator stops after the last page rather than paying an extra empty-page request.
        "paginator": PageNumberPaginator(base_page=1, page_param="page", total_path="pages"),
    }

    if config.fanout is not None:
        return _fanout_source(config, endpoint, client_config, team_id, job_id)

    endpoint_config: Endpoint = (
        {"path": config.path, "data_selector": "$", "paginator": "single_page"}
        if config.single_object
        else {"path": config.path, "params": {"page_size": PAGE_SIZE}, "data_selector": "data"}
    )
    rest_config: RESTAPIConfig = {
        "client": client_config,
        "resources": [{"name": endpoint, "endpoint": endpoint_config}],
    }

    initial_paginator_state: Optional[dict[str, Any]] = None
    if resumable_source_manager.can_resume():
        resume = resumable_source_manager.load_state()
        if resume is not None:
            initial_paginator_state = {"page": resume.next_page}

    def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
        # Persist only when a next page remains; the paginator state already points at the next
        # unfetched page and is saved AFTER the current page is yielded (and committed downstream), so
        # a crash resumes at the next page without re-fetching committed rows or skipping any.
        if state and state.get("page") is not None:
            resumable_source_manager.save_state(LinodeResumeConfig(next_page=int(state["page"])))

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

    return _make_source_response(config, endpoint, lambda: resource)


def _fanout_source(
    config: LinodeEndpointConfig,
    endpoint: str,
    client_config: ClientConfig,
    team_id: int,
    job_id: str,
) -> SourceResponse:
    assert config.fanout is not None
    child_endpoint_extra: Endpoint = (
        {"data_selector": "$", "paginator": "single_page"} if config.single_object else {"data_selector": "data"}
    )
    # No resume state: the parent lists (invoices, LKE clusters, volume quotas) are small, so a
    # restarted run re-walks them cheaply.
    dependent_resource = cast(
        Iterable[Any],
        build_dependent_resource(
            endpoint_configs=LINODE_ENDPOINTS,
            child_endpoint=endpoint,
            fanout=config.fanout,
            client_config=client_config,
            path_format_values={},
            team_id=team_id,
            job_id=job_id,
            db_incremental_field_last_value=None,
            parent_endpoint_extra={"data_selector": "data"},
            child_endpoint_extra=child_endpoint_extra,
            page_size_param=None if config.single_object else "page_size",
        ),
    )
    return _make_source_response(config, endpoint, lambda: dependent_resource)


def _current_month_start() -> datetime:
    now = datetime.now(UTC)
    return datetime(now.year, now.month, 1, tzinfo=UTC)


def _month_start(value: Any) -> datetime | None:
    parsed = parse_datetime_value(value)
    if parsed is None:
        return None
    return datetime(parsed.year, parsed.month, 1, tzinfo=UTC)


def _add_months(month: datetime, count: int) -> datetime:
    index = month.year * 12 + month.month - 1 + count
    return datetime(index // 12, index % 12 + 1, 1, tzinfo=UTC)


def _monthly_transfer_source(
    api_token: str,
    config: LinodeEndpointConfig,
    resumable_source_manager: ResumableSourceManager[LinodeResumeConfig],
    db_incremental_field_last_value: Optional[Any],
) -> SourceResponse:
    client = RESTClient(
        base_url=LINODE_BASE_URL,
        headers=_accept_headers(),
        auth=create_auth({"type": "bearer", "token": api_token}),
    )

    def _list_linodes() -> list[tuple[Any, datetime | None]]:
        linodes: list[tuple[Any, datetime | None]] = []
        for page in client.paginate(
            LINODE_ENDPOINTS["linodes"].path,
            params={"page_size": PAGE_SIZE},
            paginator=PageNumberPaginator(base_page=1, page_param="page", total_path="pages"),
            data_selector="data",
        ):
            linodes.extend((linode["id"], _month_start(linode.get("created"))) for linode in page if "id" in linode)
            # The listing yields no rows to the pipeline, so a long one must not hold up a shutdown.
            resumable_source_manager.safe_point()
        return linodes

    def _rows() -> Iterator[dict[str, Any]]:
        current_month = _current_month_start()
        first_month = _month_start(db_incremental_field_last_value) or _add_months(
            current_month, 1 - MONTHLY_TRANSFER_LOOKBACK_MONTHS
        )
        linodes = _list_linodes()

        # Month-major order keeps rows ascending on `month_start` across all Linodes, so the
        # watermark never passes a month that some Linode has not been read for yet.
        month = first_month
        while month <= current_month:
            for linode_id, created_month in linodes:
                if created_month is not None and created_month > month:
                    continue
                path = config.path.format(linode_id=linode_id, year=month.year, month=month.month)
                try:
                    for page in client.paginate(path, paginator=SinglePagePaginator(), data_selector="$"):
                        for stats in page:
                            yield {
                                "linode_id": linode_id,
                                "year": month.year,
                                "month": month.month,
                                "month_start": month,
                                **stats,
                            }
                except HTTPError as error:
                    # The Linode can be deleted between the listing and this request.
                    if error.response is None or error.response.status_code != 404:
                        raise
                    resumable_source_manager.safe_point()
            month = _add_months(month, 1)

    return _make_source_response(config, LINODE_MONTHLY_TRANSFER, _rows)


def _make_source_response(
    config: LinodeEndpointConfig, endpoint: str, items: Callable[[], Iterable[Any]]
) -> SourceResponse:
    return SourceResponse(
        name=endpoint,
        items=items,
        primary_keys=config.primary_keys,
        # The X-Filter header orders results ascending on the cursor field, so rows arrive oldest-first
        # and the watermark advances safely after each batch.
        sort_mode="asc",
        partition_count=1,
        partition_size=1,
        partition_mode="datetime" if config.partition_key else None,
        partition_format="month" if config.partition_key else None,
        partition_keys=[config.partition_key] if config.partition_key else None,
    )