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

from products.warehouse_sources.sources.canny._config import CannySourceConfig
from products.warehouse_sources.sources.canny.canny import (
    CannyResumeConfig,
    canny_source,
    validate_credentials as validate_canny_credentials,
)
from products.warehouse_sources.sources.canny.settings import (
    CANNY_API_VERSION_V1,
    CANNY_API_VERSION_V2,
    CANNY_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 CannySource(ResumableSource[CannySourceConfig, CannyResumeConfig]):
    codebase_detection = detect(env=("^CANNY_",), script_hosts=("sdk.canny.io", "canny.io"))

    # Oldest→newest; the default is always the last entry. v2 is Canny's cursor-paginated wire,
    # served today for a subset of endpoints (see settings.py) — new sources default to it while
    # v1-pinned rows keep their skip/limit request path unchanged.
    supported_versions = (CANNY_API_VERSION_V1, CANNY_API_VERSION_V2)
    default_version = CANNY_API_VERSION_V2
    api_docs_url = "https://developers.canny.io/api-reference"

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.CANNY,
            category=DataWarehouseSourceCategory.PRODUCTIVITY,
            label="Canny",
            releaseStatus=ReleaseStatus.BETA,
            caption="""Enter your Canny API key to sync your Canny feedback, posts, and roadmap data into the PostHog Data warehouse.

Find your secret API key under **Settings → API** in your Canny dashboard.""",
            iconPath="/static/services/canny.png",
            docsUrl="https://posthog.com/docs/cdp/sources/canny",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        invalid_key_message = (
            "Your Canny API key is invalid or has been revoked. Find your secret API key under "
            "Settings → API in your Canny dashboard, then reconnect."
        )
        return {
            # Canny reports a bad API key either via an `{"error": ...}` body (raised as an HTTPError
            # carrying the error text) or a 401/403 status. Match the stable host, not the per-request
            # path/params. The exact wording is API-version dependent, so match the broad signals.
            "invalid API key": invalid_key_message,
            "401 Client Error: Unauthorized for url: https://canny.io": invalid_key_message,
            "403 Client Error: Forbidden for url: https://canny.io": invalid_key_message,
        }

    def get_schemas(
        self,
        config: CannySourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # No Canny list endpoint exposes a server-side updated-since filter, so every stream is
        # full refresh only — neither incremental nor append is offered (every INCREMENTAL_FIELDS
        # entry is empty, which build_endpoint_schemas maps to both flags off).
        return build_endpoint_schemas(CANNY_ENDPOINTS, INCREMENTAL_FIELDS, names)

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

        return False, "Invalid Canny API key"

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

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

        return CANONICAL_DESCRIPTIONS

    def source_for_pipeline(
        self,
        config: CannySourceConfig,
        resumable_source_manager: ResumableSourceManager[CannyResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return canny_source(
            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,
            api_version=self.resolve_api_version(inputs.api_version),
        )