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.

8.6 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.decagon._config import DecagonSourceConfig
from products.warehouse_sources.sources.decagon.decagon import (
    CONTRACT_MISMATCH_ERROR,
    UNREADABLE_ENVELOPE_ERROR,
    DecagonResumeConfig,
    decagon_source,
    validate_credentials as validate_decagon_credentials,
)
from products.warehouse_sources.sources.decagon.settings import DECAGON_ENDPOINTS
from products.warehouse_sources.sources.sdk import (
    NOT_DETECTABLE,
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
)


@SourceRegistry.register
class DecagonSource(ResumableSource[DecagonSourceConfig, DecagonResumeConfig]):
    codebase_detection = NOT_DETECTABLE

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    api_docs_url = "https://docs.decagon.ai/api-reference/getting-started"

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.DECAGON,
            category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
            label="Decagon",
            caption="""Enter a Decagon API key to pull your Decagon conversations into the PostHog Data warehouse.

You can find your API key on the **Developer** page of the [Decagon dashboard](https://decagon.ai/).
""",
            iconPath="/static/services/decagon.png",
            docsUrl="https://posthog.com/docs/cdp/sources/decagon",
            keywords=["ai agents", "customer support", "conversations", "csat"],
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
            releaseStatus=ReleaseStatus.GA,
        )

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

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        # Insertion order matters: the finalization activity surfaces the first matching
        # pattern's message, so endpoint-specific 403 entries must precede the bare 403 one.
        # A bare 403 does not establish a key problem, because the same key keeps syncing
        # sibling tables when Decagon gates an endpoint on an account plan (#87958). The 403
        # messages therefore point the operator at the sibling-table check instead of the key.
        return {
            "401 Client Error: Unauthorized": (
                "Decagon rejected the API key. Generate a new key on the Developer page of the "
                "Decagon dashboard and reconnect."
            ),
            "403 Client Error: Forbidden for url: https://api.decagon.ai/agent_assist": (
                "Decagon refused access to the Agent Assist export. If your other Decagon tables "
                "are syncing, the API key works and your Decagon plan likely does not include "
                "Agent Assist. Ask Decagon to enable it, then re-enable the sync. If every table "
                "is failing, generate a new key on the Developer page of the Decagon dashboard "
                "and reconnect."
            ),
            "403 Client Error: Forbidden": (
                "Decagon refused access to the endpoint behind this table. If your other Decagon "
                "tables are syncing, the API key works and your Decagon plan likely does not "
                "include this endpoint. Ask Decagon to enable it, then re-enable the sync. If "
                "every table is failing, generate a new key on the Developer page of the Decagon "
                "dashboard and reconnect."
            ),
            # The walk read the endpoint and kept nothing while the endpoint reported rows, so
            # the response no longer matches the config this source ships. Every attempt repeats
            # the same request and fails the same way, so retrying only multiplies the reports
            # and leaves the schema enabled to repeat it on the next schedule.
            CONTRACT_MISMATCH_ERROR: (
                "Decagon reports rows for this table, but PostHog could not read any of them. This "
                "is not a problem with your API key. Contact support so we can update the sync to "
                "match what Decagon now sends."
            ),
            # Same cause as above, caught one step earlier: the response holds lists, but none of
            # them is the row list this table is configured to read. Most endpoints report no total
            # for the guard above to read, so this failure is what stops an empty full refresh from
            # replacing the table.
            UNREADABLE_ENVELOPE_ERROR: (
                "PostHog could not find this table's rows in Decagon's response. This is not a "
                "problem with your API key. Contact support so we can update the sync to match "
                "what Decagon now sends."
            ),
        }

    def get_retryable_errors(self) -> set[str]:
        # `fetch_page` (decagon.py) already retries `DecagonRetryableError` (429/5xx),
        # `requests.ReadTimeout`, and `requests.ConnectionError` with backoff; if that budget
        # still exhausts, Temporal retries the whole activity, so the failure is transient and
        # self-recovering. Match the host rather than the per-endpoint path, so a timeout or
        # dropped connection on any Decagon endpoint is covered.
        return {
            "HTTPSConnectionPool(host='api.decagon.ai', port=443)",
            "Decagon API error (retryable)",
        }

    def get_schemas(
        self,
        config: DecagonSourceConfig,
        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,
                # Incremental writes merge on the primary key, so a keyless stream can
                # only offer append (gated per endpoint) or full refresh.
                supports_incremental=endpoint_config.primary_keys is not None
                and len(endpoint_config.incremental_fields) > 0,
                supports_append=endpoint_config.supports_append and len(endpoint_config.incremental_fields) > 0,
                incremental_fields=endpoint_config.incremental_fields,
                should_sync_default=endpoint_config.should_sync_default,
            )
            for endpoint, endpoint_config in DECAGON_ENDPOINTS.items()
        ]

        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: DecagonSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        if validate_decagon_credentials(config.api_key):
            return True, None

        return False, "Invalid Decagon API key"

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

    def source_for_pipeline(
        self,
        config: DecagonSourceConfig,
        resumable_source_manager: ResumableSourceManager[DecagonResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return decagon_source(
            api_key=config.api_key,
            endpoint=inputs.schema_name,
            logger=inputs.logger,
            resumable_source_manager=resumable_source_manager,
            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,
            incremental_field=inputs.incremental_field,
        )