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.

7.8 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.raygun._config import RaygunSourceConfig
from products.warehouse_sources.sources.raygun.raygun import RaygunResumeConfig, raygun_source, validate_token
from products.warehouse_sources.sources.raygun.settings import (
    ENDPOINTS,
    INCREMENTAL_FIELDS,
    METRICS_ENDPOINTS,
    METRICS_INCREMENTAL_LOOKBACK_SECONDS,
)
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ProductKey,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    build_endpoint_schemas,
    detect,
)

RAYGUN_CAPTION = """Enter a Raygun [personal access token](https://raygun.com/documentation/product-guides/apis/personal-access-tokens/) to pull your Raygun crash reporting and real user monitoring data into the PostHog Data warehouse.

Grant the token these read scopes for the tables you want to sync:
- `applications:read` — Applications
- `cr.errors:read` — Error groups
- `deployments:read` — Deployments
- `customers:read` — Customers
- `rum.sessions:read` — Sessions
- `rum.pages:read` — Pages
- `cr.errors:read` — Error instances
- `deployments:read` and `cr.errors:read` — Deployment error groups
- `metrics:errors` — Error metrics
- `metrics:pages` — Page metrics
"""


@SourceRegistry.register
class RaygunSource(ResumableSource[RaygunSourceConfig, RaygunResumeConfig]):
    codebase_detection = detect(
        env=("^RAYGUN_", "^SS_RAYGUN_APP_KEY$", "^SS_CUSTOM_RAYGUN_APP_KEY$"),
        script_hosts=("cdn.raygun.io",),
        npm=(
            "raygun",
            "raygun4js",
            "raygun4reactnative",
            "raygun-apm",
            "@raygun.io/aws-lambda",
            "@raygun.io/webpack-plugin",
            "@raygun.io/mcp-server-raygun",
            "ember-cli-raygun",
            "grunt-raygun-deployment",
            "gulp-raygun-sourcemaps",
        ),
        pypi=("raygun4py",),
        cocoapods=("raygun4apple", "Raygun4iOS"),
        composer=(
            "mindscape/raygun4php",
            "silverstripe/raygun",
            "davibennun/laravel-raygun",
            "magenizr/magento2-raygun",
        ),
        go=("github.com/MindscapeHQ/raygun4go",),
        hex=("raygun",),
        maven=(
            "com.raygun:raygun4android",
            "com.mindscapehq:core",
            "com.mindscapehq:webprovider",
            "com.mindscapehq:webproviderjakarta",
            "com.mindscapehq:raygun4java-play2",
            "com.mindscapehq.raygun4java:core",
            "com.mindscapehq.raygun4java:webprovider",
            "com.mindscapehq.android:raygun4android",
            "com.midtrans:raygun-spring-boot-starter",
        ),
        pub=("raygun4flutter", "raygun_cli"),
        rubygems=(
            "raygun4ruby",
            "raygun-apm",
            "raygun-apm-rails",
            "raygun-apm-sidekiq",
            "capistrano-raygun-deployment",
            "rake-raygun-deployment",
            "fluent-plugin-raygun",
        ),
        swiftpm=("github.com/mindscapehq/raygun4apple",),
        alternative_to=(ProductKey.ERROR_TRACKING,),
    )

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    supported_versions = ("v3",)
    default_version = "v3"
    api_docs_url = "https://raygun.com/documentation/product-guides/raygun-api/"

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

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized for url: https://api.raygun.com": "Your Raygun personal access token is invalid or has been revoked. Create a new token in your Raygun account settings, then reconnect.",
            "403 Client Error: Forbidden for url: https://api.raygun.com": "Your Raygun personal access token is missing a read scope needed to sync this data. Grant the required scope to the token, then reconnect.",
        }

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

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: RaygunSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Incremental endpoints re-read rows at the watermark (metric buckets, the last page of error
        # instances), so append would duplicate them; they merge on their primary keys instead.
        return build_endpoint_schemas(
            ENDPOINTS,
            INCREMENTAL_FIELDS,
            names,
            merge_only=[name for name, fields in INCREMENTAL_FIELDS.items() if fields],
            default_incremental_lookback_seconds=dict.fromkeys(METRICS_ENDPOINTS, METRICS_INCREMENTAL_LOOKBACK_SECONDS),
        )

    def validate_credentials(
        self,
        config: RaygunSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        is_valid, status_code = validate_token(config.personal_access_token)
        if is_valid:
            return True, None

        # A valid token may legitimately lack a scope for endpoints the user won't sync. Accept 403
        # at source-create (schema_name is None); only reject it for a specific schema probe.
        if status_code == 403 and schema_name is None:
            return True, None

        if status_code == 401:
            return False, "Invalid Raygun personal access token"
        if status_code == 403:
            return False, "Your Raygun personal access token is missing the read scope for this table"

        return False, "Could not validate Raygun personal access token"

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

    def source_for_pipeline(
        self,
        config: RaygunSourceConfig,
        resumable_source_manager: ResumableSourceManager[RaygunResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return raygun_source(
            personal_access_token=config.personal_access_token,
            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=(
                inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None
            ),
        )

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.RAYGUN,
            category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
            label="Raygun",
            releaseStatus=ReleaseStatus.BETA,
            caption=RAYGUN_CAPTION,
            iconPath="/static/services/raygun.png",
            docsUrl="https://posthog.com/docs/cdp/sources/raygun",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="personal_access_token",
                        label="Personal access token",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )