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.

7.6 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.datahub._config import DatahubSourceConfig
from products.warehouse_sources.sources.datahub.datahub import (
    MIN_TIMESERIES_SCROLL_VERSION,
    TIMESERIES_SCROLL_UNSUPPORTED_ERROR,
    DatahubResumeConfig,
    check_endpoint_permissions,
    datahub_source,
    validate_credentials as validate_datahub_credentials,
)
from products.warehouse_sources.sources.datahub.settings import (
    DATAHUB_ENDPOINTS,
    ENDPOINTS,
    INCREMENTAL_FIELDS,
    TIMESERIES_ENDPOINTS,
)
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 DatahubSource(ResumableSource[DatahubSourceConfig, DatahubResumeConfig]):
    codebase_detection = detect(
        env=("^DATAHUB_",),
        pypi=("acryl-datahub",),
        maven=(
            "io.acryl:datahub-client",
            "io.acryl:datahub-auth-api",
            "io.acryl:datahub-client-java8",
            "io.acryl:datahub-custom-plugin-lib",
            "io.acryl:datahub-protobuf",
            "io.acryl:datahub-ranger-plugin",
            "io.acryl:datahub-spark-lineage",
        ),
    )

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs

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

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.DATAHUB,
            category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
            label="DataHub",
            releaseStatus=ReleaseStatus.BETA,
            keywords=["acryl", "data catalog", "metadata", "lineage"],
            caption="""Enter your DataHub instance URL and an access token to sync your metadata catalog — datasets, dashboards, charts, pipelines, owners, domains, glossary, and tags — into the PostHog Data warehouse.

The instance URL is where your DataHub API is served: for DataHub Cloud (Acryl) that's `https://<your-tenant>.acryl.io/gms`; for self-hosted it's your metadata service (GMS) URL, or the DataHub frontend URL, which proxies the API. Your instance must have [Metadata Service Authentication](https://docs.datahub.com/docs/authentication/introducing-metadata-service-authentication) enabled.

The token is a [personal access token](https://docs.datahub.com/docs/authentication/personal-access-tokens) generated under **Settings → Access Tokens**; it inherits its owner's view privileges, so the owner must be able to view the entity types you want to sync.
""",
            iconPath="/static/services/datahub.png",
            docsUrl="https://posthog.com/docs/cdp/sources/datahub",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="instance_url",
                        label="Instance URL",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="https://your-tenant.acryl.io/gms",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="api_token",
                        label="Access token",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )

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

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error": "Your DataHub access token is invalid or has expired. Generate a new personal access token under Settings → Access Tokens and reconnect.",
            "Unauthorized for url": "Your DataHub access token is invalid or has expired. Generate a new personal access token under Settings → Access Tokens and reconnect.",
            "403 Client Error": "Your DataHub access token does not have permission to read this data. Check the token owner's view privileges, then reconnect.",
            TIMESERIES_SCROLL_UNSUPPORTED_ERROR: (
                f"Your DataHub instance is older than {MIN_TIMESERIES_SCROLL_VERSION}, whose timeseries API cannot "
                "paginate. Upgrade the instance to sync the run event, profile, usage and operation tables, or turn "
                "those tables off."
            ),
        }

    def get_schemas(
        self,
        config: DatahubSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # The entity endpoints are full refresh only, because the generic entity scroll exposes no
        # server-side updated-since filter, so there is no timestamp cursor to advance an
        # incremental sync. The timeseries aspect endpoints do take one (see settings.py).
        return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=TIMESERIES_ENDPOINTS)

    def validate_credentials(
        self,
        config: DatahubSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_datahub_credentials(config.instance_url, config.api_token, schema_name, team_id)

    def get_endpoint_permissions(
        self, config: DatahubSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None
    ) -> dict[str, str | None]:
        # Tokens inherit their owner's privileges, and DataHub policies can scope view access per
        # entity type. Probe each endpoint so the schema picker can flag unreadable tables.
        return check_endpoint_permissions(config.instance_url, config.api_token, endpoints, team_id)

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

    def source_for_pipeline(
        self,
        config: DatahubSourceConfig,
        resumable_source_manager: ResumableSourceManager[DatahubResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        if inputs.schema_name not in DATAHUB_ENDPOINTS:
            raise ValueError(f"Unknown DataHub schema '{inputs.schema_name}'")

        return datahub_source(
            instance_url=config.instance_url,
            api_token=config.api_token,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            logger=inputs.logger,
            resumable_source_manager=resumable_source_manager,
            db_incremental_field_last_value=inputs.db_incremental_field_last_value
            if inputs.should_use_incremental_field
            else None,
        )