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 rippling import source (#62884)

Tom Owers629894a436c1
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index de05bf7a42d5..bc56a922b25d 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -127,6 +127,7 @@ the row lists both.
| redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |
| resend | HTTP | requests | ✅ |
| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
+| rippling | HTTP | requests | ✅ |
| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
| salesloft | HTTP | requests | ✅ |
| sendgrid | HTTP | requests | ✅ |
@@ -283,7 +284,6 @@ doesn't conflict with concurrent PRs.
- quickbooks
- ramp
- ringcentral
-- rippling
- rollbar
- sage_intacct
- sailthru
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 637766a3e8e7..a928df29bd90 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -1096,7 +1096,7 @@ class RingCentralSourceConfig(config.Config):
@config.config
class RipplingSourceConfig(config.Config):
- pass
+ api_token: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/rippling/rippling.py b/posthog/temporal/data_imports/sources/rippling/rippling.py
new file mode 100644
index 000000000000..bb53a7a0b482
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/rippling/rippling.py
@@ -0,0 +1,196 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urljoin, urlsplit
+
+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.rippling.settings import RIPPLING_ENDPOINTS
+
+RIPPLING_BASE_URL = "https://rest.ripplingapis.com"
+RIPPLING_HOST = urlsplit(RIPPLING_BASE_URL).netloc
+# Rippling list pages cap at 100 items.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Rippling's rate limits are not publicly documented — honor 429s with backoff.
+MAX_RETRY_ATTEMPTS = 5
+
+
+class RipplingRetryableError(Exception):
+ pass
+
+
+class RipplingResumeConfig:
+ # Rippling cursor pagination returns a `next_link` URL (sometimes relative);
+ # we persist it absolutized, so it's all we need to pick back up.
+ next_url: str
+
+
+def _get_session(api_token: str) -> requests.Session:
+ return make_tracked_session(headers={"Authorization": f"Bearer {api_token}"}, redact_values=(api_token,))
+
+
+def _format_filter_timestamp(value: Any) -> str:
+ """Format an incremental cursor for Rippling's OData-style filter (e.g. updated_at ge 2024-10-01T00:00:00)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00")
+ return str(value)
+
+
+def _build_params(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ cursor_field = incremental_field or "updated_at"
+ params["filter"] = f"{cursor_field} ge {_format_filter_timestamp(db_incremental_field_last_value)}"
+ # Ascending order on the cursor field so the incremental watermark
+ # advances monotonically as pages are consumed (order_by defaults to asc).
+ params["order_by"] = cursor_field
+ else:
+ # Full refresh: a stable creation-time sort prevents page-boundary
+ # skips/duplicates if rows change mid-sync.
+ params["order_by"] = "created_at"
+
+ return params
+
+
+def _absolutize_next_url(next_link: str) -> str:
+ """Absolutize a pagination link against the Rippling host, rejecting off-domain targets.
+
+ The session carries the user's bearer token in its default headers, so a malicious or
+ buggy `next_link` pointing at another host could leak that token. Only https URLs on the
+ Rippling API host (or relative paths resolving to it) are allowed."""
+ next_url = urljoin(RIPPLING_BASE_URL, next_link)
+ parts = urlsplit(next_url)
+ if parts.scheme != "https" or parts.netloc != RIPPLING_HOST:
+ raise ValueError(f"Rippling pagination link points off-domain: {next_link}")
+ return next_url
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ if not params:
+ return f"{RIPPLING_BASE_URL}{path}"
+ return f"{RIPPLING_BASE_URL}{path}?{urlencode(params)}"
+
+
+def validate_credentials(api_token: str) -> bool:
+ """Confirm the API token is valid with a cheap one-company listing probe.
+
+ Scoped tokens may lack individual dataset scopes (403); only 401 means the
+ token itself is bad, so 403 is accepted at source-create time."""
+ try:
+ response = _get_session(api_token).get(
+ _build_url("/companies", {"limit": 1}),
+ timeout=10,
+ )
+ return response.status_code != 401
+ except Exception:
+ return False
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RipplingResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = RIPPLING_ENDPOINTS[endpoint]
+ session = _get_session(api_token)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url: str = resume_config.next_url
+ logger.debug(f"Rippling: resuming {endpoint} from URL: {url}")
+ else:
+ url = _build_url(
+ config.path,
+ _build_params(should_use_incremental_field, db_incremental_field_last_value, incremental_field),
+ )
+
+ @retry(
+ retry=retry_if_exception_type((RipplingRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise RipplingRetryableError(
+ f"Rippling API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Rippling API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+ items = data.get("results", []) or []
+
+ if items:
+ yield items
+
+ next_link = data.get("next_link")
+ if not next_link:
+ break
+
+ # next_link can be a relative path; absolutize against the API host and
+ # reject any off-domain target before reusing the token-bearing session.
+ next_url = _absolutize_next_url(next_link)
+ # 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(RipplingResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def rippling_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RipplingResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = RIPPLING_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_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,
+ incremental_field=incremental_field,
+ ),
+ 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,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/rippling/settings.py b/posthog/temporal/data_imports/sources/rippling/settings.py
new file mode 100644
index 000000000000..fa9d668ca3b0
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/rippling/settings.py
@@ -0,0 +1,82 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+# Every Rippling REST list endpoint supports the same standard query params
+# (cursor/limit pagination, OData-style `filter`, `order_by` on id/created_at/
+# updated_at), so the incremental menu is shared.
+_STANDARD_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass
+class RipplingEndpointConfig:
+ name: str
+ path: str
+ primary_key: str = "id"
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_STANDARD_INCREMENTAL_FIELDS))
+ # Stable creation-time field used for datetime partitioning. Never an
+ # updated_at-style field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+
+
+RIPPLING_ENDPOINTS: dict[str, RipplingEndpointConfig] = {
+ "workers": RipplingEndpointConfig(
+ name="workers",
+ path="/workers",
+ partition_key="created_at",
+ ),
+ "users": RipplingEndpointConfig(
+ name="users",
+ path="/users",
+ partition_key="created_at",
+ ),
+ "companies": RipplingEndpointConfig(
+ name="companies",
+ path="/companies",
+ ),
+ "departments": RipplingEndpointConfig(
+ name="departments",
+ path="/departments",
+ ),
+ "teams": RipplingEndpointConfig(
+ name="teams",
+ path="/teams",
+ ),
+ "levels": RipplingEndpointConfig(
+ name="levels",
+ path="/levels",
+ ),
+ "work_locations": RipplingEndpointConfig(
+ name="work_locations",
+ path="/work-locations",
+ ),
+ "employment_types": RipplingEndpointConfig(
+ name="employment_types",
+ path="/employment-types",
+ ),
+ "compensations": RipplingEndpointConfig(
+ name="compensations",
+ path="/compensations",
+ partition_key="created_at",
+ ),
+}
+
+ENDPOINTS = tuple(RIPPLING_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in RIPPLING_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/rippling/source.py b/posthog/temporal/data_imports/sources/rippling/source.py
index 3418868bbea2..c1bc22d39a23 100644
--- a/posthog/temporal/data_imports/sources/rippling/source.py
+++ b/posthog/temporal/data_imports/sources/rippling/source.py
@@ -1,29 +1,116 @@
-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 RipplingSourceConfig
+from posthog.temporal.data_imports.sources.rippling.rippling import (
+ RipplingResumeConfig,
+ rippling_source,
+ validate_credentials as validate_rippling_credentials,
+)
+from posthog.temporal.data_imports.sources.rippling.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class RipplingSource(SimpleSource[RipplingSourceConfig]):
+class RipplingSource(ResumableSource[RipplingSourceConfig, RipplingResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.RIPPLING
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://rest.ripplingapis.com": "Rippling authentication failed. Please check your API token (tokens expire after 30 days of inactivity).",
+ "403 Client Error: Forbidden for url: https://rest.ripplingapis.com": "Rippling denied access. Please check that your API token has the read scope enabled for this dataset.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.RIPPLING,
label="Rippling",
+ caption="""Enter your Rippling API token to pull your Rippling workforce data into the PostHog Data warehouse.
+
+A Rippling admin can create a scoped API token under Settings > Company Settings > API Access. Enable the read scope for each dataset you want to sync (e.g. `companies.read`, `users.read`, `workers.read`, `departments.read`, `teams.read`, `levels.read`, `work-locations.read`, `employment-types.read`, `compensations.read`). Note that tokens expire after 30 days of inactivity.""",
iconPath="/static/services/rippling.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/rippling",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: RipplingSourceConfig,
+ 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: RipplingSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_rippling_credentials(config.api_token):
+ return True, None
+
+ return False, "Invalid Rippling API token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RipplingResumeConfig]:
+ return ResumableSourceManager[RipplingResumeConfig](inputs, RipplingResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: RipplingSourceConfig,
+ resumable_source_manager: ResumableSourceManager[RipplingResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return rippling_source(
+ api_token=config.api_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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/rippling/tests/test_rippling.py b/posthog/temporal/data_imports/sources/rippling/tests/test_rippling.py
new file mode 100644
index 000000000000..94d708be7416
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/rippling/tests/test_rippling.py
@@ -0,0 +1,248 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.rippling.rippling import (
+ PAGE_SIZE,
+ RipplingResumeConfig,
+ _absolutize_next_url,
+ _build_params,
+ _build_url,
+ _format_filter_timestamp,
+ get_rows,
+ rippling_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.rippling.settings import ENDPOINTS, RIPPLING_ENDPOINTS
+
+
+def _make_manager(resume_state: RipplingResumeConfig | 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(items: list[dict[str, Any]], next_link: str | None = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = {"results": items, "next_link": next_link}
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+class TestFormatFilterTimestamp:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2024, 10, 1, 3, 4, 5, tzinfo=UTC), "2024-10-01T03:04:05"),
+ (datetime(2024, 10, 1, 3, 4, 5), "2024-10-01T03:04:05"),
+ (date(2024, 10, 1), "2024-10-01T00:00:00"),
+ ("2024-10-01T00:00:00", "2024-10-01T00:00:00"),
+ ],
+ )
+ def test_format_values(self, value, expected):
+ assert _format_filter_timestamp(value) == expected
+
+
+class TestBuildParams:
+ def test_incremental_builds_odata_filter_and_sort(self):
+ params = _build_params(
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 10, 1, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+
+ assert params["filter"] == "updated_at ge 2024-10-01T00:00:00"
+ assert params["order_by"] == "updated_at"
+ assert params["limit"] == PAGE_SIZE
+
+ def test_incremental_honors_created_at_cursor(self):
+ params = _build_params(
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 10, 1, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+
+ assert params["filter"] == "created_at ge 2024-10-01T00:00:00"
+ assert params["order_by"] == "created_at"
+
+ def test_incremental_without_last_value_falls_back_to_full_refresh_sort(self):
+ params = _build_params(
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="updated_at",
+ )
+
+ assert "filter" not in params
+ assert params["order_by"] == "created_at"
+
+ def test_full_refresh_sorts_on_stable_creation_date(self):
+ params = _build_params(
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+
+ assert "filter" not in params
+ assert params["order_by"] == "created_at"
+
+
+class TestBuildUrl:
+ def test_encodes_filter_expression(self):
+ url = _build_url("/workers", {"limit": 100, "filter": "updated_at ge 2024-10-01T00:00:00"})
+ parsed = urlparse(url)
+ assert parsed.netloc == "rest.ripplingapis.com"
+ assert parse_qs(parsed.query)["filter"] == ["updated_at ge 2024-10-01T00:00:00"]
+
+
+class TestAbsolutizeNextUrl:
+ @pytest.mark.parametrize(
+ "next_link, expected",
+ [
+ ("/workers?cursor=abc", "https://rest.ripplingapis.com/workers?cursor=abc"),
+ (
+ "https://rest.ripplingapis.com/workers?cursor=xyz",
+ "https://rest.ripplingapis.com/workers?cursor=xyz",
+ ),
+ ],
+ )
+ def test_allows_on_domain_links(self, next_link, expected):
+ assert _absolutize_next_url(next_link) == expected
+
+ @pytest.mark.parametrize(
+ "next_link",
+ [
+ "https://attacker.example/workers",
+ "//attacker.example/workers",
+ "http://rest.ripplingapis.com/workers",
+ "https://rest.ripplingapis.com.attacker.example/workers",
+ ],
+ )
+ def test_rejects_off_domain_links(self, next_link):
+ with pytest.raises(ValueError):
+ _absolutize_next_url(next_link)
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ # A valid token without the companies.read scope still 403s; only 401
+ # means the token itself is bad.
+ (403, True),
+ (401, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.rippling.rippling.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.rippling.rippling.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 TestGetRows:
+ @mock.patch("posthog.temporal.data_imports.sources.rippling.rippling.make_tracked_session")
+ def test_paginates_via_next_link_and_absolutizes_relative_urls(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "1"}], next_link="/workers?limit=100&cursor=abc"),
+ _response([{"id": "2"}]),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "workers", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2"]
+ manager.save_state.assert_called_once()
+ saved_url = manager.save_state.call_args.args[0].next_url
+ assert saved_url == "https://rest.ripplingapis.com/workers?limit=100&cursor=abc"
+ assert mock_session.return_value.get.call_args_list[1].args[0] == saved_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.rippling.rippling.make_tracked_session")
+ def test_absolute_next_link_used_as_is(self, mock_session):
+ absolute = "https://rest.ripplingapis.com/workers?cursor=xyz"
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "1"}], next_link=absolute),
+ _response([]),
+ ]
+
+ manager = _make_manager()
+ list(get_rows("token", "workers", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_args_list[1].args[0] == absolute
+
+ @mock.patch("posthog.temporal.data_imports.sources.rippling.rippling.make_tracked_session")
+ def test_resumes_from_saved_state(self, mock_session):
+ mock_session.return_value.get.return_value = _response([{"id": "9"}])
+
+ resume_url = "https://rest.ripplingapis.com/workers?cursor=resume"
+ manager = _make_manager(RipplingResumeConfig(next_url=resume_url))
+
+ list(get_rows("token", "workers", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.rippling.rippling.make_tracked_session")
+ def test_incremental_request_includes_filter(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "token",
+ "workers",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 10, 1, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ query = parse_qs(urlparse(url).query)
+ assert query["filter"] == ["updated_at ge 2024-10-01T00:00:00"]
+ assert query["order_by"] == ["updated_at"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.rippling.rippling.make_tracked_session")
+ def test_empty_response_stops_without_saving_state(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "workers", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+
+class TestRipplingSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = RIPPLING_ENDPOINTS[endpoint]
+ response = rippling_source("token", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ 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(RIPPLING_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key == "created_at"
diff --git a/posthog/temporal/data_imports/sources/rippling/tests/test_rippling_source.py b/posthog/temporal/data_imports/sources/rippling/tests/test_rippling_source.py
new file mode 100644
index 000000000000..eb689e0b043b
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/rippling/tests/test_rippling_source.py
@@ -0,0 +1,141 @@
+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 RipplingSourceConfig
+from posthog.temporal.data_imports.sources.rippling.rippling import RipplingResumeConfig
+from posthog.temporal.data_imports.sources.rippling.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.rippling.source import RipplingSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestRipplingSource:
+ def setup_method(self):
+ self.source = RipplingSource()
+ self.team_id = 123
+ self.config = RipplingSourceConfig(api_token="api-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.RIPPLING
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Rippling"
+ assert config.label == "Rippling"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/rippling.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_token"]
+
+ def test_api_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 == "api_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://rest.ripplingapis.com/workers?limit=100",
+ "403 Client Error: Forbidden for url: https://rest.ripplingapis.com/compensations",
+ ],
+ )
+ 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://rest.ripplingapis.com/workers",
+ ],
+ )
+ 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)
+ # Every Rippling list endpoint supports the standard OData-style filter.
+ assert all(schema.supports_incremental for schema in schemas)
+ assert all(schema.supports_append for schema in schemas)
+
+ def test_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["workers"].incremental_fields == INCREMENTAL_FIELDS["workers"]
+ assert {f["field"] for f in schemas["workers"].incremental_fields} == {"updated_at", "created_at"}
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["workers"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "workers"
+
+ 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 Rippling API token"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.rippling.source.validate_rippling_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.api_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 RipplingResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.rippling.source.rippling_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_rippling_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "workers"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-10-01T00:00:00"
+ inputs.incremental_field = "updated_at"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_rippling_source.assert_called_once()
+ kwargs = mock_rippling_source.call_args.kwargs
+ assert kwargs["api_token"] == "api-token"
+ assert kwargs["endpoint"] == "workers"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-10-01T00:00:00"
+ assert kwargs["incremental_field"] == "updated_at"
+
+ @mock.patch("posthog.temporal.data_imports.sources.rippling.source.rippling_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_rippling_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "companies"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-10-01T00:00:00"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_rippling_source.call_args.kwargs["db_incremental_field_last_value"] is None