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.

feat(data-warehouse): implement raygun import source (#71153)

Tom Owersbd9fcddfac71
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 8f249d51cc41..fde66048628b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -367,6 +367,7 @@ the row lists both.
| recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |
| ramp | HTTP | requests | ✅ |
| rapid7_insightvm | HTTP | requests | ✅ |
+| raygun | HTTP | requests | ✅ |
| recharge | HTTP | requests | ✅ |
| recruitee | HTTP | requests | ✅ |
| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -825,6 +826,7 @@ doesn't conflict with concurrent PRs.
- quickbooks
- railway
- railz
+- rapid7_insightvm
- raygun
- razorpay
- rb2b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 3561967f745f..f7494e4970a8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -3409,7 +3409,7 @@ class Rapid7InsightvmSourceConfig(config.Config):
@config.config
class RaygunSourceConfig(config.Config):
- pass
+ personal_access_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/canonical_descriptions.py
new file mode 100644
index 000000000000..b96b20099103
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/canonical_descriptions.py
@@ -0,0 +1,102 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Raygun v3 API spec (https://api.raygun.com/v3/swagger).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "applications": {
+ "description": "An application monitored by Raygun (a project receiving crash, APM, or RUM data).",
+ "docs_url": "https://raygun.com/documentation/product-guides/apis/rest-api/",
+ "columns": {
+ "identifier": "Unique identifier for the application.",
+ "planIdentifier": "Identifier of the Raygun plan the application belongs to.",
+ "name": "Display name of the application.",
+ "hasSentCrashData": "Whether the application has received crash reporting data.",
+ "hasSentApmData": "Whether the application has received APM data.",
+ "hasSentRumData": "Whether the application has received real user monitoring data.",
+ "rumDataType": "The type of real user monitoring data the application collects.",
+ },
+ },
+ "error_groups": {
+ "description": "A group of error instances sharing the same root cause within an application.",
+ "docs_url": "https://raygun.com/documentation/product-guides/apis/rest-api/",
+ "columns": {
+ "identifier": "Unique identifier for the error group.",
+ "applicationIdentifier": "Identifier of the application the error group belongs to.",
+ "message": "The error message representing the group.",
+ "status": "Current status of the error group (e.g. active, resolved, ignored).",
+ "lastOccurredAt": "Timestamp when the error group most recently occurred.",
+ "createdAt": "Timestamp when the error group was first created.",
+ "resolvedIn": "The deployment version the error group was resolved in, if any.",
+ "discardNewOccurrences": "Whether new occurrences of this error group are discarded.",
+ "applicationUrl": "URL to view the error group in the Raygun dashboard.",
+ },
+ },
+ "deployments": {
+ "description": "A deployment of an application recorded in Raygun.",
+ "docs_url": "https://raygun.com/documentation/product-guides/apis/rest-api/",
+ "columns": {
+ "identifier": "Unique identifier for the deployment.",
+ "applicationIdentifier": "Identifier of the application the deployment belongs to.",
+ "version": "Version string of the deployment.",
+ "emailAddress": "Email address of the deployment owner.",
+ "ownerName": "Name of the deployment owner.",
+ "comment": "Comment or release note attached to the deployment.",
+ "scmIdentifier": "Source control identifier (e.g. commit hash) for the deployment.",
+ "scmType": "Source control system type for the deployment.",
+ "deployedAt": "Timestamp when the deployment occurred.",
+ "applicationUrl": "URL to view the deployment in the Raygun dashboard.",
+ },
+ },
+ "customers": {
+ "description": "An end user (customer) seen by an application's real user monitoring.",
+ "docs_url": "https://raygun.com/documentation/product-guides/apis/rest-api/",
+ "columns": {
+ "identifier": "Unique identifier for the customer.",
+ "applicationIdentifier": "Identifier of the application the customer belongs to.",
+ "externalIdentifier": "Customer identifier supplied by your application.",
+ "emailAddress": "Email address of the customer.",
+ "firstName": "First name of the customer.",
+ "fullName": "Full name of the customer.",
+ "isAnonymous": "Whether the customer is anonymous.",
+ "firstSeenAt": "Timestamp when the customer was first seen.",
+ "lastSeenAt": "Timestamp when the customer was most recently seen.",
+ },
+ },
+ "sessions": {
+ "description": "A real user monitoring session for an application.",
+ "docs_url": "https://raygun.com/documentation/product-guides/apis/rest-api/",
+ "columns": {
+ "identifier": "Unique identifier for the session.",
+ "applicationIdentifier": "Identifier of the application the session belongs to.",
+ "customerIdentifier": "Identifier of the customer the session belongs to.",
+ "isActive": "Whether the session is currently active.",
+ "startedAt": "Timestamp when the session started.",
+ "updatedAt": "Timestamp when the session was last updated.",
+ "endedAt": "Timestamp when the session ended.",
+ "ipAddress": "IP address of the session.",
+ "countryCode": "Country code derived from the session's IP address.",
+ "platformName": "Platform name of the session's device.",
+ "operatingSystemName": "Operating system name of the session's device.",
+ "operatingSystemVersion": "Operating system version of the session's device.",
+ "browserName": "Browser name used in the session.",
+ "browserVersion": "Browser version used in the session.",
+ "viewportWidth": "Viewport width of the session in pixels.",
+ "viewportHeight": "Viewport height of the session in pixels.",
+ "deploymentVersion": "Deployment version active during the session.",
+ "applicationUrl": "URL to view the session in the Raygun dashboard.",
+ },
+ },
+ "pages": {
+ "description": "A page (web or mobile view) seen by an application's real user monitoring.",
+ "docs_url": "https://raygun.com/documentation/product-guides/apis/rest-api/",
+ "columns": {
+ "identifier": "Unique identifier for the page.",
+ "applicationIdentifier": "Identifier of the application the page belongs to.",
+ "uri": "URI of the web page (web pages only).",
+ "name": "Name of the mobile page (mobile pages only).",
+ "type": "Type of the page.",
+ "lastSeenAt": "Timestamp when the page was most recently seen.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/raygun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/raygun.py
new file mode 100644
index 000000000000..4e3aa7357668
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/raygun.py
@@ -0,0 +1,230 @@
+import dataclasses
+from collections.abc import Callable, Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.raygun.settings import (
+ PAGE_SIZE,
+ RAYGUN_BASE_URL,
+ RAYGUN_ENDPOINTS,
+ RaygunEndpointConfig,
+)
+
+# Per-request timeout. Raygun list endpoints return at most `count` (<=500) rows, so pages
+# stay small; a generous ceiling covers a slow response without wedging the worker.
+REQUEST_TIMEOUT = 60
+
+# Fields dropped from ingested rows before they reach the warehouse table, keyed by endpoint path.
+# The `applications` response carries `apiKey` — the ingestion key for that application — which
+# anyone with warehouse viewer access could otherwise read and use to submit forged crash/APM/RUM
+# data. It is never needed downstream, so strip it at the source; disabling HTTP sample capture
+# does not protect the imported table.
+_SENSITIVE_FIELDS: dict[str, frozenset[str]] = {
+ RAYGUN_ENDPOINTS["applications"].path: frozenset({"apiKey"}),
+}
+
+
+def _scrub(path: str, data: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ sensitive = _SENSITIVE_FIELDS.get(path)
+ if not sensitive:
+ return data
+ return [{key: value for key, value in row.items() if key not in sensitive} for row in data]
+
+
+class RaygunResumeConfig:
+ # Offset (rows to skip) for the next page of the endpoint/application currently in progress.
+ offset: int = 0
+ # For fan-out endpoints, the application whose child list we were paging when state was saved.
+ # None for the top-level `applications` endpoint.
+ application_identifier: str | None = None
+
+
+def _get_headers(personal_access_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {personal_access_token}",
+ "Accept": "application/json",
+ }
+
+
+def _make_session(personal_access_token: str) -> Any:
+ # `capture=False`: customer and session rows carry end-user PII (externalIdentifier, names,
+ # IP addresses) and application rows carry ingestion API keys — fields the name-based sample
+ # scrubbers can't recognise, so keep response bodies out of HTTP sample storage entirely.
+ # Requests are still metered and logged (status + url). `redact_values` masks the token as
+ # defense in depth.
+ return make_tracked_session(redact_values=(personal_access_token,), capture=False)
+
+
+def validate_token(personal_access_token: str) -> tuple[bool, int | None]:
+ """Probe the token against the cheapest scoped endpoint. Returns (is_valid, status_code).
+
+ A 200 confirms the token is genuine and carries `applications:read`. The status code lets the
+ caller distinguish a bad token (401) from a valid token missing a scope (403)."""
+ url = f"{RAYGUN_BASE_URL}/applications?{urlencode({'count': 1})}"
+ try:
+ response = _make_session(personal_access_token).get(
+ url, headers=_get_headers(personal_access_token), timeout=REQUEST_TIMEOUT
+ )
+ except Exception:
+ return False, None
+ return response.status_code == 200, response.status_code
+
+
+def _fetch_page(
+ session: Any, path: str, params: dict[str, Any], headers: dict[str, str], logger: FilteringBoundLogger
+) -> list[dict[str, Any]]:
+ """Fetch one offset/count page. Raygun list endpoints return a bare JSON array."""
+ url = f"{RAYGUN_BASE_URL}{path}?{urlencode(params)}"
+ # The tracked session's DEFAULT_RETRY already backs off on 429/5xx (honoring Retry-After);
+ # anything still non-2xx here is terminal for this request.
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT)
+ if not response.ok:
+ logger.error(f"Raygun API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+ data = response.json()
+ if not isinstance(data, list):
+ return []
+ return _scrub(path, data)
+
+
+def _iter_application_identifiers(session: Any, headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:
+ """Enumerate every application identifier, following offset pagination to completion."""
+ identifiers: list[str] = []
+ offset = 0
+ while True:
+ page = _fetch_page(
+ session,
+ RAYGUN_ENDPOINTS["applications"].path,
+ {"count": PAGE_SIZE, "offset": offset, "orderby": RAYGUN_ENDPOINTS["applications"].orderby},
+ headers,
+ logger,
+ )
+ identifiers.extend(item["identifier"] for item in page if item.get("identifier"))
+ if len(page) < PAGE_SIZE:
+ break
+ offset += PAGE_SIZE
+ return identifiers
+
+
+def _paginate(
+ session: Any,
+ path: str,
+ orderby: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ start_offset: int,
+ on_page: Callable[[int], None],
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield successive offset/count pages for a single list, starting at `start_offset`.
+
+ `on_page(next_offset)` is invoked after each yielded page (only when another page remains) so
+ the caller can persist resume state pointing at the page we have not yet fetched."""
+ offset = start_offset
+ while True:
+ page = _fetch_page(session, path, {"count": PAGE_SIZE, "offset": offset, "orderby": orderby}, headers, logger)
+ if page:
+ yield page
+ # A short page (fewer than a full `count`) is the last one.
+ if len(page) < PAGE_SIZE:
+ break
+ offset += PAGE_SIZE
+ on_page(offset)
+
+
+def _get_top_level_rows(
+ session: Any,
+ config: RaygunEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RaygunResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_offset = resume.offset if resume is not None else 0
+
+ def save(next_offset: int) -> None:
+ resumable_source_manager.save_state(RaygunResumeConfig(offset=next_offset))
+
+ yield from _paginate(session, config.path, config.orderby, headers, logger, start_offset, save)
+
+
+def _get_fan_out_rows(
+ session: Any,
+ config: RaygunEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RaygunResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ application_identifiers = _iter_application_identifiers(session, headers, logger)
+
+ # Resolve the saved bookmark to the slice of applications still to process. If the bookmarked
+ # application no longer exists, start over from the first — merge dedupes re-pulled rows on the
+ # primary key.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = application_identifiers
+ resume_offset = 0
+ if resume is not None and resume.application_identifier in application_identifiers:
+ remaining = application_identifiers[application_identifiers.index(resume.application_identifier) :]
+ resume_offset = resume.offset
+ logger.debug(f"Raygun: resuming {config.name} from application={resume.application_identifier}")
+
+ for index, application_identifier in enumerate(remaining):
+ path = config.path.format(application_identifier=application_identifier)
+ start_offset = resume_offset if index == 0 else 0
+
+ def save(next_offset: int, app: str = application_identifier) -> None:
+ resumable_source_manager.save_state(RaygunResumeConfig(offset=next_offset, application_identifier=app))
+
+ yield from _paginate(session, path, config.orderby, headers, logger, start_offset, save)
+
+ # Advance the bookmark to the next application so a crash between applications resumes at
+ # its first page rather than re-walking the one just completed.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(
+ RaygunResumeConfig(offset=0, application_identifier=remaining[index + 1])
+ )
+
+
+def get_rows(
+ personal_access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RaygunResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = RAYGUN_ENDPOINTS[endpoint]
+ headers = _get_headers(personal_access_token)
+ # One session reused across every page so urllib3 keeps the connection alive.
+ session = _make_session(personal_access_token)
+
+ if config.fan_out_over_applications:
+ yield from _get_fan_out_rows(session, config, headers, logger, resumable_source_manager)
+ else:
+ yield from _get_top_level_rows(session, config, headers, logger, resumable_source_manager)
+
+
+def raygun_source(
+ personal_access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RaygunResumeConfig],
+) -> SourceResponse:
+ config = RAYGUN_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ personal_access_token=personal_access_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/settings.py
new file mode 100644
index 000000000000..a75db294e5eb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/settings.py
@@ -0,0 +1,89 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Raygun's data API is a single global host (no regional variants) exposing v3 REST/JSON.
+RAYGUN_BASE_URL = "https://api.raygun.com/v3"
+
+# Page size for offset/count pagination. The API caps `count` at 500; 100 keeps individual
+# responses small while limiting the number of round trips.
+PAGE_SIZE = 100
+
+
+@dataclass
+class RaygunEndpointConfig:
+ name: str
+ # Path relative to RAYGUN_BASE_URL. Fan-out children carry a `{application_identifier}`
+ # placeholder resolved once per application.
+ path: str
+ primary_keys: list[str]
+ # `orderby` value passed on every request. Offset pagination over data that is being
+ # inserted concurrently can skip or duplicate rows, so we always sort by a stable
+ # (immutable or create-time) field to keep page boundaries deterministic.
+ orderby: str
+ # Stable create-time field used for datetime partitioning. Only set when the field is
+ # guaranteed present on every row (in the API's `required` set) — never `lastSeenAt`/
+ # `updatedAt`, which move over time and would rewrite partitions each sync.
+ partition_key: Optional[str] = None
+ # When True, iterate every application and call `path` per application. When False the
+ # endpoint is a single top-level list.
+ fan_out_over_applications: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+# Raygun exposes no server-side "updated since" filter on any list endpoint (only offset/count
+# pagination plus an `orderby`), so every endpoint syncs as a full refresh — declaring an
+# incremental field here would fetch every page anyway, giving no cost saving. See the source
+# docstring and PR notes.
+RAYGUN_ENDPOINTS: dict[str, RaygunEndpointConfig] = {
+ "applications": RaygunEndpointConfig(
+ name="applications",
+ path="/applications",
+ primary_keys=["identifier"],
+ orderby="name",
+ ),
+ "error_groups": RaygunEndpointConfig(
+ name="error_groups",
+ path="/applications/{application_identifier}/error-groups",
+ primary_keys=["applicationIdentifier", "identifier"],
+ orderby="createdAt",
+ partition_key="createdAt",
+ fan_out_over_applications=True,
+ ),
+ "deployments": RaygunEndpointConfig(
+ name="deployments",
+ path="/applications/{application_identifier}/deployments",
+ primary_keys=["applicationIdentifier", "identifier"],
+ orderby="deployedAt",
+ fan_out_over_applications=True,
+ ),
+ "customers": RaygunEndpointConfig(
+ name="customers",
+ path="/applications/{application_identifier}/customers",
+ primary_keys=["applicationIdentifier", "identifier"],
+ orderby="firstSeenAt",
+ fan_out_over_applications=True,
+ ),
+ "sessions": RaygunEndpointConfig(
+ name="sessions",
+ path="/applications/{application_identifier}/sessions",
+ primary_keys=["applicationIdentifier", "identifier"],
+ orderby="startedAt",
+ partition_key="startedAt",
+ fan_out_over_applications=True,
+ ),
+ "pages": RaygunEndpointConfig(
+ name="pages",
+ path="/applications/{application_identifier}/pages",
+ primary_keys=["applicationIdentifier", "identifier"],
+ orderby="uri",
+ fan_out_over_applications=True,
+ ),
+}
+
+ENDPOINTS = tuple(RAYGUN_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in RAYGUN_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/source.py
index 9a303f095b48..c29e917eb09f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/source.py
@@ -1,30 +1,151 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RaygunSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.raygun.raygun import (
+ RaygunResumeConfig,
+ raygun_source,
+ validate_token,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.raygun.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+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
+"""
+
@SourceRegistry.register
-class RaygunSource(SimpleSource[RaygunSourceConfig]):
+class RaygunSource(ResumableSource[RaygunSourceConfig, RaygunResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@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.backend.temporal.data_imports.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,
+ ) -> list[SourceSchema]:
+ # Raygun exposes no server-side "updated since" filter, so every endpoint is full refresh.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in 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: RaygunSourceConfig, team_id: int, schema_name: Optional[str] = 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,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.RAYGUN,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Raygun",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=RAYGUN_CAPTION,
iconPath="/static/services/raygun.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ 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,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/tests/test_raygun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/tests/test_raygun.py
new file mode 100644
index 000000000000..0841a5e8522d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/tests/test_raygun.py
@@ -0,0 +1,215 @@
+import json
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.raygun.raygun import (
+ RaygunResumeConfig,
+ get_rows,
+ raygun_source,
+ validate_token,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.raygun.raygun"
+
+
+def _response(body: Any, status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _offset_of(url: str) -> int | None:
+ params = parse_qs(urlparse(url).query)
+ return int(params["offset"][0]) if "offset" in params else None
+
+
+def _path_of(url: str) -> str:
+ return urlparse(url).path
+
+
+class _FakeSession:
+ """Session stub returning responses from a URL handler; records requested URLs."""
+
+ def __init__(self, handler) -> None:
+ self.handler = handler
+ self.urls: list[str] = []
+ self.headers: dict[str, str] = {}
+
+ def get(self, url: str, headers: dict[str, str] | None = None, timeout: int | None = None) -> Response:
+ self.urls.append(url)
+ return self.handler(url)
+
+
+class TestValidateToken:
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_status_mapping(self, mock_session: MagicMock) -> None:
+ for status, expected in [(200, True), (401, False), (403, False), (500, False)]:
+ mock_session.return_value.get.return_value = _response([], status_code=status)
+ assert validate_token("tok") == (expected, status)
+ # Response bodies stay out of HTTP sample storage and the token is value-redacted.
+ assert mock_session.call_args.kwargs["capture"] is False
+ assert "tok" in mock_session.call_args.kwargs["redact_values"]
+
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_network_error_returns_none_status(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_token("tok") == (False, None)
+
+
+class TestTopLevelPagination:
+ @patch(f"{MODULE}.PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_offset_advances_and_saves_between_pages(self, mock_session: MagicMock) -> None:
+ # Two full pages then a short terminal page for /applications.
+ pages = {
+ 0: [{"identifier": "app-1"}, {"identifier": "app-2"}],
+ 2: [{"identifier": "app-3"}, {"identifier": "app-4"}],
+ 4: [{"identifier": "app-5"}],
+ }
+
+ def handler(url: str) -> Response:
+ return _response(pages[_offset_of(url) or 0])
+
+ session = _FakeSession(handler)
+ mock_session.return_value = session
+
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ yielded = list(get_rows("tok", "applications", MagicMock(), manager))
+
+ assert [_offset_of(u) for u in session.urls] == [0, 2, 4]
+ assert sum(len(page) for page in yielded) == 5
+ # Sync sessions carry PII-bearing bodies, so sample capture must stay off.
+ assert mock_session.call_args.kwargs["capture"] is False
+ assert "tok" in mock_session.call_args.kwargs["redact_values"]
+ # State is saved pointing at the next unfetched offset after each non-terminal page only.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [RaygunResumeConfig(offset=2), RaygunResumeConfig(offset=4)]
+
+ @patch(f"{MODULE}.PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_single_short_page_saves_no_state(self, mock_session: MagicMock) -> None:
+ session = _FakeSession(lambda url: _response([{"identifier": "app-1"}]))
+ mock_session.return_value = session
+
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ list(get_rows("tok", "applications", MagicMock(), manager))
+
+ manager.save_state.assert_not_called()
+
+ @patch(f"{MODULE}.PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_application_api_key_is_stripped(self, mock_session: MagicMock) -> None:
+ # `apiKey` is an ingestion credential and must never reach the warehouse table.
+ session = _FakeSession(lambda url: _response([{"identifier": "app-1", "name": "App", "apiKey": "secret"}]))
+ mock_session.return_value = session
+
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ rows = [row for page in get_rows("tok", "applications", MagicMock(), manager) for row in page]
+
+ assert rows == [{"identifier": "app-1", "name": "App"}]
+
+ @patch(f"{MODULE}.PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_resume_starts_from_saved_offset(self, mock_session: MagicMock) -> None:
+ session = _FakeSession(lambda url: _response([{"identifier": "app-9"}]))
+ mock_session.return_value = session
+
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = RaygunResumeConfig(offset=4)
+
+ list(get_rows("tok", "applications", MagicMock(), manager))
+
+ assert _offset_of(session.urls[0]) == 4
+
+
+class TestFanOutPagination:
+ def _fan_out_handler(self, apps: list[str], child_rows: dict[str, list[dict[str, Any]]]):
+ def handler(url: str) -> Response:
+ path = _path_of(url)
+ offset = _offset_of(url) or 0
+ if path.endswith("/applications"):
+ # One full page of apps then a terminal empty page.
+ return _response([{"identifier": a} for a in apps] if offset == 0 else [])
+ for app in apps:
+ if f"/applications/{app}/" in path:
+ return _response(child_rows.get(app, []) if offset == 0 else [])
+ return _response([])
+
+ return handler
+
+ @patch(f"{MODULE}.PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_fans_out_over_apps_and_bookmarks_next_app(self, mock_session: MagicMock) -> None:
+ apps = ["app-1", "app-2"]
+ child_rows = {
+ "app-1": [{"identifier": "eg-1", "applicationIdentifier": "app-1"}],
+ "app-2": [{"identifier": "eg-2", "applicationIdentifier": "app-2"}],
+ }
+ session = _FakeSession(self._fan_out_handler(apps, child_rows))
+ mock_session.return_value = session
+
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ yielded = list(get_rows("tok", "error_groups", MagicMock(), manager))
+
+ rows = [row for page in yielded for row in page]
+ assert {r["applicationIdentifier"] for r in rows} == {"app-1", "app-2"}
+ # After finishing app-1 the bookmark advances to app-2 at offset 0.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert RaygunResumeConfig(offset=0, application_identifier="app-2") in saved
+
+ @patch(f"{MODULE}.PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_resume_skips_to_bookmarked_app_and_offset(self, mock_session: MagicMock) -> None:
+ apps = ["app-1", "app-2"]
+ child_rows = {"app-2": [{"identifier": "eg-2", "applicationIdentifier": "app-2"}]}
+ session = _FakeSession(self._fan_out_handler(apps, child_rows))
+ mock_session.return_value = session
+
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = RaygunResumeConfig(offset=6, application_identifier="app-2")
+
+ list(get_rows("tok", "error_groups", MagicMock(), manager))
+
+ child_urls = [u for u in session.urls if "/applications/app-1/" in u or "/applications/app-2/" in u]
+ # app-1 is skipped entirely; the first child fetch targets app-2 at the saved offset.
+ assert all("/applications/app-2/" in u for u in child_urls)
+ assert _offset_of(child_urls[0]) == 6
+
+
+class TestRaygunSource:
+ def test_primary_keys_and_partitioning_per_endpoint(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ applications = raygun_source("tok", "applications", MagicMock(), manager)
+ assert applications.primary_keys == ["identifier"]
+ assert applications.partition_mode is None
+
+ error_groups = raygun_source("tok", "error_groups", MagicMock(), manager)
+ assert error_groups.primary_keys == ["applicationIdentifier", "identifier"]
+ assert error_groups.partition_mode == "datetime"
+ assert error_groups.partition_keys == ["createdAt"]
+
+ sessions = raygun_source("tok", "sessions", MagicMock(), manager)
+ assert sessions.partition_keys == ["startedAt"]
+
+ # A fan-out endpoint without a guaranteed create-time field is left unpartitioned.
+ deployments = raygun_source("tok", "deployments", MagicMock(), manager)
+ assert deployments.primary_keys == ["applicationIdentifier", "identifier"]
+ assert deployments.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/tests/test_raygun_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/tests/test_raygun_source.py
new file mode 100644
index 000000000000..03100fd95993
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/raygun/tests/test_raygun_source.py
@@ -0,0 +1,117 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RaygunSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.raygun.raygun import RaygunResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.raygun.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.raygun.source import RaygunSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.raygun.source"
+
+
+def _config() -> RaygunSourceConfig:
+ return RaygunSourceConfig(personal_access_token="tok")
+
+
+class TestRaygunSourceConfig:
+ def test_source_type(self) -> None:
+ assert RaygunSource().source_type == ExternalDataSourceType.RAYGUN
+
+ def test_get_source_config_shape(self) -> None:
+ config = RaygunSource().get_source_config
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ # A finished source ships visible with a soft ALPHA label, never hidden.
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+
+ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert len(fields) == 1
+ token_field = fields[0]
+ assert token_field.name == "personal_access_token"
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.required is True
+ assert token_field.secret is True
+
+ def test_get_schemas_full_refresh_only(self) -> None:
+ schemas = RaygunSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # No endpoint has a server-side timestamp filter, so none support incremental sync.
+ assert all(s.supports_incremental is False for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = RaygunSource().get_schemas(_config(), team_id=1, names=["applications", "sessions"])
+ assert {s.name for s in schemas} == {"applications", "sessions"}
+
+ def test_non_retryable_errors_cover_auth_failures(self) -> None:
+ errors = RaygunSource().get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas does no I/O, so the public docs catalog can render.
+ assert RaygunSource.lists_tables_without_credentials is True
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = RaygunSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is RaygunResumeConfig
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("token_result", "schema_name", "expected_valid"),
+ [
+ ((True, 200), None, True),
+ # A valid token missing a scope is accepted at source-create (no schema)...
+ ((False, 403), None, True),
+ # ...but rejected when probing a specific table's scope.
+ ((False, 403), "sessions", False),
+ ((False, 401), None, False),
+ ((False, None), None, False),
+ ],
+ )
+ @patch(f"{MODULE}.validate_token")
+ def test_status_to_result(
+ self,
+ mock_validate: MagicMock,
+ token_result: tuple[bool, int | None],
+ schema_name: str | None,
+ expected_valid: bool,
+ ) -> None:
+ mock_validate.return_value = token_result
+ is_valid, _ = RaygunSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)
+ assert is_valid is expected_valid
+
+
+class TestSourceForPipeline:
+ @patch(f"{MODULE}.raygun_source")
+ def test_plumbs_token_and_endpoint(self, mock_raygun_source: MagicMock) -> None:
+ sentinel = object()
+ mock_raygun_source.return_value = sentinel
+
+ inputs = MagicMock()
+ inputs.schema_name = "error_groups"
+ logger: Any = MagicMock()
+ inputs.logger = logger
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ result = RaygunSource().source_for_pipeline(_config(), manager, inputs)
+
+ assert result is sentinel
+ _, kwargs = mock_raygun_source.call_args
+ assert kwargs["personal_access_token"] == "tok"
+ assert kwargs["endpoint"] == "error_groups"
+ assert kwargs["resumable_source_manager"] is manager