: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 healthchecks import source (#70032)
Tom Owers0a0a844dbd8a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 5eca429f2ecb..c90154ed7c0d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -198,6 +198,7 @@ the row lists both.| guardian | HTTP | requests | ✅ || guru | HTTP | requests | ✅ || harvey | HTTP | requests | ✅ |+| healthchecks | HTTP | requests | ✅ || height | HTTP | requests | ✅ || hellobaton | HTTP | requests | ✅ || hibob | HTTP | requests | ✅ |@@ -585,7 +586,6 @@ doesn't conflict with concurrent PRs.- harness- harvey- hatchet-- healthchecks- heap- helicone- helpscoutdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 996ed5d81c63..7c459bbdbc8d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1684,7 +1684,8 @@ class HatchetSourceConfig(config.Config):@config.configclass HealthchecksSourceConfig(config.Config):- pass+ api_key: str+ base_url: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/canonical_descriptions.pynew file mode 100644index 000000000000..8fee98b1cb05--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/canonical_descriptions.py@@ -0,0 +1,69 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Sourced from the Healthchecks.io Management API v3 docs: https://healthchecks.io/docs/api/+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "checks": {+ "description": "Each check monitors one cron job or scheduled task, tracking its current status and configuration.",+ "docs_url": "https://healthchecks.io/docs/api/",+ "columns": {+ "id": "Stable identifier for the check: its UUID for full API keys, or its unique_key for read-only keys.",+ "uuid": "Unique identifier of the check. Omitted when using a read-only API key.",+ "unique_key": "Stable, read-only identifier of the check. Present only when using a read-only API key.",+ "name": "Human-readable name of the check.",+ "slug": "URL-friendly version of the check's name.",+ "tags": "Space-separated list of tags assigned to the check.",+ "desc": "Free-form description of the check.",+ "grace": "Grace period, in seconds, before a late check is reported as down.",+ "n_pings": "Total number of pings the check has received.",+ "status": "Current status: new, up, grace, down, or paused.",+ "started": "Whether the check is currently in the middle of a run (a start signal was received).",+ "last_ping": "ISO 8601 timestamp of the last received ping.",+ "next_ping": "ISO 8601 timestamp when the next ping is expected.",+ "manual_resume": "Whether a paused check must be resumed manually rather than by the next ping.",+ "methods": "Allowed HTTP methods for pinging the check.",+ "timeout": "Expected period between pings, in seconds (for simple checks).",+ "schedule": "Cron expression describing the check's schedule (for cron checks).",+ "tz": "Timezone the cron schedule is evaluated in.",+ "ping_url": "URL to ping to signal a successful run. Omitted when using a read-only API key.",+ "update_url": "API URL to update the check. Omitted when using a read-only API key.",+ "channels": "Comma-separated list of integration IDs assigned to the check.",+ },+ },+ "channels": {+ "description": "Notification integrations (email, SMS, webhook, chat, ...) that alerts are delivered through.",+ "docs_url": "https://healthchecks.io/docs/api/",+ "columns": {+ "id": "Unique identifier of the integration.",+ "name": "Human-readable name of the integration.",+ "kind": "Type of integration (e.g. email, sms, webhook, slack).",+ },+ },+ "flips": {+ "description": "Status transitions (up/down) for each check over time. The most analytics-valuable stream.",+ "docs_url": "https://healthchecks.io/docs/api/",+ "columns": {+ "check_id": "Identifier of the check this flip belongs to (its UUID or unique_key).",+ "timestamp": "ISO 8601 timestamp when the status change occurred.",+ "up": "New status after the flip: 1 for up, 0 for down.",+ },+ },+ "pings": {+ "description": "Recent execution log for each check. Limited to the plan-bounded retention window (100 free / 1000 paid).",+ "docs_url": "https://healthchecks.io/docs/api/",+ "columns": {+ "check_id": "Identifier of the check this ping belongs to (its UUID).",+ "type": "Ping type: success, start, fail, log, or ign (ignored).",+ "date": "ISO 8601 timestamp when the ping was received.",+ "n": "Sequential ping number, monotonically increasing per check.",+ "scheme": "Protocol the ping was made over (http, https, or email).",+ "remote_addr": "IP address the ping originated from.",+ "method": "HTTP method used for the ping.",+ "ua": "User agent string of the ping request.",+ "rid": "Client-supplied run ID (rid query parameter), if any.",+ "body_url": "API URL to fetch the ping's request body, if a body was stored.",+ "duration": "For success pings following a start ping, the measured run duration in seconds.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/healthchecks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/healthchecks.pynew file mode 100644index 000000000000..761e2ac64510--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/healthchecks.py@@ -0,0 +1,331 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.settings import (+ HEALTHCHECKS_ENDPOINTS,+ HealthchecksEndpointConfig,+)++DEFAULT_BASE_URL = "https://healthchecks.io"+REQUEST_TIMEOUT_SECONDS = 30+MAX_RETRY_ATTEMPTS = 5+++class HealthchecksRetryableError(Exception):+ pass+++class HealthchecksResumeConfig:+ # The check we're about to fan out over. A stable check-key bookmark (not a positional+ # index) so checks added/removed between a crash and the retry can't resume into the wrong+ # check. None for the non-fan-out endpoints (checks, channels), which are single requests.+ check_key: str | None = None+++def normalize_base_url(base_url: str | None) -> str:+ """Normalize the (optional) instance URL and reject anything that isn't plain http(s).++ Defaults to healthchecks.io; self-hosted deployments pass their own base URL.++ Rejects URLs where the host `urlparse` reports could diverge from the host the HTTP+ client actually dials, which would let a caller slip past the downstream SSRF allowlist+ (which validates the parsed hostname). Backslashes are treated as path separators by+ browsers and some clients but not by `urlparse`, so `http://169.254.169.254\\@internal`+ parses as host `internal` while the client connects to `169.254.169.254`. Userinfo+ (`user@host`) hides the real host after an `@`, and a query/fragment has no place in a+ base URL — all are refused.+ """+ host = (base_url or "").strip() or DEFAULT_BASE_URL+ if "://" not in host:+ host = f"https://{host}"+ # Catch raw and percent-encoded backslashes before urlparse silently keeps them.+ if "\\" in host or "%5c" in host.lower():+ raise ValueError(f"Invalid Healthchecks base URL: {base_url}")+ host = host.rstrip("/")+ parsed = urlparse(host)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise ValueError(f"Invalid Healthchecks base URL: {base_url}")+ if parsed.username is not None or parsed.password is not None or "@" in parsed.netloc:+ raise ValueError(f"Invalid Healthchecks base URL: {base_url}")+ if parsed.query or parsed.fragment or parsed.params:+ raise ValueError(f"Invalid Healthchecks base URL: {base_url}")+ return host+++def hostname_of(base_url: str | None) -> str:+ return urlparse(normalize_base_url(base_url)).hostname or ""+++def scheme_of(base_url: str | None) -> str:+ return urlparse(normalize_base_url(base_url)).scheme+++def _api_base(base_url: str | None) -> str:+ return f"{normalize_base_url(base_url)}/api/v3"+++def _headers(api_key: str) -> dict[str, str]:+ return {"X-Api-Key": api_key, "Accept": "application/json"}+++def _to_unix_seconds(value: Any) -> int | None:+ """Convert a datetime/date/ISO-string/number incremental cursor to a UNIX timestamp for the+ flips `start` filter. Returns None when the value can't be interpreted."""+ if value is None:+ return None+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return int(aware.timestamp())+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())+ if isinstance(value, (int, float)):+ return int(value)+ if isinstance(value, str):+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ aware = parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+ return int(aware.timestamp())+ return None+++def _check_key(check: dict[str, Any]) -> str | None:+ """The identifier to address a check's sub-endpoints. Full API keys expose `uuid`;+ read-only keys omit it and expose `unique_key` instead."""+ return check.get("uuid") or check.get("unique_key")+++@retry(+ retry=retry_if_exception_type(+ (+ HealthchecksRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> requests.Response:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # Only ever log the status here. The URL carries the check key (a ping credential — the+ # ping URL is derived from it) in its path, and error bodies from `/checks/` carry `uuid`+ # and `ping_url`, so neither belongs in a log line. The tracked transport already logs+ # every request with those values redacted.+ if response.status_code == 429 or response.status_code >= 500:+ # Healthchecks rate-limits at ~100 requests/minute (429 beyond that); 5xx are transient.+ raise HealthchecksRetryableError(f"Healthchecks API returned retryable status {response.status_code}")++ if not response.ok:+ logger.warning(f"Healthchecks API error: status={response.status_code}")+ response.raise_for_status()++ return response+++def validate_credentials(base_url: str | None, api_key: str) -> tuple[bool, str | None]:+ """Probe the checks list endpoint. Works with both full and read-only keys."""+ url = f"{_api_base(base_url)}/checks/"+ try:+ # capture=False: the checks response carries `uuid`/`ping_url` (ping credentials) that+ # the name-based scrubbers can't recognise, so keep it out of the HTTP sample store.+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False).get(+ url, headers=_headers(api_key), timeout=REQUEST_TIMEOUT_SECONDS+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Healthchecks API key"+ return False, f"Healthchecks returned status {response.status_code}"+++def _iter_checks(+ session: requests.Session, base_url: str | None, api_key: str, logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ """Fetch every check once, up front, so the fan-out can enumerate parents."""+ response = _fetch(session, f"{_api_base(base_url)}/checks/", _headers(api_key), logger)+ body = response.json()+ checks = body.get("checks", []) if isinstance(body, dict) else []+ return [c for c in checks if isinstance(c, dict)]+++def _normalize_check(check: dict[str, Any]) -> dict[str, Any]:+ """Stamp a stable `id` onto each check (uuid for full keys, unique_key for read-only keys)+ so the primary key survives regardless of which API-key type is connected."""+ return {"id": _check_key(check), **check}+++def _fan_out_url(+ config: HealthchecksEndpointConfig, base_url: str | None, check_key: str, params: dict[str, Any]+) -> str:+ path = config.path.format(check_key=check_key)+ url = f"{_api_base(base_url)}{path}"+ return f"{url}?{urlencode(params)}" if params else url+++def _get_fan_out_rows(+ base_url: str | None,+ api_key: str,+ config: HealthchecksEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HealthchecksResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ headers = _headers(api_key)+ # The listing request carries no check key in its URL, so the API key is the only secret to+ # redact here; capture is off so the response body (which holds `uuid`/`ping_url`) is never+ # persisted to the HTTP sample store.+ listing_session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)+ checks = _iter_checks(listing_session, base_url, api_key, logger)+ # A stable order so the resume bookmark resolves deterministically across runs.+ check_keys = [key for key in (_check_key(c) for c in checks) if key]++ # Each fan-out request puts a check key in the URL path, and a check key doubles as a ping+ # credential (the ping URL is derived from it). Redact every key from request telemetry+ # alongside the API key so it can't be recovered from logged URLs or captured samples.+ session = make_tracked_session(redact_values=(api_key, *check_keys), allow_redirects=False, capture=False)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = check_keys+ if resume is not None and resume.check_key is not None and resume.check_key in check_keys:+ remaining = check_keys[check_keys.index(resume.check_key) :]+ # The bookmarked key is a ping credential, so log that we resumed without naming it.+ logger.debug(f"Healthchecks: resuming {config.name} fan-out from bookmarked check")++ params: dict[str, Any] = {}+ if config.supports_incremental and should_use_incremental_field:+ start = _to_unix_seconds(db_incremental_field_last_value)+ if start is not None:+ # `start` returns flips newer than this UNIX timestamp (server-side filter).+ params["start"] = start++ for index, check_key in enumerate(remaining):+ url = _fan_out_url(config, base_url, check_key, params)+ try:+ response = _fetch(session, url, headers, logger)+ except requests.HTTPError as exc:+ status = exc.response.status_code if exc.response is not None else None+ # The pings sub-endpoint only accepts the full uuid, so read-only keys (unique_key+ # only) 404 here — skip that check rather than failing the whole sync. A check+ # deleted mid-sync also 404s; same benign skip.+ if status == 404:+ # `index` is a positional counter, not the check key (a ping credential).+ logger.warning(f"Healthchecks: {config.name} not available for check #{index} (404), skipping")+ continue+ raise++ body = response.json()+ if config.data_key is None:+ items = body if isinstance(body, list) else []+ else:+ items = body.get(config.data_key, []) if isinstance(body, dict) else []++ rows = [{"check_id": check_key, **item} for item in items if isinstance(item, dict)]+ if rows:+ yield rows++ # Bookmark the NEXT check only after the current one is fully yielded, so a resume starts+ # at the next unprocessed check rather than re-emitting a check whose rows already landed+ # (which would duplicate rows for the full-refresh pings table). Flips finalize their+ # incremental watermark at job end (desc sort_mode), so a bounded re-pull on crash is+ # merge-deduped regardless.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(HealthchecksResumeConfig(check_key=remaining[index + 1]))+++def get_rows(+ base_url: str | None,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HealthchecksResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = HEALTHCHECKS_ENDPOINTS[endpoint]++ if config.fan_out_over_checks:+ # The fan-out builds its own sessions once the per-check keys are known, so they can be+ # redacted from request telemetry (see `_get_fan_out_rows`).+ yield from _get_fan_out_rows(+ base_url,+ api_key,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ return++ # Top-level endpoints (checks, channels): a single unpaginated request.+ # `base_url` is user-supplied (self-hosted), so pin redirects off: validation and the+ # outbound request must stay on the same target (SSRF defense-in-depth). capture=False keeps+ # the response body — which holds `uuid`/`ping_url` (ping credentials) — out of the HTTP+ # sample store.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)+ response = _fetch(session, f"{_api_base(base_url)}{config.path}", _headers(api_key), logger)+ body = response.json()+ items = body.get(config.data_key, []) if (config.data_key and isinstance(body, dict)) else []+ rows = [item for item in items if isinstance(item, dict)]+ if endpoint == "checks":+ rows = [_normalize_check(row) for row in rows]+ if rows:+ yield rows+++def healthchecks_source(+ base_url: str | None,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HealthchecksResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = HEALTHCHECKS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ base_url=base_url,+ api_key=api_key,+ 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=list(config.primary_keys),+ # Flips fan out over many checks, so rows do not arrive in a single global timestamp+ # order. desc mode defers persisting the incremental watermark until the job completes+ # (see finalize_desc_sort_incremental_value): a partial run can't advance the watermark+ # past checks it never reached. Other endpoints stream in one request, so asc is correct.+ sort_mode="desc" if config.fan_out_over_checks and config.supports_incremental else "asc",+ 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/settings.pynew file mode 100644index 000000000000..44f66c28f1e7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/settings.py@@ -0,0 +1,85 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class HealthchecksEndpointConfig:+ name: str+ # Path relative to the API base (e.g. "/checks/"). Fan-out child paths carry a+ # `{check_key}` placeholder filled per parent check.+ path: str+ # Top-level key wrapping the list in the JSON envelope ("checks"/"channels"/"pings").+ # None means the endpoint returns a bare JSON array (flips).+ data_key: str | None+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # True only when the API exposes a genuine server-side timestamp filter (flips `start`).+ supports_incremental: bool = False+ # A STABLE datetime field to partition by — never one that mutates on update.+ partition_key: str | None = None+ # Iterate every check and query this endpoint per check, injecting `check_id`.+ fan_out_over_checks: bool = False+ should_sync_default: bool = True+++HEALTHCHECKS_ENDPOINTS: dict[str, HealthchecksEndpointConfig] = {+ # All checks and their current config + status. Small, unpaginated, no server-side+ # updated-since filter, so full refresh. No stable creation timestamp is exposed, so no+ # partition key. `id` is synthesized in the transport as uuid (full key) or unique_key+ # (read-only key) so the primary key is stable regardless of API-key type.+ "checks": HealthchecksEndpointConfig(+ name="checks",+ path="/checks/",+ data_key="checks",+ primary_keys=["id"],+ ),+ # Notification integrations (email, sms, webhook, ...). Small, unpaginated, no timestamps.+ "channels": HealthchecksEndpointConfig(+ name="channels",+ path="/channels/",+ data_key="channels",+ primary_keys=["id"],+ ),+ # Up/down status-change history — the analytics-valuable stream. Fanned out per check.+ # The flips endpoint accepts `start=<unix>` (server-side "newer than" filter), so this is+ # genuinely incremental on `timestamp`. `timestamp` is immutable, so it doubles as the+ # partition key. Accepts uuid OR unique_key, so it works with read-only API keys.+ "flips": HealthchecksEndpointConfig(+ name="flips",+ path="/checks/{check_key}/flips/",+ data_key=None,+ primary_keys=["check_id", "timestamp"],+ supports_incremental=True,+ partition_key="timestamp",+ fan_out_over_checks=True,+ incremental_fields=[+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # Recent execution log, fanned out per check. The API returns only the plan-bounded window+ # (100 free / 1000 paid, newest-first) with no server-side time filter, so full refresh —+ # the table reflects the currently-retained window. `date` is immutable (partition key).+ # `n` (ping number) is monotonic per check, so [check_id, n] is a stable composite key.+ # The pings sub-endpoint only accepts the full uuid, so a read-only key (uuid omitted)+ # cannot sync it; the transport skips such checks with a warning.+ "pings": HealthchecksEndpointConfig(+ name="pings",+ path="/checks/{check_key}/pings/",+ data_key="pings",+ primary_keys=["check_id", "n"],+ partition_key="date",+ fan_out_over_checks=True,+ ),+}++ENDPOINTS = tuple(HEALTHCHECKS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in HEALTHCHECKS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/source.pyindex 40db66c4d7ee..7be22bfe37b3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/source.py@@ -1,31 +1,187 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.cloud_utils import is_cloud++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+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.mixins import ValidateDatabaseHostMixinfrom 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HealthchecksSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.healthchecks import (+ HealthchecksResumeConfig,+ healthchecks_source,+ hostname_of,+ scheme_of,+ validate_credentials as validate_healthchecks_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.settings import (+ ENDPOINTS,+ HEALTHCHECKS_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HealthchecksSource(SimpleSource[HealthchecksSourceConfig]):+class HealthchecksSource(+ ResumableSource[HealthchecksSourceConfig, HealthchecksResumeConfig], ValidateDatabaseHostMixin+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HEALTHCHECKS+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` is where the stored API key is sent, so retargeting it must re-require the key.+ return ["base_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.HEALTHCHECKS,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- keywords=["healthchecks.io", "cron monitoring"],+ keywords=["healthchecks.io", "cron monitoring", "uptime"],label="Healthchecks.io",+ caption="""Enter your Healthchecks.io API key to pull your cron and scheduled-task monitoring data into the PostHog Data warehouse.++Create a project-scoped API key under **Project settings > API Access**. A read-only key is enough for the checks, channels, and flips tables; syncing the pings table requires a full-access (read-write) key.++Leave the base URL blank for Healthchecks.io Cloud, or set it to your instance URL for a self-hosted deployment.""",iconPath="/static/services/healthchecks.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/healthchecks",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_url",+ label="Base URL (self-hosted only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://healthchecks.io",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A missing, invalid, or revoked API key surfaces as a 401 when `_fetch` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.+ "401 Client Error: Unauthorized for url": "Your Healthchecks API key is invalid or has been revoked. Create a new key under Project settings > API Access, then reconnect.",+ }++ def get_schemas(+ self,+ config: HealthchecksSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ descriptions = {+ "flips": "Up/down status-change history per check. Incrementally synced on the flip timestamp; retention is plan-limited to roughly the current month plus two prior.",+ "pings": "Recent execution log per check. Reflects the plan-bounded window the API retains (100 pings on the free plan, 1000 on paid). Requires a full-access (read-write) API key.",+ }++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = HEALTHCHECKS_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ # Flips are immutable events, so append is a valid (and cheaper) alternative to merge.+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=descriptions.get(endpoint),+ )++ schemas = [_build_schema(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_base_url(self, base_url: str | None, team_id: int) -> tuple[bool, str | None]:+ try:+ host_valid, host_error = self.is_database_host_valid(hostname_of(base_url), team_id)+ scheme = scheme_of(base_url)+ except ValueError:+ return False, "Invalid Healthchecks base URL"+ if not host_valid:+ return False, host_error+ # On Cloud the required API key would otherwise be sent in cleartext to a customer-supplied+ # http:// host. Self-hosted deployments (not is_cloud) may still use http on their own network.+ if is_cloud() and scheme != "https":+ return False, "Healthchecks base URL must use https"+ return True, None++ def validate_credentials(+ self, config: HealthchecksSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ base_url_valid, base_url_error = self._validate_base_url(config.base_url, team_id)+ if not base_url_valid:+ return False, base_url_error++ return validate_healthchecks_credentials(config.base_url, config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HealthchecksResumeConfig]:+ return ResumableSourceManager[HealthchecksResumeConfig](inputs, HealthchecksResumeConfig)++ def source_for_pipeline(+ self,+ config: HealthchecksSourceConfig,+ resumable_source_manager: ResumableSourceManager[HealthchecksResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ base_url_valid, base_url_error = self._validate_base_url(config.base_url, inputs.team_id)+ if not base_url_valid:+ raise ValueError(base_url_error or "Invalid Healthchecks base URL")++ return healthchecks_source(+ base_url=config.base_url,+ api_key=config.api_key,+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/tests/test_healthchecks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/tests/test_healthchecks.pynew file mode 100644index 000000000000..5816eff3f95d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/tests/test_healthchecks.py@@ -0,0 +1,363 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.healthchecks import (+ DEFAULT_BASE_URL,+ HealthchecksResumeConfig,+ HealthchecksRetryableError,+ _check_key,+ _fetch,+ _to_unix_seconds,+ get_rows,+ healthchecks_source,+ hostname_of,+ normalize_base_url,+ validate_credentials,+)++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.healthchecks"+++def _make_manager(resume_state: HealthchecksResumeConfig | 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: Any, status_code: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = status_code < 400+ resp.text = str(body)+ return resp+++def _routing_session(routes: dict[str, mock.MagicMock]) -> mock.MagicMock:+ """A fake session whose .get(url) returns the response whose route substring matches the URL."""++ def _get(url: str, **_: Any) -> mock.MagicMock:+ # Match on the path (drop any query string) by suffix, so "/checks/u-1/flips/" routes to+ # flips rather than the "/checks/" list endpoint that shares its prefix.+ path = url.split("?", 1)[0]+ for fragment in sorted(routes, key=len, reverse=True):+ if path.endswith(fragment):+ return routes[fragment]+ raise AssertionError(f"No route registered for URL: {url}")++ session = mock.MagicMock()+ session.get.side_effect = _get+ return session+++class TestNormalizeBaseUrl:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, DEFAULT_BASE_URL),+ ("", DEFAULT_BASE_URL),+ (" ", DEFAULT_BASE_URL),+ ("https://healthchecks.io", "https://healthchecks.io"),+ ("healthchecks.example.com", "https://healthchecks.example.com"),+ ("https://hc.example.com/", "https://hc.example.com"),+ ("http://hc.internal:8000", "http://hc.internal:8000"),+ ],+ )+ def test_valid(self, value, expected):+ assert normalize_base_url(value) == expected++ @pytest.mark.parametrize(+ "value",+ [+ "ftp://example.com",+ "https://",+ # SSRF host-confusion tricks: the parsed hostname (validated by the SSRF allowlist)+ # must not diverge from the host the HTTP client dials. Reject backslashes (raw and+ # encoded), userinfo, and query/fragment so the allowlist can't be bypassed.+ "http://169.254.169.254\\@example.com/",+ "http://169.254.169.254%[email protected]/",+ "http://[email protected]",+ "http://[email protected]",+ "https://[email protected]",+ "https://example.com#@169.254.169.254",+ ],+ )+ def test_invalid_raises(self, value):+ with pytest.raises(ValueError):+ normalize_base_url(value)++ def test_hostname_of_default(self):+ assert hostname_of(None) == "healthchecks.io"+++class TestToUnixSeconds:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ (1700000000, 1700000000),+ (1700000000.5, 1700000000),+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),+ # Naive datetimes are treated as UTC.+ (datetime(2023, 11, 14, 22, 13, 20), 1700000000),+ ("2023-11-14T22:13:20Z", 1700000000),+ ("2023-11-14T22:13:20+00:00", 1700000000),+ ("not-a-date", None),+ ],+ )+ def test_conversion(self, value, expected):+ assert _to_unix_seconds(value) == expected++ def test_date_conversion(self):+ assert _to_unix_seconds(date(2023, 11, 14)) == int(datetime(2023, 11, 14, tzinfo=UTC).timestamp())+++class TestCheckKey:+ def test_prefers_uuid(self):+ assert _check_key({"uuid": "u-1", "unique_key": "k-1"}) == "u-1"++ def test_falls_back_to_unique_key(self):+ assert _check_key({"unique_key": "k-1"}) == "k-1"++ def test_none_when_absent(self):+ assert _check_key({"name": "x"}) is None+++class TestFetch:+ @pytest.mark.parametrize("status_code", [429, 500, 502, 503])+ def test_retryable_statuses_raise(self, status_code):+ session = mock.MagicMock()+ session.get.return_value = _response({}, status_code=status_code)+ # Skip tenacity's real backoff sleeps so the retry exhausts instantly.+ _fetch.retry.sleep = lambda *_: None # type: ignore[attr-defined]+ with pytest.raises(HealthchecksRetryableError):+ _fetch(session, "https://healthchecks.io/api/v3/checks/", {}, mock.MagicMock())+ # 5 attempts (stop_after_attempt) before it gives up and reraises.+ assert session.get.call_count == 5++ def test_client_error_raises_for_status(self):+ session = mock.MagicMock()+ resp = _response({"error": "missing api key"}, status_code=401)+ resp.raise_for_status.side_effect = requests.HTTPError(+ "401 Client Error: Unauthorized for url", response=requests.Response()+ )+ session.get.return_value = resp+ with pytest.raises(requests.HTTPError):+ _fetch(session, "https://healthchecks.io/api/v3/checks/", {}, mock.MagicMock())+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid(self, mock_session):+ mock_session.return_value.get.return_value = _response({"checks": []})+ assert validate_credentials(None, "key") == (True, None)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_invalid_key(self, mock_session):+ mock_session.return_value.get.return_value = _response({"error": "wrong api key"}, status_code=401)+ ok, err = validate_credentials(None, "bad")+ assert ok is False+ assert err == "Invalid Healthchecks API key"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_network_error(self, mock_session):+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")+ ok, err = validate_credentials(None, "key")+ assert ok is False+ assert "boom" in (err or "")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_disables_sample_capture(self, mock_session):+ # The checks response carries uuid/ping_url (ping credentials); the session must keep it+ # out of the HTTP sample store.+ mock_session.return_value.get.return_value = _response({"checks": []})+ validate_credentials(None, "key")+ assert mock_session.call_args.kwargs["capture"] is False+++class TestGetRowsTopLevel:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_checks_normalizes_id_from_uuid(self, mock_session):+ mock_session.return_value = _routing_session(+ {"/checks/": _response({"checks": [{"uuid": "u-1", "name": "job"}]})}+ )+ rows = list(get_rows(None, "key", "checks", mock.MagicMock(), _make_manager()))+ assert rows == [[{"id": "u-1", "uuid": "u-1", "name": "job"}]]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_checks_normalizes_id_from_unique_key(self, mock_session):+ # Read-only keys omit uuid and expose unique_key; id must still be populated.+ mock_session.return_value = _routing_session(+ {"/checks/": _response({"checks": [{"unique_key": "k-1", "name": "job"}]})}+ )+ rows = list(get_rows(None, "key", "checks", mock.MagicMock(), _make_manager()))+ assert rows[0][0]["id"] == "k-1"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_channels(self, mock_session):+ mock_session.return_value = _routing_session(+ {"/channels/": _response({"channels": [{"id": "c-1", "kind": "email"}]})}+ )+ rows = list(get_rows(None, "key", "channels", mock.MagicMock(), _make_manager()))+ assert rows == [[{"id": "c-1", "kind": "email"}]]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_yields_nothing(self, mock_session):+ mock_session.return_value = _routing_session({"/channels/": _response({"channels": []})})+ assert list(get_rows(None, "key", "channels", mock.MagicMock(), _make_manager())) == []++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_disables_sample_capture(self, mock_session):+ # The checks response carries uuid/ping_url (ping credentials); the session must keep it+ # out of the HTTP sample store.+ mock_session.return_value = _routing_session({"/checks/": _response({"checks": []})})+ list(get_rows(None, "key", "checks", mock.MagicMock(), _make_manager()))+ assert mock_session.call_args.kwargs["capture"] is False+++class TestGetRowsFanOut:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_flips_injects_check_id_and_bare_array(self, mock_session):+ mock_session.return_value = _routing_session(+ {+ "/checks/": _response({"checks": [{"uuid": "u-1"}]}),+ "/checks/u-1/flips/": _response([{"timestamp": "2023-11-14T22:13:20+00:00", "up": 1}]),+ }+ )+ rows = list(get_rows(None, "key", "flips", mock.MagicMock(), _make_manager()))+ assert rows == [[{"check_id": "u-1", "timestamp": "2023-11-14T22:13:20+00:00", "up": 1}]]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_flips_incremental_passes_start_param(self, mock_session):+ session = _routing_session(+ {+ "/checks/": _response({"checks": [{"uuid": "u-1"}]}),+ "/flips/": _response([]),+ }+ )+ mock_session.return_value = session+ list(+ get_rows(+ None,+ "key",+ "flips",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC),+ )+ )+ flip_call = next(c for c in session.get.call_args_list if "/flips/" in c.args[0])+ assert "start=1700000000" in flip_call.args[0]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_flips_no_incremental_omits_start(self, mock_session):+ session = _routing_session({"/checks/": _response({"checks": [{"uuid": "u-1"}]}), "/flips/": _response([])})+ mock_session.return_value = session+ list(get_rows(None, "key", "flips", mock.MagicMock(), _make_manager()))+ flip_call = next(c for c in session.get.call_args_list if "/flips/" in c.args[0])+ assert "start=" not in flip_call.args[0]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_pings_404_is_skipped(self, mock_session):+ # A read-only key can't address the pings sub-endpoint (needs the full uuid) -> 404 skip.+ not_found = _response({}, status_code=404)+ not_found.raise_for_status.side_effect = requests.HTTPError(response=not_found)+ mock_session.return_value = _routing_session(+ {+ "/checks/": _response({"checks": [{"unique_key": "k-1"}]}),+ "/checks/k-1/pings/": not_found,+ }+ )+ rows = list(get_rows(None, "key", "pings", mock.MagicMock(), _make_manager()))+ assert rows == []++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_pings_injects_check_id(self, mock_session):+ mock_session.return_value = _routing_session(+ {+ "/checks/": _response({"checks": [{"uuid": "u-1"}]}),+ "/checks/u-1/pings/": _response({"pings": [{"n": 5, "type": "success"}]}),+ }+ )+ rows = list(get_rows(None, "key", "pings", mock.MagicMock(), _make_manager()))+ assert rows == [[{"check_id": "u-1", "n": 5, "type": "success"}]]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_fan_out_redacts_check_keys_and_disables_capture(self, mock_session):+ # Each fan-out URL puts a check key in its path, and a check key doubles as a ping+ # credential, so the fan-out session must redact the keys from request telemetry (and+ # keep response bodies out of the sample store).+ mock_session.return_value = _routing_session(+ {+ "/checks/": _response({"checks": [{"uuid": "u-1"}, {"uuid": "u-2"}]}),+ "/checks/u-1/flips/": _response([]),+ "/checks/u-2/flips/": _response([]),+ }+ )+ list(get_rows(None, "key", "flips", mock.MagicMock(), _make_manager()))+ assert all(c.kwargs["capture"] is False for c in mock_session.call_args_list)+ # The fan-out session is built last, once the per-check keys are known.+ fan_out_call = mock_session.call_args_list[-1]+ assert set(fan_out_call.kwargs["redact_values"]) == {"key", "u-1", "u-2"}++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_fan_out_resumes_from_bookmark(self, mock_session):+ # Two checks; resume bookmarked at the second, so only it is fetched.+ session = _routing_session(+ {+ "/checks/": _response({"checks": [{"uuid": "u-1"}, {"uuid": "u-2"}]}),+ "/checks/u-2/flips/": _response([{"timestamp": "2023-01-01T00:00:00+00:00", "up": 0}]),+ }+ )+ mock_session.return_value = session+ manager = _make_manager(HealthchecksResumeConfig(check_key="u-2"))+ rows = list(get_rows(None, "key", "flips", mock.MagicMock(), manager))+ assert rows == [[{"check_id": "u-2", "timestamp": "2023-01-01T00:00:00+00:00", "up": 0}]]+ fetched = [c.args[0] for c in session.get.call_args_list]+ assert not any("/checks/u-1/flips/" in u for u in fetched)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_fan_out_bookmarks_next_check_after_completing_current(self, mock_session):+ # After finishing u-1 the bookmark advances to u-2, so a resume skips the already-yielded+ # u-1 rather than re-emitting them. The final check saves nothing (nothing left to resume).+ mock_session.return_value = _routing_session(+ {+ "/checks/": _response({"checks": [{"uuid": "u-1"}, {"uuid": "u-2"}]}),+ "/checks/u-1/flips/": _response([{"timestamp": "2023-01-01T00:00:00+00:00", "up": 1}]),+ "/checks/u-2/flips/": _response([{"timestamp": "2023-01-02T00:00:00+00:00", "up": 0}]),+ }+ )+ manager = _make_manager()+ list(get_rows(None, "key", "flips", mock.MagicMock(), manager))+ saved = [c.args[0].check_key for c in manager.save_state.call_args_list]+ assert saved == ["u-2"]+++class TestHealthchecksSource:+ @pytest.mark.parametrize(+ "endpoint, expected_keys, expected_sort, has_partition",+ [+ ("checks", ["id"], "asc", False),+ ("channels", ["id"], "asc", False),+ ("flips", ["check_id", "timestamp"], "desc", True),+ ("pings", ["check_id", "n"], "asc", True),+ ],+ )+ def test_source_response_shape(self, endpoint, expected_keys, expected_sort, has_partition):+ response = healthchecks_source(None, "key", endpoint, mock.MagicMock(), _make_manager())+ assert response.name == endpoint+ assert response.primary_keys == expected_keys+ assert response.sort_mode == expected_sort+ if has_partition:+ assert response.partition_mode == "datetime"+ assert response.partition_keys is not None+ else:+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/tests/test_healthchecks_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/tests/test_healthchecks_source.pynew file mode 100644index 000000000000..bdf0fae1464f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/healthchecks/tests/test_healthchecks_source.py@@ -0,0 +1,224 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HealthchecksSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.healthchecks import (+ HealthchecksResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.source import HealthchecksSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestHealthchecksSource:+ def setup_method(self):+ self.source = HealthchecksSource()+ self.team_id = 123+ self.config = HealthchecksSourceConfig(api_key="key", base_url=None)++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.HEALTHCHECKS++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Healthchecks"+ assert config.label == "Healthchecks.io"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/healthchecks"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key", "base_url"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_base_url_field_is_optional_text(self):+ config = self.source.get_source_config+ base_url_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "base_url"+ )+ assert base_url_field.type == SourceFieldInputConfigType.TEXT+ assert base_url_field.required is False+ assert base_url_field.secret is False++ def test_connection_host_fields_cover_base_url(self):+ # The base URL decides where the stored API key gets sent.+ assert self.source.connection_host_fields == ["base_url"]++ def test_lists_tables_without_credentials(self):+ # get_schemas is a static catalog with no I/O, so the public docs table list can render.+ assert self.source.lists_tables_without_credentials is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://healthchecks.io/api/v3/checks/",+ ],+ )+ def test_non_retryable_errors_match_known_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)++ def test_non_retryable_errors_ignore_server_errors(self):+ non_retryable_errors = self.source.get_non_retryable_errors()+ error = "500 Server Error for url: https://healthchecks.io/api/v3/checks/"+ assert not any(key in error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # Only flips exposes a genuine server-side timestamp filter (start=), so only it is incremental.+ assert schemas["flips"].supports_incremental is True+ assert schemas["checks"].supports_incremental is False+ assert schemas["channels"].supports_incremental is False+ assert schemas["pings"].supports_incremental is False+ assert [f["field"] for f in schemas["flips"].incremental_fields] == ["timestamp"]+ assert schemas["flips"].incremental_fields == INCREMENTAL_FIELDS["flips"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["flips"])+ assert len(schemas) == 1+ assert schemas[0].name == "flips"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self):+ tables = self.source.get_documented_tables()+ by_name = {t["name"]: t for t in tables}+ assert set(by_name) == set(ENDPOINTS)+ # flips advertises Incremental; checks is full refresh only.+ assert "Incremental" in by_name["flips"]["sync_methods"]+ assert by_name["checks"]["sync_methods"] == ["Full refresh"]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.source.validate_healthchecks_credentials"+ )+ @mock.patch.object(HealthchecksSource, "is_database_host_valid")+ def test_validate_credentials_happy_path(self, mock_host_valid, mock_validate):+ mock_host_valid.return_value = (True, None)+ mock_validate.return_value = (True, None)++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is True+ assert error_message is None+ mock_host_valid.assert_called_once_with("healthchecks.io", self.team_id)+ mock_validate.assert_called_once_with(None, "key")++ @mock.patch.object(HealthchecksSource, "is_database_host_valid")+ def test_validate_credentials_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error_message == "Host is not allowed"++ @mock.patch.object(HealthchecksSource, "is_database_host_valid")+ def test_validate_credentials_rejects_invalid_url(self, mock_host_valid):+ config = HealthchecksSourceConfig(api_key="key", base_url="ftp://nope")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error_message == "Invalid Healthchecks base URL"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.source.is_cloud")+ @mock.patch.object(HealthchecksSource, "is_database_host_valid")+ def test_validate_credentials_rejects_http_on_cloud(self, mock_host_valid, mock_is_cloud):+ # On Cloud the required API key would travel in cleartext to a customer-supplied http:// host.+ mock_host_valid.return_value = (True, None)+ mock_is_cloud.return_value = True+ config = HealthchecksSourceConfig(api_key="key", base_url="http://hc.internal:8000")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error_message == "Healthchecks base URL must use https"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.source.validate_healthchecks_credentials"+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.source.is_cloud")+ @mock.patch.object(HealthchecksSource, "is_database_host_valid")+ def test_validate_credentials_allows_http_when_self_hosted(self, mock_host_valid, mock_is_cloud, mock_validate):+ # Self-hosted deployments may reach their instance over http on their own network.+ mock_host_valid.return_value = (True, None)+ mock_is_cloud.return_value = False+ mock_validate.return_value = (True, None)+ config = HealthchecksSourceConfig(api_key="key", base_url="http://hc.internal:8000")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is True+ assert error_message is None++ 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 HealthchecksResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.source.healthchecks_source"+ )+ @mock.patch.object(HealthchecksSource, "is_database_host_valid")+ def test_source_for_pipeline_plumbs_arguments(self, mock_host_valid, mock_healthchecks_source):+ mock_host_valid.return_value = (True, None)+ inputs = mock.MagicMock()+ inputs.schema_name = "flips"+ inputs.team_id = self.team_id+ 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)++ kwargs = mock_healthchecks_source.call_args.kwargs+ assert kwargs["base_url"] is None+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "flips"+ 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(+ "products.warehouse_sources.backend.temporal.data_imports.sources.healthchecks.source.healthchecks_source"+ )+ @mock.patch.object(HealthchecksSource, "is_database_host_valid")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_host_valid, mock_healthchecks_source):+ mock_host_valid.return_value = (True, None)+ inputs = mock.MagicMock()+ inputs.schema_name = "checks"+ inputs.team_id = self.team_id+ 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_healthchecks_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @mock.patch.object(HealthchecksSource, "is_database_host_valid")+ def test_source_for_pipeline_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")+ inputs = mock.MagicMock()+ inputs.schema_name = "flips"+ inputs.team_id = self.team_id++ with pytest.raises(ValueError, match="Host is not allowed"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)