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.

9.9 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.metabase._config import MetabaseSourceConfig
from products.warehouse_sources.sources.metabase.metabase import (
    API_KEY_AUTH,
    HOST_NOT_ALLOWED_ERROR,
    QUERY_LOGS_UNAVAILABLE_ERROR,
    SESSION_AUTH,
    SESSION_RESPONSE_NOT_JSON_ERROR,
    MetabaseAuth,
    MetabaseResumeConfig,
    metabase_source,
    validate_credentials as validate_metabase_credentials,
)
from products.warehouse_sources.sources.metabase.settings import ENDPOINTS, METABASE_ENDPOINTS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceFieldSelectConfig,
    SourceFieldSelectConfigOption,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    detect,
)


@SourceRegistry.register
class MetabaseSource(ResumableSource[MetabaseSourceConfig, MetabaseResumeConfig]):
    codebase_detection = detect(env=("^METABASE_",), npm=("@metabase/embedding-sdk-react",))

    api_docs_url = "https://www.metabase.com/docs/latest/api"

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.METABASE,
            category=DataWarehouseSourceCategory.ANALYTICS,
            label="Metabase",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Metabase instance URL and credentials to pull your Metabase data into the PostHog Data warehouse.

Create an API key in your Metabase under **Admin settings > Authentication > API keys** (Metabase v0.47+). Older instances can authenticate with a username and password instead.

The API key (or user) needs read access to the data you want to sync.""",
            iconPath="/static/services/metabase.png",
            docsUrl="https://posthog.com/docs/cdp/sources/metabase",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="host",
                        label="Instance URL",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="https://your-company.metabaseapp.com",
                        secret=False,
                    ),
                    SourceFieldSelectConfig(
                        name="auth_method",
                        label="Authentication method",
                        required=True,
                        defaultValue=API_KEY_AUTH,
                        options=[
                            SourceFieldSelectConfigOption(
                                label="API key",
                                value=API_KEY_AUTH,
                                fields=cast(
                                    list[FieldType],
                                    [
                                        SourceFieldInputConfig(
                                            name="api_key",
                                            label="API key",
                                            type=SourceFieldInputConfigType.PASSWORD,
                                            required=False,
                                            placeholder="mb_...",
                                            secret=True,
                                        ),
                                    ],
                                ),
                            ),
                            SourceFieldSelectConfigOption(
                                label="Username & password",
                                value=SESSION_AUTH,
                                fields=cast(
                                    list[FieldType],
                                    [
                                        SourceFieldInputConfig(
                                            name="username",
                                            label="Username (email)",
                                            type=SourceFieldInputConfigType.EMAIL,
                                            required=False,
                                            placeholder="[email protected]",
                                            secret=False,
                                        ),
                                        SourceFieldInputConfig(
                                            name="password",
                                            label="Password",
                                            type=SourceFieldInputConfigType.PASSWORD,
                                            required=False,
                                            placeholder="",
                                            secret=True,
                                        ),
                                    ],
                                ),
                            ),
                        ],
                    ),
                ],
            ),
        )

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "Invalid Metabase credentials": "Your Metabase credentials are invalid or expired. Update them and reconnect.",
            "Invalid Metabase username or password": "Your Metabase username or password is incorrect. Update them and reconnect.",
            "Missing Metabase API key": "No Metabase API key is configured. Update the source configuration and reconnect.",
            "401 Client Error": "Your Metabase credentials are invalid or expired. Update them and reconnect.",
            "403 Client Error": "Your Metabase credentials lack the permissions needed to sync this data. Grant read access and reconnect.",
            HOST_NOT_ALLOWED_ERROR: "The Metabase host is not allowed. Please use your instance's public URL.",
            QUERY_LOGS_UNAVAILABLE_ERROR: "The query_executions table needs Metabase Pro or Enterprise. Deselect it, or upgrade your Metabase plan and reconnect.",
            SESSION_RESPONSE_NOT_JSON_ERROR: "Metabase didn't return a valid session response. Check that the Instance URL points to your Metabase instance, then reconnect.",
            # `_is_host_safe` raises this when the Instance URL doesn't resolve via DNS — a
            # hostname the customer typed wrong or one that's no longer publicly reachable.
            # Deterministic and permanent until the Instance URL is corrected, so stop
            # retrying. Match the stable prefix, not the customer's hostname that follows it.
            "Couldn't resolve the host": "The Metabase Instance URL could not be resolved via DNS. Check that it's spelled correctly and reachable from the public internet, then reconnect.",
            # `_is_host_safe` raises this when the Instance URL resolves to an internal or
            # private address (SSRF guard). Deterministic and permanent until the customer
            # points the source at a publicly reachable host, so stop retrying.
            "internal or private IP address": "The Metabase Instance URL resolves to an internal or private IP address. Use your instance's public URL, then reconnect.",
        }

    def _build_auth(self, config: MetabaseSourceConfig) -> MetabaseAuth:
        return MetabaseAuth(
            method=config.auth_method.selection,
            api_key=config.auth_method.api_key,
            username=config.auth_method.username,
            password=config.auth_method.password,
        )

    def get_schemas(
        self,
        config: MetabaseSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Only the query log has a server-side time filter (its month window); every other
        # endpoint is full refresh only.
        schemas = [
            SourceSchema(
                name=endpoint,
                supports_incremental=bool(METABASE_ENDPOINTS[endpoint].incremental_fields),
                supports_append=False,
                incremental_fields=METABASE_ENDPOINTS[endpoint].incremental_fields,
            )
            for endpoint in ENDPOINTS
        ]
        if names is not None:
            names_set = set(names)
            schemas = [s for s in schemas if s.name in names_set]
        return schemas

    def validate_credentials(
        self,
        config: MetabaseSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_metabase_credentials(config.host, self._build_auth(config), team_id, schema_name)

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

    def source_for_pipeline(
        self,
        config: MetabaseSourceConfig,
        resumable_source_manager: ResumableSourceManager[MetabaseResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return metabase_source(
            host=config.host,
            auth=self._build_auth(config),
            endpoint=inputs.schema_name,
            logger=inputs.logger,
            team_id=inputs.team_id,
            resumable_source_manager=resumable_source_manager,
            job_id=inputs.job_id,
            should_use_incremental_field=inputs.should_use_incremental_field,
            db_incremental_field_last_value=inputs.db_incremental_field_last_value,
        )

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.metabase.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS