: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement ruddr import source (#68581)
Tom Owers099cd4a176aa
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 63e9dbd02b80..56561df8323a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -287,6 +287,7 @@ the row lists both.| rippling | HTTP | requests | ✅ || rollbar | HTTP | requests | ✅ || rootly | HTTP | requests | ✅ |+| ruddr | HTTP | requests | ✅ || salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ || salesloft | HTTP | requests | ✅ || secoda | HTTP | requests | ✅ |@@ -627,7 +628,6 @@ doesn't conflict with concurrent PRs.- rocket_chat- rocketlane- rss-- ruddr- safetyculture- sage_hr- sage_intacctdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 79260c390d4f..49f6a314b790 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@@ -2814,7 +2814,7 @@ class RssSourceConfig(config.Config):@config.configclass RuddrSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/canonical_descriptions.pynew file mode 100644index 000000000000..779f21a5b855--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/canonical_descriptions.py@@ -0,0 +1,87 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Ruddr API docs (https://docs.ruddr.io).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "clients": {+ "description": "A client (customer company) tracked in your Ruddr workspace.",+ "docs_url": "https://docs.ruddr.io",+ "columns": {+ "id": "The unique ID of the client.",+ "key": "The short human-readable key of the client.",+ "name": "The client's name.",+ "code": "An optional external code for the client.",+ "currency": "The client's default currency.",+ "isInternal": "Whether the client represents internal (non-billable) work.",+ "createdAt": "When the client was created.",+ },+ },+ "projects": {+ "description": "A project delivered for a client in Ruddr.",+ "docs_url": "https://docs.ruddr.io",+ "columns": {+ "id": "The unique ID of the project.",+ "key": "The short human-readable key of the project.",+ "name": "The project's name.",+ "code": "An optional external code for the project.",+ "statusId": "The current status of the project.",+ "start": "The project's start date.",+ "end": "The project's end date.",+ "isBillable": "Whether time on the project is billable.",+ "currency": "The project's currency.",+ "fixedFee": "The fixed fee for the project, if any.",+ },+ },+ "project_tasks": {+ "description": "A task within a project in Ruddr.",+ "docs_url": "https://docs.ruddr.io",+ "columns": {+ "id": "The unique ID of the task.",+ "name": "The task's name.",+ "notes": "Free-text notes on the task.",+ "statusId": "The current status of the task.",+ "start": "The task's start date.",+ "end": "The task's end date.",+ "isBillable": "Whether time on the task is billable.",+ "budgetedHours": "The budgeted hours for the task.",+ "project": "The project the task belongs to.",+ "createdAt": "When the task was created.",+ },+ },+ "members": {+ "description": "A member (user) of your Ruddr workspace.",+ "docs_url": "https://docs.ruddr.io",+ "columns": {+ "id": "The unique ID of the member.",+ "name": "The member's full name.",+ "email": "The member's email address.",+ "isActive": "Whether the member is currently active.",+ "isBillable": "Whether the member's time is billable by default.",+ "employmentTypeId": "The member's employment type.",+ "defaultRate": "The member's default billing rate.",+ "defaultRateCurrency": "The currency of the member's default rate.",+ "activeStartDate": "When the member became active.",+ "activeEndDate": "When the member's active period ends.",+ },+ },+ "time_entries": {+ "description": "A time entry logged by a member against a project or task in Ruddr.",+ "docs_url": "https://docs.ruddr.io",+ "columns": {+ "id": "The unique ID of the time entry.",+ "date": "The date the time was logged for.",+ "minutes": "The number of minutes logged.",+ "notes": "Free-text notes on the time entry.",+ "typeId": "The type of the time entry.",+ "statusId": "The current status of the time entry.",+ "isBillable": "Whether the entry is billable.",+ "invoiced": "Whether the entry has been invoiced.",+ "member": "The member who logged the time.",+ "project": "The project the time was logged against.",+ "task": "The task the time was logged against.",+ "createdAt": "When the time entry was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/ruddr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/ruddr.pynew file mode 100644index 000000000000..0fb2405e2bcb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/ruddr.py@@ -0,0 +1,158 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++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.ruddr.settings import RUDDR_ENDPOINTS++RUDDR_BASE_URL = "https://www.ruddr.io/api/workspace"+# List endpoints accept a `limit` of up to 100; the largest page minimises round trips.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API key is genuine. The key is workspace-wide, so one probe+# validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/clients"+++class RuddrRetryableError(Exception):+ pass+++class RuddrResumeConfig:+ # Cursor for the next page: Ruddr paginates by passing the last item's `id` as `startingAfter`.+ # A crashed full-refresh sync resumes from the page after the last one yielded; merge dedupes on+ # `id`. `None` means start from the first page.+ cursor: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((RuddrRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ cursor: str | None,+ limit: int,+ logger: FilteringBoundLogger,+) -> tuple[list[dict[str, Any]], bool]:+ params: dict[str, Any] = {"limit": limit}+ if cursor is not None:+ params["startingAfter"] = cursor++ response = session.get(+ f"{RUDDR_BASE_URL}{path}",+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise RuddrRetryableError(f"Ruddr API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Ruddr API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # Ruddr list endpoints wrap records in {"results": [...], "hasMore": bool}.+ if not isinstance(data, dict) or not isinstance(data.get("results"), list):+ raise RuddrRetryableError(f"Ruddr returned an unexpected payload for {path}: {type(data).__name__}")++ results: list[dict[str, Any]] = data["results"]+ has_more = bool(data.get("hasMore"))+ return results, has_more+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RuddrResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = RUDDR_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.cursor if resume else None+ if resume and resume.cursor is not None:+ logger.debug(f"Ruddr: resuming {endpoint} from cursor {cursor}")++ while True:+ items, has_more = _fetch_page(session, config.path, cursor, PAGE_SIZE, logger)+ if items:+ yield items++ # `hasMore` is false (or the page came back empty) once we've reached the end of the list.+ if not has_more or not items:+ break++ # Cursor pagination advances by the last item's id — Ruddr has no numeric offset.+ cursor = items[-1]["id"]+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(RuddrResumeConfig(cursor=cursor))+++def ruddr_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RuddrResumeConfig],+) -> SourceResponse:+ config = RUDDR_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{RUDDR_BASE_URL}{path}", params={"limit": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Ruddr: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Ruddr returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Ruddr API key"+ return False, message or "Could not validate Ruddr API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/settings.pynew file mode 100644index 000000000000..fa0d861904cc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/settings.py@@ -0,0 +1,25 @@+from dataclasses import dataclass, field+++@dataclass+class RuddrEndpointConfig:+ name: str+ path: str+ # Ruddr object IDs are globally unique within a workspace, so `id` is a safe primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Ruddr workspace API list endpoints. All are full-refresh only: Ruddr exposes no documented+# monotonic `updatedAt`/`modifiedSince` cursor, so there is no reliable incremental cursor to+# advance (its Airbyte connector is likewise full-refresh only).+RUDDR_ENDPOINTS: dict[str, RuddrEndpointConfig] = {+ "clients": RuddrEndpointConfig(name="clients", path="/clients"),+ "projects": RuddrEndpointConfig(name="projects", path="/projects"),+ "project_tasks": RuddrEndpointConfig(name="project_tasks", path="/project-tasks"),+ "members": RuddrEndpointConfig(name="members", path="/members"),+ "time_entries": RuddrEndpointConfig(name="time_entries", path="/time-entries"),+}++ENDPOINTS = tuple(RUDDR_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/source.pyindex 7e3df7ea34e7..0424d7f095b7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/source.py@@ -1,19 +1,39 @@-from typing import cast+from typing import Optional, castfrom 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RuddrSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.ruddr import (+ RuddrResumeConfig,+ ruddr_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.settings import ENDPOINTS, RUDDR_ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class RuddrSource(SimpleSource[RuddrSourceConfig]):+class RuddrSource(ResumableSource[RuddrSourceConfig, RuddrResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RUDDR@@ -24,7 +44,86 @@ class RuddrSource(SimpleSource[RuddrSourceConfig]):name=SchemaExternalDataSourceType.RUDDR,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Ruddr",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Ruddr API key to pull your professional services data into the PostHog Data warehouse.++You can create a workspace API key under **Settings → API Keys** in [Ruddr](https://www.ruddr.io). The key grants read access to your clients, projects, tasks, members, and time entries.+""",iconPath="/static/services/ruddr.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/ruddr",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://www.ruddr.io": "Your Ruddr API key is invalid or has been revoked. Generate a new key under Settings → API Keys, then reconnect.",+ "403 Client Error: Forbidden for url: https://www.ruddr.io": "Your Ruddr API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: RuddrSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Ruddr's list endpoints expose no reliably ordered+ # server-side update timestamp, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: RuddrSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is workspace-wide, so a single probe validates access to every schema.+ return validate_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RuddrResumeConfig]:+ return ResumableSourceManager[RuddrResumeConfig](inputs, RuddrResumeConfig)++ def source_for_pipeline(+ self,+ config: RuddrSourceConfig,+ resumable_source_manager: ResumableSourceManager[RuddrResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in RUDDR_ENDPOINTS:+ raise ValueError(f"Unknown Ruddr schema '{inputs.schema_name}'")++ return ruddr_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/tests/test_ruddr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/tests/test_ruddr.pynew file mode 100644index 000000000000..c89390b84b4d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/tests/test_ruddr.py@@ -0,0 +1,239 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.ruddr import ruddr+from products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.ruddr import (+ PAGE_SIZE,+ RuddrResumeConfig,+ RuddrRetryableError,+ check_access,+ get_rows,+ ruddr_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.settings import ENDPOINTS, RUDDR_ENDPOINTS++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = ruddr._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: RuddrResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[RuddrResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> RuddrResumeConfig | None:+ return self._state++ def save_state(self, data: RuddrResumeConfig) -> None:+ self.saved.append(data)+++def _full_page(start_id: int) -> list[dict]:+ # Ruddr resource ids are strings, and the cursor (RuddrResumeConfig.cursor) is typed str | None.+ return [{"id": str(start_id + i)} for i in range(PAGE_SIZE)]+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[str | None, tuple[list[dict], bool]],+ endpoint: str = "clients",+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, cursor: str | None, limit: int, logger: Any) -> tuple[list[dict], bool]:+ return pages[cursor]++ monkeypatch.setattr(ruddr, "_fetch_page", fake_fetch)+ monkeypatch.setattr(ruddr, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="ruddr-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_hasmore_false_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([{"id": 1}, {"id": 2}], False)})+ assert rows == [{"id": 1}, {"id": 2}]+ # hasMore is false, so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_cursor_pagination_until_hasmore_false(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ # First page is full with hasMore true; the cursor becomes the last item's id (PAGE_SIZE - 1).+ last_id = str(PAGE_SIZE - 1)+ pages: dict[str | None, tuple[list[dict], bool]] = {+ None: (_full_page(0), True),+ last_id: ([{"id": "999"}], False),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1+ # State is saved after the first page (cursor advances to the last id), then we stop.+ assert [s.cursor for s in manager.saved] == [last_id]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(RuddrResumeConfig(cursor="cur-99"))+ # The initial (cursor=None) page must never be fetched on resume.+ rows = self._collect(manager, monkeypatch, {"cur-99": ([{"id": "5"}], False)})+ assert rows == [{"id": "5"}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([], False)})+ assert rows == []+ assert manager.saved == []+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"results": [], "hasMore": False}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(RuddrRetryableError):+ _fetch_page_unwrapped(session, "/clients", None, PAGE_SIZE, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/clients", None, PAGE_SIZE, MagicMock())++ def test_success_returns_results_and_hasmore(self) -> None:+ body = {"results": [{"id": 1}], "hasMore": True}+ session = self._session_returning(200, body)+ results, has_more = _fetch_page_unwrapped(session, "/clients", None, PAGE_SIZE, MagicMock())+ assert results == [{"id": 1}]+ assert has_more is True++ def test_non_dict_body_is_retryable(self) -> None:+ session = self._session_returning(200, [{"id": 1}])+ with pytest.raises(RuddrRetryableError):+ _fetch_page_unwrapped(session, "/clients", None, PAGE_SIZE, MagicMock())++ def test_missing_results_key_is_retryable(self) -> None:+ session = self._session_returning(200, {"hasMore": False})+ with pytest.raises(RuddrRetryableError):+ _fetch_page_unwrapped(session, "/clients", None, PAGE_SIZE, MagicMock())++ def test_first_page_uses_limit_without_cursor(self) -> None:+ session = self._session_returning(200, {"results": [], "hasMore": False})+ _fetch_page_unwrapped(session, "/projects", None, PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": PAGE_SIZE}++ def test_subsequent_page_sends_starting_after_cursor(self) -> None:+ session = self._session_returning(200, {"results": [], "hasMore": False})+ _fetch_page_unwrapped(session, "/projects", "cur-42", PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": PAGE_SIZE, "startingAfter": "cur-42"}+++class TestCheckAccess:+ @staticmethod+ def _session(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Ruddr returned HTTP 500"),+ ]+ )+ @patch(f"{ruddr.__name__}.make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_session.return_value = self._session(response)+ assert check_access("ruddr-key") == (expected_status, expected_message)++ @patch(f"{ruddr.__name__}.make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session(requests.ConnectionError("boom"))+ status, message = check_access("ruddr-key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Ruddr API key"),+ ("forbidden", 403, False, "Invalid Ruddr API key"),+ ("server_error", 500, False, "Ruddr returned HTTP 500"),+ ]+ )+ @patch(f"{ruddr.__name__}.make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_session.return_value = self._session(response)+ assert validate_credentials("ruddr-key") == (expected_valid, expected_message)+++class TestRuddrSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = ruddr_source(+ api_key="ruddr-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # No stable creation timestamp is guaranteed across every object, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in RUDDR_ENDPOINTS.values())+ assert set(RUDDR_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/tests/test_ruddr_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/tests/test_ruddr_source.pynew file mode 100644index 000000000000..9bcf73d58d63--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ruddr/tests/test_ruddr_source.py@@ -0,0 +1,133 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import 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 RuddrSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.ruddr import RuddrResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.source import RuddrSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestRuddrSource:+ def setup_method(self) -> None:+ self.source = RuddrSource()+ self.team_id = 123+ self.config = RuddrSourceConfig(api_key="ruddr-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.RUDDR++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Ruddr"+ assert config.label == "Ruddr"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/ruddr"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved key against another workspace.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["projects"])+ assert len(schemas) == 1+ assert schemas[0].name == "projects"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://www.ruddr.io/api/workspace/clients?limit=100",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://www.ruddr.io/api/workspace/projects?limit=100"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://www.ruddr.io/api/workspace/clients",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://www.ruddr.io/api/workspace/projects",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.source.validate_credentials")+ def test_validate_credentials_delegates_with_api_key(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in ruddr.validate_credentials; here we only assert the+ # source probes with the configured key and returns the delegate's verdict unchanged.+ mock_validate.return_value = (False, "Invalid Ruddr API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("ruddr-key")+ assert result == (False, "Invalid Ruddr API key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is RuddrResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ruddr.source.ruddr_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "clients"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "ruddr-key"+ assert kwargs["endpoint"] == "clients"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Ruddr schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)