: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 pingdom import source (#62882)
Tom Owersc12f662eb064
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 686bba5459f4..de05bf7a42d5 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -113,6 +113,7 @@ the row lists both.| pagerduty | HTTP | requests | ✅ || pandadoc | HTTP | requests | ✅ || pendo | HTTP | requests | ✅ |+| pingdom | HTTP | requests | ✅ || pinterest_ads | HTTP | requests | ✅ || pipedrive | HTTP | requests | ✅ || plain | HTTP | requests | ✅ |@@ -276,7 +277,6 @@ doesn't conflict with concurrent PRs.- paypal- pendo- personio-- pingdom- plaid- planetscale- qualtricsdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 96ed6f9f636a..637766a3e8e7 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -977,7 +977,7 @@ class PgAnalyzeSourceConfig(config.Config):@config.configclass PingdomSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/pingdom/pingdom.py b/posthog/temporal/data_imports/sources/pingdom/pingdom.pynew file mode 100644index 000000000000..76a3900c04cd--- /dev/null+++ b/posthog/temporal/data_imports/sources/pingdom/pingdom.py@@ -0,0 +1,173 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++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.pingdom.settings import PINGDOM_ENDPOINTS, PingdomEndpointConfig++PINGDOM_BASE_URL = "https://api.pingdom.com/api/3.1"+REQUEST_TIMEOUT_SECONDS = 60+# Pingdom enforces two-tier rate limits (Req-Limit-Short / Req-Limit-Long+# headers) and returns 429 on exceed; exponential backoff is sufficient.+MAX_RETRY_ATTEMPTS = 5+++class PingdomRetryableError(Exception):+ pass+++class PingdomResumeConfig:+ # Pingdom paginates with limit/offset; the static query params (limit,+ # incremental `from` filter) are deterministically rebuilt from the endpoint+ # config and job inputs on resume.+ offset: int+++def _get_session(api_token: str) -> requests.Session:+ return make_tracked_session(headers={"Authorization": f"Bearer {api_token}"}, redact_values=(api_token,))+++def _to_epoch(value: Any) -> Optional[int]:+ """Coerce an incremental cursor value to UNIX epoch seconds for Pingdom's `from` filter."""+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value)+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return int(dt.timestamp())+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())+ try:+ return int(value)+ except (TypeError, ValueError):+ return None+++def _extract_items(data: dict[str, Any], data_key: str) -> list[dict[str, Any]]:+ node: Any = data+ for key in data_key.split("."):+ if not isinstance(node, dict):+ return []+ node = node.get(key)+ return node if isinstance(node, list) else []+++def _build_params(config: PingdomEndpointConfig, from_value: Optional[int], offset: int) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": config.page_size, "offset": offset}+ if from_value is not None:+ params["from"] = from_value+ return params+++def _build_url(path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{PINGDOM_BASE_URL}{path}"+ return f"{PINGDOM_BASE_URL}{path}?{urlencode(params)}"+++def validate_credentials(api_token: str) -> bool:+ """Confirm the API token is valid with a cheap one-check listing probe."""+ try:+ response = _get_session(api_token).get(+ _build_url("/checks", {"limit": 1}),+ timeout=10,+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PingdomResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = PINGDOM_ENDPOINTS[endpoint]+ session = _get_session(api_token)++ from_value = _to_epoch(db_incremental_field_last_value) if should_use_incremental_field else None++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume_config.offset if resume_config is not None else 0+ if resume_config is not None:+ logger.debug(f"Pingdom: resuming {endpoint} from offset {offset}")++ @retry(+ retry=retry_if_exception_type((PingdomRetryableError, 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 PingdomRetryableError(f"Pingdom API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"Pingdom API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ while True:+ url = _build_url(config.path, _build_params(config, from_value, offset))+ data = fetch_page(url)+ items = _extract_items(data, config.data_key)++ if items:+ yield items++ if len(items) < config.page_size:+ break++ offset += config.page_size+ # 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(PingdomResumeConfig(offset=offset))+++def pingdom_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PingdomResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = PINGDOM_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,+ ),+ primary_keys=config.primary_keys,+ 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",+ has_duplicate_primary_keys=config.has_duplicate_primary_keys or None,+ )diff --git a/posthog/temporal/data_imports/sources/pingdom/settings.py b/posthog/temporal/data_imports/sources/pingdom/settings.pynew file mode 100644index 000000000000..bf48ec193603--- /dev/null+++ b/posthog/temporal/data_imports/sources/pingdom/settings.py@@ -0,0 +1,70 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class PingdomEndpointConfig:+ name: str+ path: str+ # Dotted path to the list of rows in the response body (e.g. "actions.alerts"+ # for the nested {"actions": {"alerts": [...]}} wrapper).+ data_key: str+ # Alerts have no unique id, so the primary key can be composite.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-time field used for datetime partitioning.+ partition_key: Optional[str] = None+ # Max page size the endpoint accepts (checks allow 25000, actions 1000).+ page_size: int = 1000+ # Composite keys on alerts may still collide (same check/user/second/channel).+ has_duplicate_primary_keys: bool = False+++# Pingdom API 3.1 timestamps are UNIX epoch seconds. Only /actions exposes a+# server-side `from`/`to` time filter among the endpoints we sync; /checks,+# /probes and /maintenance are small full-refresh dimension tables.+PINGDOM_ENDPOINTS: dict[str, PingdomEndpointConfig] = {+ "checks": PingdomEndpointConfig(+ name="checks",+ path="/checks",+ data_key="checks",+ page_size=25000,+ ),+ "probes": PingdomEndpointConfig(+ name="probes",+ path="/probes",+ data_key="probes",+ ),+ "maintenance": PingdomEndpointConfig(+ name="maintenance",+ path="/maintenance",+ data_key="maintenance",+ ),+ "alerts": PingdomEndpointConfig(+ name="alerts",+ path="/actions",+ data_key="actions.alerts",+ # Alert rows carry no id; (checkid, time, userid, via) is the closest+ # natural key and can still collide, so flag duplicates for the pipeline.+ primary_keys=["checkid", "time", "userid", "via"],+ partition_key="time",+ page_size=1000,+ has_duplicate_primary_keys=True,+ incremental_fields=[+ {+ "label": "time",+ "type": IncrementalFieldType.DateTime,+ "field": "time",+ "field_type": IncrementalFieldType.Integer,+ },+ ],+ ),+}++ENDPOINTS = tuple(PINGDOM_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PINGDOM_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/pingdom/source.py b/posthog/temporal/data_imports/sources/pingdom/source.pyindex 5c944abf0cb4..15f6427f85b9 100644--- a/posthog/temporal/data_imports/sources/pingdom/source.py+++ b/posthog/temporal/data_imports/sources/pingdom/source.py@@ -1,29 +1,115 @@-from typing import cast+from typing import Optional, castfrom 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, 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 PingdomSourceConfig+from posthog.temporal.data_imports.sources.pingdom.pingdom import (+ PingdomResumeConfig,+ pingdom_source,+ validate_credentials as validate_pingdom_credentials,+)+from posthog.temporal.data_imports.sources.pingdom.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class PingdomSource(SimpleSource[PingdomSourceConfig]):+class PingdomSource(ResumableSource[PingdomSourceConfig, PingdomResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PINGDOM+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.pingdom.com": "Pingdom authentication failed. Please check your API token.",+ "403 Client Error: Forbidden for url: https://api.pingdom.com": "Pingdom denied access. Please check that your API token has the required permissions.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.PINGDOM,label="Pingdom",+ caption="""Enter your Pingdom API token to pull your Pingdom uptime monitoring data into the PostHog Data warehouse.++You can create an API token in [My Pingdom](https://my.pingdom.com/app/api-tokens) under Settings > Pingdom API. A read-only token is sufficient.""",iconPath="/static/services/pingdom.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/pingdom",+ 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: PingdomSourceConfig,+ 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: PingdomSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_pingdom_credentials(config.api_token):+ return True, None++ return False, "Invalid Pingdom API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PingdomResumeConfig]:+ return ResumableSourceManager[PingdomResumeConfig](inputs, PingdomResumeConfig)++ def source_for_pipeline(+ self,+ config: PingdomSourceConfig,+ resumable_source_manager: ResumableSourceManager[PingdomResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return pingdom_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,)diff --git a/posthog/temporal/data_imports/sources/pingdom/tests/test_pingdom.py b/posthog/temporal/data_imports/sources/pingdom/tests/test_pingdom.pynew file mode 100644index 000000000000..3aced944e350--- /dev/null+++ b/posthog/temporal/data_imports/sources/pingdom/tests/test_pingdom.py@@ -0,0 +1,220 @@+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.pingdom.pingdom import (+ PingdomResumeConfig,+ _build_params,+ _build_url,+ _extract_items,+ _to_epoch,+ get_rows,+ pingdom_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.pingdom.settings import ENDPOINTS, PINGDOM_ENDPOINTS+++def _make_manager(resume_state: PingdomResumeConfig | 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(body: dict[str, Any]) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = 200+ resp.ok = True+ return resp+++class TestToEpoch:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ (1700000000, 1700000000),+ (1700000000.9, 1700000000),+ ("1700000000", 1700000000),+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),+ (date(2023, 11, 15), int(datetime(2023, 11, 15, tzinfo=UTC).timestamp())),+ ("not-a-number", None),+ (True, None),+ ],+ )+ def test_to_epoch_values(self, value, expected):+ assert _to_epoch(value) == expected+++class TestExtractItems:+ @pytest.mark.parametrize(+ "body, data_key, expected",+ [+ ({"checks": [{"id": 1}]}, "checks", [{"id": 1}]),+ ({"actions": {"alerts": [{"time": 1}]}}, "actions.alerts", [{"time": 1}]),+ ],+ )+ def test_extracts_items(self, body, data_key, expected):+ assert _extract_items(body, data_key) == expected++ @pytest.mark.parametrize(+ "body",+ [+ {},+ {"actions": {}},+ {"actions": {"alerts": None}},+ {"actions": None},+ {"actions": {"alerts": {"not": "a list"}}},+ ],+ )+ def test_missing_or_malformed_returns_empty(self, body):+ assert _extract_items(body, "actions.alerts") == []+++class TestBuildParams:+ def test_includes_limit_and_offset(self):+ params = _build_params(PINGDOM_ENDPOINTS["alerts"], from_value=None, offset=0)+ assert params == {"limit": 1000, "offset": 0}++ def test_includes_from_when_set(self):+ params = _build_params(PINGDOM_ENDPOINTS["alerts"], from_value=1700000000, offset=2000)+ assert params == {"limit": 1000, "offset": 2000, "from": 1700000000}++ def test_checks_uses_large_page_size(self):+ params = _build_params(PINGDOM_ENDPOINTS["checks"], from_value=None, offset=0)+ assert params["limit"] == 25000+++class TestBuildUrl:+ def test_with_params(self):+ url = _build_url("/checks", {"limit": 1})+ assert url == "https://api.pingdom.com/api/3.1/checks?limit=1"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.pingdom.pingdom.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.pingdom.pingdom.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.pingdom.pingdom.make_tracked_session")+ def test_paginates_until_short_page(self, mock_session):+ page_size = PINGDOM_ENDPOINTS["alerts"].page_size+ full_page = {"actions": {"alerts": [{"time": i} for i in range(page_size)]}}+ short_page = {"actions": {"alerts": [{"time": page_size}]}}+ mock_session.return_value.get.side_effect = [_response(full_page), _response(short_page)]++ manager = _make_manager()+ batches = list(get_rows("token", "alerts", mock.MagicMock(), manager))++ assert len(batches) == 2+ assert len(batches[0]) == page_size+ # State saved once, after the first (full) page, pointing at the next offset.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].offset == page_size+ second_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert parse_qs(urlparse(second_url).query)["offset"] == [str(page_size)]++ @mock.patch("posthog.temporal.data_imports.sources.pingdom.pingdom.make_tracked_session")+ def test_resumes_from_saved_offset(self, mock_session):+ mock_session.return_value.get.return_value = _response({"checks": [{"id": 1}]})++ manager = _make_manager(PingdomResumeConfig(offset=50000))+ list(get_rows("token", "checks", mock.MagicMock(), manager))++ url = mock_session.return_value.get.call_args.args[0]+ assert parse_qs(urlparse(url).query)["offset"] == ["50000"]++ @mock.patch("posthog.temporal.data_imports.sources.pingdom.pingdom.make_tracked_session")+ def test_incremental_request_includes_from_filter(self, mock_session):+ mock_session.return_value.get.return_value = _response({"actions": {"alerts": []}})++ manager = _make_manager()+ list(+ get_rows(+ "token",+ "alerts",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ )+ )++ url = mock_session.return_value.get.call_args.args[0]+ assert parse_qs(urlparse(url).query)["from"] == ["1700000000"]++ @mock.patch("posthog.temporal.data_imports.sources.pingdom.pingdom.make_tracked_session")+ def test_full_refresh_has_no_from_filter(self, mock_session):+ mock_session.return_value.get.return_value = _response({"actions": {"alerts": []}})++ manager = _make_manager()+ list(get_rows("token", "alerts", mock.MagicMock(), manager))++ url = mock_session.return_value.get.call_args.args[0]+ assert "from" not in parse_qs(urlparse(url).query)++ @mock.patch("posthog.temporal.data_imports.sources.pingdom.pingdom.make_tracked_session")+ def test_empty_response_stops_without_saving_state(self, mock_session):+ mock_session.return_value.get.return_value = _response({"checks": []})++ manager = _make_manager()+ batches = list(get_rows("token", "checks", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()+++class TestPingdomSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = PINGDOM_ENDPOINTS[endpoint]+ response = pingdom_source("token", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ 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++ def test_alerts_flag_duplicate_primary_keys(self):+ response = pingdom_source("token", "alerts", mock.MagicMock(), _make_manager())+ assert response.has_duplicate_primary_keys is True++ def test_checks_do_not_flag_duplicate_primary_keys(self):+ response = pingdom_source("token", "checks", mock.MagicMock(), _make_manager())+ assert response.has_duplicate_primary_keys is None++ @pytest.mark.parametrize("config", list(PINGDOM_ENDPOINTS.values()))+ def test_partition_keys_are_stable_fields(self, config):+ if config.partition_key:+ # Alert timestamps are immutable event times.+ assert config.partition_key == "time"diff --git a/posthog/temporal/data_imports/sources/pingdom/tests/test_pingdom_source.py b/posthog/temporal/data_imports/sources/pingdom/tests/test_pingdom_source.pynew file mode 100644index 000000000000..4384c44cef09--- /dev/null+++ b/posthog/temporal/data_imports/sources/pingdom/tests/test_pingdom_source.py@@ -0,0 +1,139 @@+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 PingdomSourceConfig+from posthog.temporal.data_imports.sources.pingdom.pingdom import PingdomResumeConfig+from posthog.temporal.data_imports.sources.pingdom.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.pingdom.source import PingdomSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestPingdomSource:+ def setup_method(self):+ self.source = PingdomSource()+ self.team_id = 123+ self.config = PingdomSourceConfig(api_token="api-token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.PINGDOM++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Pingdom"+ assert config.label == "Pingdom"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/pingdom.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://api.pingdom.com/api/3.1/checks?limit=25000",+ "403 Client Error: Forbidden for url: https://api.pingdom.com/api/3.1/actions",+ ],+ )+ 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://api.pingdom.com/api/3.1/checks",+ ],+ )+ 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)+ incremental = {schema.name for schema in schemas if schema.supports_incremental}+ # Only /actions exposes a server-side from/to time filter.+ assert incremental == {"alerts"}++ 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["alerts"].incremental_fields == INCREMENTAL_FIELDS["alerts"]+ assert schemas["checks"].incremental_fields == []+ assert schemas["checks"].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["alerts"])+ assert len(schemas) == 1+ assert schemas[0].name == "alerts"++ 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 Pingdom API token"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.pingdom.source.validate_pingdom_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 PingdomResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.pingdom.source.pingdom_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_pingdom_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "alerts"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1700000000+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_pingdom_source.assert_called_once()+ kwargs = mock_pingdom_source.call_args.kwargs+ assert kwargs["api_token"] == "api-token"+ assert kwargs["endpoint"] == "alerts"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == 1700000000++ @mock.patch("posthog.temporal.data_imports.sources.pingdom.source.pingdom_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_pingdom_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "checks"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = 1700000000++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_pingdom_source.call_args.kwargs["db_incremental_field_last_value"] is None