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 rollbar import source (#62900)

Tom Owers4b8b762912a2
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index f6b26d793672..6c07e0be1ffd 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -133,6 +133,7 @@ the row lists both.
| resend | HTTP | requests | ✅ |
| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| rippling | HTTP | requests | ✅ |
+| rollbar | HTTP | requests | ✅ |
| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
| salesloft | HTTP | requests | ✅ |
| sendgrid | HTTP | requests | ✅ |
@@ -285,7 +286,6 @@ doesn't conflict with concurrent PRs.
- quickbooks
- ramp
- ringcentral
-- rollbar
- sage_intacct
- sailthru
- salesforce_marketing_cloud
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 87cac1757563..a9f0a0e310cf 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -1109,7 +1109,7 @@ class RipplingSourceConfig(config.Config):
@config.config
class RollbarSourceConfig(config.Config):
- pass
+ access_token: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/rollbar/rollbar.py b/posthog/temporal/data_imports/sources/rollbar/rollbar.py
new file mode 100644
index 000000000000..e99991fa7d1d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/rollbar/rollbar.py
@@ -0,0 +1,187 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.rollbar.settings import ROLLBAR_ENDPOINTS
+
+ROLLBAR_BASE_URL = "https://api.rollbar.com/api/1"
+# Instances support a keyset `limit` of up to 5000; keep it moderate so pages
+# stay well under the pipeline's buffering thresholds.
+KEYSET_PAGE_SIZE = 1000
+REQUEST_TIMEOUT_SECONDS = 60
+# Rate limits are per-token and user-configurable; 429 on breach.
+MAX_RETRY_ATTEMPTS = 5
+
+
+class RollbarRetryableError(Exception):
+ pass
+
+
+class RollbarResumeConfig:
+ # Page-paginated endpoints persist the 1-indexed page; the occurrences
+ # keyset walk persists the last (lowest) occurrence id seen instead.
+ page: Optional[int] = None
+ last_id: Optional[int] = None
+
+
+def _get_session(access_token: str) -> requests.Session:
+ return make_tracked_session(headers={"X-Rollbar-Access-Token": access_token}, redact_values=(access_token,))
+
+
+def _to_int(value: Any) -> Optional[int]:
+ if value is None or isinstance(value, bool):
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _extract_items(body: Any, data_key: Optional[str]) -> list[dict[str, Any]]:
+ result = body.get("result") if isinstance(body, dict) else None
+ if isinstance(result, list):
+ return result
+ if isinstance(result, dict) and data_key is not None:
+ items = result.get(data_key)
+ return items if isinstance(items, list) else []
+ return []
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ if not params:
+ return f"{ROLLBAR_BASE_URL}{path}"
+ return f"{ROLLBAR_BASE_URL}{path}?{urlencode(params)}"
+
+
+def validate_credentials(access_token: str) -> bool:
+ """Confirm the project access token is valid with a cheap environments probe."""
+ try:
+ response = _get_session(access_token).get(
+ _build_url("/environments", {}),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RollbarResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = ROLLBAR_ENDPOINTS[endpoint]
+ session = _get_session(access_token)
+
+ @retry(
+ retry=retry_if_exception_type((RollbarRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch(url: str) -> Any:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise RollbarRetryableError(f"Rollbar API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Rollbar API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.pagination == "keyset":
+ # Occurrences are strictly descending by id. Walk from the head (or the
+ # resumed keyset position) and stop once rows cross the persisted
+ # incremental watermark.
+ watermark = _to_int(db_incremental_field_last_value) if should_use_incremental_field else None
+ last_id: Optional[int] = resume_config.last_id if resume_config is not None else None
+ if last_id is not None:
+ logger.debug(f"Rollbar: resuming {endpoint} from lastId {last_id}")
+
+ while True:
+ params: dict[str, Any] = {"limit": KEYSET_PAGE_SIZE}
+ if last_id is not None:
+ params["lastId"] = last_id
+ body = fetch(_build_url(config.path, params))
+ items = _extract_items(body, config.data_key)
+
+ if watermark is not None:
+ items = [item for item in items if (_to_int(item["id"]) or 0) > watermark]
+
+ if items:
+ yield items
+
+ if len(items) < KEYSET_PAGE_SIZE:
+ # Short page: either the stream is exhausted or we crossed the
+ # watermark (filtered rows out).
+ break
+
+ last_id = min((_to_int(item["id"]) or 0) for item in items)
+ # Save state AFTER yielding the page so a crash re-yields the last
+ # page (merge dedupes on primary key) rather than skipping it.
+ resumable_source_manager.save_state(RollbarResumeConfig(last_id=last_id))
+ return
+
+ page = resume_config.page if resume_config is not None and resume_config.page is not None else 1
+ if resume_config is not None:
+ logger.debug(f"Rollbar: resuming {endpoint} from page {page}")
+
+ while True:
+ body = fetch(_build_url(config.path, {"page": page}))
+ items = _extract_items(body, config.data_key)
+
+ if not items:
+ break
+
+ yield items
+
+ page += 1
+ resumable_source_manager.save_state(RollbarResumeConfig(page=page))
+
+
+def rollbar_source(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RollbarResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = ROLLBAR_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ 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,
+ # Occurrences arrive newest-first; the pipeline only commits the
+ # incremental watermark for desc sources once the run completes.
+ sort_mode="desc" if config.pagination == "keyset" else "asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/rollbar/settings.py b/posthog/temporal/data_imports/sources/rollbar/settings.py
new file mode 100644
index 000000000000..03ba1e3ca32d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/rollbar/settings.py
@@ -0,0 +1,64 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class RollbarEndpointConfig:
+ name: str
+ path: str
+ # Key the rows live under inside the response `result`. Every Rollbar list
+ # endpoint nests its rows under a key (e.g. `result.environments`); `None`
+ # is only for the defensive case where `result` is itself a bare list.
+ data_key: Optional[str]
+ primary_key: str = "id"
+ pagination: Literal["page", "keyset"] = "page"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable event-time field used for datetime partitioning.
+ partition_key: Optional[str] = None
+
+
+# Rollbar's project-scoped API (api.rollbar.com/api/1, X-Rollbar-Access-Token
+# header with a read-scope project token). No list endpoint has a server-side
+# timestamp filter; occurrences are strictly descending by id, so they get an
+# id high-water-mark incremental (walk from the head until crossing the
+# watermark). Items mutate in place (counters), so they stay full refresh.
+ROLLBAR_ENDPOINTS: dict[str, RollbarEndpointConfig] = {
+ "items": RollbarEndpointConfig(
+ name="items",
+ path="/items",
+ data_key="items",
+ ),
+ "occurrences": RollbarEndpointConfig(
+ name="occurrences",
+ path="/instances",
+ data_key="instances",
+ pagination="keyset",
+ partition_key="timestamp",
+ incremental_fields=[
+ {
+ "label": "id",
+ "type": IncrementalFieldType.Integer,
+ "field": "id",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ ),
+ "deploys": RollbarEndpointConfig(
+ name="deploys",
+ path="/deploys",
+ data_key="deploys",
+ ),
+ "environments": RollbarEndpointConfig(
+ name="environments",
+ path="/environments",
+ data_key="environments",
+ ),
+}
+
+ENDPOINTS = tuple(ROLLBAR_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ROLLBAR_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/rollbar/source.py b/posthog/temporal/data_imports/sources/rollbar/source.py
index 9a4a5cbb14e6..6f3b59d99585 100644
--- a/posthog/temporal/data_imports/sources/rollbar/source.py
+++ b/posthog/temporal/data_imports/sources/rollbar/source.py
@@ -1,29 +1,115 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import RollbarSourceConfig
+from posthog.temporal.data_imports.sources.rollbar.rollbar import (
+ RollbarResumeConfig,
+ rollbar_source,
+ validate_credentials as validate_rollbar_credentials,
+)
+from posthog.temporal.data_imports.sources.rollbar.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class RollbarSource(SimpleSource[RollbarSourceConfig]):
+class RollbarSource(ResumableSource[RollbarSourceConfig, RollbarResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ROLLBAR
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.rollbar.com": "Rollbar authentication failed. Please check your project access token.",
+ "403 Client Error: Forbidden for url: https://api.rollbar.com": "Rollbar denied access. Please check that your project access token has the read scope.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ROLLBAR,
label="Rollbar",
+ caption="""Enter your Rollbar project access token to pull your Rollbar error data into the PostHog Data warehouse.
+
+You can find or create a project access token in your Rollbar project under Settings > Project Access Tokens. A token with the `read` scope is sufficient. Each PostHog source connects to one Rollbar project — add one source per project.""",
iconPath="/static/services/rollbar.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/rollbar",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Project access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: RollbarSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ 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: RollbarSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_rollbar_credentials(config.access_token):
+ return True, None
+
+ return False, "Invalid Rollbar project access token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RollbarResumeConfig]:
+ return ResumableSourceManager[RollbarResumeConfig](inputs, RollbarResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: RollbarSourceConfig,
+ resumable_source_manager: ResumableSourceManager[RollbarResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return rollbar_source(
+ access_token=config.access_token,
+ 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,
)
diff --git a/posthog/temporal/data_imports/sources/rollbar/tests/test_rollbar.py b/posthog/temporal/data_imports/sources/rollbar/tests/test_rollbar.py
new file mode 100644
index 000000000000..73595babe411
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/rollbar/tests/test_rollbar.py
@@ -0,0 +1,234 @@
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.rollbar.rollbar import (
+ KEYSET_PAGE_SIZE,
+ RollbarResumeConfig,
+ _extract_items,
+ _to_int,
+ get_rows,
+ rollbar_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.rollbar.settings import ENDPOINTS, ROLLBAR_ENDPOINTS
+
+
+def _make_manager(resume_state: RollbarResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(data_key: Optional[str], items: list[dict[str, Any]]) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ result: Any = items if data_key is None else {data_key: items}
+ resp.json.return_value = {"err": 0, "result": result}
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+class TestToInt:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (123, 123),
+ ("123", 123),
+ (123.9, 123),
+ ("nope", None),
+ (True, None),
+ ],
+ )
+ def test_to_int_values(self, value, expected):
+ assert _to_int(value) == expected
+
+
+class TestExtractItems:
+ def test_dict_result_with_key(self):
+ assert _extract_items({"err": 0, "result": {"items": [{"id": 1}]}}, "items") == [{"id": 1}]
+
+ def test_bare_list_result(self):
+ # Defensive: a `result` that is itself a list is returned as-is regardless of data_key.
+ assert _extract_items({"err": 0, "result": [{"id": 1}]}, "items") == [{"id": 1}]
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ {},
+ {"err": 1, "message": "nope"},
+ {"err": 0, "result": {"items": None}},
+ {"err": 0, "result": None},
+ "not-a-dict",
+ ],
+ )
+ def test_missing_or_malformed_returns_empty(self, body):
+ assert _extract_items(body, "items") == []
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.rollbar.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("token") is expected
+
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.rollbar.make_tracked_session")
+ def test_validate_credentials_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("token") is False
+
+
+class TestGetRowsPagePagination:
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.rollbar.make_tracked_session")
+ def test_pages_until_empty(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response("items", [{"id": 1}]),
+ _response("items", [{"id": 2}]),
+ _response("items", []),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "items", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == [1, 2]
+ # Saved after each yielded page, pointing at the next page.
+ assert [call.args[0].page for call in manager.save_state.call_args_list] == [2, 3]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert parse_qs(urlparse(urls[0]).query)["page"] == ["1"]
+ assert parse_qs(urlparse(urls[2]).query)["page"] == ["3"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.rollbar.make_tracked_session")
+ def test_resumes_from_saved_page(self, mock_session):
+ mock_session.return_value.get.return_value = _response("deploys", [])
+
+ manager = _make_manager(RollbarResumeConfig(page=7))
+ list(get_rows("token", "deploys", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["page"] == ["7"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.rollbar.make_tracked_session")
+ def test_environments_keyed_result(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response("environments", [{"id": 1, "environment": "production"}]),
+ _response("environments", []),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "environments", mock.MagicMock(), manager))
+
+ assert batches == [[{"id": 1, "environment": "production"}]]
+
+
+class TestGetRowsKeyset:
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.rollbar.make_tracked_session")
+ def test_walks_keyset_descending(self, mock_session):
+ first_page = [{"id": KEYSET_PAGE_SIZE * 2 - i} for i in range(KEYSET_PAGE_SIZE)]
+ second_page = [{"id": 5}]
+ mock_session.return_value.get.side_effect = [
+ _response("instances", first_page),
+ _response("instances", second_page),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "occurrences", mock.MagicMock(), manager))
+
+ assert len(batches) == 2
+ manager.save_state.assert_called_once()
+ saved = manager.save_state.call_args.args[0]
+ assert saved.last_id == min(item["id"] for item in first_page)
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert parse_qs(urlparse(second_url).query)["lastId"] == [str(saved.last_id)]
+
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.rollbar.make_tracked_session")
+ def test_incremental_stops_at_watermark(self, mock_session):
+ # Page contains rows above and below the watermark — only newer rows
+ # are yielded and the walk stops.
+ page = [{"id": 100 - i} for i in range(KEYSET_PAGE_SIZE)]
+ mock_session.return_value.get.return_value = _response("instances", page)
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "token",
+ "occurrences",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=50,
+ )
+ )
+
+ yielded_ids = [item["id"] for batch in batches for item in batch]
+ assert yielded_ids == [100 - i for i in range(50)]
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.rollbar.make_tracked_session")
+ def test_incremental_with_no_new_rows_yields_nothing(self, mock_session):
+ page = [{"id": 50 - i} for i in range(10)]
+ mock_session.return_value.get.return_value = _response("instances", page)
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "token",
+ "occurrences",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=50,
+ )
+ )
+
+ assert batches == []
+
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.rollbar.make_tracked_session")
+ def test_resumes_from_saved_last_id(self, mock_session):
+ mock_session.return_value.get.return_value = _response("instances", [])
+
+ manager = _make_manager(RollbarResumeConfig(last_id=12345))
+ list(get_rows("token", "occurrences", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["lastId"] == ["12345"]
+
+
+class TestRollbarSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = ROLLBAR_ENDPOINTS[endpoint]
+ response = rollbar_source("token", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ if config.pagination == "keyset":
+ assert response.sort_mode == "desc"
+ else:
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("config", list(ROLLBAR_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_event_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key == "timestamp"
diff --git a/posthog/temporal/data_imports/sources/rollbar/tests/test_rollbar_source.py b/posthog/temporal/data_imports/sources/rollbar/tests/test_rollbar_source.py
new file mode 100644
index 000000000000..acc2108a61ae
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/rollbar/tests/test_rollbar_source.py
@@ -0,0 +1,143 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import RollbarSourceConfig
+from posthog.temporal.data_imports.sources.rollbar.rollbar import RollbarResumeConfig
+from posthog.temporal.data_imports.sources.rollbar.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.rollbar.source import RollbarSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestRollbarSource:
+ def setup_method(self):
+ self.source = RollbarSource()
+ self.team_id = 123
+ self.config = RollbarSourceConfig(access_token="access-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.ROLLBAR
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Rollbar"
+ assert config.label == "Rollbar"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/rollbar.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["access_token"]
+
+ def test_access_token_field_is_secret_password(self):
+ config = self.source.get_source_config
+ token_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_token"
+ )
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.rollbar.com/api/1/items?page=1",
+ "403 Client Error: Forbidden for url: https://api.rollbar.com/api/1/instances",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.rollbar.com/api/1/items",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only occurrences have a usable high-water-mark cursor (descending id
+ # keyset); items mutate in place and deploys/environments are small.
+ assert incremental == {"occurrences"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["occurrences"].incremental_fields == INCREMENTAL_FIELDS["occurrences"]
+ assert [f["field"] for f in schemas["occurrences"].incremental_fields] == ["id"]
+ assert schemas["items"].incremental_fields == []
+ assert schemas["items"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["occurrences"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "occurrences"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Rollbar project access token"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.source.validate_rollbar_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.access_token)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is RollbarResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.source.rollbar_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_rollbar_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "occurrences"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 12345
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_rollbar_source.assert_called_once()
+ kwargs = mock_rollbar_source.call_args.kwargs
+ assert kwargs["access_token"] == "access-token"
+ assert kwargs["endpoint"] == "occurrences"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 12345
+
+ @mock.patch("posthog.temporal.data_imports.sources.rollbar.source.rollbar_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_rollbar_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "items"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 12345
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_rollbar_source.call_args.kwargs["db_incremental_field_last_value"] is None