Skip to content

: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.

feat(data-warehouse): implement incident.io source (#62658)

Tom Owers1445e22a05f6
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index a40bc9e3dc18..1cd6e6cd3ded 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -85,6 +85,7 @@ the row lists both.
| gorgias | HTTP | requests | ✅ |
| greenhouse | HTTP | requests | ✅ |
| hubspot | HTTP | requests | ✅ |
+| incident_io | HTTP | requests | ✅ |
| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
| iterable | HTTP | requests | ✅ |
| jira | HTTP | requests | ✅ |
@@ -247,7 +248,6 @@ doesn't conflict with concurrent PRs.
- heap
- helpscout
- hibob
-- incident_io
- instagram
- kafka
- kustomer
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 8c872e5387f6..b18e36ae4c21 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -696,7 +696,7 @@ class HubspotSourceConfig(config.Config):
@config.config
class IncidentIoSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/incident_io/incident_io.py b/posthog/temporal/data_imports/sources/incident_io/incident_io.py
new file mode 100644
index 000000000000..1b4ce8fdcdb4
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/incident_io/incident_io.py
@@ -0,0 +1,256 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import date, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qsl, urlencode, urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, 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.incident_io.settings import INCIDENT_IO_ENDPOINTS, IncidentIoEndpointConfig
+
+# Single global host — incident.io has no regions or per-account base paths.
+INCIDENT_IO_BASE_URL = "https://api.incident.io"
+REQUEST_TIMEOUT_SECONDS = 60
+VALIDATION_TIMEOUT_SECONDS = 10
+MAX_RETRIES = 5
+MAX_RETRY_AFTER_SECONDS = 120
+
+
+class IncidentIoRetryableError(Exception):
+ def __init__(self, message: str, retry_after: Optional[float] = None):
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class IncidentIoResumeConfig:
+ next_url: str
+
+
+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:
+ clean_params = {key: value for key, value in params.items() if value is not None}
+ if not clean_params:
+ return f"{INCIDENT_IO_BASE_URL}{path}"
+ return f"{INCIDENT_IO_BASE_URL}{path}?{urlencode(clean_params)}"
+
+
+def _params_from_url(url: str) -> dict[str, str]:
+ """Recover the query params of a saved next-page URL, minus the page cursor.
+
+ On resume we keep the original chain's filters instead of rebuilding them from the
+ (possibly advanced) incremental watermark — mixing a fresh `gte` filter with an old
+ `after` cursor could skip rows the cursor hadn't reached yet.
+ """
+ params = dict(parse_qsl(urlsplit(url).query))
+ params.pop("after", None)
+ return params
+
+
+def _format_filter_value(value: Any) -> Optional[str]:
+ """Coerce an incremental cursor value to a date string for incident.io `[gte]` filters.
+
+ The API docs only show date-formatted filter values (e.g. `2024-05-01`), so we
+ conservatively truncate to a date. `gte` is inclusive and we merge on `id`, so the
+ up-to-a-day overlap is deduped downstream.
+ """
+ if value is None or isinstance(value, bool):
+ return None
+ if isinstance(value, datetime):
+ return value.date().isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ if isinstance(value, str):
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date().isoformat()
+ except ValueError:
+ return None
+ return None
+
+
+def _build_params(
+ config: IncidentIoEndpointConfig,
+ incremental_field: Optional[str],
+ incremental_value: Optional[str],
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if config.paginated:
+ params["page_size"] = config.page_size
+ if config.sort_by:
+ params["sort_by"] = config.sort_by
+ if incremental_field and incremental_value:
+ params[f"{incremental_field}[gte]"] = incremental_value
+ return params
+
+
+def _parse_retry_after(header_value: Optional[str]) -> Optional[float]:
+ if not header_value:
+ return None
+ try:
+ return max(0.0, float(header_value))
+ except ValueError:
+ # Retry-After can also be an HTTP date; fall back to exponential backoff.
+ return None
+
+
+_fallback_wait = wait_exponential_jitter(initial=1, max=60)
+
+
+def _wait_with_retry_after(retry_state: RetryCallState) -> float:
+ exception = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exception, IncidentIoRetryableError) and exception.retry_after is not None:
+ return min(exception.retry_after, MAX_RETRY_AFTER_SECONDS)
+ return _fallback_wait(retry_state)
+
+
+def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
+ """Probe the API to confirm the key is genuine.
+
+ incident.io API keys carry granular per-resource view/list scopes, so a 403 from one
+ endpoint can just mean a missing scope rather than a bad key. At source-create
+ (``schema_name=None``) we accept 403 — the key authenticated, it's only missing a
+ scope the user may not need. When validating a specific schema, a 403 is an error.
+ """
+ config = INCIDENT_IO_ENDPOINTS.get(schema_name or "", INCIDENT_IO_ENDPOINTS["incidents"])
+ params: dict[str, Any] = {"page_size": 1} if config.paginated else {}
+
+ try:
+ response = make_tracked_session().get(
+ _build_url(config.path, params),
+ headers=_get_headers(api_key),
+ timeout=VALIDATION_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ return False, "Unable to reach the incident.io API. Please try again."
+
+ if response.status_code == 401:
+ return False, "incident.io authentication failed. Please check that your API key is valid."
+
+ if response.status_code == 403:
+ if schema_name is None:
+ return True, None
+ return (
+ False,
+ f"Your incident.io API key can't list {schema_name}. incident.io API keys have per-resource permissions — grant the key the 'view' scope for this resource and try again.",
+ )
+
+ if response.ok:
+ return True, None
+
+ return False, f"incident.io API returned an unexpected response (status {response.status_code})."
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[IncidentIoResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = INCIDENT_IO_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+
+ incremental_value = _format_filter_value(db_incremental_field_last_value) if should_use_incremental_field else None
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url: str = resume_config.next_url
+ params: dict[str, Any] = _params_from_url(url)
+ logger.debug(f"incident.io: resuming from URL: {url}")
+ else:
+ params = _build_params(config, incremental_field if should_use_incremental_field else None, incremental_value)
+ url = _build_url(config.path, params)
+
+ @retry(
+ retry=retry_if_exception_type((IncidentIoRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_wait_with_retry_after,
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # incident.io rate-limits at 1,200 req/min; honor Retry-After when present and
+ # fall back to exponential backoff otherwise.
+ if response.status_code == 429:
+ raise IncidentIoRetryableError(
+ f"incident.io rate limit hit: url={page_url}",
+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),
+ )
+
+ if response.status_code >= 500:
+ raise IncidentIoRetryableError(
+ f"incident.io API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"incident.io API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+ items = data.get(config.data_key) or []
+
+ if items:
+ yield items
+
+ # `pagination_meta.after` is a record ID tied to this run's ordering — it's only
+ # valid as a within-run page cursor, never persisted as the incremental watermark
+ # (the pipeline persists the max incremental field value instead).
+ after = (data.get("pagination_meta") or {}).get("after")
+ if not config.paginated or not after:
+ break
+
+ url = _build_url(config.path, {**params, "after": after})
+ resumable_source_manager.save_state(IncidentIoResumeConfig(next_url=url))
+
+
+def incident_io_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[IncidentIoResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = INCIDENT_IO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=[config.primary_key],
+ # Incidents are requested with `sort_by=created_at_oldest_first` (the only sortable
+ # endpoint). When syncing incrementally on `updated_at`, values within a run aren't
+ # monotonic — the final watermark is still correct because a run fetches every row
+ # matching the filter, and merge-on-id dedupes any overlap on the next run.
+ 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/incident_io/settings.py b/posthog/temporal/data_imports/sources/incident_io/settings.py
new file mode 100644
index 000000000000..cd2682f9d4df
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/incident_io/settings.py
@@ -0,0 +1,141 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class IncidentIoEndpointConfig:
+ name: str
+ # Versioned path — incident.io mixes /v1 and /v2 across resources.
+ path: str
+ # Key the list of objects is nested under in the response body (e.g. {"incidents": [...]}).
+ data_key: str
+ # Small config-style endpoints (severities, statuses, ...) return the full list in one
+ # response and accept no pagination params.
+ paginated: bool = False
+ page_size: int = 250
+ primary_key: str = "id"
+ # Fields with a documented server-side `<field>[gte]` filter on the list endpoint.
+ # Endpoints without one are full refresh only.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style
+ # field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ # Server-side sort. Only the incidents list supports sorting; `created_at_oldest_first`
+ # keeps pages stable and lets the incremental watermark advance monotonically.
+ sort_by: Optional[str] = None
+
+
+_DATETIME_INCREMENTAL_FIELD_CREATED_AT: IncrementalField = {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+_DATETIME_INCREMENTAL_FIELD_UPDATED_AT: IncrementalField = {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+
+# Alerts and escalations also document `created_at[gte]` filters, but neither endpoint
+# accepts a sort param and the default ordering is undocumented, so we keep them full
+# refresh rather than risk an unstable incremental watermark.
+INCIDENT_IO_ENDPOINTS: dict[str, IncidentIoEndpointConfig] = {
+ "incidents": IncidentIoEndpointConfig(
+ name="incidents",
+ path="/v2/incidents",
+ data_key="incidents",
+ paginated=True,
+ page_size=250,
+ partition_key="created_at",
+ sort_by="created_at_oldest_first",
+ incremental_fields=[
+ _DATETIME_INCREMENTAL_FIELD_UPDATED_AT,
+ _DATETIME_INCREMENTAL_FIELD_CREATED_AT,
+ ],
+ ),
+ "incident_updates": IncidentIoEndpointConfig(
+ name="incident_updates",
+ path="/v2/incident_updates",
+ data_key="incident_updates",
+ paginated=True,
+ page_size=250,
+ partition_key="created_at",
+ ),
+ "follow_ups": IncidentIoEndpointConfig(
+ name="follow_ups",
+ path="/v2/follow_ups",
+ data_key="follow_ups",
+ paginated=True,
+ page_size=250,
+ partition_key="created_at",
+ ),
+ "alerts": IncidentIoEndpointConfig(
+ name="alerts",
+ path="/v2/alerts",
+ data_key="alerts",
+ paginated=True,
+ # The alerts list caps page_size at 50, unlike incidents' 250.
+ page_size=50,
+ partition_key="created_at",
+ ),
+ "escalations": IncidentIoEndpointConfig(
+ name="escalations",
+ path="/v2/escalations",
+ data_key="escalations",
+ paginated=True,
+ page_size=50,
+ partition_key="created_at",
+ ),
+ "users": IncidentIoEndpointConfig(
+ name="users",
+ path="/v2/users",
+ data_key="users",
+ paginated=True,
+ page_size=250,
+ ),
+ "schedules": IncidentIoEndpointConfig(
+ name="schedules",
+ path="/v2/schedules",
+ data_key="schedules",
+ paginated=True,
+ page_size=250,
+ partition_key="created_at",
+ ),
+ "severities": IncidentIoEndpointConfig(
+ name="severities",
+ path="/v1/severities",
+ data_key="severities",
+ ),
+ "incident_roles": IncidentIoEndpointConfig(
+ name="incident_roles",
+ path="/v2/incident_roles",
+ data_key="incident_roles",
+ ),
+ "incident_statuses": IncidentIoEndpointConfig(
+ name="incident_statuses",
+ path="/v1/incident_statuses",
+ data_key="incident_statuses",
+ ),
+ "incident_types": IncidentIoEndpointConfig(
+ name="incident_types",
+ path="/v1/incident_types",
+ data_key="incident_types",
+ ),
+ "custom_fields": IncidentIoEndpointConfig(
+ name="custom_fields",
+ path="/v2/custom_fields",
+ data_key="custom_fields",
+ ),
+}
+
+ENDPOINTS = tuple(INCIDENT_IO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in INCIDENT_IO_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/incident_io/source.py b/posthog/temporal/data_imports/sources/incident_io/source.py
index 33a1f030b776..05b62857b1b6 100644
--- a/posthog/temporal/data_imports/sources/incident_io/source.py
+++ b/posthog/temporal/data_imports/sources/incident_io/source.py
@@ -1,29 +1,113 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from 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 SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import IncidentIoSourceConfig
+from posthog.temporal.data_imports.sources.incident_io.incident_io import (
+ IncidentIoResumeConfig,
+ incident_io_source,
+ validate_credentials as validate_incident_io_credentials,
+)
+from posthog.temporal.data_imports.sources.incident_io.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class IncidentIoSource(SimpleSource[IncidentIoSourceConfig]):
+class IncidentIoSource(ResumableSource[IncidentIoSourceConfig, IncidentIoResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.INCIDENTIO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.incident.io": "incident.io authentication failed. Please check that your API key is valid and has not been revoked.",
+ "403 Client Error: Forbidden for url: https://api.incident.io": "Your incident.io API key is missing a required permission. incident.io API keys have per-resource permissions — grant the key the 'view' scope for the resources you want to sync.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.INCIDENT_IO,
label="incident.io",
+ caption="""Enter your incident.io API key to pull your incident data into the PostHog Data warehouse.
+
+You can create an API key in your [incident.io dashboard](https://app.incident.io/settings/api-keys). API keys have per-resource permissions — grant the `view` scope for each resource you want to sync (incidents, follow-ups, alerts, users, and so on).""",
iconPath="/static/services/incident_io.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/incident-io",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: IncidentIoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ 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: IncidentIoSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_incident_io_credentials(config.api_key, schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[IncidentIoResumeConfig]:
+ return ResumableSourceManager[IncidentIoResumeConfig](inputs, IncidentIoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: IncidentIoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[IncidentIoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return incident_io_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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/incident_io/tests/test_incident_io.py b/posthog/temporal/data_imports/sources/incident_io/tests/test_incident_io.py
new file mode 100644
index 000000000000..9a585542e36c
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/incident_io/tests/test_incident_io.py
@@ -0,0 +1,400 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.incident_io.incident_io import (
+ IncidentIoResumeConfig,
+ IncidentIoRetryableError,
+ _build_params,
+ _build_url,
+ _format_filter_value,
+ _params_from_url,
+ _parse_retry_after,
+ _wait_with_retry_after,
+ get_rows,
+ incident_io_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.incident_io.settings import ENDPOINTS, INCIDENT_IO_ENDPOINTS
+
+
+def _make_manager(resume_state: IncidentIoResumeConfig | 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 _page(data_key: str, items: list[dict[str, Any]], after: str | None) -> dict[str, Any]:
+ return {data_key: items, "pagination_meta": {"after": after, "page_size": 250}}
+
+
+def _response(body: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.json.return_value = body
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.headers = {}
+ return response
+
+
+class TestFormatFilterValue:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (True, None),
+ (datetime(2024, 5, 1, 12, 30, tzinfo=UTC), "2024-05-01"),
+ (datetime(2024, 5, 1, 12, 30), "2024-05-01"),
+ (date(2024, 5, 1), "2024-05-01"),
+ ("2024-05-01T12:30:00Z", "2024-05-01"),
+ ("2024-05-01T12:30:00+00:00", "2024-05-01"),
+ ("2024-05-01", "2024-05-01"),
+ ("not-a-date", None),
+ (1700000000, None),
+ ],
+ )
+ def test_format_filter_value(self, value, expected):
+ assert _format_filter_value(value) == expected
+
+
+class TestBuildParams:
+ def test_incidents_include_page_size_and_sort(self):
+ params = _build_params(INCIDENT_IO_ENDPOINTS["incidents"], None, None)
+ assert params == {"page_size": 250, "sort_by": "created_at_oldest_first"}
+
+ def test_incremental_filter_included_when_set(self):
+ params = _build_params(INCIDENT_IO_ENDPOINTS["incidents"], "updated_at", "2024-05-01")
+ assert params["updated_at[gte]"] == "2024-05-01"
+
+ def test_incremental_filter_omitted_without_value(self):
+ params = _build_params(INCIDENT_IO_ENDPOINTS["incidents"], "updated_at", None)
+ assert "updated_at[gte]" not in params
+
+ def test_non_paginated_endpoint_has_no_params(self):
+ assert _build_params(INCIDENT_IO_ENDPOINTS["severities"], None, None) == {}
+
+ @pytest.mark.parametrize("endpoint", ["alerts", "escalations"])
+ def test_small_page_endpoints_use_capped_page_size(self, endpoint):
+ params = _build_params(INCIDENT_IO_ENDPOINTS[endpoint], None, None)
+ assert params == {"page_size": 50}
+
+
+class TestBuildUrl:
+ def test_no_params(self):
+ assert _build_url("/v1/severities", {}) == "https://api.incident.io/v1/severities"
+
+ def test_drops_none_values_and_encodes_brackets(self):
+ url = _build_url("/v2/incidents", {"page_size": 250, "after": None, "updated_at[gte]": "2024-05-01"})
+ assert url == "https://api.incident.io/v2/incidents?page_size=250&updated_at%5Bgte%5D=2024-05-01"
+
+
+class TestParamsFromUrl:
+ def test_strips_after_and_keeps_filters(self):
+ url = _build_url(
+ "/v2/incidents",
+ {"page_size": 250, "sort_by": "created_at_oldest_first", "updated_at[gte]": "2024-05-01", "after": "01H"},
+ )
+ params = _params_from_url(url)
+ assert params == {
+ "page_size": "250",
+ "sort_by": "created_at_oldest_first",
+ "updated_at[gte]": "2024-05-01",
+ }
+
+ def test_url_without_query(self):
+ assert _params_from_url("https://api.incident.io/v1/severities") == {}
+
+
+class TestRetryAfter:
+ @pytest.mark.parametrize(
+ "header_value, expected",
+ [
+ (None, None),
+ ("", None),
+ ("30", 30.0),
+ ("0", 0.0),
+ ("-5", 0.0),
+ ("1.5", 1.5),
+ ("Wed, 21 Oct 2026 07:28:00 GMT", None),
+ ],
+ )
+ def test_parse_retry_after(self, header_value, expected):
+ assert _parse_retry_after(header_value) == expected
+
+ def test_wait_honors_retry_after(self):
+ retry_state = mock.MagicMock()
+ retry_state.outcome.exception.return_value = IncidentIoRetryableError("rate limited", retry_after=30.0)
+ assert _wait_with_retry_after(retry_state) == 30.0
+
+ def test_wait_caps_retry_after(self):
+ retry_state = mock.MagicMock()
+ retry_state.outcome.exception.return_value = IncidentIoRetryableError("rate limited", retry_after=9999.0)
+ assert _wait_with_retry_after(retry_state) == 120.0
+
+ @pytest.mark.parametrize(
+ "exception",
+ [
+ IncidentIoRetryableError("server error"),
+ ValueError("boom"),
+ ],
+ )
+ def test_wait_falls_back_to_exponential_backoff(self, exception):
+ retry_state = mock.MagicMock()
+ retry_state.outcome.exception.return_value = exception
+ retry_state.attempt_number = 1
+ wait = _wait_with_retry_after(retry_state)
+ assert isinstance(wait, float)
+ assert wait >= 0
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid",
+ [
+ (200, True),
+ (401, False),
+ (403, True),
+ (500, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_status_mapping_at_source_create(self, mock_session, status_code, expected_valid):
+ mock_session.return_value.get.return_value = _response({}, status_code)
+
+ is_valid, _ = validate_credentials("key")
+
+ assert is_valid is expected_valid
+
+ @pytest.mark.parametrize(
+ "status_code, expected_valid",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_status_mapping_with_schema_name(self, mock_session, status_code, expected_valid):
+ mock_session.return_value.get.return_value = _response({}, status_code)
+
+ is_valid, error = validate_credentials("key", schema_name="alerts")
+
+ assert is_valid is expected_valid
+ if status_code == 403:
+ assert error is not None and "alerts" in error
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_probes_incidents_with_minimal_page_at_source_create(self, mock_session):
+ mock_session.return_value.get.return_value = _response({})
+
+ validate_credentials("key")
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert url == "https://api.incident.io/v2/incidents?page_size=1"
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_probes_non_paginated_endpoint_without_page_size(self, mock_session):
+ mock_session.return_value.get.return_value = _response({})
+
+ validate_credentials("key", schema_name="severities")
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert url == "https://api.incident.io/v1/severities"
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_sends_bearer_auth_header(self, mock_session):
+ mock_session.return_value.get.return_value = _response({})
+
+ validate_credentials("secret-key")
+
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "Bearer secret-key"
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_swallows_network_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+
+ is_valid, error = validate_credentials("key")
+
+ assert is_valid is False
+ assert error is not None
+
+
+class TestGetRows:
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_paginates_via_pagination_meta_after(self, mock_session):
+ pages = [
+ _page("incidents", [{"id": "01A"}, {"id": "01B"}], "01B"),
+ _page("incidents", [{"id": "01C"}], None),
+ ]
+ mock_session.return_value.get.side_effect = [_response(page) for page in pages]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "incidents", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["01A", "01B", "01C"]
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert "after=01B" in second_url
+ # State is saved only while a next page exists, after the batch was yielded.
+ manager.save_state.assert_called_once()
+ assert "after=01B" in manager.save_state.call_args.args[0].next_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_incremental_request_includes_filter_and_sort(self, mock_session):
+ mock_session.return_value.get.return_value = _response(_page("incidents", [], None))
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "key",
+ "incidents",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 5, 1, 12, 30, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "updated_at%5Bgte%5D=2024-05-01" in url
+ assert "sort_by=created_at_oldest_first" in url
+ assert "page_size=250" in url
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_full_refresh_ignores_incremental_value(self, mock_session):
+ mock_session.return_value.get.return_value = _response(_page("incidents", [], None))
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "key",
+ "incidents",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2024, 5, 1, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "gte" not in url
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_resumes_from_saved_state_and_preserves_filters(self, mock_session):
+ resume_url = _build_url(
+ "/v2/incidents",
+ {"page_size": 250, "sort_by": "created_at_oldest_first", "updated_at[gte]": "2024-05-01", "after": "01B"},
+ )
+ pages = [
+ _page("incidents", [{"id": "01C"}], "01C"),
+ _page("incidents", [], None),
+ ]
+ mock_session.return_value.get.side_effect = [_response(page) for page in pages]
+
+ manager = _make_manager(IncidentIoResumeConfig(next_url=resume_url))
+ list(get_rows("key", "incidents", mock.MagicMock(), manager))
+
+ first_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert first_url == resume_url
+ # The next page keeps the original chain's filter and swaps in the new cursor.
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert "updated_at%5Bgte%5D=2024-05-01" in second_url
+ assert "after=01C" in second_url
+ assert "after=01B" not in second_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_non_paginated_endpoint_fetches_once(self, mock_session):
+ body = {"severities": [{"id": "01A"}], "pagination_meta": {"after": "01A"}}
+ mock_session.return_value.get.return_value = _response(body)
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "severities", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_count == 1
+ assert [item["id"] for batch in batches for item in batch] == ["01A"]
+ manager.save_state.assert_not_called()
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_empty_response_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _response(_page("alerts", [], None))
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "alerts", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_missing_data_key_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"pagination_meta": {"after": None}})
+
+ manager = _make_manager()
+ assert list(get_rows("key", "incidents", mock.MagicMock(), manager)) == []
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_retries_on_429_honoring_retry_after(self, mock_session):
+ rate_limited = _response({}, 429)
+ rate_limited.headers = {"Retry-After": "0"}
+ ok = _response(_page("incidents", [{"id": "01A"}], None))
+ mock_session.return_value.get.side_effect = [rate_limited, ok]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "incidents", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_count == 2
+ assert [item["id"] for batch in batches for item in batch] == ["01A"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_retries_on_5xx(self, mock_session):
+ server_error = _response({}, 500)
+ ok = _response(_page("incidents", [{"id": "01A"}], None))
+ mock_session.return_value.get.side_effect = [server_error, ok]
+
+ with mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io._fallback_wait", return_value=0):
+ manager = _make_manager()
+ batches = list(get_rows("key", "incidents", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_count == 2
+ assert [item["id"] for batch in batches for item in batch] == ["01A"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session")
+ def test_raises_on_client_error(self, mock_session):
+ not_found = _response({}, 404)
+ not_found.raise_for_status.side_effect = Exception("404 Client Error")
+ mock_session.return_value.get.return_value = not_found
+
+ manager = _make_manager()
+ with pytest.raises(Exception, match="404 Client Error"):
+ list(get_rows("key", "incidents", mock.MagicMock(), manager))
+
+
+class TestIncidentIoSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = INCIDENT_IO_ENDPOINTS[endpoint]
+ response = incident_io_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("config", list(INCIDENT_IO_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key == "created_at"
+
+ @pytest.mark.parametrize("config", list(INCIDENT_IO_ENDPOINTS.values()))
+ def test_endpoint_paths_are_versioned(self, config):
+ assert config.path.startswith(("/v1/", "/v2/"))
diff --git a/posthog/temporal/data_imports/sources/incident_io/tests/test_incident_io_source.py b/posthog/temporal/data_imports/sources/incident_io/tests/test_incident_io_source.py
new file mode 100644
index 000000000000..1e618851846b
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/incident_io/tests/test_incident_io_source.py
@@ -0,0 +1,149 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import IncidentIoSourceConfig
+from posthog.temporal.data_imports.sources.incident_io.incident_io import IncidentIoResumeConfig
+from posthog.temporal.data_imports.sources.incident_io.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.incident_io.source import IncidentIoSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestIncidentIoSource:
+ def setup_method(self):
+ self.source = IncidentIoSource()
+ self.team_id = 123
+ self.config = IncidentIoSourceConfig(api_key="api-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.INCIDENTIO
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "IncidentIo"
+ assert config.label == "incident.io"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/incident_io.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.incident.io/v2/incidents?page_size=250",
+ "403 Client Error: Forbidden for url: https://api.incident.io/v2/alerts",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.incident.io/v2/incidents",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only the incidents list exposes server-side timestamp filters with a sortable order.
+ assert incremental == {"incidents"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["incidents"].incremental_fields == INCREMENTAL_FIELDS["incidents"]
+ assert {f["field"] for f in schemas["incidents"].incremental_fields} == {"created_at", "updated_at"}
+
+ @pytest.mark.parametrize("endpoint", [e for e in ENDPOINTS if e != "incidents"])
+ def test_full_refresh_endpoints_do_not_advertise_incremental(self, endpoint):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas[endpoint].supports_incremental is False
+ assert schemas[endpoint].supports_append is False
+ assert schemas[endpoint].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["incidents"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "incidents"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "schema_name, mock_return",
+ [
+ (None, (True, None)),
+ (None, (False, "incident.io authentication failed. Please check that your API key is valid.")),
+ ("alerts", (False, "Your incident.io API key can't list alerts.")),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.source.validate_incident_io_credentials")
+ def test_validate_credentials_passthrough(self, mock_validate, schema_name, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+
+ assert result == mock_return
+ mock_validate.assert_called_once_with(self.config.api_key, schema_name)
+
+ 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 IncidentIoResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.source.incident_io_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_incident_io_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "incidents"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-05-01T00:00:00Z"
+ inputs.incremental_field = "updated_at"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_incident_io_source.assert_called_once()
+ kwargs = mock_incident_io_source.call_args.kwargs
+ assert kwargs["api_key"] == "api-key"
+ assert kwargs["endpoint"] == "incidents"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-05-01T00:00:00Z"
+ assert kwargs["incremental_field"] == "updated_at"
+
+ @mock.patch("posthog.temporal.data_imports.sources.incident_io.source.incident_io_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_incident_io_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "severities"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-05-01T00:00:00Z"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_incident_io_source.call_args.kwargs["db_incremental_field_last_value"] is None