: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 xmatters import source (#71147)
Tom Owers34b1a12a6d6d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex efc0d5a3f29c..fab04f9ea27d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -463,6 +463,7 @@ the row lists both.| wrike | HTTP | requests | ✅ || writesonic | HTTP | requests | ✅ || wufoo | HTTP | requests | ✅ |+| xmatters | HTTP | requests | ✅ || zapier_supported_storage | HTTP | requests | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ || zendesk_sell | HTTP | requests | ✅ |@@ -966,7 +967,6 @@ doesn't conflict with concurrent PRs.- workramp- wufoo- xero-- xmatters- xsolla- yahoo_finance- yandex_metricadiff --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 0027ae55deb7..564d203c2cd1 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@@ -4589,7 +4589,9 @@ class XeroSourceConfig(config.Config):@config.configclass XmattersSourceConfig(config.Config):- pass+ subdomain: str+ username: str+ password: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/canonical_descriptions.pynew file mode 100644index 000000000000..6629b5c878c0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/canonical_descriptions.py@@ -0,0 +1,132 @@+"""Canonical, documentation-sourced descriptions for xMatters endpoints and columns.++Sourced from the official xMatters REST API reference (https://help.xmatters.com/xmapi/).+Keyed by the endpoint names in `settings.py` `XMATTERS_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced xMatters table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Fields shared by most xMatters REST objects; merged into each entry so we don't repeat them.+_COMMON_COLUMNS = {+ "id": "Unique identifier (UUID) for the object.",+ "targetName": "Human-readable name that uniquely identifies the object within the instance.",+ "links": "Object containing a `self` link to retrieve this resource from the API.",+}+++def _columns(**overrides: str) -> dict[str, str]:+ return {**_COMMON_COLUMNS, **overrides}+++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "events": {+ "description": "An alert (event) initiated in xMatters, including its status, priority, and timestamps.",+ "docs_url": "https://help.xmatters.com/xmapi/index.html#get-events",+ "columns": _columns(+ eventId="Sequential, human-readable identifier for the event.",+ created="Date and time the event was created; the incremental cursor.",+ terminated="Date and time the event was terminated, if applicable.",+ status="Current status of the event (e.g. ACTIVE, SUSPENDED, TERMINATED).",+ priority="Priority of the event (LOW, MEDIUM, HIGH).",+ eventType="Whether the event is a normal alert or a signal.",+ submitter="The person or system that initiated the event.",+ recipients="The recipients targeted by the event.",+ responseCountsEnabled="Whether response counts are tracked for the event.",+ plan="The communication plan the event belongs to, if any.",+ form="The form used to initiate the event, if any.",+ ),+ },+ "people": {+ "description": "A user in the xMatters instance who can be notified and can respond to events.",+ "docs_url": "https://help.xmatters.com/xmapi/index.html#get-people",+ "columns": _columns(+ firstName="The user's first name.",+ lastName="The user's last name.",+ status="Whether the user is ACTIVE or INACTIVE.",+ externallyOwned="Whether the user is managed by an external system.",+ roles="The roles assigned to the user, which control their permissions.",+ site="The site the user is associated with.",+ timezone="The user's time zone.",+ language="The user's preferred language.",+ ),+ },+ "groups": {+ "description": "A group of recipients used to target and escalate notifications.",+ "docs_url": "https://help.xmatters.com/xmapi/index.html#get-groups",+ "columns": _columns(+ name="The name of the group.",+ status="Whether the group is ACTIVE or INACTIVE.",+ groupType="The type of group (e.g. ON_CALL, BROADCAST, DYNAMIC).",+ description="A description of the group.",+ observedByAll="Whether all users can observe the group.",+ allowDuplicates="Whether duplicate notifications to a recipient are allowed.",+ useDefaultDevices="Whether the group uses recipients' default devices.",+ ),+ },+ "devices": {+ "description": "A contact method (device) belonging to a user, such as email, SMS, or push.",+ "docs_url": "https://help.xmatters.com/xmapi/index.html#get-devices",+ "columns": _columns(+ name="The name of the device (e.g. 'Work Email').",+ deviceType="The type of device (e.g. EMAIL, TEXT_PHONE, VOICE, ANDROID_PUSH).",+ owner="The user who owns the device.",+ status="Whether the device is ACTIVE or INACTIVE.",+ testStatus="Whether the device has been validated.",+ priorityThreshold="The minimum event priority that triggers this device.",+ delay="Delay in minutes before this device is contacted.",+ ),+ },+ "sites": {+ "description": "A physical or logical location that users can be associated with.",+ "docs_url": "https://help.xmatters.com/xmapi/index.html#get-sites",+ "columns": _columns(+ name="The name of the site.",+ status="Whether the site is ACTIVE or INACTIVE.",+ timezone="The time zone of the site.",+ country="The country the site is located in.",+ language="The default language of the site.",+ ),+ },+ "roles": {+ "description": "A role that defines the set of permissions a user has in xMatters.",+ "docs_url": "https://help.xmatters.com/xmapi/index.html#get-roles",+ "columns": _columns(+ name="The name of the role.",+ ),+ },+ "dynamic_teams": {+ "description": "A team whose membership is derived dynamically from user attributes.",+ "docs_url": "https://help.xmatters.com/xmapi/index.html#get-dynamic-teams",+ "columns": _columns(+ name="The name of the dynamic team.",+ recipientType="The recipient type of the team (DYNAMIC_TEAM).",+ observedByAll="Whether all users can observe the team.",+ supervisors="The users who supervise the dynamic team.",+ ),+ },+ "plans": {+ "description": "A communication plan that groups forms, integrations, and configuration used to initiate events.",+ "docs_url": "https://help.xmatters.com/xmapi/index.html#get-plans",+ "columns": _columns(+ name="The name of the communication plan.",+ enabled="Whether the plan is enabled.",+ editable="Whether the plan can be edited.",+ planType="The type of the plan.",+ created="Date and time the plan was created.",+ ),+ },+ "subscriptions": {+ "description": "A subscription that notifies users when events matching its criteria are initiated.",+ "docs_url": "https://help.xmatters.com/xmapi/index.html#get-subscriptions",+ "columns": _columns(+ name="The name of the subscription.",+ description="A description of the subscription.",+ criteria="The criteria events must match to trigger the subscription.",+ owner="The user who owns the subscription.",+ createdDate="Date and time the subscription was created.",+ ),+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/settings.pynew file mode 100644index 000000000000..ab7bc670ea33--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/settings.py@@ -0,0 +1,74 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class XmattersEndpointConfig:+ path: str # Path under the API base URL, e.g. "/events"+ primary_key: str = "id"+ partition_key: Optional[str] = None # Stable datetime field used to partition (never a mutable field)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # True only when the endpoint exposes a server-side time-window filter (`from`) on the+ # created timestamp AND accepts a `sortBy`/`sortOrder` ordering we control. Both are+ # required for safe incremental sync: the filter bounds the window and the ascending+ # sort guarantees a stable watermark. Reference/config endpoints stay full-refresh.+ supports_from: bool = False+++_CREATED_INCREMENTAL: list[IncrementalField] = [+ {+ "label": "created",+ "type": IncrementalFieldType.DateTime,+ "field": "created",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++# Top-level list endpoints. xMatters also exposes per-parent resources (e.g. /audits requires+# an eventId, /on-call and /shifts require a group), which need fan-out and are not included+# here. Every list response is wrapped in a `data` array with `count`, `total`, and `links`.+XMATTERS_ENDPOINTS: dict[str, XmattersEndpointConfig] = {+ "events": XmattersEndpointConfig(+ path="/events",+ partition_key="created",+ incremental_fields=_CREATED_INCREMENTAL,+ # `/events` accepts `from`/`to` (ISO 8601) that filter by the event's created time and a+ # `sortBy=START_TIME&sortOrder=ASCENDING` ordering we control, so incremental sync is safe.+ # Note this picks up newly *created* events only — status changes to events created before+ # the cursor are not re-fetched (xMatters filters on created time, not an updated cursor).+ supports_from=True,+ ),+ "people": XmattersEndpointConfig(+ path="/people",+ ),+ "groups": XmattersEndpointConfig(+ path="/groups",+ ),+ "devices": XmattersEndpointConfig(+ path="/devices",+ ),+ "sites": XmattersEndpointConfig(+ path="/sites",+ ),+ "roles": XmattersEndpointConfig(+ path="/roles",+ ),+ "dynamic_teams": XmattersEndpointConfig(+ path="/dynamic-teams",+ ),+ "plans": XmattersEndpointConfig(+ path="/plans",+ ),+ "subscriptions": XmattersEndpointConfig(+ path="/subscriptions",+ ),+}++ENDPOINTS = tuple(XMATTERS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in XMATTERS_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/source.pyindex 537c173ae3b8..d66160c93d49 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/source.py@@ -1,19 +1,49 @@-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 XmattersSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.xmatters.settings import (+ ENDPOINTS,+ XMATTERS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.xmatters.xmatters import (+ XmattersResumeConfig,+ is_valid_subdomain,+ validate_credentials as validate_xmatters_credentials,+ xmatters_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class XmattersSource(SimpleSource[XmattersSourceConfig]):+class XmattersSource(ResumableSource[XmattersSourceConfig, XmattersResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ # The stored password/API key is sent to the host derived from `subdomain`, so retargeting+ # `subdomain` must re-require the secret (prevents credential exfiltration to another host).+ @property+ def connection_host_fields(self) -> list[str]:+ return ["subdomain"]+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.XMATTERS@@ -24,7 +54,116 @@ class XmattersSource(SimpleSource[XmattersSourceConfig]):name=SchemaExternalDataSourceType.XMATTERS,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="xMatters (Everbridge)",+ caption="""Enter your xMatters instance subdomain and REST API credentials to pull your xMatters data into the PostHog Data warehouse.++Use HTTP Basic auth with a REST Web Service User (or an API key as the username and its secret as the password). The account needs read access to the resources you want to sync.""",iconPath="/static/services/xmatters.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/xmatters",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Company subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="username",+ label="Username or API key",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Password or API key secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.xmatters.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: XmattersSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=XMATTERS_ENDPOINTS[endpoint].supports_from,+ supports_append=False,+ incremental_fields=XMATTERS_ENDPOINTS[endpoint].incremental_fields,+ )+ for endpoint in 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: XmattersSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if not is_valid_subdomain(config.subdomain):+ return False, "xMatters subdomain is invalid"++ ok, status, error = validate_xmatters_credentials(+ config.subdomain, config.username, config.password, schema_name+ )+ if ok:+ return True, None++ # A valid account may legitimately lack permission for a specific endpoint. Accept 403 at+ # source-create (schema_name is None) so users can connect with credentials scoped to only+ # the resources they want; re-raise it for per-schema checks.+ if status == 403 and schema_name is None:+ return True, None++ return False, error++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your xMatters credentials are invalid or expired. Please check them and reconnect.",+ "403 Client Error: Forbidden for url": "Your xMatters account does not have the required permissions. Please check its access and try again.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[XmattersResumeConfig]:+ return ResumableSourceManager[XmattersResumeConfig](inputs, XmattersResumeConfig)++ def source_for_pipeline(+ self,+ config: XmattersSourceConfig,+ resumable_source_manager: ResumableSourceManager[XmattersResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return xmatters_source(+ subdomain=config.subdomain,+ username=config.username,+ password=config.password,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/tests/test_xmatters.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/tests/test_xmatters.pynew file mode 100644index 000000000000..e6f8d0660edb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/tests/test_xmatters.py@@ -0,0 +1,280 @@+import base64+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.xmatters.settings import XMATTERS_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.xmatters.xmatters import (+ PAGE_SIZE,+ XmattersResumeConfig,+ _base_url,+ _build_params,+ _format_incremental_value,+ _get_headers,+ get_rows,+ is_valid_subdomain,+ validate_credentials,+ xmatters_source,+)++XMATTERS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.xmatters.xmatters"+++class FakeResumableManager:+ """In-memory stand-in for ResumableSourceManager that records saved state."""++ def __init__(self, resume_state: Optional[XmattersResumeConfig] = None) -> None:+ self._resume_state = resume_state+ self.saved_states: list[XmattersResumeConfig] = []++ def can_resume(self) -> bool:+ return self._resume_state is not None++ def load_state(self) -> Optional[XmattersResumeConfig]:+ return self._resume_state++ def save_state(self, data: XmattersResumeConfig) -> None:+ self.saved_states.append(data)+++def _mock_response(status_code: int = 200, body: Any = None, text: str = "") -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.text = text+ response.json.return_value = body if body is not None else {}+ if not response.ok:+ error_response = requests.Response()+ error_response.status_code = status_code+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status_code} Client Error: error for url: https://acme.xmatters.com", response=error_response+ )+ return response+++def _patch_session(get_side_effect: Any) -> Any:+ session = MagicMock()+ session.get.side_effect = get_side_effect+ return patch(f"{XMATTERS_MODULE}.make_tracked_session", return_value=session), session+++def _page(items: list[dict], next_url: Optional[str] = None) -> dict:+ body: dict[str, Any] = {"count": len(items), "total": len(items), "data": items}+ if next_url is not None:+ body["links"] = {"next": next_url}+ return body+++class TestFormatIncrementalValue:+ @pytest.mark.parametrize(+ "value,expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),+ (date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),+ ("already-a-cursor", "already-a-cursor"),+ ],+ )+ def test_format(self, value: Any, expected: str) -> None:+ assert _format_incremental_value(value) == expected+++class TestSubdomainValidation:+ @pytest.mark.parametrize("subdomain", ["acme", "acme-corp", "a", "acme123", "123acme"])+ def test_valid_subdomains(self, subdomain: str) -> None:+ assert is_valid_subdomain(subdomain) is True+ assert _base_url(subdomain) == f"https://{subdomain}.xmatters.com/api/xm/1"++ # An editor-controlled subdomain like `attacker.example/` would make the worker send its+ # requests (and Basic auth header) to an arbitrary host instead of *.xmatters.com (SSRF).+ @pytest.mark.parametrize(+ "subdomain",+ [+ "attacker.example/",+ "[email protected]",+ "acme.evil.example",+ "127.0.0.1:8443/",+ "acme/path",+ "acme?x=",+ "acme#frag",+ "",+ "-acme",+ "acme-",+ "a" * 64,+ ],+ )+ def test_hostile_subdomains_rejected(self, subdomain: str) -> None:+ assert is_valid_subdomain(subdomain) is False+ with pytest.raises(ValueError):+ _base_url(subdomain)+++class TestHeaders:+ def test_basic_auth_header(self) -> None:+ headers = _get_headers("svc", "secret")+ expected = base64.b64encode(b"svc:secret").decode("ascii")+ assert headers["Authorization"] == f"Basic {expected}"+ assert headers["Accept"] == "application/json"+++class TestBuildParams:+ def test_events_full_refresh_sends_stable_sort_only(self) -> None:+ params = _build_params(+ XMATTERS_ENDPOINTS["events"],+ offset=0,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert params == {"limit": PAGE_SIZE, "offset": 0, "sortBy": "START_TIME", "sortOrder": "ASCENDING"}++ def test_events_incremental_sends_from(self) -> None:+ params = _build_params(+ XMATTERS_ENDPOINTS["events"],+ offset=2000,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ assert params["offset"] == 2000+ assert params["sortBy"] == "START_TIME"+ assert params["sortOrder"] == "ASCENDING"+ assert params["from"] == "2026-01-01T00:00:00+00:00"++ def test_reference_endpoint_has_no_sort_or_from(self) -> None:+ params = _build_params(+ XMATTERS_ENDPOINTS["people"],+ offset=0,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ assert params == {"limit": PAGE_SIZE, "offset": 0}+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code,expected_ok,expected_status",+ [+ (200, True, 200),+ (401, False, 401),+ (403, False, 403),+ (500, False, 500),+ ],+ )+ def test_status_mapping(self, status_code: int, expected_ok: bool, expected_status: int) -> None:+ ctx, _ = _patch_session([_mock_response(status_code, body={}, text="boom")])+ with ctx:+ ok, status, _error = validate_credentials("acme", "svc", "secret")+ assert ok is expected_ok+ assert status == expected_status++ def test_transport_failure_returns_zero_status(self) -> None:+ ctx, _ = _patch_session(requests.ConnectionError("no network"))+ with ctx:+ ok, status, error = validate_credentials("acme", "svc", "secret")+ assert ok is False+ assert status == 0+ assert error == "no network"++ def test_probe_targets_instance_subdomain_and_endpoint_path(self) -> None:+ ctx, session = _patch_session([_mock_response(200)])+ with ctx:+ validate_credentials("acme", "svc", "secret", endpoint="events")+ called_url = session.get.call_args.args[0]+ assert called_url.startswith("https://acme.xmatters.com/api/xm/1/events?")+++class TestGetRows:+ def test_paginates_following_links_next(self) -> None:+ page1 = _mock_response(200, body=_page([{"id": "1"}, {"id": "2"}], next_url="/api/xm/1/events?offset=1000"))+ page2 = _mock_response(200, body=_page([{"id": "3"}]))+ manager = FakeResumableManager()++ ctx, session = _patch_session([page1, page2])+ with ctx:+ batches = list(get_rows("acme", "svc", "secret", "events", MagicMock(), manager)) # type: ignore[arg-type]++ assert batches == [[{"id": "1"}, {"id": "2"}], [{"id": "3"}]]+ assert session.get.call_count == 2++ def test_saves_state_after_yielding_each_page(self) -> None:+ page1 = _mock_response(200, body=_page([{"id": "1"}], next_url="/api/xm/1/events?offset=1000"))+ page2 = _mock_response(200, body=_page([{"id": "2"}]))+ manager = FakeResumableManager()++ ctx, _ = _patch_session([page1, page2])+ with ctx:+ list(get_rows("acme", "svc", "secret", "events", MagicMock(), manager)) # type: ignore[arg-type]++ # Checkpoint written once (next offset) after the first page; the last page has no+ # `links.next` so no further checkpoint.+ assert [s.offset for s in manager.saved_states] == [PAGE_SIZE]++ def test_advances_offset_between_pages(self) -> None:+ page1 = _mock_response(200, body=_page([{"id": "1"}], next_url="/api/xm/1/events?offset=1000"))+ page2 = _mock_response(200, body=_page([{"id": "2"}]))+ manager = FakeResumableManager()++ ctx, session = _patch_session([page1, page2])+ with ctx:+ list(get_rows("acme", "svc", "secret", "events", MagicMock(), manager)) # type: ignore[arg-type]++ assert "offset=0" in session.get.call_args_list[0].args[0]+ assert f"offset={PAGE_SIZE}" in session.get.call_args_list[1].args[0]++ def test_resumes_from_saved_offset(self) -> None:+ manager = FakeResumableManager(resume_state=XmattersResumeConfig(offset=PAGE_SIZE))+ page = _mock_response(200, body=_page([{"id": "x"}]))++ ctx, session = _patch_session([page])+ with ctx:+ list(get_rows("acme", "svc", "secret", "events", MagicMock(), manager)) # type: ignore[arg-type]++ assert f"offset={PAGE_SIZE}" in session.get.call_args_list[0].args[0]++ def test_empty_page_stops_iteration(self) -> None:+ page = _mock_response(200, body=_page([], next_url="/api/xm/1/events?offset=1000"))+ manager = FakeResumableManager()++ ctx, session = _patch_session([page])+ with ctx:+ batches = list(get_rows("acme", "svc", "secret", "events", MagicMock(), manager)) # type: ignore[arg-type]++ assert batches == []+ assert session.get.call_count == 1++ def test_stops_when_no_next_link_and_partial_page(self) -> None:+ # A short page without a `links.next` terminates without another request.+ page = _mock_response(200, body=_page([{"id": "1"}]))+ manager = FakeResumableManager()++ ctx, session = _patch_session([page])+ with ctx:+ batches = list(get_rows("acme", "svc", "secret", "people", MagicMock(), manager)) # type: ignore[arg-type]++ assert batches == [[{"id": "1"}]]+ assert session.get.call_count == 1+++class TestXmattersSourceResponse:+ def test_events_partitioned_on_created(self) -> None:+ response = xmatters_source("acme", "svc", "secret", "events", MagicMock(), MagicMock())+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["created"]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"++ def test_reference_endpoint_has_no_partition_settings(self) -> None:+ response = xmatters_source("acme", "svc", "secret", "people", MagicMock(), MagicMock())+ assert response.primary_keys == ["id"]+ assert response.partition_keys is None+ assert response.partition_mode is None++ @pytest.mark.parametrize("endpoint", list(XMATTERS_ENDPOINTS.keys()))+ def test_every_endpoint_builds_a_response(self, endpoint: str) -> None:+ response = xmatters_source("acme", "svc", "secret", endpoint, MagicMock(), MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == [XMATTERS_ENDPOINTS[endpoint].primary_key]+ assert callable(response.items)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/tests/test_xmatters_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/tests/test_xmatters_source.pynew file mode 100644index 000000000000..c86c891b294c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/tests/test_xmatters_source.py@@ -0,0 +1,163 @@+import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import 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.xmatters.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.xmatters.source import XmattersSource+from products.warehouse_sources.backend.temporal.data_imports.sources.xmatters.xmatters import XmattersResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalFieldType++XMATTERS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.xmatters"+++class TestXmattersSource:+ def setup_method(self) -> None:+ self.source = XmattersSource()+ self.config = MagicMock(subdomain="acme", username="svc", password="secret")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.XMATTERS++ def test_source_config_is_visible_and_alpha(self) -> None:+ # A finished source must not carry `unreleasedSource` (which hides it) and marks+ # newness via releaseStatus instead.+ config = self.source.get_source_config+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/xmatters.png"++ def test_source_config_fields(self) -> None:+ fields = self.source.get_source_config.fields+ assert fields is not None+ by_name = {f.name: f for f in fields if isinstance(f, SourceFieldInputConfig)}+ assert set(by_name) == {"subdomain", "username", "password"}+ # Only the password is a secret; the subdomain is the connection host.+ assert by_name["password"].type == SourceFieldInputConfigType.PASSWORD+ assert by_name["password"].secret is True+ assert by_name["subdomain"].secret is not True++ def test_subdomain_is_a_connection_host_field(self) -> None:+ # Retargeting the subdomain must re-require the stored secret.+ assert self.source.connection_host_fields == ["subdomain"]++ def test_only_events_supports_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}+ assert set(schemas) == set(ENDPOINTS)++ assert schemas["events"].supports_incremental is True+ assert schemas["events"].incremental_fields[0]["field"] == "created"+ assert schemas["events"].incremental_fields[0]["field_type"] == IncrementalFieldType.DateTime++ for name in ENDPOINTS:+ if name == "events":+ continue+ assert schemas[name].supports_incremental is False, name+ assert schemas[name].incremental_fields == [], name++ def test_no_endpoint_supports_append(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)+ assert all(s.supports_append is False for s in schemas)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["events", "people"])+ assert {s.name for s in schemas} == {"events", "people"}++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog powers the public docs table list.+ 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(+ "pattern",+ [+ "401 Client Error: Unauthorized for url",+ "403 Client Error: Forbidden for url",+ ],+ )+ def test_non_retryable_errors_includes_pattern(self, pattern: str) -> None:+ assert pattern in self.source.get_non_retryable_errors()++ def test_validate_credentials_rejects_hostile_subdomain_without_probing(self) -> None:+ # SSRF guard: an invalid subdomain must be rejected before any request is sent.+ self.config.subdomain = "attacker.example/"+ with patch(f"{XMATTERS_MODULE}.source.validate_xmatters_credentials") as mock_validate:+ ok, error = self.source.validate_credentials(self.config, team_id=1)+ assert ok is False+ assert error == "xMatters subdomain is invalid"+ mock_validate.assert_not_called()++ def test_validate_credentials_success(self) -> None:+ with patch(f"{XMATTERS_MODULE}.source.validate_xmatters_credentials", return_value=(True, 200, None)):+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)++ def test_validate_credentials_invalid(self) -> None:+ with patch(+ f"{XMATTERS_MODULE}.source.validate_xmatters_credentials",+ return_value=(False, 401, "Invalid xMatters credentials"),+ ):+ ok, error = self.source.validate_credentials(self.config, team_id=1)+ assert ok is False+ assert error == "Invalid xMatters credentials"++ def test_validate_credentials_accepts_403_at_source_create(self) -> None:+ # A valid account may only be scoped to a subset of resources; don't block connection.+ with patch(+ f"{XMATTERS_MODULE}.source.validate_xmatters_credentials",+ return_value=(False, 403, "no access"),+ ):+ assert self.source.validate_credentials(self.config, team_id=1, schema_name=None) == (True, None)++ def test_validate_credentials_rejects_403_for_specific_schema(self) -> None:+ with patch(+ f"{XMATTERS_MODULE}.source.validate_xmatters_credentials",+ return_value=(False, 403, "no access"),+ ):+ ok, error = self.source.validate_credentials(self.config, team_id=1, schema_name="events")+ assert ok is False+ assert error == "no access"++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock(team_id=1, job_id="job_1", logger=MagicMock())+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is XmattersResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ manager = MagicMock()+ inputs = MagicMock(+ schema_name="events",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",+ logger=MagicMock(),+ )++ with patch(f"{XMATTERS_MODULE}.source.xmatters_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["subdomain"] == "acme"+ assert kwargs["username"] == "svc"+ assert kwargs["password"] == "secret"+ assert kwargs["endpoint"] == "events"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00+00:00"++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:+ manager = MagicMock()+ inputs = MagicMock(+ schema_name="people",+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",+ logger=MagicMock(),+ )++ with patch(f"{XMATTERS_MODULE}.source.xmatters_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/xmatters.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/xmatters.pynew file mode 100644index 000000000000..c5e39655f44c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xmatters/xmatters.py@@ -0,0 +1,222 @@+import re+import base64+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+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.xmatters.settings import (+ XMATTERS_ENDPOINTS,+ XmattersEndpointConfig,+)++# xMatters is per-instance: every account lives at a customer-specific subdomain.+BASE_URL_TEMPLATE = "https://{subdomain}.xmatters.com/api/xm/1"++# A single DNS label: letters, digits, and internal hyphens only. Anything else (slashes, dots,+# `@`, etc.) could redirect worker requests to an attacker-controlled host (SSRF).+SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$")++# xMatters caps `limit` at 1000; using the max reduces round-trips.+PAGE_SIZE = 1000++# Retry/throttle settings kept near the top for easy tuning.+RETRY_ATTEMPTS = 5+REQUEST_TIMEOUT_SECONDS = 60+++class XmattersRetryableError(Exception):+ pass+++class XmattersResumeConfig:+ offset: int+++def is_valid_subdomain(subdomain: str) -> bool:+ return bool(SUBDOMAIN_REGEX.match(subdomain))+++def _base_url(subdomain: str) -> str:+ if not is_valid_subdomain(subdomain):+ raise ValueError("xMatters subdomain is invalid")+ return BASE_URL_TEMPLATE.format(subdomain=subdomain)+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental field value as an ISO 8601 UTC string for xMatters' `from` filter."""+ if isinstance(value, datetime):+ utc_value = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ return utc_value.isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _get_headers(username: str, password: str) -> dict[str, str]:+ # HTTP Basic works for both a service account (username/password) and an xMatters REST API+ # key (key as username, secret as password).+ basic_token = base64.b64encode(f"{username}:{password}".encode()).decode("ascii")+ return {+ "Authorization": f"Basic {basic_token}",+ "Accept": "application/json",+ "Content-Type": "application/json",+ }+++def _build_params(+ config: XmattersEndpointConfig,+ offset: int,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": PAGE_SIZE, "offset": offset}++ if config.supports_from:+ # START_TIME is the event's initiation (created) time, which is exactly what `from`+ # filters on — sorting ascending on it means new events append to the end and never+ # shift pages we've already read. Sent on every sync so full refreshes paginate over a+ # stable ordering too.+ params["sortBy"] = "START_TIME"+ params["sortOrder"] = "ASCENDING"+ if should_use_incremental_field and db_incremental_field_last_value:+ params["from"] = _format_incremental_value(db_incremental_field_last_value)++ return params+++def validate_credentials(+ subdomain: str, username: str, password: str, endpoint: Optional[str] = None+) -> tuple[bool, int, str | None]:+ """Probe xMatters with a cheap single-row request.++ Returns ``(ok, status_code, error_message)``. ``status_code`` is 0 on transport failure.+ The caller decides how to treat 403 (valid credentials, missing permission for the probed+ endpoint).+ """+ config = XMATTERS_ENDPOINTS.get(endpoint) if endpoint else None+ path = config.path if config else "/people"+ url = f"{_base_url(subdomain)}{path}?{urlencode({'limit': 1})}"++ try:+ response = make_tracked_session().get(url, headers=_get_headers(username, password), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, 0, str(e)++ if response.status_code == 200:+ return True, 200, None+ if response.status_code == 401:+ return False, 401, "Invalid xMatters credentials"+ if response.status_code == 403:+ return False, 403, "Your xMatters account does not have access to this resource"++ try:+ message = response.json().get("message", response.text)+ except Exception:+ message = response.text+ return False, response.status_code, message+++def get_rows(+ subdomain: str,+ username: str,+ password: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[XmattersResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = XMATTERS_ENDPOINTS[endpoint]+ headers = _get_headers(username, password)+ base_url = _base_url(subdomain)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume_config.offset if resume_config is not None else 0+ if resume_config is not None:+ logger.debug(f"xMatters: resuming {endpoint} from offset {offset}")++ @retry(+ retry=retry_if_exception_type((XmattersRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_offset: int) -> dict:+ params = _build_params(config, page_offset, should_use_incremental_field, db_incremental_field_last_value)+ url = f"{base_url}{config.path}?{urlencode(params)}"+ response = make_tracked_session().get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise XmattersRetryableError(f"xMatters API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"xMatters API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()++ while True:+ data = fetch_page(offset)++ items = data.get("data", [])+ if not items:+ break++ yield items++ # xMatters signals more pages via a `links.next` URL. Fall back to the page-fill+ # heuristic if the field is absent.+ has_next = bool(data.get("links", {}).get("next")) or len(items) >= PAGE_SIZE+ if not has_next:+ break++ offset += PAGE_SIZE++ # Save AFTER yielding so a crash re-fetches the last page; merge dedupes on primary key.+ resumable_source_manager.save_state(XmattersResumeConfig(offset=offset))+++def xmatters_source(+ subdomain: str,+ username: str,+ password: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[XmattersResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = XMATTERS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ subdomain=subdomain,+ username=username,+ password=password,+ 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,+ ),+ primary_keys=[config.primary_key],+ # We request START_TIME ascending where a sort is available, and full-refresh endpoints+ # replace wholesale, so ascending is correct everywhere.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )