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): add incident.io catalog, alert link and lookup tables (#111531)

Tom Owers455d8e2541d0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 41c081778341..65d28f7e028f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4229,17 +4229,17 @@ Note: docs.imagga.com is a JS SPA that ships no server-rendered resource list, n
## IncidentIo — gaps
-Today (12): `alerts`, `custom_fields`, `escalations`, `follow_ups`, `incident_roles`, `incident_statuses`, `incident_types`, `incident_updates`, `incidents`, `schedules`, `severities`, `users`
+Today (17): `alerts`, `catalog_entries`, `catalog_types`, `custom_field_options`, `custom_fields`, `escalations`, `follow_ups`, `incident_alerts`, `incident_roles`, `incident_statuses`, `incident_timestamps`, `incident_types`, `incident_updates`, `incidents`, `schedules`, `severities`, `users`
Diffed against: <https://api-docs.incident.io/>
-- [ ] `/v2/incident_alerts` — join table linking alerts to the incidents they triggered - without it the synced `alerts` and `incidents` tables cannot be related at all (high)
-- [ ] `/v1/custom_field_options` — lookup resolving the option IDs stored inside the custom field values on every incident; `custom\_fields` alone only gives definitions (high)
-- [ ] `/v2/incident_timestamps` — lookup naming the timestamp IDs carried in incident timestamp_values - required to compute MTTA/MTTR from the incidents table (high)
+- [x] `/v2/incident_alerts` — join table linking alerts to the incidents they triggered - without it the synced `alerts` and `incidents` tables cannot be related at all (high)
+- [x] `/v1/custom_field_options` — lookup resolving the option IDs stored inside the custom field values on every incident; `custom\_fields` alone only gives definitions (high). Added as `custom_field_options` (fan-out over `custom_fields`, since `custom_field_id` is a required query param).
+- [x] `/v2/incident_timestamps` — lookup naming the timestamp IDs carried in incident timestamp_values - required to compute MTTA/MTTR from the incidents table (high)
- [ ] `/v2/escalation_paths` — lookup resolving the escalation path IDs referenced by the already-synced `escalations` rows (high)
- [ ] `/v2/alert_sources` — lookup resolving alert_source_config IDs on `alerts`, so alert volume can be attributed to Datadog/Sentry/etc (high)
- [ ] `/v2/schedule_entries` — the actual on-call shifts; `schedules` today is only the rota config, so no one can query who was on call when (high)
-- [ ] `/v3/catalog_types and /v3/catalog_entries` — the service/team catalog that custom fields, alert routes and escalation paths all reference by ID - the master lookup for the whole account (high)
+- [x] `/v3/catalog_types and /v3/catalog_entries` — the service/team catalog that custom fields, alert routes and escalation paths all reference by ID - the master lookup for the whole account (high). Added as `catalog_types` and `catalog_entries` (fan-out over `catalog_types`, since `catalog_type_id` is a required query param).
- [ ] `/v3/teams` — team lookup for attributing incidents, escalations and follow-ups to owning teams (medium)
- [ ] `/v2/actions` — per-incident action items during the response, complementing the already-synced follow_ups (medium)
- [ ] `/v2/incident_participants and /v2/incident_participant_workloads` — membership table of who participated in each incident plus incident.io's on-call workload metric (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/canonical_descriptions.py
index b002b4fcd888..485751fc5c7b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/canonical_descriptions.py
@@ -179,4 +179,65 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "Time at which the custom field was last updated.",
},
},
+ "custom_field_options": {
+ "description": "An option that can be chosen for a single- or multi-select custom field in incident.io.",
+ "docs_url": "https://docs.incident.io/api-reference/custom-field-options-v1/list",
+ "columns": {
+ "id": "Unique identifier for the custom field option.",
+ "custom_field_id": "Identifier of the custom field this option belongs to.",
+ "value": "Human-readable name of the option.",
+ "sort_key": "Sort key used to order the custom field's options.",
+ },
+ },
+ "incident_timestamps": {
+ "description": "A named timestamp (e.g. impact started, reported, resolved) that incidents in incident.io can record.",
+ "docs_url": "https://docs.incident.io/api-reference/incident-timestamps-v2/list",
+ "columns": {
+ "id": "Unique identifier for the incident timestamp.",
+ "name": "Unique name of the timestamp.",
+ "rank": "Order in which the timestamp is shown.",
+ },
+ },
+ "incident_alerts": {
+ "description": "A link between an alert and the incident it is attached to in incident.io.",
+ "docs_url": "https://docs.incident.io/api-reference/incident-alerts-v2/list",
+ "columns": {
+ "id": "Unique identifier for the incident alert link.",
+ "alert": "The alert attached to the incident.",
+ "incident": "Key fields of the incident the alert is attached to.",
+ "alert_route_id": "Identifier of the alert route that created this link.",
+ },
+ },
+ "catalog_types": {
+ "description": "A type of entry in the incident.io catalog, such as services or teams, with the schema of its attributes.",
+ "docs_url": "https://docs.incident.io/api-reference/catalog-types-v3/list-types",
+ "columns": {
+ "id": "Unique identifier for the catalog type.",
+ "name": "Human-readable name of the catalog type.",
+ "description": "Human-readable description of the catalog type.",
+ "type_name": "Name used to reference this type when defining attributes.",
+ "schema": "The attributes that entries of this type carry.",
+ "is_editable": "Whether the type can be edited. Types synced from external resources cannot.",
+ "ranked": "Whether entries of this type are ranked.",
+ "last_synced_at": "Time at which the type was last synced from an external resource.",
+ "created_at": "Time at which the catalog type was created.",
+ "updated_at": "Time at which the catalog type was last updated.",
+ },
+ },
+ "catalog_entries": {
+ "description": "An entry in the incident.io catalog, such as a single service or team, with its attribute values.",
+ "docs_url": "https://docs.incident.io/api-reference/catalog-entries-v3/list-entries",
+ "columns": {
+ "id": "Unique identifier for the catalog entry.",
+ "catalog_type_id": "Identifier of the catalog type this entry belongs to.",
+ "name": "Human-readable name of the entry.",
+ "external_id": "Optional alternative identifier, unique within the catalog type.",
+ "aliases": "Optional aliases that can be used to reference the entry.",
+ "attribute_values": "Values of the entry's attributes, keyed by attribute ID.",
+ "rank": "Position used to order entries when the catalog type is ranked.",
+ "archived_at": "Time at which the entry was archived.",
+ "created_at": "Time at which the catalog entry was created.",
+ "updated_at": "Time at which the catalog entry was last updated.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/incident_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/incident_io.py
index 0120a0dc097e..3d24f7dff6fa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/incident_io.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/incident_io.py
@@ -1,13 +1,17 @@
import dataclasses
+from collections.abc import Iterable
from datetime import date, datetime
-from typing import Any, Optional
-from urllib.parse import parse_qsl, urlencode, urlsplit
+from typing import Any, Optional, cast
+from urllib.parse import parse_qsl, quote, urlencode, urlsplit
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.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
JSONResponseCursorPaginator,
@@ -27,9 +31,12 @@ INCIDENT_IO_BASE_URL = "https://api.incident.io"
VALIDATION_TIMEOUT_SECONDS = 10
[email protected](frozen=True)
class IncidentIoResumeConfig:
- next_url: str
+ next_url: Optional[str] = None
+ # Framework fan-out resume state for the parent-scoped endpoints, opaque to this source and
+ # passed straight back to the fan-out helper.
+ fanout_state: Optional[dict[str, Any]] = None
def _build_url(path: str, params: dict[str, Any]) -> str:
@@ -101,21 +108,38 @@ def _client_config(api_key: str) -> ClientConfig:
}
-def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
- """Probe the API to confirm the key is genuine.
+def _probe_headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
- 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.
+
+def _fanout_child_probe_url(api_key: str, config: IncidentIoEndpointConfig) -> Optional[str]:
+ """Build a one-row child request bound to a real parent id, or None when there is no parent row.
+
+ A fan-out child can have its own scope (catalog entries need `catalog_entries.view`, separate
+ from `catalog_types.view`), so probing only the parent can pass a key that can't sync the child.
"""
- config = INCIDENT_IO_ENDPOINTS.get(schema_name or "", INCIDENT_IO_ENDPOINTS["incidents"])
- params: dict[str, Any] = {"page_size": 1} if config.paginated else {}
+ assert config.fanout is not None
+ parent = INCIDENT_IO_ENDPOINTS[config.fanout.parent_name]
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ _build_url(parent.path, {}), headers=_probe_headers(api_key), timeout=VALIDATION_TIMEOUT_SECONDS
+ )
+ response.raise_for_status()
+ rows = response.json().get(parent.data_key) or []
+ except Exception:
+ return None
+ if not rows:
+ return None
+ parent_id = quote(str(rows[0][config.fanout.resolve_field]), safe="")
+ path = config.path.replace(f"{{{config.fanout.resolve_param}}}", parent_id)
+ return f"{INCIDENT_IO_BASE_URL}{path}&{urlencode({'page_size': 1})}"
+
+def _probe_result(api_key: str, url: str, schema_name: Optional[str]) -> tuple[bool, str | None]:
_ok, status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,)),
- _build_url(config.path, params),
- headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ url,
+ headers=_probe_headers(api_key),
timeout=VALIDATION_TIMEOUT_SECONDS,
)
@@ -139,6 +163,101 @@ def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tup
return False, f"incident.io API returned an unexpected response (status {status})."
+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"])
+ # A fan-out child can't be listed without a parent id, so the parent list is probed first.
+ probe_config = INCIDENT_IO_ENDPOINTS[config.fanout.parent_name] if config.fanout is not None else config
+ params: dict[str, Any] = {"page_size": 1} if probe_config.paginated else {}
+
+ is_valid, error = _probe_result(api_key, _build_url(probe_config.path, params), schema_name)
+ if not is_valid or config.fanout is None:
+ return is_valid, error
+
+ child_url = _fanout_child_probe_url(api_key, config)
+ if child_url is None:
+ return True, None
+ return _probe_result(api_key, child_url, schema_name)
+
+
+def _paginator(config: IncidentIoEndpointConfig) -> BasePaginator:
+ # incident.io paginates via a record-ID cursor in `pagination_meta.after`, replayed as the
+ # `after` query param. Config-style endpoints return the full list in one unpaginated response.
+ return (
+ JSONResponseCursorPaginator(cursor_path="pagination_meta.after", cursor_param="after")
+ if config.paginated
+ else SinglePagePaginator()
+ )
+
+
+def _source_response(config: IncidentIoEndpointConfig, items: Iterable[Any]) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=lambda: items,
+ primary_keys=config.primary_keys,
+ # 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,
+ )
+
+
+def _fanout_source(
+ api_key: str,
+ config: IncidentIoEndpointConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[IncidentIoResumeConfig],
+) -> SourceResponse:
+ """Fetch a parent-scoped endpoint once per row of its parent lookup list."""
+ assert config.fanout is not None
+ parent_config = INCIDENT_IO_ENDPOINTS[config.fanout.parent_name]
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.fanout_state:
+ initial_paginator_state = resume.fanout_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ resumable_source_manager.save_state(IncidentIoResumeConfig(fanout_state=state))
+
+ resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=INCIDENT_IO_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=config.fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ # The parent lookup lists are unpaginated and take no page-size param, so the child's
+ # page size rides in `child_params_extra` instead.
+ page_size_param=None,
+ child_params_extra={"page_size": config.page_size},
+ parent_endpoint_extra={"paginator": _paginator(parent_config), "data_selector": parent_config.data_key},
+ child_endpoint_extra={"paginator": _paginator(config), "data_selector": config.data_key},
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+ return _source_response(config, resource)
+
+
def incident_io_source(
api_key: str,
endpoint: str,
@@ -150,10 +269,12 @@ def incident_io_source(
incremental_field: str | None = None,
) -> SourceResponse:
config = INCIDENT_IO_ENDPOINTS[endpoint]
+ if config.fanout is not None:
+ return _fanout_source(api_key, config, team_id, job_id, resumable_source_manager)
initial_paginator_state: Optional[dict[str, Any]] = None
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- if resume is not None:
+ if resume is not None and resume.next_url:
# Preserve the interrupted chain's filters and cursor verbatim — never recompute the
# `gte` filter from a possibly-advanced watermark against an old `after` cursor.
params: dict[str, Any] = _params_from_url(resume.next_url)
@@ -166,14 +287,6 @@ def incident_io_source(
)
params = _build_params(config, incremental_field if should_use_incremental_field else None, incremental_value)
- # incident.io paginates via a record-ID cursor in `pagination_meta.after`, replayed as the
- # `after` query param. Config-style endpoints return the full list in one unpaginated response.
- paginator: BasePaginator = (
- JSONResponseCursorPaginator(cursor_path="pagination_meta.after", cursor_param="after")
- if config.paginated
- else SinglePagePaginator()
- )
-
rest_config: RESTAPIConfig = {
"client": _client_config(api_key),
"resources": [
@@ -183,7 +296,7 @@ def incident_io_source(
"path": config.path,
"params": params,
"data_selector": config.data_key,
- "paginator": paginator,
+ "paginator": _paginator(config),
},
}
],
@@ -206,18 +319,4 @@ def incident_io_source(
initial_paginator_state=initial_paginator_state,
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- 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,
- )
+ return _source_response(config, resource)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/settings.py
index 7dc9f7e8084c..0603aceb78f3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/settings.py
@@ -1,13 +1,16 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
class IncidentIoEndpointConfig:
name: str
- # Versioned path — incident.io mixes /v1 and /v2 across resources.
+ # Versioned path — incident.io mixes /v1, /v2 and /v3 across resources.
path: str
# Key the list of objects is nested under in the response body (e.g. {"incidents": [...]}).
data_key: str
@@ -15,7 +18,7 @@ class IncidentIoEndpointConfig:
# response and accept no pagination params.
paginated: bool = False
page_size: int = 250
- primary_key: str = "id"
+ primary_keys: list[str] = field(default_factory=lambda: ["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)
@@ -25,6 +28,13 @@ class IncidentIoEndpointConfig:
# 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
+ # Set for endpoints that require a parent id filter and so are fetched once per parent row.
+ fanout: Optional[DependentEndpointConfig] = None
+
+ @property
+ def default_incremental_field(self) -> Optional[str]:
+ # Read by the fan-out helper only for incremental children; every fan-out here is full refresh.
+ return None
_DATETIME_INCREMENTAL_FIELD_CREATED_AT: IncrementalField = {
@@ -42,6 +52,22 @@ _DATETIME_INCREMENTAL_FIELD_UPDATED_AT: IncrementalField = {
}
+# The child rows already carry the parent id, so nothing is copied from the parent row.
+_CATALOG_ENTRIES_FANOUT = DependentEndpointConfig(
+ parent_name="catalog_types",
+ resolve_param="catalog_type_id",
+ resolve_field="id",
+ include_from_parent=[],
+)
+
+_CUSTOM_FIELD_OPTIONS_FANOUT = DependentEndpointConfig(
+ parent_name="custom_fields",
+ resolve_param="custom_field_id",
+ resolve_field="id",
+ include_from_parent=[],
+)
+
+
# 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.
@@ -132,6 +158,45 @@ INCIDENT_IO_ENDPOINTS: dict[str, IncidentIoEndpointConfig] = {
path="/v2/custom_fields",
data_key="custom_fields",
),
+ "custom_field_options": IncidentIoEndpointConfig(
+ name="custom_field_options",
+ # `{custom_field_id}` is bound per parent custom field row by the fan-out.
+ path="/v1/custom_field_options?custom_field_id={custom_field_id}",
+ data_key="custom_field_options",
+ paginated=True,
+ page_size=250,
+ primary_keys=["custom_field_id", "id"],
+ fanout=_CUSTOM_FIELD_OPTIONS_FANOUT,
+ ),
+ "incident_timestamps": IncidentIoEndpointConfig(
+ name="incident_timestamps",
+ path="/v2/incident_timestamps",
+ data_key="incident_timestamps",
+ ),
+ "incident_alerts": IncidentIoEndpointConfig(
+ name="incident_alerts",
+ path="/v2/incident_alerts",
+ data_key="incident_alerts",
+ paginated=True,
+ page_size=50,
+ ),
+ "catalog_types": IncidentIoEndpointConfig(
+ name="catalog_types",
+ path="/v3/catalog_types",
+ data_key="catalog_types",
+ partition_key="created_at",
+ ),
+ "catalog_entries": IncidentIoEndpointConfig(
+ name="catalog_entries",
+ # `{catalog_type_id}` is bound per parent catalog type row by the fan-out.
+ path="/v3/catalog_entries?catalog_type_id={catalog_type_id}",
+ data_key="catalog_entries",
+ paginated=True,
+ page_size=250,
+ primary_keys=["catalog_type_id", "id"],
+ partition_key="created_at",
+ fanout=_CATALOG_ENTRIES_FANOUT,
+ ),
}
ENDPOINTS = tuple(INCIDENT_IO_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io.py
index 6b3b196defea..3529fc0cd36f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io.py
@@ -2,6 +2,7 @@ import json
from collections.abc import Iterable
from datetime import UTC, date, datetime
from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
import pytest
from unittest import mock
@@ -50,7 +51,7 @@ def _make_manager(resume_state: IncidentIoResumeConfig | None = None) -> mock.Ma
return manager
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+def _wire(session: mock.MagicMock, responses: list[Response], urls: list[str] | None = None) -> list[dict[str, Any]]:
"""Wire a mock session and capture each request's params AT SEND TIME.
``request.params`` is a single dict mutated in place across pages, so inspecting it after the
@@ -61,6 +62,8 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
def _prepare(request: Any) -> mock.MagicMock:
param_snapshots.append(dict(request.params or {}))
+ if urls is not None:
+ urls.append(request.url)
return mock.MagicMock()
session.prepare_request.side_effect = _prepare
@@ -189,14 +192,73 @@ class TestValidateCredentials:
url = mock_session.return_value.get.call_args.args[0]
assert url == "https://api.incident.io/v2/incidents?page_size=1"
+ @pytest.mark.parametrize(
+ "schema_name, expected_url",
+ [
+ ("severities", "https://api.incident.io/v1/severities"),
+ ],
+ )
@mock.patch(INCIDENT_IO_SESSION_PATCH)
- def test_probes_non_paginated_endpoint_without_page_size(self, mock_session):
+ def test_probe_url_per_schema(self, mock_session, schema_name, expected_url):
mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- validate_credentials("key", schema_name="severities")
+ validate_credentials("key", schema_name=schema_name)
url = mock_session.return_value.get.call_args.args[0]
- assert url == "https://api.incident.io/v1/severities"
+ assert url == expected_url
+
+ @pytest.mark.parametrize(
+ "schema_name, parent_key, parent_rows, child_status, expected_urls, expected_valid",
+ [
+ (
+ "catalog_entries",
+ "catalog_types",
+ [{"id": "T1"}],
+ 403,
+ [
+ "https://api.incident.io/v3/catalog_types",
+ "https://api.incident.io/v3/catalog_types",
+ "https://api.incident.io/v3/catalog_entries?catalog_type_id=T1&page_size=1",
+ ],
+ False,
+ ),
+ (
+ "custom_field_options",
+ "custom_fields",
+ [{"id": "F1"}],
+ 200,
+ [
+ "https://api.incident.io/v2/custom_fields",
+ "https://api.incident.io/v2/custom_fields",
+ "https://api.incident.io/v1/custom_field_options?custom_field_id=F1&page_size=1",
+ ],
+ True,
+ ),
+ # No parent row to bind, so the child scope can't be probed and the parent probe decides.
+ (
+ "catalog_entries",
+ "catalog_types",
+ [],
+ 403,
+ ["https://api.incident.io/v3/catalog_types", "https://api.incident.io/v3/catalog_types"],
+ True,
+ ),
+ ],
+ )
+ @mock.patch(INCIDENT_IO_SESSION_PATCH)
+ def test_fanout_schema_probes_parent_then_child(
+ self, mock_session, schema_name, parent_key, parent_rows, child_status, expected_urls, expected_valid
+ ):
+ parent = mock.MagicMock(status_code=200)
+ parent.json.return_value = {parent_key: parent_rows}
+ mock_session.return_value.get.side_effect = [parent, parent, mock.MagicMock(status_code=child_status)]
+
+ is_valid, error = validate_credentials("key", schema_name=schema_name)
+
+ assert [call.args[0] for call in mock_session.return_value.get.call_args_list] == expected_urls
+ assert is_valid is expected_valid
+ if not expected_valid:
+ assert error is not None and schema_name in error
@mock.patch(INCIDENT_IO_SESSION_PATCH)
def test_sends_bearer_auth_header(self, mock_session):
@@ -371,6 +433,43 @@ class TestGetRows:
[row for page in cast("Iterable[Any]", response.items()) for row in page]
+class TestFanout:
+ @pytest.mark.parametrize(
+ "endpoint, parent_key, child_path, parent_id_param",
+ [
+ ("catalog_entries", "catalog_types", "/v3/catalog_entries", "catalog_type_id"),
+ ("custom_field_options", "custom_fields", "/v1/custom_field_options", "custom_field_id"),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fetches_child_pages_per_parent(self, MockSession, endpoint, parent_key, child_path, parent_id_param):
+ session = MockSession.return_value
+ manager = _make_manager()
+ urls: list[str] = []
+ params = _wire(
+ session,
+ [
+ _response({parent_key: [{"id": "P1"}, {"id": "P2"}]}),
+ _response(_page_body(endpoint, [{"id": "C1", parent_id_param: "P1"}], "C1")),
+ _response(_page_body(endpoint, [{"id": "C2", parent_id_param: "P1"}], None)),
+ _response(_page_body(endpoint, [{"id": "C3", parent_id_param: "P2"}], None)),
+ ],
+ urls,
+ )
+
+ response = incident_io_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)
+ rows = [row for page in cast("Iterable[Any]", response.items()) for row in page]
+
+ assert [(r["id"], r[parent_id_param]) for r in rows] == [("C1", "P1"), ("C2", "P1"), ("C3", "P2")]
+ # The unpaginated parent list takes no params; each child request is bound to its parent.
+ assert params[0] == {}
+ assert [urlsplit(url).path for url in urls[1:]] == [child_path] * 3
+ assert [parse_qs(urlsplit(url).query)[parent_id_param] for url in urls[1:]] == [["P1"], ["P1"], ["P2"]]
+ assert [p.get("page_size") for p in params[1:]] == [250, 250, 250]
+ assert [p.get("after") for p in params[1:]] == [None, "C1", None]
+ assert manager.save_state.call_args.args[0].fanout_state is not None
+
+
class TestIncidentIoSourceResponse:
@mock.patch(CLIENT_SESSION_PATCH)
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
@@ -379,7 +478,7 @@ class TestIncidentIoSourceResponse:
response = incident_io_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager())
assert response.name == endpoint
- assert response.primary_keys == [config.primary_key]
+ assert response.primary_keys == config.primary_keys
assert response.sort_mode == "asc"
if config.partition_key:
assert response.partition_mode == "datetime"
@@ -395,4 +494,4 @@ class TestIncidentIoSourceResponse:
@pytest.mark.parametrize("config", list(INCIDENT_IO_ENDPOINTS.values()))
def test_endpoint_paths_are_versioned(self, config):
- assert config.path.startswith(("/v1/", "/v2/"))
+ assert config.path.startswith(("/v1/", "/v2/", "/v3/"))