: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 statuscake import source (#71191)
Tom Owers84693a55387a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 183076fd1616..b495c11d46f0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -486,6 +486,7 @@ the row lists both.| squadcast | HTTP | requests | ✅ || square | HTTP | requests | ✅ || squarespace | HTTP | requests | ✅ |+| statuscake | HTTP | requests | ✅ || statuspage | HTTP | requests | ✅ || stigg | HTTP | requests | ✅ || stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |@@ -928,7 +929,6 @@ doesn't conflict with concurrent PRs.- spotify_ads- spotlercrm- statsig-- statuscake- stockdata- strava- streamelementsdiff --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 736d37565747..2817da992831 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@@ -4154,7 +4154,7 @@ class StatsigSourceConfig(config.Config):@config.configclass StatuscakeSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/canonical_descriptions.pynew file mode 100644index 000000000000..60c05071cf9b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/canonical_descriptions.py@@ -0,0 +1,150 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions are taken from the StatusCake API v1 docs (https://developers.statuscake.com/api/).+# The "test_id" column on every per-test history table is injected by the connector (the raw+# history rows carry no test identifier), so it is documented here even though it isn't part of+# the raw endpoint payload.+_TEST_ID_COLUMN = "Identifier of the test this record belongs to (added by the connector)."++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "uptime_tests": {+ "description": "Uptime checks configured in your StatusCake account.",+ "docs_url": "https://developers.statuscake.com/api/#tag/uptime",+ "columns": {+ "id": "Unique identifier for the uptime check.",+ "name": "Display name of the uptime check.",+ "website_url": "URL or IP address the check monitors.",+ "test_type": "Type of check (HTTP, HEAD, TCP, DNS, SMTP, SSH, PING, PUSH).",+ "check_rate": "Number of seconds between checks.",+ "contact_groups": "List of contact group ids alerted by this check.",+ "paused": "Whether the check is paused.",+ "status": "Current status of the check (up or down).",+ "tags": "List of tags assigned to the check.",+ "uptime": "Uptime percentage of the check.",+ },+ },+ "uptime_history": {+ "description": "Raw uptime check results (one row per check execution) for every uptime test.",+ "docs_url": "https://developers.statuscake.com/api/#tag/uptime/operation/list-uptime-test-history",+ "columns": {+ "test_id": _TEST_ID_COLUMN,+ "created_at": "Timestamp the check result was recorded.",+ "status_code": "HTTP status code returned by the monitored endpoint.",+ "location": "Monitoring location the check ran from.",+ "performance": "Time taken to complete the check, in milliseconds.",+ },+ },+ "uptime_periods": {+ "description": "Continuous up/down periods for every uptime test — the basis for availability and SLA reporting.",+ "docs_url": "https://developers.statuscake.com/api/#tag/uptime/operation/list-uptime-test-periods",+ "columns": {+ "test_id": _TEST_ID_COLUMN,+ "status": "Status of the test during the period (up or down).",+ "created_at": "Timestamp the period started.",+ },+ },+ "uptime_alerts": {+ "description": "Alerts triggered by uptime tests changing state.",+ "docs_url": "https://developers.statuscake.com/api/#tag/uptime/operation/list-uptime-test-alerts",+ "columns": {+ "test_id": _TEST_ID_COLUMN,+ "id": "Unique identifier for the alert.",+ "status": "Status of the test when the alert triggered (up or down).",+ "status_code": "HTTP status code returned by the monitored endpoint at alert time.",+ "triggered_at": "Timestamp the alert was triggered.",+ },+ },+ "pagespeed_tests": {+ "description": "Pagespeed checks configured in your StatusCake account.",+ "docs_url": "https://developers.statuscake.com/api/#tag/pagespeed",+ "columns": {+ "id": "Unique identifier for the pagespeed check.",+ "name": "Display name of the pagespeed check.",+ "website_url": "URL the check measures.",+ "location": "Monitoring location the check runs from.",+ "check_rate": "Number of seconds between checks.",+ "contact_groups": "List of contact group ids alerted by this check.",+ "paused": "Whether the check is paused.",+ "latest_stats": "Latest performance statistics for the check.",+ },+ },+ "pagespeed_history": {+ "description": "Historical pagespeed measurements (load time, page size, request count) for every pagespeed test.",+ "docs_url": "https://developers.statuscake.com/api/#tag/pagespeed/operation/list-pagespeed-test-history",+ "columns": {+ "test_id": _TEST_ID_COLUMN,+ "created_at": "Timestamp the measurement was recorded.",+ "loadtime_ms": "Page load time in milliseconds.",+ "filesize_kb": "Total page size in kilobytes.",+ "requests": "Number of requests made to load the page.",+ },+ },+ "ssl_tests": {+ "description": "SSL certificate checks configured in your StatusCake account, including current certificate details.",+ "docs_url": "https://developers.statuscake.com/api/#tag/ssl",+ "columns": {+ "id": "Unique identifier for the SSL check.",+ "website_url": "URL whose certificate is checked.",+ "check_rate": "Number of seconds between checks.",+ "contact_groups": "List of contact group ids alerted by this check.",+ "issuer_common_name": "Common name of the certificate issuer.",+ "certificate_score": "Certificate quality score.",+ "certificate_status": "Current status of the certificate.",+ "valid_from": "Timestamp the certificate became valid.",+ "valid_until": "Timestamp the certificate expires.",+ "paused": "Whether the check is paused.",+ },+ },+ "heartbeat_tests": {+ "description": "Heartbeat (push) checks configured in your StatusCake account.",+ "docs_url": "https://developers.statuscake.com/api/#tag/heartbeat",+ "columns": {+ "id": "Unique identifier for the heartbeat check.",+ "name": "Display name of the heartbeat check.",+ "period": "Number of seconds since the last ping before the check is considered down.",+ "contact_groups": "List of contact group ids alerted by this check.",+ "status": "Current status of the check (up or down).",+ "paused": "Whether the check is paused.",+ },+ },+ "contact_groups": {+ "description": "Contact groups that receive alerts from StatusCake checks.",+ "docs_url": "https://developers.statuscake.com/api/#tag/contact-groups",+ "columns": {+ "id": "Unique identifier for the contact group.",+ "name": "Display name of the contact group.",+ "email_addresses": "Email addresses alerted through this group.",+ "mobile_numbers": "Mobile numbers alerted through this group.",+ "integrations": "Third-party integration ids attached to this group.",+ "ping_url": "URL called when an alert fires for this group.",+ },+ },+ "maintenance_windows": {+ "description": "Maintenance windows during which uptime test alerts are suppressed.",+ "docs_url": "https://developers.statuscake.com/api/#tag/maintenance-windows",+ "columns": {+ "id": "Unique identifier for the maintenance window.",+ "name": "Display name of the maintenance window.",+ "start_at": "Timestamp the window starts.",+ "end_at": "Timestamp the window ends.",+ "repeat_interval": "How often the window repeats (never, daily, weekly, monthly).",+ "state": "Current state of the window (pending, active, paused).",+ "tests": "List of uptime test ids covered by the window.",+ "timezone": "Timezone the window's start and end times are expressed in.",+ },+ },+ "uptime_locations": {+ "description": "Monitoring locations available for uptime checks — a dimension for the location field on uptime history.",+ "docs_url": "https://developers.statuscake.com/api/#tag/locations",+ "columns": {+ "description": "Human-readable name of the monitoring location.",+ "region": "Geographic region of the location.",+ "region_code": "Short code for the region.",+ "status": "Operational status of the location.",+ "ipv4": "IPv4 address the location's checks originate from.",+ "ipv6": "IPv6 address the location's checks originate from.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/settings.pynew file mode 100644index 000000000000..71b80df8e00e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/settings.py@@ -0,0 +1,127 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class StatusCakeEndpointConfig:+ name: str+ # Path template relative to the API base. Top-level endpoints are absolute (e.g. "/uptime");+ # per-test history endpoints carry a {test_id} placeholder filled in during fan-out.+ path: str+ # Unique across the whole table. Fan-out children include "test_id" (injected by the connector)+ # because a single sync aggregates rows from every test — the raw history rows carry no test id+ # and their timestamps are only unique within one test.+ primary_key: Optional[list[str]]+ # Name of the parent endpoint whose test ids this endpoint fans out over (None for top-level).+ fan_out_over: Optional[str] = None+ # Row field carrying the record's event time. Doubles as the incremental cursor (mapped to the+ # API's `after` UNIX-timestamp param) and the partition key — these timestamps are immutable+ # event times, never updated_at-style fields.+ timestamp_field: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ should_sync_default: bool = True+ # Response fields dropped before rows are persisted. The warehouse is readable by any project+ # user, so a field carrying a live credential (e.g. a heartbeat push URL with its PK secret)+ # must never land there — otherwise it could be read back and used to spoof pings.+ scrub_fields: Optional[list[str]] = None+++# StatusCake API v1 (https://developers.statuscake.com/api/). Config/test lists have no+# changed-since filter and are full refresh only; the per-test history endpoints accept+# `before`/`after` UNIX-timestamp bounds, which is what powers incremental sync.+STATUSCAKE_ENDPOINTS: dict[str, StatusCakeEndpointConfig] = {+ "uptime_tests": StatusCakeEndpointConfig(+ name="uptime_tests",+ path="/uptime",+ primary_key=["id"],+ ),+ "uptime_history": StatusCakeEndpointConfig(+ name="uptime_history",+ path="/uptime/{test_id}/history",+ # History rows have no id of their own; a test can be checked from more than one location,+ # so the location is part of the identity alongside the check timestamp.+ primary_key=["test_id", "created_at", "location"],+ fan_out_over="uptime_tests",+ timestamp_field="created_at",+ incremental_fields=[_datetime_field("created_at")],+ ),+ "uptime_periods": StatusCakeEndpointConfig(+ name="uptime_periods",+ path="/uptime/{test_id}/periods",+ primary_key=["test_id", "created_at"],+ fan_out_over="uptime_tests",+ timestamp_field="created_at",+ incremental_fields=[_datetime_field("created_at")],+ ),+ "uptime_alerts": StatusCakeEndpointConfig(+ name="uptime_alerts",+ path="/uptime/{test_id}/alerts",+ primary_key=["test_id", "triggered_at"],+ fan_out_over="uptime_tests",+ timestamp_field="triggered_at",+ incremental_fields=[_datetime_field("triggered_at")],+ ),+ "pagespeed_tests": StatusCakeEndpointConfig(+ name="pagespeed_tests",+ path="/pagespeed",+ primary_key=["id"],+ ),+ "pagespeed_history": StatusCakeEndpointConfig(+ name="pagespeed_history",+ path="/pagespeed/{test_id}/history",+ primary_key=["test_id", "created_at"],+ fan_out_over="pagespeed_tests",+ timestamp_field="created_at",+ incremental_fields=[_datetime_field("created_at")],+ ),+ "ssl_tests": StatusCakeEndpointConfig(+ name="ssl_tests",+ path="/ssl",+ primary_key=["id"],+ ),+ "heartbeat_tests": StatusCakeEndpointConfig(+ name="heartbeat_tests",+ path="/heartbeat",+ primary_key=["id"],+ # The push `url` embeds the check's PK credential; drop it so it never reaches the warehouse.+ scrub_fields=["url"],+ ),+ "contact_groups": StatusCakeEndpointConfig(+ name="contact_groups",+ path="/contact-groups",+ primary_key=["id"],+ # The `ping_url` callback is invoked when the group is alerted and commonly embeds a webhook+ # secret; drop it so it never reaches the warehouse and can't be read back to spoof alerts.+ scrub_fields=["ping_url"],+ ),+ "maintenance_windows": StatusCakeEndpointConfig(+ name="maintenance_windows",+ path="/maintenance-windows",+ primary_key=["id"],+ ),+ # Monitoring-location dimension. Locations carry no id, so the table is full-refresh replace+ # with no primary key (there is nothing to merge on).+ "uptime_locations": StatusCakeEndpointConfig(+ name="uptime_locations",+ path="/uptime-locations",+ primary_key=None,+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(STATUSCAKE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in STATUSCAKE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/source.pyindex 05717e257d48..0c46f0ba7eae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/source.py@@ -1,19 +1,43 @@-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 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.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 StatuscakeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ STATUSCAKE_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.statuscake import (+ StatusCakeResumeConfig,+ statuscake_source,+ validate_credentials as validate_statuscake_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class StatuscakeSource(SimpleSource[StatuscakeSourceConfig]):+class StatuscakeSource(ResumableSource[StatuscakeSourceConfig, StatusCakeResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.STATUSCAKE@@ -24,7 +48,99 @@ class StatuscakeSource(SimpleSource[StatuscakeSourceConfig]):name=SchemaExternalDataSourceType.STATUSCAKE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="StatusCake",+ caption=(+ "Sync your StatusCake uptime, SSL, pagespeed, and heartbeat monitoring data. "+ "Generate an API token under **[Account Settings > API Keys](https://app.statuscake.com/User.php)** "+ "in your StatusCake dashboard and paste it below. The token has account-wide read access; "+ "no extra scopes are required."+ ),iconPath="/static/services/statuscake.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/statuscake",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["uptime", "monitoring", "ssl"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your StatusCake API token",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.statuscake.com": "Your StatusCake API token is invalid or has been revoked. Generate a new token in your StatusCake account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.statuscake.com": "Your StatusCake API token does not have permission to read this data. Please check the token and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: StatuscakeSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if STATUSCAKE_ENDPOINTS[endpoint].fan_out_over is not None:+ return (+ "Fetched per test, so a sync makes one request chain per test in your account. "+ "History retention on StatusCake depends on your plan"+ )+ return None++ schemas = [+ SourceSchema(+ name=endpoint,+ # Only the per-test history endpoints expose a server-side `after` timestamp bound;+ # the config/test lists have no changed-since filter and are full refresh only.+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=STATUSCAKE_ENDPOINTS[endpoint].should_sync_default,+ description=_description(endpoint),+ )+ for endpoint in list(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: StatuscakeSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_statuscake_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[StatusCakeResumeConfig]:+ return ResumableSourceManager[StatusCakeResumeConfig](inputs, StatusCakeResumeConfig)++ def source_for_pipeline(+ self,+ config: StatuscakeSourceConfig,+ resumable_source_manager: ResumableSourceManager[StatusCakeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return statuscake_source(+ 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/statuscake/statuscake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/statuscake.pynew file mode 100644index 000000000000..8eeff35cf325--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/statuscake.py@@ -0,0 +1,356 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from 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.statuscake.settings import (+ STATUSCAKE_ENDPOINTS,+ StatusCakeEndpointConfig,+)++STATUSCAKE_BASE_URL = "https://api.statuscake.com/v1"++# StatusCake rate-limits per account (60 requests/minute on free plans, 5 requests/second on paid)+# and answers HTTP 429 when exceeded. The backoff cap sits above the free plan's 60s window so a+# throttled fan-out (one request chain per test) clears rather than exhausting its retries.+_MAX_ATTEMPTS = 8+_REQUEST_TIMEOUT_SECONDS = 60+_PAGE_SIZE = 100 # documented maximum for `limit`+++class StatusCakeRetryableError(Exception):+ """Raised for rate-limit (429) and transient 5xx responses so tenacity retries them."""++ pass+++class StatusCakeResumeConfig:+ # Top-level list endpoints: the page number most recently yielded. On resume we re-fetch and+ # re-yield that page (merge dedupes on the primary key) rather than risk skipping rows that+ # were buffered but not yet persisted when the worker stopped.+ page: Optional[int] = None+ # Fan-out endpoints: the test id currently being read — a stable bookmark (not a positional+ # index) so tests added/removed between a crash and the retry can't resume us into the wrong+ # test. None for top-level endpoints.+ test_id: Optional[str] = None+ # Fan-out endpoints: full URL of the next history page (from the response's links.next). None+ # means "start the bookmarked test at its first page".+ next_url: Optional[str] = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _build_url(path: str, params: dict[str, Any]) -> str:+ base = f"{STATUSCAKE_BASE_URL}{path}"+ return f"{base}?{urlencode(params)}" if params else base+++def _scrub_rows(rows: list[dict[str, Any]], fields: Optional[list[str]]) -> list[dict[str, Any]]:+ """Drop sensitive fields (e.g. heartbeat push credentials) before rows reach the warehouse."""+ if not fields:+ return rows+ for row in rows:+ for field in fields:+ row.pop(field, None)+ return rows+++def _is_api_url(url: Any) -> bool:+ """Only follow pagination URLs pinned to the StatusCake API origin.++ The session's default headers carry the account token, so an off-origin `links.next` (a+ tampered upstream response, or poisoned resume state read back from Redis) would send the+ credential to an attacker-controlled host. `allow_redirects=False` doesn't cover a direct+ off-origin request, so the URL itself must be validated before it's persisted or fetched.+ """+ if not isinstance(url, str):+ return False+ parts = urlsplit(url)+ return parts.scheme == "https" and parts.netloc == "api.statuscake.com" and parts.path.startswith("/v1/")+++def _get_session(api_key: str) -> requests.Session:+ # One session per sync so keep-alive is preserved across pages and the per-test fan-out.+ # `redact_values` masks the token from request telemetry/log samples, and+ # `allow_redirects=False` keeps a credentialed request pinned to the StatusCake host.+ return make_tracked_session(+ headers=_get_headers(api_key),+ redact_values=(api_key,),+ allow_redirects=False,+ )+++def _to_unix_timestamp(value: Any) -> Optional[int]:+ """Convert an incremental watermark (datetime/date/unix int/RFC3339 string) to UNIX seconds."""+ 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):+ parsed = _parse_rfc3339(value)+ return int(parsed.timestamp()) if parsed else None+ return None+++def _parse_rfc3339(value: Any) -> Optional[datetime]:+ if not isinstance(value, str):+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+++@retry(+ retry=retry_if_exception_type((StatusCakeRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(_MAX_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ response = session.get(url, timeout=_REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise StatusCakeRetryableError(f"StatusCake API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404 is expected during the fan-out (a test deleted mid-sync) and handled by the caller.+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"StatusCake API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _iter_list_pages(+ session: requests.Session,+ path: str,+ logger: FilteringBoundLogger,+ start_page: int = 1,+) -> Iterator[tuple[list[dict[str, Any]], int]]:+ """Yield (rows, page_number) for each non-empty page of a top-level list endpoint.++ Paginated list endpoints return a `metadata` object with `page`/`page_count`; we advance until+ `page_count` is exhausted. Some list endpoints (SSL, heartbeat, locations) return everything in+ one response with no metadata — for those the absence of `page_count` terminates after the+ first page, which also protects against endpoints that ignore the `page` param and would+ otherwise return the same full list forever.+ """+ page = start_page+ while True:+ url = _build_url(path, {"page": page, "limit": _PAGE_SIZE})+ data = _fetch_page(session, url, logger)+ rows = data.get("data", [])+ if not rows:+ return+ yield rows, page+ page_count = (data.get("metadata") or {}).get("page_count")+ if page_count is None or page >= page_count:+ return+ page += 1+++def _list_test_ids(+ session: requests.Session, parent: StatusCakeEndpointConfig, logger: FilteringBoundLogger+) -> list[str]:+ """List every test id of the parent endpoint that history endpoints fan out over."""+ test_ids: list[str] = []+ for rows, _page in _iter_list_pages(session, parent.path, logger):+ for row in rows:+ # Direct access: the id drives the entire fan-out, so a test without one is a malformed+ # response we want to surface loudly rather than silently drop its history.+ test_ids.append(str(row["id"]))+ return test_ids+++def _page_predates_watermark(+ rows: list[dict[str, Any]], timestamp_field: Optional[str], watermark: Optional[datetime]+) -> bool:+ """True when the oldest row of a (newest-first) page is older than the incremental watermark.++ Belt and braces for incremental pagination: even if the API ignores `after` (or drops it from+ the `links.next` cursor URL), we must not re-walk each test's full history on every sync.+ Unparseable timestamps never stop pagination — better to over-fetch than skip rows.+ """+ if watermark is None or timestamp_field is None or not rows:+ return False+ oldest = _parse_rfc3339(rows[-1].get(timestamp_field))+ return oldest is not None and oldest < watermark+++def _iter_history_rows(+ session: requests.Session,+ config: StatusCakeEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StatusCakeResumeConfig],+ watermark_ts: Optional[int],+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every parent test, yielding its (newest-first) history pages.++ History endpoints paginate with a cursor in the response's `links.next` and accept an `after`+ UNIX-timestamp lower bound, which carries the incremental watermark. The injected `test_id`+ makes the composite primary key unique table-wide.+ """+ assert config.fan_out_over is not None+ parent = STATUSCAKE_ENDPOINTS[config.fan_out_over]+ test_ids = _list_test_ids(session, parent, logger)++ params: dict[str, Any] = {"limit": _PAGE_SIZE}+ if watermark_ts is not None:+ # One second of overlap in case `after` is exclusive; merge dedupes on the primary key.+ params["after"] = watermark_ts - 1+ watermark = datetime.fromtimestamp(watermark_ts, tz=UTC) if watermark_ts is not None else None++ # Resolve the saved test-id bookmark to the slice of tests still to process. If the bookmarked+ # test no longer exists, start over from the first test — merge dedupes re-pulled rows.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = test_ids+ resume_url: Optional[str] = None+ if resume is not None and resume.test_id is not None and resume.test_id in test_ids:+ remaining = test_ids[test_ids.index(resume.test_id) :]+ # An off-origin resume URL restarts the bookmarked test from its first page instead.+ resume_url = resume.next_url if _is_api_url(resume.next_url) else None+ logger.debug(f"StatusCake: resuming {config.name} from test_id={resume.test_id}, url={resume_url}")++ for index, test_id in enumerate(remaining):+ url = resume_url or _build_url(config.path.format(test_id=test_id), params)+ resume_url = None # only the resumed-into test uses the saved URL; the rest start fresh++ try:+ while True:+ data = _fetch_page(session, url, logger)+ rows = data.get("data", [])+ if not rows:+ break+ for row in rows:+ row["test_id"] = test_id+ next_url = (data.get("links") or {}).get("next")+ if next_url and not _is_api_url(next_url):+ logger.warning(f"StatusCake: ignoring off-origin next link for test {test_id}: {next_url}")+ next_url = None+ yield rows+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the+ # last page rather than skipping it — merge dedupes on the primary key.+ if next_url:+ resumable_source_manager.save_state(StatusCakeResumeConfig(next_url=next_url, test_id=test_id))+ if not next_url or _page_predates_watermark(rows, config.timestamp_field, watermark):+ break+ url = next_url+ except requests.HTTPError as exc:+ # A test deleted between enumeration and this fetch 404s. Skip it rather than failing+ # the whole sync — its history is genuinely gone. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"StatusCake: test {test_id} not found while fetching {config.name}, skipping")+ else:+ raise++ # Advance the bookmark to the next test so a crash between tests resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(StatusCakeResumeConfig(test_id=remaining[index + 1], next_url=None))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StatusCakeResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = STATUSCAKE_ENDPOINTS[endpoint]+ session = _get_session(api_key)++ if config.fan_out_over is not None:+ watermark_ts = (+ _to_unix_timestamp(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value is not None+ else None+ )+ for rows in _iter_history_rows(session, config, logger, resumable_source_manager, watermark_ts):+ yield _scrub_rows(rows, config.scrub_fields)+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_page = resume.page if resume is not None and resume.page is not None else 1+ if resume is not None:+ logger.debug(f"StatusCake: resuming {endpoint} from page {start_page}")+ for rows, page in _iter_list_pages(session, config.path, logger, start_page=start_page):+ yield _scrub_rows(rows, config.scrub_fields)+ resumable_source_manager.save_state(StatusCakeResumeConfig(page=page))+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """Confirm the API token is genuine with one cheap probe against the uptime test listing."""+ url = _build_url("/uptime", {"limit": 1, "page": 1})+ try:+ response = _get_session(api_key).get(url, timeout=10)+ 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 StatusCake API token. Please check your token and try again."+ if response.status_code == 403:+ return False, "Your StatusCake API token does not have permission to list uptime checks."++ try:+ message = response.json().get("message", response.text)+ except Exception:+ message = response.text+ return False, message+++def statuscake_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StatusCakeResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = STATUSCAKE_ENDPOINTS[endpoint]++ def items() -> Iterator[list[dict[str, Any]]]:+ return get_rows(+ api_key,+ endpoint,+ logger,+ resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_key,+ # History endpoints return rows newest-first, and the fan-out means a partial run's max+ # timestamp says nothing about tests it never reached — desc persists the incremental+ # watermark only at successful job end. Top-level lists are full refresh in stable page+ # order, so asc is correct there.+ sort_mode="desc" if config.fan_out_over is not None else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.timestamp_field else None,+ partition_format="month" if config.timestamp_field else None,+ partition_keys=[config.timestamp_field] if config.timestamp_field else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/tests/test_statuscake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/tests/test_statuscake.pynew file mode 100644index 000000000000..f4c750bbfc26--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/tests/test_statuscake.py@@ -0,0 +1,415 @@+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.settings import STATUSCAKE_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.statuscake import (+ StatusCakeResumeConfig,+ StatusCakeRetryableError,+ _build_url,+ _fetch_page,+ _get_headers,+ _to_unix_timestamp,+ get_rows,+ statuscake_source,+ validate_credentials,+)++_TRANSPORT = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.statuscake.make_tracked_session"+)+++def _make_manager(resume_state: StatusCakeResumeConfig | 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 = 200 <= status_code < 300+ return resp+++def _session_returning(*bodies: Any) -> mock.MagicMock:+ """Build a session whose successive .get() calls return the given JSON bodies."""+ session = mock.MagicMock()+ session.get.side_effect = [_response(b) for b in bodies]+ return session+++def _list_body(rows: list[dict[str, Any]], page: int, page_count: int) -> dict[str, Any]:+ return {"data": rows, "metadata": {"page": page, "per_page": 100, "page_count": page_count}}+++def _history_body(rows: list[dict[str, Any]], next_url: str | None = None) -> dict[str, Any]:+ links: dict[str, Any] = {"self": "..."}+ if next_url:+ links["next"] = next_url+ return {"data": rows, "links": links}+++class TestHeaders:+ def test_bearer_token(self):+ assert _get_headers("abc123")["Authorization"] == "Bearer abc123"+++class TestBuildUrl:+ def test_encodes_params(self):+ assert (+ _build_url("/uptime", {"page": 1, "limit": 100}) == "https://api.statuscake.com/v1/uptime?page=1&limit=100"+ )++ def test_no_params(self):+ assert _build_url("/uptime-locations", {}) == "https://api.statuscake.com/v1/uptime-locations"+++class TestFetchPage:+ @pytest.mark.parametrize("status_code", [429, 500, 503])+ def test_retryable_statuses_raise_after_retries(self, status_code, monkeypatch):+ # Skip tenacity's real exponential-backoff sleeps while still exercising the retry count.+ monkeypatch.setattr("tenacity.nap.time.sleep", lambda _seconds: None)+ session = mock.MagicMock()+ session.get.return_value = _response({}, status_code=status_code)+ with pytest.raises(StatusCakeRetryableError):+ _fetch_page(session, "https://api.statuscake.com/v1/uptime", mock.MagicMock())+ assert session.get.call_count == 8++ def test_client_error_raises_for_status(self):+ resp = _response({"message": "Invalid token"}, status_code=401)+ resp.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=resp)+ session = mock.MagicMock()+ session.get.return_value = resp+ with pytest.raises(requests.HTTPError):+ _fetch_page(session, "https://api.statuscake.com/v1/uptime", mock.MagicMock())+++class TestToUnixTimestamp:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 1, 1, tzinfo=UTC), 1767225600),+ (datetime(2026, 1, 1), 1767225600), # naive datetimes are treated as UTC+ (1767225600, 1767225600),+ ("2026-01-01T00:00:00Z", 1767225600),+ ("not a date", None),+ (None, None),+ ],+ )+ def test_conversions(self, value, expected):+ assert _to_unix_timestamp(value) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected_ok",+ [(200, True), (401, False), (403, False), (500, False)],+ )+ @mock.patch(_TRANSPORT)+ def test_status_mapping(self, mock_session, status_code, expected_ok):+ body = _list_body([], 1, 1) if status_code == 200 else {"message": "nope"}+ mock_session.return_value.get.return_value = _response(body, status_code=status_code)+ ok, error = validate_credentials("token")+ assert ok is expected_ok+ if not ok:+ assert error++ @mock.patch(_TRANSPORT)+ def test_request_exception_is_failure(self, mock_session):+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")+ ok, error = validate_credentials("token")+ assert ok is False+ assert "boom" in (error or "")+++class TestGetRowsTopLevel:+ @mock.patch(_TRANSPORT)+ def test_paginates_until_page_count_exhausted(self, mock_session):+ mock_session.return_value = _session_returning(+ _list_body([{"id": "1"}, {"id": "2"}], page=1, page_count=2),+ _list_body([{"id": "3"}], page=2, page_count=2),+ )+ manager = _make_manager()++ batches = list(get_rows("token", "uptime_tests", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]+ saved = [c.args[0] for c in manager.save_state.call_args_list]+ assert [s.page for s in saved] == [1, 2]++ @mock.patch(_TRANSPORT)+ def test_stops_after_one_page_without_metadata(self, mock_session):+ # SSL/heartbeat/locations return everything in one unpaginated response. Without this+ # guard an endpoint that ignores the `page` param would return the same list forever.+ mock_session.return_value = _session_returning({"data": [{"id": "s1"}, {"id": "s2"}]})+ manager = _make_manager()++ batches = list(get_rows("token", "ssl_tests", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["s1", "s2"]+ assert mock_session.return_value.get.call_count == 1++ @mock.patch(_TRANSPORT)+ def test_heartbeat_push_credential_is_scrubbed(self, mock_session):+ # The /heartbeat push `url` embeds the check's PK credential. It must never reach the+ # warehouse, where any project user could read it back and spoof heartbeat pings.+ mock_session.return_value = _session_returning(+ {"data": [{"id": "h1", "name": "cron", "url": "https://push.statuscake.com/?PK=secret&TestID=h1"}]}+ )+ manager = _make_manager()++ batches = list(get_rows("token", "heartbeat_tests", mock.MagicMock(), manager))+ rows = [row for batch in batches for row in batch]++ assert rows == [{"id": "h1", "name": "cron"}]++ @mock.patch(_TRANSPORT)+ def test_contact_group_ping_url_is_scrubbed(self, mock_session):+ # The /contact-groups `ping_url` is a callback invoked on alert and can embed a webhook+ # secret. It must never reach the warehouse, where any project user could read it back.+ mock_session.return_value = _session_returning(+ {"data": [{"id": "c1", "name": "ops", "ping_url": "https://hooks.example.com/?token=secret"}]}+ )+ manager = _make_manager()++ batches = list(get_rows("token", "contact_groups", mock.MagicMock(), manager))+ rows = [row for batch in batches for row in batch]++ assert rows == [{"id": "c1", "name": "ops"}]++ @mock.patch(_TRANSPORT)+ def test_resumes_from_saved_page(self, mock_session):+ mock_session.return_value = _session_returning(+ _list_body([{"id": "9"}], page=3, page_count=3),+ )+ manager = _make_manager(StatusCakeResumeConfig(page=3))++ list(get_rows("token", "uptime_tests", mock.MagicMock(), manager))++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "page=3" in first_url+++class TestGetRowsFanOut:+ @mock.patch(_TRANSPORT)+ def test_fans_out_over_tests_and_injects_test_id(self, mock_session):+ mock_session.return_value = _session_returning(+ _list_body([{"id": "t1"}, {"id": "t2"}], page=1, page_count=1),+ _history_body([{"created_at": "2026-01-02T00:00:00Z", "status_code": 200, "location": "UK"}]),+ _history_body([{"created_at": "2026-01-03T00:00:00Z", "status_code": 200, "location": "US"}]),+ )+ manager = _make_manager()++ batches = list(get_rows("token", "uptime_history", mock.MagicMock(), manager))+ rows = [row for batch in batches for row in batch]++ assert [row["test_id"] for row in rows] == ["t1", "t2"]+ # The bookmark advances to the next test between fan-out iterations.+ saved = [c.args[0] for c in manager.save_state.call_args_list]+ assert [(s.test_id, s.next_url) for s in saved] == [("t2", None)]++ @mock.patch(_TRANSPORT)+ def test_follows_next_links_and_saves_resume_url(self, mock_session):+ next_url = "https://api.statuscake.com/v1/uptime/t1/history?before=123&limit=100"+ mock_session.return_value = _session_returning(+ _list_body([{"id": "t1"}], page=1, page_count=1),+ _history_body([{"created_at": "2026-01-02T00:00:00Z", "location": "UK"}], next_url=next_url),+ _history_body([{"created_at": "2026-01-01T00:00:00Z", "location": "UK"}]),+ )+ manager = _make_manager()++ list(get_rows("token", "uptime_history", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_args_list[2].args[0] == next_url+ saved = [c.args[0] for c in manager.save_state.call_args_list]+ assert (saved[0].test_id, saved[0].next_url) == ("t1", next_url)++ @mock.patch(_TRANSPORT)+ def test_resumes_at_saved_test_and_url(self, mock_session):+ resume_url = "https://api.statuscake.com/v1/uptime/t2/history?before=456&limit=100"+ mock_session.return_value = _session_returning(+ _list_body([{"id": "t1"}, {"id": "t2"}], page=1, page_count=1),+ _history_body([{"created_at": "2026-01-01T00:00:00Z", "location": "UK"}]),+ )+ manager = _make_manager(StatusCakeResumeConfig(test_id="t2", next_url=resume_url))++ batches = list(get_rows("token", "uptime_history", mock.MagicMock(), manager))+ rows = [row for batch in batches for row in batch]++ # t1 is skipped entirely and t2 resumes from the saved cursor URL.+ assert all(row["test_id"] == "t2" for row in rows)+ history_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/history" in c.args[0]]+ assert history_urls == [resume_url]++ @mock.patch(_TRANSPORT)+ def test_off_origin_next_link_is_never_fetched_or_persisted(self, mock_session):+ # The session's default headers carry the account token: a tampered response pointing+ # links.next off-origin must not receive a request (or be saved as resume state).+ hostile = "https://evil.example.com/v1/uptime/t1/history?before=123"+ mock_session.return_value = _session_returning(+ _list_body([{"id": "t1"}], page=1, page_count=1),+ _history_body([{"created_at": "2026-01-02T00:00:00Z", "location": "UK"}], next_url=hostile),+ )+ manager = _make_manager()++ list(get_rows("token", "uptime_history", mock.MagicMock(), manager))++ fetched = [c.args[0] for c in mock_session.return_value.get.call_args_list]+ assert hostile not in fetched+ assert all(c.args[0].next_url != hostile for c in manager.save_state.call_args_list)++ @mock.patch(_TRANSPORT)+ def test_off_origin_resume_url_restarts_test_from_first_page(self, mock_session):+ hostile = "https://evil.example.com/v1/uptime/t1/history?before=456"+ mock_session.return_value = _session_returning(+ _list_body([{"id": "t1"}], page=1, page_count=1),+ _history_body([{"created_at": "2026-01-01T00:00:00Z", "location": "UK"}]),+ )+ manager = _make_manager(StatusCakeResumeConfig(test_id="t1", next_url=hostile))++ list(get_rows("token", "uptime_history", mock.MagicMock(), manager))++ history_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/history" in c.args[0]]+ assert history_urls == ["https://api.statuscake.com/v1/uptime/t1/history?limit=100"]++ @mock.patch(_TRANSPORT)+ def test_deleted_test_404_is_skipped(self, mock_session):+ not_found = _response({"message": "not found"}, status_code=404)+ not_found.raise_for_status.side_effect = requests.HTTPError("404 Client Error", response=not_found)+ session = mock.MagicMock()+ session.get.side_effect = [+ _response(_list_body([{"id": "t1"}, {"id": "t2"}], page=1, page_count=1)),+ not_found,+ _response(_history_body([{"created_at": "2026-01-01T00:00:00Z", "location": "UK"}])),+ ]+ mock_session.return_value = session+ manager = _make_manager()++ batches = list(get_rows("token", "uptime_history", mock.MagicMock(), manager))+ rows = [row for batch in batches for row in batch]++ assert [row["test_id"] for row in rows] == ["t2"]+++class TestIncremental:+ @mock.patch(_TRANSPORT)+ def test_watermark_maps_to_after_param(self, mock_session):+ mock_session.return_value = _session_returning(+ _list_body([{"id": "t1"}], page=1, page_count=1),+ _history_body([{"created_at": "2026-01-02T00:00:00Z", "location": "UK"}]),+ )+ manager = _make_manager()+ watermark = datetime(2026, 1, 1, tzinfo=UTC)++ list(+ get_rows(+ "token",+ "uptime_history",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ )++ history_url = mock_session.return_value.get.call_args_list[1].args[0]+ # One second of overlap in case `after` is exclusive; merge dedupes on the primary key.+ assert f"after={int(watermark.timestamp()) - 1}" in history_url++ @mock.patch(_TRANSPORT)+ def test_full_refresh_sends_no_after_param(self, mock_session):+ mock_session.return_value = _session_returning(+ _list_body([{"id": "t1"}], page=1, page_count=1),+ _history_body([{"created_at": "2026-01-02T00:00:00Z", "location": "UK"}]),+ )+ manager = _make_manager()++ list(get_rows("token", "uptime_history", mock.MagicMock(), manager))++ history_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert "after=" not in history_url++ @mock.patch(_TRANSPORT)+ def test_pagination_stops_once_page_predates_watermark(self, mock_session):+ # Guards the incremental-cost regression: if the API ignores `after` (or drops it from the+ # links.next cursor), we must stop client-side instead of re-walking the full history.+ mock_session.return_value = _session_returning(+ _list_body([{"id": "t1"}], page=1, page_count=1),+ _history_body(+ [{"created_at": "2025-12-31T00:00:00Z", "location": "UK"}],+ next_url="https://api.statuscake.com/v1/uptime/t1/history?before=1",+ ),+ )+ manager = _make_manager()++ list(+ get_rows(+ "token",+ "uptime_history",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ )++ # The next link is never followed: 1 parent-list call + 1 history call.+ assert mock_session.return_value.get.call_count == 2++ @mock.patch(_TRANSPORT)+ def test_pagination_keeps_walking_without_watermark(self, mock_session):+ mock_session.return_value = _session_returning(+ _list_body([{"id": "t1"}], page=1, page_count=1),+ _history_body(+ [{"created_at": "2025-12-31T00:00:00Z", "location": "UK"}],+ next_url="https://api.statuscake.com/v1/uptime/t1/history?before=1",+ ),+ _history_body([{"created_at": "2025-12-30T00:00:00Z", "location": "UK"}]),+ )+ manager = _make_manager()++ batches = list(get_rows("token", "uptime_history", mock.MagicMock(), manager))++ assert len([row for batch in batches for row in batch]) == 2+++class TestStatuscakeSourceResponse:+ @pytest.mark.parametrize("endpoint", list(STATUSCAKE_ENDPOINTS.keys()))+ def test_source_response_shape(self, endpoint):+ config = STATUSCAKE_ENDPOINTS[endpoint]+ response = statuscake_source("token", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_key+ if config.fan_out_over is not None:+ # History rows arrive newest-first and the fan-out means a partial run's max timestamp+ # says nothing about tests it never reached — asc here would corrupt the watermark.+ assert response.sort_mode == "desc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.timestamp_field]+ else:+ assert response.sort_mode == "asc"+ assert response.partition_mode is None++ @pytest.mark.parametrize(+ "endpoint, expected_keys",+ [+ ("uptime_tests", ["id"]),+ ("uptime_history", ["test_id", "created_at", "location"]),+ ("uptime_periods", ["test_id", "created_at"]),+ ("uptime_alerts", ["test_id", "triggered_at"]),+ ("pagespeed_history", ["test_id", "created_at"]),+ ],+ )+ def test_primary_keys_are_unique_table_wide(self, endpoint, expected_keys):+ # Fan-out children carry the injected test id in their key so rows from different tests+ # never collide on a bare per-test timestamp.+ assert STATUSCAKE_ENDPOINTS[endpoint].primary_key == expected_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/tests/test_statuscake_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/tests/test_statuscake_source.pynew file mode 100644index 000000000000..8c6dd43a103c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/statuscake/tests/test_statuscake_source.py@@ -0,0 +1,127 @@+from datetime import UTC, datetime++import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ 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 StatuscakeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.source import StatuscakeSource+from products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.statuscake import (+ StatusCakeResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_INCREMENTAL_ENDPOINTS = {"uptime_history", "uptime_periods", "uptime_alerts", "pagespeed_history"}+++class TestStatuscakeSource:+ def setup_method(self):+ self.source = StatuscakeSource()+ self.team_id = 123++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.STATUSCAKE++ def test_source_config_is_released_alpha(self):+ config = self.source.get_source_config+ assert config.label == "StatusCake"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # The scaffold shipped hidden; a finished source must be visible to users.+ assert not config.unreleasedSource++ def test_source_config_has_secret_api_key_field(self):+ fields = self.source.get_source_config.fields+ assert len(fields) == 1+ api_key = fields[0]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.name == "api_key"+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.required is True+ assert api_key.secret is True++ def test_get_schemas_incremental_split(self):+ schemas = self.source.get_schemas(StatuscakeSourceConfig(api_key="token"), self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Only the per-test history endpoints have a server-side `after` bound; config/test lists+ # have no changed-since filter and must stay full refresh.+ assert {s.name for s in schemas if s.supports_incremental} == _INCREMENTAL_ENDPOINTS+ assert all(s.incremental_fields for s in schemas if s.supports_incremental)+ assert all(not s.incremental_fields for s in schemas if not s.supports_incremental)++ def test_get_schemas_filters_by_names(self):+ schemas = self.source.get_schemas(+ StatuscakeSourceConfig(api_key="token"), self.team_id, names=["uptime_tests", "uptime_history"]+ )+ assert {s.name for s in schemas} == {"uptime_tests", "uptime_history"}++ @pytest.mark.parametrize(+ "expected_key",+ [+ "401 Client Error: Unauthorized for url: https://api.statuscake.com",+ "403 Client Error: Forbidden for url: https://api.statuscake.com",+ ],+ )+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_canonical_descriptions_cover_every_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.source.validate_statuscake_credentials"+ )+ def test_validate_credentials_delegates_with_api_key(self, mock_validate):+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(StatuscakeSourceConfig(api_key="secret-token"), self.team_id)+ assert result == (True, None)+ mock_validate.assert_called_once_with("secret-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 StatusCakeResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.source.statuscake_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_statuscake_source):+ config = StatuscakeSourceConfig(api_key="token")+ manager = mock.MagicMock()+ inputs = mock.MagicMock()+ inputs.schema_name = "uptime_history"+ inputs.logger = mock.MagicMock()+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = datetime(2026, 1, 1, tzinfo=UTC)++ self.source.source_for_pipeline(config, manager, inputs)++ mock_statuscake_source.assert_called_once_with(+ api_key="token",+ endpoint="uptime_history",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.statuscake.source.statuscake_source")+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self, mock_statuscake_source):+ # A full refresh must not carry a stale watermark into the transport, or the sync would+ # silently skip history older than the last incremental run.+ inputs = mock.MagicMock()+ inputs.schema_name = "uptime_history"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = datetime(2026, 1, 1, tzinfo=UTC)++ self.source.source_for_pipeline(StatuscakeSourceConfig(api_key="token"), mock.MagicMock(), inputs)++ assert mock_statuscake_source.call_args.kwargs["db_incremental_field_last_value"] is None