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.

6.6 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.pagerduty._config import PagerDutySourceConfig
from products.warehouse_sources.sources.pagerduty.pagerduty import (
    ANALYTICS_PERSONAL_KEY_ERROR,
    ANALYTICS_READ_ONLY_KEY_ERROR,
    PagerDutyResumeConfig,
    pagerduty_source,
    validate_credentials as validate_pagerduty_credentials,
)
from products.warehouse_sources.sources.pagerduty.settings import ENDPOINTS, INCREMENTAL_FIELDS, PAGERDUTY_ENDPOINTS
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 PagerDutySource(ResumableSource[PagerDutySourceConfig, PagerDutyResumeConfig]):
    codebase_detection = detect(
        env=("^PAGERDUTY_", "^PD_API_KEY$"),
        npm=("@pagerduty/pdjs",),
        pypi=("pdpyras", "pagerduty"),
        go=("github.com/PagerDuty/go-pagerduty",),
    )

    supported_versions = ("2",)
    default_version = "2"
    api_docs_url = "https://developer.pagerduty.com/api-reference"

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

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.PAGERDUTY,
            category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
            label="PagerDuty",
            caption="""Enter your PagerDuty REST API key to pull your PagerDuty data into the PostHog Data warehouse.

You can create an account-level API key in your PagerDuty account under **Integrations → API Access Keys**. A **Read-only** key syncs every table except `incident_analytics`, because the PagerDuty Analytics API only accepts POST requests. To sync `incident_analytics`, create a full access key instead.""",
            iconPath="/static/services/pagerduty.svg",
            docsUrl="https://posthog.com/docs/cdp/sources/pagerduty",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_token",
                        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.pagerduty.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: PagerDutySourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Incidents and their analytics rows mutate after creation, so they merge (incremental) but are
        # never append-only.
        return build_endpoint_schemas(
            ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only={"incidents", "incident_analytics"}
        )

    def validate_credentials(
        self,
        config: PagerDutySourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        ok, status, error = validate_pagerduty_credentials(config.api_token, schema_name)
        if ok:
            return True, None

        # A valid token may legitimately lack scope for a specific endpoint. Accept 403 at
        # source-create (schema_name is None) so users can connect with a key scoped to only
        # the resources they want; re-raise it for per-schema checks.
        if status == 403 and schema_name is None:
            return True, None

        # A plan-gated endpoint answers its declared status (402 for teams, 404 for priorities) for
        # every account whose plan lacks the feature. The sync already skips that table with a
        # warning, so the credentials are fine and the schema settings must stay reachable. Any
        # other status on that same endpoint is a genuine failure and still falls through below.
        endpoint_config = PAGERDUTY_ENDPOINTS.get(schema_name) if schema_name else None
        if (
            endpoint_config is not None
            and endpoint_config.plan_gated_feature
            and status == endpoint_config.plan_gated_status
        ):
            return True, None

        return False, error

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        # The Analytics entries come first: the first matching entry supplies the message.
        return {
            "403 Client Error: Forbidden for url: https://api.pagerduty.com/analytics": ANALYTICS_READ_ONLY_KEY_ERROR,
            "400 Client Error: Bad Request for url: https://api.pagerduty.com/analytics": ANALYTICS_PERSONAL_KEY_ERROR,
            "401 Client Error: Unauthorized for url: https://api.pagerduty.com": "Your PagerDuty API key is invalid or expired. Please generate a new key and reconnect.",
            "403 Client Error: Forbidden for url: https://api.pagerduty.com": "Your PagerDuty API key does not have the required permissions. Please check the key's access and try again.",
        }

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

    def source_for_pipeline(
        self,
        config: PagerDutySourceConfig,
        resumable_source_manager: ResumableSourceManager[PagerDutyResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return pagerduty_source(
            api_token=config.api_token,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            resumable_source_manager=resumable_source_manager,
            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,
        )