: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 ramp import source (#62981)
Tom Owers9dc28393e8f6
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex a72ec1590906..d4d1f39e4150 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -141,6 +141,7 @@ the row lists both.| postmark | HTTP | requests | ✅ || productboard | HTTP | requests | ✅ || recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |+| ramp | HTTP | requests | ✅ || recharge | HTTP | requests | ✅ || reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |@@ -284,7 +285,6 @@ doesn't conflict with concurrent PRs.- planetscale- qualtrics- quickbooks-- ramp- ringcentral- sage_intacct- sailthrudiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 3b49759bed39..f5f35afed932 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -1075,7 +1075,9 @@ class QuickBooksSourceConfig(config.Config):@config.configclass RampSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ environment: Literal["production", "sandbox"] = config.value(default="production")@config.configdiff --git a/posthog/temporal/data_imports/sources/ramp/ramp.py b/posthog/temporal/data_imports/sources/ramp/ramp.pynew file mode 100644index 000000000000..82a503bc4e1e--- /dev/null+++ b/posthog/temporal/data_imports/sources/ramp/ramp.py@@ -0,0 +1,219 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, 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.ramp.settings import RAMP_ENDPOINTS, TOKEN_SCOPES, RampEndpointConfig++RAMP_HOSTS = {+ "production": "https://api.ramp.com",+ "sandbox": "https://demo-api.ramp.com",+}+# Ramp list pages cap at 100 items.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# ~100 req/min per token; 429s back off.+MAX_RETRY_ATTEMPTS = 5+++class RampRetryableError(Exception):+ pass+++class RampResumeConfig:+ # Ramp paginates via the self-contained page.next URL.+ next_url: str+++def _get_session(client_secret: str) -> requests.Session:+ return make_tracked_session(redact_values=(client_secret,))+++def _base_url(environment: str) -> str:+ host = RAMP_HOSTS.get(environment)+ if host is None:+ raise ValueError(f"Invalid Ramp environment: {environment}")+ return host+++def _assert_trusted_url(url: str, environment: str) -> str:+ """Pin a pagination/resume URL to the configured Ramp host before forwarding the bearer token.++ Both the API-derived ``page.next`` value and the Redis-persisted resume URL are+ attacker-influenceable, so we refuse to send credentials anywhere other than the+ environment's own scheme + host."""+ base = urlsplit(_base_url(environment))+ target = urlsplit(url)+ if (target.scheme, target.netloc) != (base.scheme, base.netloc):+ raise ValueError(f"Refusing to send Ramp credentials to untrusted URL host: {target.netloc or url!r}")+ return url+++def _mint_token(session: requests.Session, environment: str, client_id: str, client_secret: str) -> str:+ """Exchange client credentials for a bearer token (~10 day lifetime)."""+ response = session.post(+ f"{_base_url(environment)}/developer/v1/token",+ data={"grant_type": "client_credentials", "scope": TOKEN_SCOPES},+ auth=(client_id, client_secret),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ return response.json()["access_token"]+++def _format_timestamp(value: Any) -> str:+ """Format an incremental cursor for Ramp's from_date filter (ISO 8601 UTC)."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ return str(value)+++def _build_initial_url(+ environment: str,+ config: RampEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str:+ params: dict[str, Any] = {"page_size": PAGE_SIZE}+ if (+ config.incremental_param is not None+ and should_use_incremental_field+ and db_incremental_field_last_value is not None+ ):+ params[config.incremental_param] = _format_timestamp(db_incremental_field_last_value)+ return f"{_base_url(environment)}/developer/v1{config.path}?{urlencode(params)}"+++def validate_credentials(environment: str, client_id: str, client_secret: str) -> tuple[bool, str | None]:+ """Confirm the developer app credentials are valid by minting a token.++ Distinguishes a genuine credential rejection (4xx) from a transient connectivity problem so the+ user sees an actionable message instead of a blanket "invalid credentials"."""+ try:+ _mint_token(_get_session(client_secret), environment, client_id, client_secret)+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status in (401, 403):+ return (+ False,+ "Ramp rejected the credentials. Check the client ID and secret, and that the developer "+ "app has the required scopes.",+ )+ return False, f"Unexpected response from Ramp (status {status})."+ except requests.RequestException as e:+ return False, f"Could not reach Ramp ({e}). Please check your network and selected environment, then retry."+ return True, None+++def get_rows(+ environment: str,+ client_id: str,+ client_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RampResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = RAMP_ENDPOINTS[endpoint]+ session = _get_session(client_secret)+ token = _mint_token(session, environment, client_id, client_secret)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ url: str = _assert_trusted_url(resume_config.next_url, environment)+ logger.debug(f"Ramp: resuming {endpoint} from URL: {url}")+ else:+ url = _build_initial_url(environment, config, should_use_incremental_field, db_incremental_field_last_value)++ @retry(+ retry=retry_if_exception_type((RampRetryableError, 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]:+ nonlocal token+ response = session.get(page_url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)++ # Tokens last ~10 days; re-mint once defensively if one ever expires+ # mid-sync.+ if response.status_code == 401:+ token = _mint_token(session, environment, client_id, client_secret)+ response = session.get(+ page_url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise RampRetryableError(f"Ramp API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"Ramp 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("data", []) or []++ if items:+ yield items++ next_url = (data.get("page") or {}).get("next")+ if not next_url or not items:+ break++ next_url = _assert_trusted_url(next_url, environment)+ # 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(RampResumeConfig(next_url=next_url))+ url = next_url+++def ramp_source(+ environment: str,+ client_id: str,+ client_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RampResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = RAMP_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ environment=environment,+ client_id=client_id,+ client_secret=client_secret,+ 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,+ # Result ordering within a from_date window is not documented, so the+ # pipeline defers incremental watermark commits until a run completes.+ sort_mode="desc" if config.incremental_fields else "asc",+ )diff --git a/posthog/temporal/data_imports/sources/ramp/settings.py b/posthog/temporal/data_imports/sources/ramp/settings.pynew file mode 100644index 000000000000..cef7f14a3a8f--- /dev/null+++ b/posthog/temporal/data_imports/sources/ramp/settings.py@@ -0,0 +1,64 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Scopes requested when minting the client-credentials token. Scopes are fixed+# on the developer app at creation, so the caption tells users to grant these.+TOKEN_SCOPES = "transactions:read reimbursements:read users:read cards:read departments:read"+++@dataclass+class RampEndpointConfig:+ name: str+ # Path under {host}/developer/v1.+ path: str+ primary_key: str = "id"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Query param that pushes the incremental cursor server-side.+ incremental_param: Optional[str] = None+ # Stable event-time field used for datetime partitioning.+ partition_key: Optional[str] = None+++RAMP_ENDPOINTS: dict[str, RampEndpointConfig] = {+ "transactions": RampEndpointConfig(+ name="transactions",+ path="/transactions",+ partition_key="user_transaction_time",+ # from_date filters on the transaction time. There is no updated_after,+ # so late state changes (pending→cleared) need an occasional full+ # refresh — the same trade-off Fivetran makes.+ incremental_param="from_date",+ incremental_fields=[+ {+ "label": "user_transaction_time",+ "type": IncrementalFieldType.DateTime,+ "field": "user_transaction_time",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "reimbursements": RampEndpointConfig(+ name="reimbursements",+ path="/reimbursements",+ ),+ "users": RampEndpointConfig(+ name="users",+ path="/users",+ ),+ "cards": RampEndpointConfig(+ name="cards",+ path="/cards",+ ),+ "departments": RampEndpointConfig(+ name="departments",+ path="/departments",+ ),+}++ENDPOINTS = tuple(RAMP_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in RAMP_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/ramp/source.py b/posthog/temporal/data_imports/sources/ramp/source.pyindex d454a1b6d832..f29531dd3a2c 100644--- a/posthog/temporal/data_imports/sources/ramp/source.py+++ b/posthog/temporal/data_imports/sources/ramp/source.py@@ -1,29 +1,144 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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, ResumableSourcefrom 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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import RampSourceConfig+from posthog.temporal.data_imports.sources.ramp.ramp import (+ RampResumeConfig,+ ramp_source,+ validate_credentials as validate_ramp_credentials,+)+from posthog.temporal.data_imports.sources.ramp.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class RampSource(SimpleSource[RampSourceConfig]):+class RampSource(ResumableSource[RampSourceConfig, RampResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RAMP+ @property+ def connection_host_fields(self) -> list[str]:+ # ``environment`` picks api.ramp.com vs demo-api.ramp.com, so changing it retargets where the+ # stored client secret is sent — require re-entering secrets when it changes.+ return ["environment"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.ramp.com/developer/v1/token": "Ramp authentication failed. Please check your client ID and client secret.",+ "401 Client Error: Unauthorized for url: https://demo-api.ramp.com/developer/v1/token": "Ramp authentication failed. Please check your client ID and client secret (and that they match the selected environment).",+ "400 Client Error: Bad Request for url: https://api.ramp.com/developer/v1/token": "Ramp rejected the token request. Please check that your developer app has the required read scopes granted.",+ "400 Client Error: Bad Request for url: https://demo-api.ramp.com/developer/v1/token": "Ramp rejected the token request. Please check that your developer app has the required read scopes granted.",+ "403 Client Error: Forbidden for url: https://api.ramp.com": "Ramp denied access. Please check that your developer app has the read scope for this dataset.",+ "403 Client Error: Forbidden for url: https://demo-api.ramp.com": "Ramp denied access. Please check that your developer app has the read scope for this dataset.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.RAMP,label="Ramp",+ caption="""Connect your Ramp account to pull your spend data into the PostHog Data warehouse.++A Ramp admin can create a developer app under Settings > Developer API. Grant it the `transactions:read`, `reimbursements:read`, `users:read`, `cards:read`, and `departments:read` scopes (scopes are fixed at app creation) and enable client credentials, then enter the app's client ID and secret here.""",iconPath="/static/services/ramp.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/ramp",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="environment",+ label="Environment",+ required=True,+ defaultValue="production",+ options=[+ SourceFieldSelectConfigOption(label="Production", value="production"),+ SourceFieldSelectConfigOption(label="Sandbox (demo)", value="sandbox"),+ ],+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="ramp_id_...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="ramp_sec_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: RampSourceConfig,+ 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: RampSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_ramp_credentials(config.environment, config.client_id, config.client_secret)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RampResumeConfig]:+ return ResumableSourceManager[RampResumeConfig](inputs, RampResumeConfig)++ def source_for_pipeline(+ self,+ config: RampSourceConfig,+ resumable_source_manager: ResumableSourceManager[RampResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return ramp_source(+ environment=config.environment,+ client_id=config.client_id,+ client_secret=config.client_secret,+ 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/ramp/tests/test_ramp.py b/posthog/temporal/data_imports/sources/ramp/tests/test_ramp.pynew file mode 100644index 000000000000..3e004e21f94e--- /dev/null+++ b/posthog/temporal/data_imports/sources/ramp/tests/test_ramp.py@@ -0,0 +1,242 @@+from datetime import UTC, date, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++import requests++from posthog.temporal.data_imports.sources.ramp.ramp import (+ PAGE_SIZE,+ RampResumeConfig,+ _base_url,+ _format_timestamp,+ get_rows,+ ramp_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.ramp.settings import ENDPOINTS, RAMP_ENDPOINTS, TOKEN_SCOPES++_MODULE = "posthog.temporal.data_imports.sources.ramp.ramp"+++def _make_manager(resume_state: RampResumeConfig | 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 _token_response() -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = {"access_token": "the-token", "expires_in": 864000}+ resp.status_code = 200+ resp.ok = True+ return resp+++def _page_response(items: list[dict[str, Any]], next_url: str | None = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = {"data": items, "page": {"next": next_url}}+ resp.status_code = 200+ resp.ok = True+ return resp+++class TestBaseUrl:+ def test_production_and_sandbox_hosts(self):+ assert _base_url("production") == "https://api.ramp.com"+ assert _base_url("sandbox") == "https://demo-api.ramp.com"++ def test_invalid_environment_raises(self):+ with pytest.raises(ValueError):+ _base_url("evil")+++class TestFormatTimestamp:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),+ ],+ )+ def test_format_values(self, value, expected):+ assert _format_timestamp(value) == expected+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_when_token_mints(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ assert validate_credentials("production", "cid", "sec") == (True, None)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_mint_requests_documented_scopes(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()++ validate_credentials("production", "cid", "sec")++ body = mock_session.return_value.post.call_args.kwargs["data"]+ assert body == {"grant_type": "client_credentials", "scope": TOKEN_SCOPES}+ assert mock_session.return_value.post.call_args.kwargs["auth"] == ("cid", "sec")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_invalid_when_token_mint_rejected(self, mock_session):+ error_response = mock.MagicMock()+ error_response.status_code = 401+ resp = mock.MagicMock()+ resp.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=error_response)+ mock_session.return_value.post.return_value = resp++ is_valid, message = validate_credentials("production", "cid", "sec")+ assert is_valid is False+ assert "credentials" in (message or "")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_transient_error_is_not_reported_as_invalid_credentials(self, mock_session):+ mock_session.return_value.post.side_effect = requests.ConnectionError("connection refused")++ is_valid, message = validate_credentials("production", "cid", "sec")+ assert is_valid is False+ assert "Could not reach Ramp" in (message or "")+++class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_paginates_via_page_next_url(self, mock_session):+ next_url = "https://api.ramp.com/developer/v1/transactions?start=abc&page_size=100"+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [+ _page_response([{"id": "t1"}], next_url=next_url),+ _page_response([{"id": "t2"}]),+ ]++ manager = _make_manager()+ batches = list(get_rows("production", "cid", "sec", "transactions", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["t1", "t2"]+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].next_url == next_url+ assert mock_session.return_value.get.call_args_list[1].args[0] == next_url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_transactions_use_from_date(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _page_response([])++ manager = _make_manager()+ list(+ get_rows(+ "production",+ "cid",+ "sec",+ "transactions",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ )+ )++ url = mock_session.return_value.get.call_args.args[0]+ query = parse_qs(urlparse(url).query)+ assert query["from_date"] == ["2024-01-02T00:00:00Z"]+ assert query["page_size"] == [str(PAGE_SIZE)]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_refresh_has_no_from_date(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _page_response([])++ manager = _make_manager()+ list(get_rows("production", "cid", "sec", "users", mock.MagicMock(), manager))++ url = mock_session.return_value.get.call_args.args[0]+ assert urlparse(url).path == "/developer/v1/users"+ assert "from_date" not in parse_qs(urlparse(url).query)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_remints_token_on_401(self, mock_session):+ expired = mock.MagicMock()+ expired.status_code = 401+ expired.ok = False+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [expired, _page_response([{"id": "t1"}])]++ manager = _make_manager()+ batches = list(get_rows("production", "cid", "sec", "transactions", mock.MagicMock(), manager))++ assert batches == [[{"id": "t1"}]]+ assert mock_session.return_value.post.call_count == 2++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_url(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _page_response([])++ resume_url = "https://api.ramp.com/developer/v1/transactions?start=resume"+ manager = _make_manager(RampResumeConfig(next_url=resume_url))+ list(get_rows("production", "cid", "sec", "transactions", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_page_with_next_url_stops(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _page_response(+ [], next_url="https://api.ramp.com/developer/v1/transactions?start=loop"+ )++ manager = _make_manager()+ batches = list(get_rows("production", "cid", "sec", "transactions", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_rejects_off_host_next_url(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _page_response(+ [{"id": "t1"}], next_url="https://evil.example.com/developer/v1/transactions"+ )++ manager = _make_manager()+ with pytest.raises(ValueError):+ list(get_rows("production", "cid", "sec", "transactions", mock.MagicMock(), manager))++ manager.save_state.assert_not_called()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_rejects_off_host_resume_url(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()++ manager = _make_manager(RampResumeConfig(next_url="https://evil.example.com/developer/v1/transactions"))+ with pytest.raises(ValueError):+ list(get_rows("production", "cid", "sec", "transactions", mock.MagicMock(), manager))+++class TestRampSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = RAMP_ENDPOINTS[endpoint]+ response = ramp_source("production", "cid", "sec", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ # Ordering within incremental windows is undocumented — desc defers+ # the watermark commit to run completion.+ assert response.sort_mode == ("desc" if config.incremental_fields else "asc")+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None++ @pytest.mark.parametrize("config", list(RAMP_ENDPOINTS.values()))+ def test_partition_keys_are_stable_fields(self, config):+ if config.partition_key:+ assert config.partition_key == "user_transaction_time"diff --git a/posthog/temporal/data_imports/sources/ramp/tests/test_ramp_source.py b/posthog/temporal/data_imports/sources/ramp/tests/test_ramp_source.pynew file mode 100644index 000000000000..df7fead3c601--- /dev/null+++ b/posthog/temporal/data_imports/sources/ramp/tests/test_ramp_source.py@@ -0,0 +1,158 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import RampSourceConfig+from posthog.temporal.data_imports.sources.ramp.ramp import RampResumeConfig+from posthog.temporal.data_imports.sources.ramp.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.ramp.source import RampSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestRampSource:+ def setup_method(self):+ self.source = RampSource()+ self.team_id = 123+ self.config = RampSourceConfig(environment="production", client_id="cid", client_secret="sec")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.RAMP++ def test_environment_is_a_connection_host_field(self):+ # Changing environment retargets where the stored client secret is sent, so it must force+ # re-entering secrets.+ assert self.source.connection_host_fields == ["environment"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Ramp"+ assert config.label == "Ramp"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/ramp.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["environment", "client_id", "client_secret"]++ def test_environment_field_is_a_select_with_default(self):+ config = self.source.get_source_config+ env_field = next(f for f in config.fields if f.name == "environment")+ assert isinstance(env_field, SourceFieldSelectConfig)+ assert env_field.defaultValue == "production"+ assert {option.value for option in env_field.options} == {"production", "sandbox"}++ def test_client_secret_field_is_secret_password(self):+ config = self.source.get_source_config+ secret_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret"+ )+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.ramp.com/developer/v1/token",+ "400 Client Error: Bad Request for url: https://demo-api.ramp.com/developer/v1/token",+ "403 Client Error: Forbidden for url: https://api.ramp.com/developer/v1/transactions",+ ],+ )+ 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_error",+ [+ "500 Server Error for url: https://api.ramp.com/developer/v1/transactions",+ # Mid-sync 401s on data endpoints are handled by token re-mint.+ "401 Client Error: Unauthorized for url: https://api.ramp.com/developer/v1/transactions",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_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 transactions expose a usable server-side date filter.+ assert incremental == {"transactions"}++ 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["transactions"].incremental_fields == INCREMENTAL_FIELDS["transactions"]+ assert [f["field"] for f in schemas["transactions"].incremental_fields] == ["user_transaction_time"]+ assert schemas["users"].incremental_fields == []+ assert schemas["users"].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["transactions"])+ assert len(schemas) == 1+ assert schemas[0].name == "transactions"++ 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",+ [+ ((True, None), True),+ ((False, "Ramp rejected the credentials"), False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.ramp.source.validate_ramp_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):+ 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 == mock_return[1]+ mock_validate.assert_called_once_with("production", "cid", "sec")++ 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 RampResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.ramp.source.ramp_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_ramp_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "transactions"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_ramp_source.assert_called_once()+ kwargs = mock_ramp_source.call_args.kwargs+ assert kwargs["environment"] == "production"+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "sec"+ assert kwargs["endpoint"] == "transactions"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"++ @mock.patch("posthog.temporal.data_imports.sources.ramp.source.ramp_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_ramp_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_ramp_source.call_args.kwargs["db_incremental_field_last_value"] is None