: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 statuspage import source (#65659)
Tom Owersc2e4c1ed0eef
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 3325ac2b5598..4134d13b7906 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -178,6 +178,7 @@ the row lists both.| snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || snowflake | DB protocol | snowflake-connector-python | ➖ || square | HTTP | requests | ✅ |+| statuspage | HTTP | requests | ✅ || stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ || surveymonkey | HTTP | requests | ✅ |@@ -634,7 +635,6 @@ doesn't conflict with concurrent PRs.- spotlercrm- squarespace- statsig-- statuspage- stigg- stockdata- stravadiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 475403fe09e0..e2be0bb93cc4 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -2949,7 +2949,7 @@ class StatsigSourceConfig(config.Config):@config.configclass StatuspageSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/statuspage/canonical_descriptions.py b/posthog/temporal/data_imports/sources/statuspage/canonical_descriptions.pynew file mode 100644index 000000000000..332d2166b5b9--- /dev/null+++ b/posthog/temporal/data_imports/sources/statuspage/canonical_descriptions.py@@ -0,0 +1,154 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Descriptions are taken from Atlassian Statuspage's Manage API docs. The "page_id" column on every+# page-scoped table is injected by the connector (it carries the parent status page id), so it is+# documented here even though it isn't part of the raw list-endpoint payload.+_PAGE_ID_COLUMN = "Identifier of the status page this record belongs to (added by the connector)."++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "pages": {+ "description": "Status pages in your Statuspage organization.",+ "docs_url": "https://developer.statuspage.io/#tag/pages",+ "columns": {+ "id": "Unique identifier for the status page.",+ "name": "Display name of the status page.",+ "url": "Public URL of the status page.",+ "subdomain": "Statuspage subdomain for the page (e.g. mycompany in mycompany.statuspage.io).",+ "domain": "Custom domain mapped to the status page, if configured.",+ "time_zone": "Time zone the page displays times in.",+ "created_at": "Timestamp when the page was created.",+ "updated_at": "Timestamp when the page was last updated.",+ },+ },+ "components": {+ "description": "Individual services or features whose status is shown on a status page.",+ "docs_url": "https://developer.statuspage.io/#tag/components",+ "columns": {+ "id": "Unique identifier for the component.",+ "page_id": _PAGE_ID_COLUMN,+ "name": "Display name of the component.",+ "description": "Description of the component.",+ "status": "Current status (operational, degraded_performance, partial_outage, major_outage, under_maintenance).",+ "position": "Display order of the component on the page.",+ "group_id": "Identifier of the component group this component belongs to, if any.",+ "showcase": "Whether the component is shown on the public status page.",+ "created_at": "Timestamp when the component was created.",+ "updated_at": "Timestamp when the component was last updated.",+ },+ },+ "component_groups": {+ "description": "Groups that bundle related components together on a status page.",+ "docs_url": "https://developer.statuspage.io/#tag/component-groups",+ "columns": {+ "id": "Unique identifier for the component group.",+ "page_id": _PAGE_ID_COLUMN,+ "name": "Display name of the component group.",+ "description": "Description of the component group.",+ "position": "Display order of the group on the page.",+ "components": "List of component ids belonging to this group.",+ "created_at": "Timestamp when the component group was created.",+ "updated_at": "Timestamp when the component group was last updated.",+ },+ },+ "incidents": {+ "description": "Incidents and scheduled maintenances published to a status page.",+ "docs_url": "https://developer.statuspage.io/#tag/incidents",+ "columns": {+ "id": "Unique identifier for the incident.",+ "page_id": _PAGE_ID_COLUMN,+ "name": "Title of the incident.",+ "status": "Current incident status (investigating, identified, monitoring, resolved, scheduled, etc.).",+ "impact": "Impact level of the incident (none, maintenance, minor, major, critical).",+ "shortlink": "Short public URL for the incident.",+ "incident_updates": "List of updates posted to the incident.",+ "started_at": "Timestamp when the incident started.",+ "resolved_at": "Timestamp when the incident was resolved.",+ "monitoring_at": "Timestamp when the incident entered the monitoring state.",+ "scheduled_for": "Start time for a scheduled maintenance.",+ "scheduled_until": "End time for a scheduled maintenance.",+ "created_at": "Timestamp when the incident was created.",+ "updated_at": "Timestamp when the incident was last updated.",+ },+ },+ "incident_templates": {+ "description": "Reusable templates for drafting incidents.",+ "docs_url": "https://developer.statuspage.io/#tag/incident-templates",+ "columns": {+ "id": "Unique identifier for the incident template.",+ "page_id": _PAGE_ID_COLUMN,+ "name": "Name of the template.",+ "title": "Default incident title produced by the template.",+ "body": "Default incident body produced by the template.",+ "group_id": "Identifier of the template group this template belongs to, if any.",+ "update_status": "Incident status the template applies.",+ "created_at": "Timestamp when the template was created.",+ "updated_at": "Timestamp when the template was last updated.",+ },+ },+ "subscribers": {+ "description": "People and endpoints subscribed to status updates for a page.",+ "docs_url": "https://developer.statuspage.io/#tag/subscribers",+ "columns": {+ "id": "Unique identifier for the subscriber.",+ "page_id": _PAGE_ID_COLUMN,+ "mode": "Delivery channel of the subscriber (email, sms, webhook, slack, etc.).",+ "email": "Email address for an email or webhook subscriber.",+ "phone_number": "Phone number for an SMS subscriber.",+ "endpoint": "Webhook URL for a webhook subscriber.",+ "quarantined_at": "Timestamp when the subscriber was quarantined due to delivery issues.",+ "purge_at": "Timestamp when a quarantined subscriber will be purged.",+ "created_at": "Timestamp when the subscriber was created.",+ },+ },+ "metrics": {+ "description": "System metrics displayed on a status page (e.g. response time, uptime).",+ "docs_url": "https://developer.statuspage.io/#tag/metrics",+ "columns": {+ "id": "Unique identifier for the metric.",+ "page_id": _PAGE_ID_COLUMN,+ "metrics_provider_id": "Identifier of the metrics provider feeding this metric.",+ "name": "Display name of the metric.",+ "display": "Whether the metric is shown on the public status page.",+ "suffix": "Unit suffix shown after the metric value.",+ "created_at": "Timestamp when the metric was created.",+ "updated_at": "Timestamp when the metric was last updated.",+ },+ },+ "metric_providers": {+ "description": "External providers (Datadog, New Relic, Pingdom, etc.) supplying metric data.",+ "docs_url": "https://developer.statuspage.io/#tag/metric-providers",+ "columns": {+ "id": "Unique identifier for the metrics provider.",+ "page_id": _PAGE_ID_COLUMN,+ "type": "Provider type (e.g. Datadog, NewRelic, Pingdom, Librato).",+ "last_revalidated_at": "Timestamp when the provider credentials were last revalidated.",+ "created_at": "Timestamp when the metrics provider was created.",+ "updated_at": "Timestamp when the metrics provider was last updated.",+ },+ },+ "page_access_users": {+ "description": "Users granted access to view a private/audience-specific status page.",+ "docs_url": "https://developer.statuspage.io/#tag/page-access-users",+ "columns": {+ "id": "Unique identifier for the page access user.",+ "page_id": _PAGE_ID_COLUMN,+ "email": "Email address of the page access user.",+ "external_login": "External login identifier for the user, if SSO is used.",+ "page_access_group_ids": "Identifiers of the page access groups the user belongs to.",+ "created_at": "Timestamp when the page access user was created.",+ "updated_at": "Timestamp when the page access user was last updated.",+ },+ },+ "page_access_groups": {+ "description": "Groups of users granted access to a private/audience-specific status page.",+ "docs_url": "https://developer.statuspage.io/#tag/page-access-group-users",+ "columns": {+ "id": "Unique identifier for the page access group.",+ "page_id": _PAGE_ID_COLUMN,+ "name": "Name of the page access group.",+ "external_identifier": "External identifier for the group, if SSO is used.",+ "created_at": "Timestamp when the page access group was created.",+ "updated_at": "Timestamp when the page access group was last updated.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/statuspage/settings.py b/posthog/temporal/data_imports/sources/statuspage/settings.pynew file mode 100644index 000000000000..a9efaa3581b4--- /dev/null+++ b/posthog/temporal/data_imports/sources/statuspage/settings.py@@ -0,0 +1,90 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField+++@dataclass+class StatuspageEndpointConfig:+ name: str+ # Path template. Top-level endpoints are absolute (e.g. "/pages"); page-scoped+ # endpoints carry a {page_id} placeholder filled in per page during fan-out.+ path: str+ # Unique across the whole table. Page-scoped children include "page_id" because a+ # single sync aggregates rows from every page the API key can see — the bare+ # resource id is only documented as unique within its parent page.+ primary_key: list[str]+ # Stable datetime field used for datetime partitioning. Every Statuspage resource+ # we sync exposes an immutable created_at, so we never partition on updated_at.+ partition_key: Optional[str] = "created_at"+ page_size: int = 100 # Statuspage caps per_page/limit at 100.+ # Most list endpoints page with `per_page`; subscribers uses `limit` instead.+ page_size_param: str = "per_page"+ # True when the resource lives under /pages/{page_id}/... and must be fanned out+ # over every page. False only for the top-level /pages listing itself.+ page_scoped: bool = True+ # Statuspage exposes no server-side updated_after/since filter on its list+ # endpoints, so every endpoint is full-refresh only (empty incremental_fields).+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++STATUSPAGE_ENDPOINTS: dict[str, StatuspageEndpointConfig] = {+ "pages": StatuspageEndpointConfig(+ name="pages",+ path="/pages",+ primary_key=["id"],+ page_scoped=False,+ ),+ "components": StatuspageEndpointConfig(+ name="components",+ path="/pages/{page_id}/components",+ primary_key=["page_id", "id"],+ ),+ "component_groups": StatuspageEndpointConfig(+ name="component_groups",+ path="/pages/{page_id}/component-groups",+ primary_key=["page_id", "id"],+ ),+ "incidents": StatuspageEndpointConfig(+ name="incidents",+ path="/pages/{page_id}/incidents",+ primary_key=["page_id", "id"],+ ),+ "incident_templates": StatuspageEndpointConfig(+ name="incident_templates",+ path="/pages/{page_id}/incident_templates",+ primary_key=["page_id", "id"],+ ),+ "subscribers": StatuspageEndpointConfig(+ name="subscribers",+ path="/pages/{page_id}/subscribers",+ primary_key=["page_id", "id"],+ page_size_param="limit",+ ),+ "metrics": StatuspageEndpointConfig(+ name="metrics",+ path="/pages/{page_id}/metrics",+ primary_key=["page_id", "id"],+ ),+ "metric_providers": StatuspageEndpointConfig(+ name="metric_providers",+ path="/pages/{page_id}/metrics_providers",+ primary_key=["page_id", "id"],+ ),+ "page_access_users": StatuspageEndpointConfig(+ name="page_access_users",+ path="/pages/{page_id}/page_access_users",+ primary_key=["page_id", "id"],+ ),+ "page_access_groups": StatuspageEndpointConfig(+ name="page_access_groups",+ path="/pages/{page_id}/page_access_groups",+ primary_key=["page_id", "id"],+ ),+}++ENDPOINTS = tuple(STATUSPAGE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in STATUSPAGE_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/statuspage/source.py b/posthog/temporal/data_imports/sources/statuspage/source.pyindex 166324dc01c0..f6aae4f6ffcd 100644--- a/posthog/temporal/data_imports/sources/statuspage/source.py+++ b/posthog/temporal/data_imports/sources/statuspage/source.py@@ -1,20 +1,33 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import StatuspageSourceConfig+from posthog.temporal.data_imports.sources.statuspage.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.statuspage.statuspage import (+ StatuspageResumeConfig,+ statuspage_source,+ validate_credentials as validate_statuspage_credentials,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class StatuspageSource(SimpleSource[StatuspageSourceConfig]):+class StatuspageSource(ResumableSource[StatuspageSourceConfig, StatuspageResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.STATUSPAGE@@ -25,7 +38,82 @@ class StatuspageSource(SimpleSource[StatuspageSourceConfig]):name=SchemaExternalDataSourceType.STATUSPAGE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Statuspage",+ caption=(+ "Sync your Atlassian Statuspage data. Create a key under "+ "**[Manage account > API info](https://manage.statuspage.io/account/api-info)** and paste it below. "+ "The key has organization-wide management access; no extra scopes are required."+ ),iconPath="/static/services/statuspage.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Statuspage API key",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Statuspage API key. Please check your API key and reconnect.",+ "403 Client Error": "Your Statuspage API key lacks the required permissions. Please check the key and reconnect.",+ "Could not authenticate": "Your Statuspage API key is invalid or expired. Please reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.statuspage.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: StatuspageSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # Statuspage has no server-side updated_after/since filter on any list endpoint, so+ # every schema is full-refresh only.+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(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: StatuspageSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_statuspage_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[StatuspageResumeConfig]:+ return ResumableSourceManager[StatuspageResumeConfig](inputs, StatuspageResumeConfig)++ def source_for_pipeline(+ self,+ config: StatuspageSourceConfig,+ resumable_source_manager: ResumableSourceManager[StatuspageResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return statuspage_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/statuspage/statuspage.py b/posthog/temporal/data_imports/sources/statuspage/statuspage.pynew file mode 100644index 000000000000..8f99e6c1b002--- /dev/null+++ b/posthog/temporal/data_imports/sources/statuspage/statuspage.py@@ -0,0 +1,209 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.statuspage.settings import STATUSPAGE_ENDPOINTS, StatuspageEndpointConfig++STATUSPAGE_BASE_URL = "https://api.statuspage.io/v1"++# Statuspage rate limits paginated reads to 60 requests/minute on a rolling 60s window and+# returns 420/429 with a Retry-After header when exceeded. We retry those (and transient 5xx)+# with bounded exponential backoff — capped well above the 60s window so a throttle clears.+_MAX_ATTEMPTS = 8+_REQUEST_TIMEOUT_SECONDS = 60+++class StatuspageRetryableError(Exception):+ """Raised for rate-limit (420/429) and transient 5xx responses so tenacity retries them."""++ pass+++class StatuspageResumeConfig:+ # The page number most recently yielded for the resource currently being read. On resume we+ # re-fetch this page and re-yield it (merge dedupes on the primary key) rather than risk+ # skipping rows that were batched but not yet persisted when the worker stopped.+ page: int+ # For page-scoped (fan-out) endpoints, the id of the status page we were reading children for.+ # None for the top-level /pages listing.+ parent_page_id: Optional[str] = None+++def _get_headers(api_key: str) -> dict[str, str]:+ # Despite the "OAuth" prefix this is a static API key, not an OAuth2 bearer token — that's the+ # header format Statuspage's Manage API requires.+ return {+ "Authorization": f"OAuth {api_key}",+ "Content-Type": "application/json",+ }+++def _build_url(path: str, params: dict[str, Any]) -> str:+ return f"{STATUSPAGE_BASE_URL}{path}?{urlencode(params)}"+++def _get_session(api_key: str) -> requests.Session:+ # One session per sync so keep-alive is preserved across pages and retries. `redact_values`+ # masks the key from request telemetry/log samples, and `allow_redirects=False` keeps a+ # credentialed request pinned to the validated Statuspage host (it can't be replayed elsewhere).+ return make_tracked_session(+ headers=_get_headers(api_key),+ redact_values=(api_key,),+ allow_redirects=False,+ )+++@retry(+ retry=retry_if_exception_type((StatuspageRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(_MAX_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> requests.Response:+ response = session.get(url, timeout=_REQUEST_TIMEOUT_SECONDS)++ if response.status_code in (420, 429) or response.status_code >= 500:+ raise StatuspageRetryableError(f"Statuspage API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Statuspage API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++def _iter_resource(+ session: requests.Session,+ path: str,+ config: StatuspageEndpointConfig,+ logger: FilteringBoundLogger,+ start_page: int = 1,+) -> Iterator[tuple[list[dict[str, Any]], int]]:+ """Yield (rows, page_number) for each non-empty page, incrementing `page` from start_page.++ Statuspage's list endpoints page with a 1-based `page` number plus a per-page size param+ (`per_page` for most resources, `limit` for subscribers), both capped at 100. Termination is+ on an empty array: we deliberately do NOT stop on a short page, because if the API ignores the+ size param and defaults below 100, a short-but-non-empty page is still not the last one.+ """+ page = start_page+ while True:+ params = {config.page_size_param: config.page_size, "page": page}+ response = _fetch_page(session, _build_url(path, params), logger)+ data = response.json()+ if not isinstance(data, list) or not data:+ return+ yield data, page+ page += 1+++def _list_page_ids(session: requests.Session, logger: FilteringBoundLogger) -> list[str]:+ """List every status page id the key can see — the parents that page-scoped endpoints fan out over."""+ pages_config = STATUSPAGE_ENDPOINTS["pages"]+ page_ids: list[str] = []+ for rows, _page in _iter_resource(session, pages_config.path, pages_config, logger):+ for row in rows:+ # Direct access: page_id drives the entire child fan-out, so a page without an id is a+ # malformed response we want to surface loudly rather than silently drop its children.+ page_ids.append(row["id"])+ return page_ids+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StatuspageResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = STATUSPAGE_ENDPOINTS[endpoint]+ session = _get_session(api_key)+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if not config.page_scoped:+ start_page = resume.page if resume is not None else 1+ if resume is not None:+ logger.debug(f"Statuspage: resuming {endpoint} from page {start_page}")+ for rows, page in _iter_resource(session, config.path, config, logger, start_page=start_page):+ yield rows+ resumable_source_manager.save_state(StatuspageResumeConfig(page=page, parent_page_id=None))+ return++ page_ids = _list_page_ids(session, logger)++ start_index = 0+ resume_start_page = 1+ if resume is not None and resume.parent_page_id is not None and resume.parent_page_id in page_ids:+ start_index = page_ids.index(resume.parent_page_id)+ resume_start_page = resume.page+ logger.debug(+ f"Statuspage: resuming {endpoint} fan-out at page_id={resume.parent_page_id}, page={resume_start_page}"+ )++ for idx in range(start_index, len(page_ids)):+ page_id = page_ids[idx]+ path = config.path.format(page_id=page_id)+ start_page = resume_start_page if idx == start_index else 1+ for rows, page in _iter_resource(session, path, config, logger, start_page=start_page):+ # Inject the parent page id so the composite primary key is unique table-wide — a sync+ # aggregates rows from every page, and the bare resource id is only unique within a page.+ for row in rows:+ row["page_id"] = page_id+ yield rows+ resumable_source_manager.save_state(StatuspageResumeConfig(page=page, parent_page_id=page_id))+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """Confirm the API key is genuine with one cheap probe against the pages listing."""+ url = _build_url("/pages", {"per_page": 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 Statuspage API key. Please check your API key and try again."+ if response.status_code == 403:+ return False, "Your Statuspage API key does not have permission to list pages."++ try:+ message = response.json().get("error", response.text)+ except Exception:+ message = response.text+ return False, message+++def statuspage_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StatuspageResumeConfig],+) -> SourceResponse:+ config = STATUSPAGE_ENDPOINTS[endpoint]++ def items() -> Iterator[list[dict[str, Any]]]:+ return get_rows(api_key, endpoint, logger, resumable_source_manager)++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_key,+ # Full refresh only — Statuspage exposes no server-side timestamp filter — but rows still+ # arrive in a stable page order, so asc is correct.+ sort_mode="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/posthog/temporal/data_imports/sources/statuspage/tests/test_statuspage.py b/posthog/temporal/data_imports/sources/statuspage/tests/test_statuspage.pynew file mode 100644index 000000000000..99c275096d6b--- /dev/null+++ b/posthog/temporal/data_imports/sources/statuspage/tests/test_statuspage.py@@ -0,0 +1,234 @@+from typing import Any++import pytest+from unittest import mock++import requests++from posthog.temporal.data_imports.sources.statuspage.settings import STATUSPAGE_ENDPOINTS+from posthog.temporal.data_imports.sources.statuspage.statuspage import (+ StatuspageResumeConfig,+ StatuspageRetryableError,+ _build_url,+ _fetch_page,+ _get_headers,+ _list_page_ids,+ get_rows,+ statuspage_source,+ validate_credentials,+)++_TRANSPORT = "posthog.temporal.data_imports.sources.statuspage.statuspage.make_tracked_session"+++def _make_manager(resume_state: StatuspageResumeConfig | 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+++class TestHeaders:+ def test_uses_static_oauth_prefix(self):+ headers = _get_headers("abc123")+ # Statuspage's static API key is sent with an "OAuth" prefix despite not being an OAuth token.+ assert headers["Authorization"] == "OAuth abc123"+++class TestBuildUrl:+ def test_encodes_params(self):+ url = _build_url("/pages", {"per_page": 100, "page": 1})+ assert url == "https://api.statuspage.io/v1/pages?per_page=100&page=1"++ def test_child_path(self):+ url = _build_url("/pages/p1/components", {"per_page": 100, "page": 2})+ assert url == "https://api.statuspage.io/v1/pages/p1/components?per_page=100&page=2"+++class TestFetchPage:+ @pytest.mark.parametrize("status_code", [420, 429, 500, 502, 503])+ def test_retryable_statuses_raise(self, status_code):+ session = mock.MagicMock()+ session.get.return_value = _response([], status_code=status_code)+ # reraise=True surfaces the final StatuspageRetryableError after retries are exhausted.+ with pytest.raises(StatuspageRetryableError):+ _fetch_page(session, "https://api.statuspage.io/v1/pages", mock.MagicMock())++ def test_client_error_raises_for_status(self):+ resp = _response({"error": "Could not authenticate"}, 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.statuspage.io/v1/pages", mock.MagicMock())++ def test_ok_response_returned(self):+ session = mock.MagicMock()+ session.get.return_value = _response([{"id": "p1"}])+ resp = _fetch_page(session, "https://api.statuspage.io/v1/pages", mock.MagicMock())+ assert resp.json() == [{"id": "p1"}]+++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 = [] if status_code == 200 else {"error": "nope"}+ mock_session.return_value.get.return_value = _response(body, status_code=status_code)+ ok, error = validate_credentials("key")+ 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("key")+ assert ok is False+ assert "boom" in (error or "")+++class TestGetRowsTopLevel:+ @mock.patch(_TRANSPORT)+ def test_paginates_pages_until_empty(self, mock_session):+ mock_session.return_value = _session_returning(+ [{"id": "p1"}, {"id": "p2"}],+ [{"id": "p3"}],+ [], # empty page terminates+ )+ manager = _make_manager()++ batches = list(get_rows("key", "pages", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["p1", "p2", "p3"]+ # State saved once per non-empty yielded page.+ assert manager.save_state.call_count == 2+ saved = [c.args[0] for c in manager.save_state.call_args_list]+ assert [(s.page, s.parent_page_id) for s in saved] == [(1, None), (2, None)]++ @mock.patch(_TRANSPORT)+ def test_resumes_from_saved_page(self, mock_session):+ mock_session.return_value = _session_returning(+ [{"id": "p9"}], # page 3 (resumed)+ [],+ )+ manager = _make_manager(StatuspageResumeConfig(page=3, parent_page_id=None))++ list(get_rows("key", "pages", 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_pages_and_injects_page_id(self, mock_session):+ mock_session.return_value = _session_returning(+ # _list_page_ids walks /pages first+ [{"id": "p1"}, {"id": "p2"}],+ [],+ # components for p1+ [{"id": "c1"}],+ [],+ # components for p2+ [{"id": "c2"}],+ [],+ )+ manager = _make_manager()++ batches = list(get_rows("key", "components", mock.MagicMock(), manager))+ rows = [row for batch in batches for row in batch]++ assert rows == [{"id": "c1", "page_id": "p1"}, {"id": "c2", "page_id": "p2"}]+ saved = [c.args[0] for c in manager.save_state.call_args_list]+ assert [(s.page, s.parent_page_id) for s in saved] == [(1, "p1"), (1, "p2")]++ @mock.patch(_TRANSPORT)+ def test_resumes_fan_out_at_saved_parent_and_page(self, mock_session):+ mock_session.return_value = _session_returning(+ # pages relisted on resume+ [{"id": "p1"}, {"id": "p2"}],+ [],+ # resume at p2, page 2 — p1 is skipped entirely+ [{"id": "c2b"}],+ [],+ )+ manager = _make_manager(StatuspageResumeConfig(page=2, parent_page_id="p2"))++ batches = list(get_rows("key", "components", mock.MagicMock(), manager))+ rows = [row for batch in batches for row in batch]++ assert rows == [{"id": "c2b", "page_id": "p2"}]+ # p1 is skipped entirely and the resumed read starts at p2 page 2 (then page 3 terminates on empty).+ child_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/components" in c.args[0]]+ assert all("/pages/p2/components" in u for u in child_urls)+ assert child_urls[0] == "https://api.statuspage.io/v1/pages/p2/components?per_page=100&page=2"++ @mock.patch(_TRANSPORT)+ def test_subscribers_uses_limit_param(self, mock_session):+ mock_session.return_value = _session_returning(+ [{"id": "p1"}],+ [],+ [{"id": "s1"}],+ [],+ )+ manager = _make_manager()++ list(get_rows("key", "subscribers", mock.MagicMock(), manager))++ child_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/subscribers" in c.args[0]]+ assert child_urls and all("limit=100" in u and "per_page" not in u for u in child_urls)+++class TestListPageIds:+ def test_collects_ids_across_pages(self):+ session = _session_returning(+ [{"id": "p1"}, {"id": "p2"}],+ [{"id": "p3"}],+ [],+ )+ assert _list_page_ids(session, mock.MagicMock()) == ["p1", "p2", "p3"]+++class TestStatuspageSource:+ @pytest.mark.parametrize("endpoint", list(STATUSPAGE_ENDPOINTS.keys()))+ def test_source_response_shape(self, endpoint):+ config = STATUSPAGE_ENDPOINTS[endpoint]+ response = statuspage_source("key", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_key+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ @pytest.mark.parametrize(+ "endpoint, expected_keys",+ [+ ("pages", ["id"]),+ ("components", ["page_id", "id"]),+ ("subscribers", ["page_id", "id"]),+ ],+ )+ def test_primary_keys_are_unique_table_wide(self, endpoint, expected_keys):+ # Fan-out children carry the parent page id in their key so rows from different pages+ # never collide on a bare resource id.+ assert STATUSPAGE_ENDPOINTS[endpoint].primary_key == expected_keysdiff --git a/posthog/temporal/data_imports/sources/statuspage/tests/test_statuspage_source.py b/posthog/temporal/data_imports/sources/statuspage/tests/test_statuspage_source.pynew file mode 100644index 000000000000..40f7df3bc539--- /dev/null+++ b/posthog/temporal/data_imports/sources/statuspage/tests/test_statuspage_source.py@@ -0,0 +1,94 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import StatuspageSourceConfig+from posthog.temporal.data_imports.sources.statuspage.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.statuspage.source import StatuspageSource+from posthog.temporal.data_imports.sources.statuspage.statuspage import StatuspageResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestStatuspageSource:+ def setup_method(self):+ self.source = StatuspageSource()+ self.team_id = 123++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.STATUSPAGE++ def test_source_config(self):+ config = self.source.get_source_config+ assert config.label == "Statuspage"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True++ 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_returns_all_endpoints_as_full_refresh(self):+ schemas = self.source.get_schemas(StatuspageSourceConfig(api_key="key"), self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # No server-side timestamp filter exists, so every schema is full-refresh only.+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filters_by_names(self):+ schemas = self.source.get_schemas(+ StatuspageSourceConfig(api_key="key"), self.team_id, names=["incidents", "components"]+ )+ assert {s.name for s in schemas} == {"incidents", "components"}++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", "Could not authenticate"])+ 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("posthog.temporal.data_imports.sources.statuspage.source.validate_statuspage_credentials")+ def test_validate_credentials_delegates_with_api_key(self, mock_validate):+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(StatuspageSourceConfig(api_key="secret-key"), self.team_id)+ assert result == (True, None)+ mock_validate.assert_called_once_with("secret-key")++ 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 StatuspageResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.statuspage.source.statuspage_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_statuspage_source):+ config = StatuspageSourceConfig(api_key="key")+ manager = mock.MagicMock()+ inputs = mock.MagicMock()+ inputs.schema_name = "incidents"+ inputs.logger = mock.MagicMock()++ self.source.source_for_pipeline(config, manager, inputs)++ mock_statuspage_source.assert_called_once_with(+ api_key="key",+ endpoint="incidents",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )