: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
fix(data-warehouse): reduce RevenueCat source connection errors (#62414)
Tom Owers1f3c4be7048a
diff --git a/posthog/temporal/data_imports/sources/revenuecat/revenuecat.py b/posthog/temporal/data_imports/sources/revenuecat/revenuecat.pyindex 45f0feb007eb..f34bd1fb4d6f 100644--- a/posthog/temporal/data_imports/sources/revenuecat/revenuecat.py+++ b/posthog/temporal/data_imports/sources/revenuecat/revenuecat.py@@ -61,6 +61,72 @@ def _project_path(project_id: str, suffix: str) -> str:return f"/projects/{project_id}{suffix}"+# How many accessible project ids we list back when an entered id 404s. Most keys+# see a single project, so this is really just a guard against a wall of text.+MAX_SUGGESTED_PROJECTS = 5+++def _normalize_project_id(raw: str | None) -> str:+ """Best-effort cleanup of a user-entered RevenueCat project id.++ The setup form points users at their dashboard URL+ (``app.revenuecat.com/projects/<project_id>``) to find the id, so a large+ share of connection failures come from pasting the whole URL, a+ ``projects/<id>`` path fragment, or a value with stray whitespace. Pull the+ id back out and trim it so those copy-paste mistakes don't become a 404.+ """+ if not raw:+ return ""+ value = raw.strip()+ # Pasted a full or partial dashboard URL / `.../projects/<id>/...` path. The+ # marker has no leading slash so it matches both `/projects/x` and the+ # bare `projects/x` form.+ marker = "projects/"+ if marker in value:+ value = value.split(marker, 1)[1]+ # Keep only the first path segment, dropping any trailing `/overview`,+ # query string, or fragment that rode along with the paste.+ value = value.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0]+ return value.strip()+++def _accessible_project_ids(payload: dict[str, Any] | None) -> list[str]:+ """Pull the project ids out of a ``GET /v2/projects`` response.++ We deliberately keep only the ids (opaque ``proj...`` tokens), never the+ project names — the error string built from this is captured into our+ analytics, and names can carry a customer's app/company identity.+ """+ items = (payload or {}).get("items")+ if not isinstance(items, list):+ return []+ return [str(item["id"]) for item in items if isinstance(item, dict) and item.get("id")]+++def _project_not_found_error(entered_project_id: str, accessible_ids: list[str]) -> str:+ """Turn an opaque 404 into an actionable message naming the reachable project ids."""+ if not accessible_ids:+ return (+ f"RevenueCat could not find the project '{entered_project_id}' (404), and this API key "+ "can't see any projects. Generate a v2 secret API key in the RevenueCat project you want "+ "to sync, then re-enter its Project ID."+ )+ if len(accessible_ids) == 1:+ only = accessible_ids[0]+ return (+ f"RevenueCat has no project '{entered_project_id}' for this API key. The key has access to "+ f"one project — '{only}'. Set the Project ID to '{only}' and reconnect."+ )+ shown = accessible_ids[:MAX_SUGGESTED_PROJECTS]+ listed = ", ".join(f"'{pid}'" for pid in shown)+ overflow = len(accessible_ids) - MAX_SUGGESTED_PROJECTS+ more = f" (+{overflow} more)" if overflow > 0 else ""+ return (+ f"RevenueCat has no project '{entered_project_id}' for this API key. The key has access to: "+ f"{listed}{more}. Copy the exact Project ID from your RevenueCat dashboard and reconnect."+ )++def _format_http_error(error: requests.HTTPError) -> str:response = error.responsestatus_code = response.status_code if response is not None else None@@ -82,11 +148,14 @@ def _format_http_error(error: requests.HTTPError) -> str:def validate_credentials(api_key: str, project_id: str | None) -> tuple[bool, str | None]:- """Probe the cheapest endpoint that confirms the key + project.-- GET /v2/projects lists every project the key can see — that's enough to- confirm the key is genuine. If a ``project_id`` is set, we additionally- fetch that project to catch typos and revoked-project access.+ """Confirm the key works and (when set) that it can reach ``project_id``.++ ``GET /v2/projects`` both validates the key and tells us every project the+ key can see. We keep that list so that if the per-project follow-up 404s —+ by far the most common failure — we can name the project ids the key *can*+ reach instead of a dead-end "double-check the project id". The entered id is+ normalized first so a pasted dashboard URL or stray whitespace doesn't+ masquerade as a missing project."""session = _session(api_key)try:@@ -97,17 +166,27 @@ def validate_credentials(api_key: str, project_id: str | None) -> tuple[bool, stexcept requests.RequestException as e:return False, f"Could not reach RevenueCat: {e}"- if project_id:- try:- response = session.get(- f"{REVENUECAT_API_BASE_URL}/projects/{project_id}",- timeout=REQUEST_TIMEOUT_SECONDS,- )- response.raise_for_status()- except requests.HTTPError as e:- return False, _format_http_error(e)- except requests.RequestException as e:- return False, f"Could not reach RevenueCat: {e}"+ normalized_project_id = _normalize_project_id(project_id)+ if not normalized_project_id:+ return True, None++ try:+ accessible_ids = _accessible_project_ids(response.json() or {})+ except (ValueError, requests.exceptions.JSONDecodeError):+ accessible_ids = []++ try:+ response = session.get(+ f"{REVENUECAT_API_BASE_URL}/projects/{normalized_project_id}",+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ except requests.HTTPError as e:+ if e.response is not None and e.response.status_code == 404:+ return False, _project_not_found_error(normalized_project_id, accessible_ids)+ return False, _format_http_error(e)+ except requests.RequestException as e:+ return False, f"Could not reach RevenueCat: {e}"return True, None@@ -153,6 +232,7 @@ def iterate_list_endpoint(save state *after* yielding so a crash re-yields the last page rather thanskipping it — merge dedupes on primary key."""+ project_id = _normalize_project_id(project_id)session = _session(api_key)params: dict[str, Any] = {"limit": DEFAULT_PAGE_SIZE}if starting_after:@@ -215,6 +295,7 @@ def create_webhook(is created without an auth header and the user finishes setup by adding onevia the webhook fields (handled by the surrounding warehouse-source flow)."""+ project_id = _normalize_project_id(project_id)logger = LOGGER.bind(project_id=project_id)body: dict[str, Any] = {@@ -307,6 +388,7 @@ def _find_webhook_integration(api_key: str, project_id: str, webhook_url: str) -def delete_webhook(api_key: str, project_id: str, webhook_url: str) -> WebhookDeletionResult:+ project_id = _normalize_project_id(project_id)logger = LOGGER.bind(project_id=project_id)try:@@ -347,6 +429,7 @@ def delete_webhook(api_key: str, project_id: str, webhook_url: str) -> WebhookDedef get_external_webhook_info(api_key: str, project_id: str, webhook_url: str) -> ExternalWebhookInfo:+ project_id = _normalize_project_id(project_id)try:integrations = _list_webhook_integrations(api_key, project_id)except requests.HTTPError as e:diff --git a/posthog/temporal/data_imports/sources/revenuecat/source.py b/posthog/temporal/data_imports/sources/revenuecat/source.pyindex 2ca5b1f19fcf..6480a8c9c574 100644--- a/posthog/temporal/data_imports/sources/revenuecat/source.py+++ b/posthog/temporal/data_imports/sources/revenuecat/source.py@@ -142,7 +142,9 @@ class RevenueCatSource(required=True,placeholder="proj1a2b3c4d5e",caption=(- "Find this in your RevenueCat dashboard URL: `app.revenuecat.com/projects/<project_id>`."+ "The id that starts with `proj`, found in your RevenueCat dashboard URL: "+ "`app.revenuecat.com/projects/<project_id>`. You can paste either the id "+ "or the full URL."),secret=False,),diff --git a/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py b/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.pyindex 745d4dc43eff..c3a027f07596 100644--- a/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py+++ b/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py@@ -107,6 +107,34 @@ class TestValidateCredentials:assert error is not Noneassert expected_substring.lower() in error.lower()+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")+ def test_skips_project_check_when_id_normalizes_to_empty(self, mock_session):+ # A whitespace-only id is truthy as a raw string but empty once trimmed,+ # so it must not trigger a `GET /projects/` with an empty path segment.+ mock_session.return_value.get.return_value = _ok_json_response({"items": []})++ success, error = api_client.validate_credentials("sk_test", project_id=" ")++ assert success is True+ assert error is None+ assert mock_session.return_value.get.call_count == 1++ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")+ def test_tolerates_invalid_json_on_projects_list(self, mock_session):+ # If `GET /projects` returns a 200 with an unparseable body, we should+ # still run the per-project check rather than crashing on `.json()`.+ bad_list = _ok_json_response({"items": []})+ bad_list.json.side_effect = requests.exceptions.JSONDecodeError("boom", "", 0)+ mock_session.return_value.get.side_effect = [+ bad_list,+ _ok_json_response({"id": "proj_test"}),+ ]++ success, error = api_client.validate_credentials("sk_test", project_id="proj_test")++ assert success is True+ assert error is None+class TestIterateListEndpoint:@patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")@@ -436,3 +464,142 @@ class TestGetExternalWebhookInfo:class TestProjectPath:def test_combines_project_id_with_suffix(self):assert api_client._project_path("proj_test", "/customers") == "/projects/proj_test/customers"+++class TestNormalizeProjectId:+ @parameterized.expand(+ [+ ("plain_id", "proj1a2b3c4d", "proj1a2b3c4d"),+ ("leading_and_trailing_whitespace", " proj1a2b3c4d ", "proj1a2b3c4d"),+ ("full_https_url", "https://app.revenuecat.com/projects/proj1a2b3c4d", "proj1a2b3c4d"),+ ("url_without_scheme", "app.revenuecat.com/projects/proj1a2b3c4d", "proj1a2b3c4d"),+ ("url_with_trailing_path", "https://app.revenuecat.com/projects/proj1a2b3c4d/overview", "proj1a2b3c4d"),+ ("url_with_query_string", "app.revenuecat.com/projects/proj1a2b3c4d?tab=settings", "proj1a2b3c4d"),+ ("url_with_fragment", "app.revenuecat.com/projects/proj1a2b3c4d#section", "proj1a2b3c4d"),+ ("bare_projects_path_fragment", "projects/proj1a2b3c4d", "proj1a2b3c4d"),+ ("trailing_slash", "proj1a2b3c4d/", "proj1a2b3c4d"),+ ("none", None, ""),+ ("empty", "", ""),+ ("whitespace_only", " ", ""),+ ]+ )+ def test_normalizes(self, _name, raw, expected):+ assert api_client._normalize_project_id(raw) == expected+++class TestAccessibleProjectIds:+ def test_extracts_ids_in_order(self):+ payload = {"items": [{"id": "proj_a", "name": "A"}, {"id": "proj_b"}]}++ assert api_client._accessible_project_ids(payload) == ["proj_a", "proj_b"]++ @parameterized.expand(+ [+ ("empty_items", {"items": []}),+ ("missing_items", {}),+ ("none_payload", None),+ ("items_not_a_list", {"items": "nope"}),+ ("rows_missing_id", {"items": [{"name": "A"}, "noise", 42]}),+ ]+ )+ def test_returns_empty_for_unusable_payloads(self, _name, payload):+ assert api_client._accessible_project_ids(payload) == []+++class TestValidateCredentialsProjectSuggestions:+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")+ def test_404_lists_single_accessible_project(self, mock_session):+ # The key works (it can list projects) but the entered id doesn't exist.+ # The error should name the one project the key can actually reach.+ mock_session.return_value.get.side_effect = [+ _ok_json_response({"items": [{"id": "proj_real", "name": "My App"}]}),+ _http_error_response(404),+ ]++ success, error = api_client.validate_credentials("sk_test", project_id="proj_typo")++ assert success is False+ assert error is not None+ assert "proj_typo" in error+ assert "proj_real" in error+ # Project names are deliberately never surfaced (they land in analytics).+ assert "My App" not in error++ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")+ def test_404_lists_multiple_accessible_projects(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _ok_json_response({"items": [{"id": "proj_a"}, {"id": "proj_b"}]}),+ _http_error_response(404),+ ]++ success, error = api_client.validate_credentials("sk_test", project_id="proj_typo")++ assert success is False+ assert error is not None+ assert "proj_a" in error and "proj_b" in error++ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")+ def test_404_with_no_accessible_projects_falls_back_to_generic_message(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _ok_json_response({"items": []}),+ _http_error_response(404),+ ]++ success, error = api_client.validate_credentials("sk_test", project_id="proj_typo")++ assert success is False+ assert error is not None+ assert "could not find" in error.lower()++ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")+ def test_normalizes_pasted_url_before_checking_project(self, mock_session):+ # A user pastes the whole dashboard URL — we should look up the bare id,+ # so the per-project request must hit `/projects/proj_real`, not the URL.+ mock_session.return_value.get.side_effect = [+ _ok_json_response({"items": [{"id": "proj_real"}]}),+ _ok_json_response({"id": "proj_real"}),+ ]++ success, error = api_client.validate_credentials(+ "sk_test", project_id="https://app.revenuecat.com/projects/proj_real/overview"+ )++ assert success is True+ assert error is None+ second_call_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert second_call_url == f"{REVENUECAT_API_BASE_URL}/projects/proj_real"++ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")+ def test_non_404_project_error_still_uses_generic_formatter(self, mock_session):+ # A 403 on the per-project call isn't a "wrong id" problem, so it should+ # not be reworded into a project-suggestion message.+ mock_session.return_value.get.side_effect = [+ _ok_json_response({"items": [{"id": "proj_real"}]}),+ _http_error_response(403),+ ]++ success, error = api_client.validate_credentials("sk_test", project_id="proj_real")++ assert success is False+ assert error is not None+ assert "denied" in error.lower()+++class TestIterateListEndpointNormalization:+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")+ def test_normalizes_project_id_in_request_url(self, mock_session):+ # A stored value that's actually a pasted URL must still resolve to the+ # bare project path during sync.+ mock_session.return_value.get.return_value = _ok_json_response({"items": [], "next_page": None})++ list(+ api_client.iterate_list_endpoint(+ "sk_test",+ project_id="https://app.revenuecat.com/projects/proj_real",+ path_suffix="/customers",+ endpoint_name="customers",+ )+ )++ called_url = mock_session.return_value.get.call_args.args[0]+ assert called_url == f"{REVENUECAT_API_BASE_URL}/projects/proj_real/customers"