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.

5.1 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.lago._config import LagoSourceConfig
from products.warehouse_sources.sources.lago.lago import (
    HOST_NOT_ALLOWED_ERROR,
    LagoResumeConfig,
    lago_source,
    validate_credentials as validate_lago_credentials,
)
from products.warehouse_sources.sources.lago.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    build_endpoint_schemas,
    detect,
)


@SourceRegistry.register
class LagoSource(ResumableSource[LagoSourceConfig, LagoResumeConfig]):
    codebase_detection = detect(
        env=("^LAGO_",),
        npm=("lago-javascript-client",),
        pypi=("lago-python-client",),
        go=("github.com/getlago/lago-go-client", "github.com/getlago/lago-cli"),
        rubygems=("lago-ruby-client", "lago_ruby"),
    )

    api_docs_url = "https://docs.getlago.com/api-reference"

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.LAGO

    @property
    def connection_host_fields(self) -> list[str]:
        # `api_url` is where the stored API key is sent; retargeting it must re-require the key.
        return ["api_url"]

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error": "Invalid Lago API key. Please generate a new key and reconnect.",
            "403 Client Error": "Your Lago API key lacks the required permissions. Please check the key and try again.",
            HOST_NOT_ALLOWED_ERROR: "The Lago API URL is not allowed. Please use a publicly reachable host.",
        }

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.lago.canonical_descriptions import (
            CANONICAL_DESCRIPTIONS,  # noqa: PLC0415
        )

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: LagoSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)

    def validate_credentials(
        self, config: LagoSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
    ) -> tuple[bool, str | None]:
        return validate_lago_credentials(config.api_url, config.api_key, schema_name, team_id)

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LagoResumeConfig]:
        return ResumableSourceManager[LagoResumeConfig](inputs, LagoResumeConfig)

    def source_for_pipeline(
        self,
        config: LagoSourceConfig,
        resumable_source_manager: ResumableSourceManager[LagoResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return lago_source(
            api_url=config.api_url,
            api_key=config.api_key,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            resumable_source_manager=resumable_source_manager,
            db_incremental_field_last_value=None,  # every Lago endpoint is full refresh
        )

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.LAGO,
            category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
            label="Lago",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Lago API key to pull your billing data into the PostHog Data warehouse.

You can create an API key in the Lago dashboard under **Developers > API keys**.

Self-hosted Lago users should set the API URL to their own Lago host (for example `https://billing.example.com`). Leave it blank to use Lago Cloud.""",
            iconPath="/static/services/lago.png",
            docsUrl="https://posthog.com/docs/cdp/sources/lago",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="api_url",
                        label="API URL (self-hosted only)",
                        type=SourceFieldInputConfigType.TEXT,
                        required=False,
                        placeholder="https://api.getlago.com",
                        secret=False,
                    ),
                ],
            ),
        )