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

from products.warehouse_sources.sources.kustomer._config import KustomerSourceConfig
from products.warehouse_sources.sources.kustomer.kustomer import (
    KustomerResumeConfig,
    kustomer_source,
    validate_credentials as validate_kustomer_credentials,
)
from products.warehouse_sources.sources.kustomer.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 KustomerSource(ResumableSource[KustomerSourceConfig, KustomerResumeConfig]):
    codebase_detection = detect(env=("^KUSTOMER_",), script_hosts=("cdn.kustomerapp.com",))

    # Kustomer exposes both a v1.0 and a v2 API version, but the resources we sync
    # are served under `/v1/`
    # for both — the "v2" docs toggle keeps these list endpoints at `/v1/`. So the
    # version is a pin recorded on the source, not a request-layer branch: every
    # version resolves to the same `/v1/<resource>` requests (see settings.py).
    supported_versions = ("v1", "v2")
    default_version = "v2"
    api_docs_url = "https://developer.kustomer.com"

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

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

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

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

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized for url": "Kustomer authentication failed. Please check your API key and organization name.",
            "403 Client Error: Forbidden for url": "Kustomer denied access. Please check that your API key's roles grant read access to this dataset.",
        }

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.KUSTOMER,
            category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
            label="Kustomer",
            caption="""Enter your Kustomer API credentials to pull your Kustomer support data into the PostHog Data warehouse.

Your organization name is the first part of your Kustomer URL — for `myorg.kustomerapp.com` enter `myorg`. Create an API key in Kustomer under Settings > Security > API Keys with read roles for the data you want to sync (e.g. `org.user.read`).""",
            iconPath="/static/services/kustomer.png",
            docsUrl="https://posthog.com/docs/cdp/sources/kustomer",
            releaseStatus=ReleaseStatus.BETA,
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="org_name",
                        label="Organization name",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="myorg",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_schemas(
        self,
        config: KustomerSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # GET list endpoints have no updated-since filter; full refresh only
        # (INCREMENTAL_FIELDS is empty, so every schema is non-incremental).
        return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)

    def validate_credentials(
        self,
        config: KustomerSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        if validate_kustomer_credentials(config.org_name, config.api_key):
            return True, None

        return False, "Invalid Kustomer API credentials"

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

    def source_for_pipeline(
        self,
        config: KustomerSourceConfig,
        resumable_source_manager: ResumableSourceManager[KustomerResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return kustomer_source(
            org_name=config.org_name,
            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 Kustomer endpoint is full refresh
        )