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.plain._config import PlainSourceConfig
from products.warehouse_sources.sources.plain.plain import (
    plain_source,
    validate_credentials as validate_plain_credentials,
)
from products.warehouse_sources.sources.plain.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    SimpleSource,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    detect,
)


@SourceRegistry.register
class PlainSource(SimpleSource[PlainSourceConfig]):
    codebase_detection = detect(
        env=("^PLAIN_API_KEY$", "^PLAIN_WEBHOOK_SECRET$"),
        script_hosts=("chat.cdn-plain.com",),
        npm=(
            "@team-plain/typescript-sdk",
            "@team-plain/graphql",
            "@team-plain/webhooks",
            "@team-plain/ui-components",
            "@team-plain/cli",
        ),
    )

    supported_versions = ("v1",)
    default_version = "v1"
    api_docs_url = "https://www.plain.com/docs"

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

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.PLAIN,
            category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
            label="Plain",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Plain API key to automatically pull your Plain customer support data into the PostHog Data warehouse.

You can create an API key in your [Plain workspace settings](https://app.plain.com/settings/api-keys).

Make sure to grant the following read permissions:
- customer:read
- thread:read
- timeline:read
- user:read
- label:read
- company:read
- machineUser:read
- labelType:read
- tenant:read
- customerGroup:read
- customerSurvey:read
- threadDiscussion:read
- workflowRule:read
""",
            iconPath="/static/services/plain.png",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="plainApiKey_...",
                        secret=True,
                    ),
                ],
            ),
        )

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

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error": "Invalid Plain credentials. Please check your API key.",
            # Plain fails the whole GraphQL request when the key lacks a scope any requested field needs.
            # Our queries read assignee (user:read), label (label:read, labelType:read), company
            # (company:read), tenant (tenant:read), and machine-user actor (machineUser:read) data on top
            # of the basics, so name every required scope — retrying a key missing one never succeeds.
            "403 Client Error": "Access forbidden. Grant your Plain API key these read permissions, then reconnect: customer:read, thread:read, timeline:read, user:read, label:read, labelType:read, company:read, tenant:read, machineUser:read, customerGroup:read, customerSurvey:read, threadDiscussion:read, workflowRule:read.",
        }

    def get_retryable_errors(self) -> set[str]:
        # Plain's API occasionally takes longer than the 60 s read timeout, which is a transient
        # blip that Temporal retries at the activity level. Match the host so the pattern is
        # scoped to Plain and doesn't suppress unrelated timeout messages.
        return {
            "HTTPSConnectionPool(host='core-api.uk.plain.com', port=443)",
        }

    def get_schemas(
        self,
        config: PlainSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        schemas = [
            SourceSchema(
                name=endpoint,
                supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
                supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
                incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
            )
            for endpoint in list(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: PlainSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
    ) -> tuple[bool, str | None]:
        return validate_plain_credentials(config.api_key)

    def source_for_pipeline(self, config: PlainSourceConfig, inputs: SourceInputs) -> SourceResponse:
        return plain_source(
            api_key=config.api_key,
            endpoint_name=inputs.schema_name,
            logger=inputs.logger,
            should_use_incremental_field=inputs.should_use_incremental_field,
            db_incremental_field_last_value=inputs.db_incremental_field_last_value
            if inputs.should_use_incremental_field
            else None,
        )