: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 instatus import source (#67833)
Tom Owersf04bb7dd29a9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 5ee28c2640aa..f0b28e67a434 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -180,6 +180,7 @@ the row lists both.| hugging_face | HTTP | requests | ✅ || incident_io | HTTP | requests | ✅ || insightly | HTTP | requests | ✅ |+| instatus | HTTP | requests | ✅ || intercom | HTTP | requests + `rest_source.RESTClient` | ✅ || intruder | HTTP | requests | ✅ || invoiceninja | HTTP | requests | ✅ |@@ -484,7 +485,6 @@ doesn't conflict with concurrent PRs.- insightful- instantly-- instatus- interzoid- invoiced- jamf_prodiff --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 fe25c89dd5f7..630adf5d96bf 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@@ -1638,7 +1638,7 @@ class InstantlySourceConfig(config.Config):@config.configclass InstatusSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/canonical_descriptions.pynew file mode 100644index 000000000000..85e9cc5429d3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/canonical_descriptions.py@@ -0,0 +1,135 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions are taken from the Instatus REST API docs (https://instatus.com/help/api). 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 payload.+_PAGE_ID_COLUMN = "Identifier of the status page this record belongs to (added by the connector)."+_DOCS = "https://instatus.com/help/api"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "pages": {+ "description": "The status pages in your Instatus account.",+ "docs_url": f"{_DOCS}/status-pages",+ "columns": {+ "id": "Unique identifier for the status page.",+ "name": "Display name of the status page.",+ "subdomain": "Instatus subdomain for the page (e.g. mycompany in mycompany.instatus.com).",+ "customDomain": "Custom domain mapped to the status page, if configured.",+ "websiteUrl": "URL of the website the status page relates to.",+ "status": "Current overall status of the page (e.g. UP, HASISSUES, UNDERMAINTENANCE).",+ "language": "Language of the status page as a language code (e.g. `en`).",+ "createdAt": "Timestamp when the status page was created.",+ "updatedAt": "Timestamp when the status page was last updated.",+ },+ },+ "components": {+ "description": "Individual services or features whose status is shown on a status page.",+ "docs_url": f"{_DOCS}/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, UNDERMAINTENANCE, DEGRADEDPERFORMANCE, PARTIALOUTAGE, MAJOROUTAGE).",+ "order": "Display order of the component on the status page.",+ "groupId": "Identifier of the parent component group, if any.",+ "showUptime": "Whether the uptime percentage and bar are shown for the component.",+ "createdAt": "Timestamp when the component was created.",+ "updatedAt": "Timestamp when the component was last updated.",+ },+ },+ "incidents": {+ "description": "Incidents published to a status page.",+ "docs_url": f"{_DOCS}/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).",+ "started": "Timestamp when the incident started.",+ "duration": "Duration of the incident in minutes, or null if unresolved.",+ "resolved": "Timestamp when the incident was resolved, or null if unresolved.",+ "updates": "List of updates posted to the incident.",+ "components": "Components affected by the incident.",+ },+ },+ "maintenances": {+ "description": "Scheduled maintenances published to a status page.",+ "docs_url": f"{_DOCS}/maintenances",+ "columns": {+ "id": "Unique identifier for the maintenance.",+ "page_id": _PAGE_ID_COLUMN,+ "name": "Title of the maintenance.",+ "status": "Current maintenance status (NOTSTARTEDYET, INPROGRESS, COMPLETED).",+ "start": "Scheduled start time of the maintenance.",+ "duration": "Duration of the maintenance in minutes, or null if not completed.",+ "autoStart": "Whether the maintenance starts automatically at the scheduled time.",+ "autoEnd": "Whether the maintenance ends automatically at the scheduled end time.",+ "updates": "List of updates posted to the maintenance.",+ "components": "Components affected by the maintenance.",+ },+ },+ "subscribers": {+ "description": "People subscribed to notifications for a status page.",+ "docs_url": f"{_DOCS}/subscribers",+ "columns": {+ "id": "Unique identifier for the subscriber.",+ "page_id": _PAGE_ID_COLUMN,+ "email": "Email address of the subscriber, if an email subscriber.",+ "phone": "Phone number of the subscriber, if an SMS subscriber.",+ "webhook": "Webhook URL of the subscriber, if a webhook subscriber.",+ "confirmed": "Whether the subscriber has confirmed their subscription.",+ "all": "Whether the subscriber is subscribed to all components on the page.",+ "components": "Ids of the specific components the subscriber follows.",+ },+ },+ "metrics": {+ "description": "Custom metrics displayed on a status page (e.g. response time, uptime).",+ "docs_url": f"{_DOCS}/metrics",+ "columns": {+ "id": "Unique identifier for the metric.",+ "page_id": _PAGE_ID_COLUMN,+ "name": "Name of the metric.",+ "active": "Whether the metric is shown in the page's system metrics section.",+ "order": "Display order of the metric on the status page.",+ "suffix": "Suffix appended to the metric value when displayed (e.g. ms).",+ },+ },+ "templates": {+ "description": "Reusable incident and maintenance templates for a status page.",+ "docs_url": f"{_DOCS}/templates",+ "columns": {+ "id": "Unique identifier for the template.",+ "page_id": _PAGE_ID_COLUMN,+ "type": "Whether the template creates incidents or maintenances.",+ "name": "Name of the notice the template creates.",+ "message": "Message used for the first update of the notice.",+ "status": "Default status applied by the template.",+ "notify": "Whether subscribers are notified when the template is used.",+ "createdAt": "Timestamp when the template was created.",+ },+ },+ "team": {+ "description": "Teammates with access to a status page.",+ "docs_url": f"{_DOCS}/teammates",+ "columns": {+ "id": "Unique identifier for the teammate record.",+ "page_id": _PAGE_ID_COLUMN,+ "user": "The user account details of the teammate.",+ },+ },+ "audience_groups": {+ "description": "Audience groups used to target subscribers on a private status page.",+ "docs_url": f"{_DOCS}/audience-groups",+ "columns": {+ "id": "Unique identifier for the audience group.",+ "page_id": _PAGE_ID_COLUMN,+ "siteId": "Identifier of the status page (site) the group belongs to.",+ "name": "Name of the audience group.",+ "teammates": "Teammates that belong to the audience group.",+ "components": "Components associated with the audience group.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/instatus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/instatus.pynew file mode 100644index 000000000000..3d028abf3f82--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/instatus.py@@ -0,0 +1,210 @@+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 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.instatus.settings import INSTATUS_ENDPOINTS++# Single global host — Instatus has no per-account subdomains (unlike Statuspage).+INSTATUS_BASE_URL = "https://api.instatus.com"++# per_page defaults to 50 and is capped at 100; we always request the maximum to minimise round-trips.+_PAGE_SIZE = 100+# The Instatus OpenAPI spec documents no rate limits, but we still retry transient 5xx and 429 with+# bounded exponential backoff so a blip or an undocumented throttle doesn't fail the whole sync.+_MAX_ATTEMPTS = 8+_REQUEST_TIMEOUT_SECONDS = 60+++class InstatusRetryableError(Exception):+ """Raised for rate-limit (429) and transient 5xx responses so tenacity retries them."""++ pass+++class InstatusResumeConfig:+ # 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 /v2/pages listing.+ parent_page_id: Optional[str] = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ # Instatus requires the JSON content type on every request, including GETs.+ "Content-Type": "application/json",+ }+++def _build_url(path: str, params: dict[str, Any]) -> str:+ return f"{INSTATUS_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 Instatus 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((InstatusRetryableError, 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 == 429 or response.status_code >= 500:+ raise InstatusRetryableError(f"Instatus API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Instatus 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,+ 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.++ Every Instatus list endpoint we sync returns a bare JSON array and pages with a 1-based `page`+ number plus `per_page` (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 = {"per_page": _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 token can see — the parents that page-scoped endpoints fan out over."""+ pages_config = INSTATUS_ENDPOINTS["pages"]+ page_ids: list[str] = []+ for rows, _page in _iter_resource(session, pages_config.path, 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[InstatusResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = INSTATUS_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"Instatus: resuming {endpoint} from page {start_page}")+ for rows, page in _iter_resource(session, config.path, logger, start_page=start_page):+ yield rows+ resumable_source_manager.save_state(InstatusResumeConfig(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"Instatus: 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, 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(InstatusResumeConfig(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 status-page listing."""+ url = _build_url("/v2/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 Instatus API key. Please check your API key and try again."+ if response.status_code == 403:+ return False, "Your Instatus API key does not have permission to list status pages."++ try:+ body = response.json()+ message = (body.get("error", {}) or {}).get("message") if isinstance(body, dict) else response.text+ except Exception:+ message = response.text+ return False, message or response.text+++def instatus_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[InstatusResumeConfig],+) -> SourceResponse:+ config = INSTATUS_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 — Instatus 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/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/settings.pynew file mode 100644index 000000000000..8e8ba63a5a14--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/settings.py@@ -0,0 +1,91 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class InstatusEndpointConfig:+ name: str+ # Full path including the version prefix. Instatus is inconsistent here: the status-page+ # listing lives under /v2/pages, while every page-scoped child lives under /v1/{page_id}/...+ # Page-scoped paths 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 status page the token can see, and the bare resource id is only+ # documented as unique within its parent page.+ primary_key: list[str]+ # Stable datetime field used for datetime partitioning, or None when the resource exposes no+ # immutable timestamp. We never partition on updatedAt — only creation-time fields that don't+ # move (createdAt, an incident's `started`, a maintenance's `start`).+ partition_key: Optional[str] = None+ # True when the resource lives under /v1/{page_id}/... and must be fanned out over every page.+ # False only for the top-level /v2/pages listing itself.+ page_scoped: bool = True+ # Instatus exposes no server-side updated_after/since filter on any list endpoint (only+ # status include/exclude on incidents and a free-text search on subscribers), so every+ # endpoint is full-refresh only (empty incremental_fields).+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++INSTATUS_ENDPOINTS: dict[str, InstatusEndpointConfig] = {+ "pages": InstatusEndpointConfig(+ name="pages",+ path="/v2/pages",+ primary_key=["id"],+ partition_key="createdAt",+ page_scoped=False,+ ),+ "components": InstatusEndpointConfig(+ name="components",+ path="/v1/{page_id}/components",+ primary_key=["page_id", "id"],+ partition_key="createdAt",+ ),+ "incidents": InstatusEndpointConfig(+ name="incidents",+ path="/v1/{page_id}/incidents",+ primary_key=["page_id", "id"],+ # Incidents have no createdAt; `started` is the immutable time the incident began.+ partition_key="started",+ ),+ "maintenances": InstatusEndpointConfig(+ name="maintenances",+ path="/v1/{page_id}/maintenances",+ primary_key=["page_id", "id"],+ # Maintenances have no createdAt; `start` is the immutable scheduled start time.+ partition_key="start",+ ),+ "subscribers": InstatusEndpointConfig(+ name="subscribers",+ path="/v1/{page_id}/subscribers",+ primary_key=["page_id", "id"],+ ),+ "metrics": InstatusEndpointConfig(+ name="metrics",+ path="/v1/{page_id}/metrics",+ primary_key=["page_id", "id"],+ ),+ "templates": InstatusEndpointConfig(+ name="templates",+ path="/v1/{page_id}/templates",+ primary_key=["page_id", "id"],+ partition_key="createdAt",+ ),+ "team": InstatusEndpointConfig(+ name="team",+ path="/v1/{page_id}/team",+ primary_key=["page_id", "id"],+ ),+ "audience_groups": InstatusEndpointConfig(+ name="audience_groups",+ path="/v1/{page_id}/audience-groups",+ primary_key=["page_id", "id"],+ ),+}++ENDPOINTS = tuple(INSTATUS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in INSTATUS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/source.pyindex ef7bac75e02a..145b957b661b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/source.py@@ -1,19 +1,44 @@-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 InstatusSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.instatus.instatus import (+ InstatusResumeConfig,+ instatus_source,+ validate_credentials as validate_instatus_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.instatus.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class InstatusSource(SimpleSource[InstatusSourceConfig]):+class InstatusSource(ResumableSource[InstatusSourceConfig, InstatusResumeConfig]):+ # get_schemas iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in the public docs without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.INSTATUS@@ -24,7 +49,84 @@ class InstatusSource(SimpleSource[InstatusSourceConfig]):name=SchemaExternalDataSourceType.INSTATUS,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Instatus",+ caption=(+ "Sync your Instatus status pages, components, incidents, maintenances and more. "+ "Create an API key under **[Developer settings](https://dashboard.instatus.com/developer)** "+ "and paste it below. The key grants access to every status page in your account."+ ),iconPath="/static/services/instatus.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/instatus",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Instatus API key",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Instatus API key. Please check your API key and reconnect.",+ "403 Client Error": "Your Instatus API key lacks the required permissions. Please check the key and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.instatus.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: InstatusSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # Instatus 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: InstatusSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_instatus_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InstatusResumeConfig]:+ return ResumableSourceManager[InstatusResumeConfig](inputs, InstatusResumeConfig)++ def source_for_pipeline(+ self,+ config: InstatusSourceConfig,+ resumable_source_manager: ResumableSourceManager[InstatusResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return instatus_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/tests/test_instatus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/tests/test_instatus.pynew file mode 100644index 000000000000..76b63c7a75fe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/tests/test_instatus.py@@ -0,0 +1,246 @@+from typing import Any++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.instatus.instatus import (+ InstatusResumeConfig,+ InstatusRetryableError,+ _build_url,+ _fetch_page,+ _get_headers,+ _list_page_ids,+ get_rows,+ instatus_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.instatus.settings import INSTATUS_ENDPOINTS++_TRANSPORT = "products.warehouse_sources.backend.temporal.data_imports.sources.instatus.instatus.make_tracked_session"+++def _make_manager(resume_state: InstatusResumeConfig | 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 TestInstatus:+ def test_headers_use_bearer_and_json_content_type(self):+ headers = _get_headers("abc123")+ assert headers["Authorization"] == "Bearer abc123"+ # Instatus requires the JSON content type on every request, including GETs.+ assert headers["Content-Type"] == "application/json"++ @pytest.mark.parametrize(+ "path, expected",+ [+ ("/v2/pages", "https://api.instatus.com/v2/pages?per_page=100&page=1"),+ ("/v1/p1/components", "https://api.instatus.com/v1/p1/components?per_page=100&page=1"),+ ],+ )+ def test_build_url(self, path, expected):+ assert _build_url(path, {"per_page": 100, "page": 1}) == expected++ @pytest.mark.parametrize("status_code", [429, 500, 502, 503])+ @mock.patch("time.sleep") # neutralize tenacity's exponential backoff so retries are instant+ def test_fetch_page_retryable_statuses_raise(self, _mock_sleep, status_code):+ session = mock.MagicMock()+ session.get.return_value = _response([], status_code=status_code)+ # reraise=True surfaces the final InstatusRetryableError after retries are exhausted.+ with pytest.raises(InstatusRetryableError):+ _fetch_page(session, "https://api.instatus.com/v2/pages", mock.MagicMock())++ def test_fetch_page_client_error_raises_for_status(self):+ resp = _response({"error": {"message": "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.instatus.com/v2/pages", mock.MagicMock())++ def test_fetch_page_ok_response_returned(self):+ session = mock.MagicMock()+ session.get.return_value = _response([{"id": "p1"}])+ resp = _fetch_page(session, "https://api.instatus.com/v2/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": {"message": "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_probes_pages_endpoint(self, mock_session):+ mock_session.return_value.get.return_value = _response([], status_code=200)+ validate_credentials("key")+ url = mock_session.return_value.get.call_args.args[0]+ assert url.startswith("https://api.instatus.com/v2/pages")++ @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(InstatusResumeConfig(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 /v2/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]++ # page_id injected so the composite [page_id, id] key stays unique table-wide.+ 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(InstatusResumeConfig(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"}]+ child_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/components" in c.args[0]]+ assert child_urls[0] == "https://api.instatus.com/v1/p2/components?per_page=100&page=2"+++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 TestInstatusSourceResponse:+ @pytest.mark.parametrize("endpoint", list(INSTATUS_ENDPOINTS.keys()))+ def test_source_response_shape(self, endpoint):+ config = INSTATUS_ENDPOINTS[endpoint]+ response = instatus_source("key", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_key+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize(+ "endpoint, expected_keys",+ [+ ("pages", ["id"]),+ ("components", ["page_id", "id"]),+ ("subscribers", ["page_id", "id"]),+ ("incidents", ["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 INSTATUS_ENDPOINTS[endpoint].primary_key == expected_keys++ @pytest.mark.parametrize(+ "endpoint, expected_partition",+ [+ ("pages", "createdAt"),+ ("components", "createdAt"),+ ("templates", "createdAt"),+ ("incidents", "started"),+ ("maintenances", "start"),+ ("subscribers", None),+ ("metrics", None),+ ],+ )+ def test_partition_keys_are_stable_fields(self, endpoint, expected_partition):+ # Partition only on immutable creation-time fields, never updatedAt.+ assert INSTATUS_ENDPOINTS[endpoint].partition_key == expected_partitiondiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/tests/test_instatus_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/tests/test_instatus_source.pynew file mode 100644index 000000000000..08e5ac2ee7db--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instatus/tests/test_instatus_source.py@@ -0,0 +1,101 @@+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 InstatusSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.instatus.instatus import InstatusResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.instatus.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.instatus.source import InstatusSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestInstatusSource:+ def setup_method(self):+ self.source = InstatusSource()+ self.team_id = 123++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.INSTATUS++ def test_source_config(self):+ config = self.source.get_source_config+ assert config.label == "Instatus"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/instatus"++ 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(InstatusSourceConfig(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(+ InstatusSourceConfig(api_key="key"), self.team_id, names=["incidents", "components"]+ )+ assert {s.name for s in schemas} == {"incidents", "components"}++ def test_lists_tables_without_credentials(self):+ # Static endpoint catalog with no I/O — the docs Supported tables section renders from it.+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ 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.instatus.source.validate_instatus_credentials"+ )+ def test_validate_credentials_delegates_with_api_key(self, mock_validate):+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(InstatusSourceConfig(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 InstatusResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.instatus.source.instatus_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_instatus_source):+ config = InstatusSourceConfig(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_instatus_source.assert_called_once_with(+ api_key="key",+ endpoint="incidents",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )