: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 the catchpoint systems import source (#112209)
Tom Owers08a9a7c99970
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 5c0137f69676..30f9bba37695 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -179,6 +179,7 @@ the row lists both.| capsule_crm | HTTP | requests | ✅ || care_quality_commission | HTTP | requests | ✅ || cast_ai | HTTP | requests + `rest_source.RESTClient` | ✅ |+| catchpoint | HTTP | requests | ✅ || cdc_open_data | HTTP | requests + `rest_source.RESTClient` | ✅ || census | HTTP | requests + `rest_source.RESTClient` | ✅ || chameleon | HTTP | requests | ✅ |@@ -1012,7 +1013,6 @@ doesn't conflict with concurrent PRs.- cart_com- cashfree- castor_edc-- catchpoint- checkly- chift- chorusdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/canonical_descriptions.pynew file mode 100644index 000000000000..2b1d8fb42d11--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/canonical_descriptions.py@@ -0,0 +1,59 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++DOCS_URL = "https://io.catchpoint.com/api/swagger/v3.0/swagger.json"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "tests": {+ "description": "Synthetic monitoring tests and their configuration.",+ "docs_url": DOCS_URL,+ "columns": {+ "id": "Unique test identifier.",+ "name": "Test name.",+ "url": "URL that the test monitors.",+ "divisionId": "Identifier of the division that contains the test.",+ "productId": "Identifier of the product that contains the test.",+ "testType": "Type of synthetic test.",+ "monitor": "Monitor type used to run the test.",+ "status": "Test status.",+ },+ },+ "nodes": {+ "description": "Monitoring nodes across all network types.",+ "docs_url": DOCS_URL,+ "columns": {+ "id": "Unique node identifier.",+ "name": "Node name.",+ "networkType": "Network type of the node.",+ "city": "City where the node runs.",+ "country": "Country where the node runs.",+ "status": "Node status.",+ },+ },+ "products": {+ "description": "Top-level containers that organize tests and define shared settings.",+ "docs_url": DOCS_URL,+ "columns": {+ "id": "Unique product identifier.",+ "name": "Product name.",+ "divisionId": "Identifier of the division that contains the product.",+ "status": "Product status.",+ },+ },+ "folders": {+ "description": "Folders that organize tests within products.",+ "docs_url": DOCS_URL,+ "columns": {+ "id": "Unique folder identifier.",+ "name": "Folder name.",+ "productId": "Identifier of the product that contains the folder.",+ "divisionId": "Identifier of the division that contains the folder.",+ },+ },+ "divisions": {+ "description": "Account divisions accessible to the API consumer.",+ "docs_url": DOCS_URL,+ "columns": {"id": "Unique division identifier.", "name": "Division name."},+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/catchpoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/catchpoint.pynew file mode 100644index 000000000000..8def27a8c43b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/catchpoint.py@@ -0,0 +1,126 @@+from typing import Any++from requests.exceptions import HTTPError++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.catchpoint.settings import (+ API_ROOT,+ AUTH_ERROR,+ ENDPOINTS,+ INCOMPLETE_ERROR,+ PAGE_SIZE,+ PERMISSION_ERROR,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+++@frozen+class CatchpointResumeConfig:+ next_url: str+++def client_config(api_key: str, api_version: str) -> ClientConfig:+ return {+ "base_url": f"{API_ROOT}/{api_version}/",+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ "paginator": {"type": "json_response", "next_url_path": "data.next"},+ "allowed_hosts": [],+ "allow_redirects": False,+ "request_timeout": 30,+ }+++def validate_credentials(api_key: str, api_version: str, team_id: int) -> tuple[bool, str | None]:+ config: RESTAPIConfig = {+ "client": client_config(api_key, api_version),+ "resources": [+ {+ "name": "useridentity",+ "endpoint": {+ "path": "useridentity",+ "paginator": "single_page",+ "data_selector": "data",+ "data_selector_required": True,+ "response_actions": [+ {+ "json_field": "completed",+ "json_values": [False],+ "action": "raise",+ "message": INCOMPLETE_ERROR,+ }+ ],+ },+ }+ ],+ }+ try:+ list(rest_api_resource(config, team_id, "catchpoint-validate", None))+ except HTTPError as error:+ if error.response is not None and error.response.status_code in (401, 403):+ return False, AUTH_ERROR if error.response.status_code == 401 else PERMISSION_ERROR+ raise+ return True, None+++def catchpoint_source(+ api_key: str,+ api_version: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CatchpointResumeConfig],+) -> SourceResponse:+ settings = ENDPOINTS[endpoint]+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ def save_checkpoint(state: dict[str, Any] | None) -> None:+ if state is not None and state.get("next_url"):+ resumable_source_manager.save_state(CatchpointResumeConfig(next_url=str(state["next_url"])))++ config: RESTAPIConfig = {+ "client": client_config(api_key, api_version),+ "resources": [+ {+ "name": endpoint,+ "table_name": endpoint,+ "write_disposition": "replace",+ "endpoint": {+ "path": settings["path"],+ "params": {"pageNumber": 1, "pageSize": PAGE_SIZE} if settings["paginated"] else {},+ "data_selector": settings["data_selector"],+ "data_selector_required": True,+ "response_actions": [+ {+ "json_field": "completed",+ "json_values": [False],+ "action": "raise",+ "message": INCOMPLETE_ERROR,+ }+ ],+ },+ }+ ],+ }+ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state={"next_url": resume.next_url} if resume is not None else None,+ )+ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=settings["primary_keys"],+ sort_mode=None,+ on_complete=resumable_source_manager.clear_state,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/settings.pynew file mode 100644index 000000000000..fff29acc48e3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/settings.py@@ -0,0 +1,23 @@+from typing import TypedDict+++class CatchpointEndpoint(TypedDict):+ path: str+ data_selector: str+ primary_keys: list[str]+ paginated: bool+++ENDPOINTS: dict[str, CatchpointEndpoint] = {+ "tests": {"path": "tests", "data_selector": "data.tests", "primary_keys": ["id"], "paginated": True},+ "nodes": {"path": "nodes/all", "data_selector": "data.nodes", "primary_keys": ["id"], "paginated": True},+ "products": {"path": "products", "data_selector": "data.products", "primary_keys": ["id"], "paginated": True},+ "folders": {"path": "folders", "data_selector": "data.folders", "primary_keys": ["id"], "paginated": True},+ "divisions": {"path": "divisions", "data_selector": "data.divisions", "primary_keys": ["id"], "paginated": False},+}++API_ROOT = "https://io.catchpoint.com/api"+PAGE_SIZE = 100+AUTH_ERROR = "Catchpoint rejected the API key. Check that the key is valid and has not expired."+PERMISSION_ERROR = "Catchpoint denied access. Check the API consumer's contact permissions and division access."+INCOMPLETE_ERROR = "Catchpoint could not complete the request. Check the API consumer's permissions and try again."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/source.pyindex ae913d9e24f8..dff8acdd80b0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/source.py@@ -1,8 +1,34 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.catchpoint.catchpoint import (+ CatchpointResumeConfig,+ catchpoint_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.catchpoint.settings import (+ AUTH_ERROR,+ ENDPOINTS,+ INCOMPLETE_ERROR,+ PERMISSION_ERROR,+)+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 (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.catchpoint import (CatchpointSourceConfig,)@@ -10,18 +36,88 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CatchpointSource(SimpleSource[CatchpointSourceConfig]):+class CatchpointSource(ResumableSource[CatchpointSourceConfig, CatchpointResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = ("v3",)+ default_version = "v3"+ api_docs_url = "https://io.catchpoint.com/api/swagger/index.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CATCHPOINT+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": AUTH_ERROR,+ "403 Client Error": PERMISSION_ERROR,+ INCOMPLETE_ERROR: INCOMPLETE_ERROR,+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.catchpoint.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CatchpointSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, {}, names)++ def validate_credentials(+ self,+ config: CatchpointSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_credentials(config.api_key, self.resolve_api_version(api_version), team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CatchpointResumeConfig]:+ return ResumableSourceManager(inputs, CatchpointResumeConfig)++ def source_for_pipeline(+ self,+ config: CatchpointSourceConfig,+ resumable_source_manager: ResumableSourceManager[CatchpointResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return catchpoint_source(+ api_key=config.api_key,+ api_version=self.resolve_api_version(inputs.api_version),+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.CATCHPOINT,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Catchpoint Systems",+ caption="Create an API key in Catchpoint under Settings > Integrations > REST API > Add Consumer.",iconPath="/static/services/catchpoint.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ )+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/tests/test_catchpoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/tests/test_catchpoint.pynew file mode 100644index 000000000000..ce5f01288fed--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/catchpoint/tests/test_catchpoint.py@@ -0,0 +1,182 @@+from collections.abc import Iterable+from typing import Any, cast+from urllib.parse import parse_qs, urlsplit++import pytest+from unittest.mock import MagicMock++import requests_mock+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.catchpoint.catchpoint import (+ CatchpointResumeConfig,+ catchpoint_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.catchpoint.settings import (+ AUTH_ERROR,+ INCOMPLETE_ERROR,+ PERMISSION_ERROR,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.catchpoint.source import CatchpointSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.catchpoint import (+ CatchpointSourceConfig,+)++BASE_URL = "https://io.catchpoint.com/api/v3"+++def manager() -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ return manager+++def source_response(manager: MagicMock, endpoint: str = "tests") -> SourceResponse:+ return catchpoint_source("test-api-key", "v3", endpoint, 1, "test-job", manager)+++def rows(response: SourceResponse) -> list[dict[str, Any]]:+ return [row for page in cast(Iterable[list[dict[str, Any]]], response.items()) for row in page]+++ ("endpoint", "path"),+ [("tests", "tests"), ("nodes", "nodes/all"), ("products", "products"), ("folders", "folders")],+)+def test_paginated_collections(manager: MagicMock, endpoint: str, path: str) -> None:+ next_path = f"/api/v3/{path}?pageNumber=2&pageSize=100"+ next_url = f"https://io.catchpoint.com{next_path}"+ with requests_mock.Mocker() as http:+ http.get(+ f"{BASE_URL}/{path}?pageNumber=1&pageSize=100",+ json={"completed": True, "data": {endpoint: [{"id": 1}], "hasMore": True, "next": next_path}},+ complete_qs=True,+ )+ http.get(+ next_url,+ json={"completed": True, "data": {endpoint: [{"id": 2}], "hasMore": False, "next": None}},+ complete_qs=True,+ )+ response = source_response(manager, endpoint)+ assert rows(response) == [{"id": 1}, {"id": 2}]+ assert http.call_count == 2+ assert response.primary_keys == ["id"]+ for request in http.request_history:+ assert request.headers["Authorization"] == "Bearer test-api-key"+ assert request.headers["Accept"] == "application/json"+ assert parse_qs(urlsplit(http.request_history[1].url).query) == {"pageNumber": ["2"], "pageSize": ["100"]}+ manager.save_state.assert_called_once_with(CatchpointResumeConfig(next_url=next_url))+ manager.clear_state.assert_not_called()+ assert response.on_complete is not None+ response.on_complete()+ manager.clear_state.assert_called_once()+++def test_divisions_do_not_send_unsupported_pagination_params(manager: MagicMock) -> None:+ with requests_mock.Mocker() as http:+ http.get(+ f"{BASE_URL}/divisions",+ json={"completed": True, "data": {"divisions": [{"id": 9}], "hasMore": False}},+ complete_qs=True,+ )+ assert rows(source_response(manager, "divisions")) == [{"id": 9}]+ assert http.call_count == 1+ manager.save_state.assert_not_called()++[email protected]("collection", [[], None, [{"id": 8}]])+def test_terminal_page(manager: MagicMock, collection: list[dict[str, int]] | None) -> None:+ with requests_mock.Mocker() as http:+ http.get(f"{BASE_URL}/tests", json={"completed": True, "data": {"tests": collection, "hasMore": False}})+ assert rows(source_response(manager)) == (collection or [])+ assert http.call_count == 1+ manager.save_state.assert_not_called()+++def test_resume_starts_at_saved_url(manager: MagicMock) -> None:+ saved_url = f"{BASE_URL}/tests?pageNumber=7&pageSize=100"+ manager.can_resume.return_value = True+ manager.load_state.return_value = CatchpointResumeConfig(next_url=saved_url)+ with requests_mock.Mocker() as http:+ http.get(+ saved_url,+ json={"completed": True, "data": {"tests": [{"id": 701}], "hasMore": False}},+ complete_qs=True,+ )+ assert rows(source_response(manager)) == [{"id": 701}]+ assert http.call_count == 1+ manager.save_state.assert_not_called()++[email protected]("resume", [False, True])+def test_off_host_pagination_cannot_receive_key(manager: MagicMock, resume: bool) -> None:+ next_url = "https://example.com/collect"+ if resume:+ manager.can_resume.return_value = True+ manager.load_state.return_value = CatchpointResumeConfig(next_url=next_url)+ with requests_mock.Mocker() as http:+ http.get(+ f"{BASE_URL}/tests",+ json={"completed": True, "data": {"tests": [{"id": 1}], "hasMore": True, "next": next_url}},+ )+ with pytest.raises(ValueError, match="disallowed host"):+ rows(source_response(manager))+ assert http.call_count == (0 if resume else 1)+++ ("body", "error"),+ [+ ({"completed": False, "errors": [{"message": "Private vendor detail"}]}, INCOMPLETE_ERROR),+ ({"completed": True, "data": {"unexpected": []}}, "Required data_selector"),+ ],+)+def test_unexpected_response_does_not_replace_table_with_empty_data(+ manager: MagicMock, body: dict[str, Any], error: str+) -> None:+ with requests_mock.Mocker() as http:+ http.get(f"{BASE_URL}/tests", json=body)+ with pytest.raises(ValueError, match=error) as caught:+ rows(source_response(manager))+ assert "Private vendor detail" not in str(caught.value)+ assert http.call_count == 1+ manager.save_state.assert_not_called()++[email protected](("status", "message"), [(401, AUTH_ERROR), (403, PERMISSION_ERROR)])+def test_sync_authentication_error_mapping(manager: MagicMock, status: int, message: str) -> None:+ with requests_mock.Mocker() as http:+ http.get(f"{BASE_URL}/tests", status_code=status)+ with pytest.raises(HTTPError) as caught:+ rows(source_response(manager))+ matches = [+ value+ for pattern, value in CatchpointSource().get_non_retryable_errors().items()+ if pattern in str(caught.value)+ ]+ assert matches == [message]+ assert http.call_count == 1+++ ("status", "expected"),+ [(200, (True, None)), (401, (False, AUTH_ERROR)), (403, (False, PERMISSION_ERROR))],+)+def test_credential_validation(status: int, expected: tuple[bool, str | None]) -> None:+ with requests_mock.Mocker() as http:+ http.get(f"{BASE_URL}/useridentity", status_code=status, json={"completed": True, "data": {"id": 1}})+ result = CatchpointSource().validate_credentials(CatchpointSourceConfig(api_key="test-api-key"), team_id=1)+ assert result == expected+ assert http.call_count == 1+ assert http.last_request is not None+ assert http.last_request.headers["Authorization"] == "Bearer test-api-key"+++def test_credential_validation_preserves_non_auth_errors() -> None:+ with requests_mock.Mocker() as http:+ http.get(f"{BASE_URL}/useridentity", status_code=400)+ with pytest.raises(HTTPError):+ CatchpointSource().validate_credentials(CatchpointSourceConfig(api_key="test-api-key"), team_id=1)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/catchpoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/catchpoint.pyindex 0ccf29807390..e8deeb51156d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/catchpoint.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/catchpoint.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CatchpointSourceConfig(config.Config):- pass+ api_key: str