: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 zenduty import source (#71155)
Tom Owerse8e9ff563640
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex f4e7af34a308..8b23c3506154 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -473,6 +473,7 @@ the row lists both.| zapier_supported_storage | HTTP | requests | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ || zendesk_sell | HTTP | requests | ✅ |+| zenduty | HTTP | requests | ✅ || zenloop | HTTP | requests | ✅ || zep | HTTP | requests | ✅ || zonka_feedback | HTTP | requests | ✅ |@@ -981,7 +982,6 @@ doesn't conflict with concurrent PRs.- zapsign- zellify- zendesk_sunshine-- zenduty- zenefits- zenloop- zoho_analyticsdiff --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 39b0ff5ecc25..abb9605e8ee4 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@@ -4679,7 +4679,7 @@ class ZendeskSunshineSourceConfig(config.Config):@config.configclass ZendutySourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/canonical_descriptions.pynew file mode 100644index 000000000000..2de2dc51bdfa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/canonical_descriptions.py@@ -0,0 +1,126 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS = "https://apidocs.zenduty.com/"++# Descriptions are sourced from Zenduty's public API reference and product docs. Partial coverage is+# fine — any endpoint, column, or table-level description not listed here falls back to LLM enrichment.+# Team-nested tables additionally carry a `_zenduty_team_id` column: the `unique_id` of the parent team+# the row was fetched under (part of the composite primary key).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "teams": {+ "description": "Teams in your Zenduty account. Each team owns its own services, escalation policies, schedules, and members.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier (UUID) for the team.",+ "name": "Name of the team.",+ "creation_date": "When the team was created.",+ },+ },+ "account_members": {+ "description": "Members (users) of your Zenduty account, with their contact details and account role.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the account member.",+ "user": "The underlying user record (email, name, username).",+ "role": "The member's account-level role.",+ },+ },+ "incidents": {+ "description": "Incidents across your Zenduty account, with their status, urgency, and timing — the basis for MTTR/MTTA and incident-volume analysis.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the incident.",+ "incident_number": "Sequential, human-readable incident number.",+ "title": "Title/summary of the incident.",+ "status": "Lifecycle status of the incident (e.g. triggered, acknowledged, resolved).",+ "urgency": "Urgency assigned to the incident.",+ "service": "The service the incident belongs to.",+ "escalation_policy": "The escalation policy applied to the incident.",+ "creation_date": "When the incident was created.",+ },+ },+ "services": {+ "description": "Services within a team. Each service maps to an escalation policy that dictates how its incidents escalate.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the service.",+ "name": "Name of the service.",+ "escalation_policy": "The escalation policy governing this service.",+ "team": "The team the service belongs to.",+ "creation_date": "When the service was created.",+ },+ },+ "escalation_policies": {+ "description": "Escalation policies for a team — the ordered rules (schedules and users) that decide who is notified as an incident escalates.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the escalation policy.",+ "name": "Name of the escalation policy.",+ "rules": "Ordered escalation rules (targets and delays).",+ },+ },+ "schedules": {+ "description": "On-call schedules for a team, defining rotations and who is on call at a given time.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the schedule.",+ "name": "Name of the schedule.",+ "time_zone": "Time zone the schedule is evaluated in.",+ },+ },+ "team_members": {+ "description": "Membership rows linking users to a team, including their role within that team.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the team membership.",+ "user": "The user who is a member of the team.",+ "role": "The user's role within the team.",+ },+ },+ "roles": {+ "description": "Incident roles defined for a team (e.g. incident commander, communications lead).",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the role.",+ "title": "Title of the role.",+ "description": "What the role is responsible for.",+ },+ },+ "postmortems": {+ "description": "Post-incident retrospectives (postmortems) authored for a team's incidents.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the postmortem.",+ "title": "Title of the postmortem.",+ "author": "The author of the postmortem.",+ },+ },+ "maintenance_windows": {+ "description": "Scheduled maintenance windows for a team, during which alerting for affected services is suppressed.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the maintenance window.",+ "name": "Name of the maintenance window.",+ "start_time": "When the maintenance window begins.",+ "end_time": "When the maintenance window ends.",+ },+ },+ "slas": {+ "description": "Service-level agreements configured for a team, used to track response and resolution targets.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the SLA.",+ "name": "Name of the SLA.",+ },+ },+ "tags": {+ "description": "Tags defined for a team, used to categorize incidents and services.",+ "docs_url": _DOCS,+ "columns": {+ "unique_id": "Unique identifier for the tag.",+ "name": "Name of the tag.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/settings.pynew file mode 100644index 000000000000..df7cff18713c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/settings.py@@ -0,0 +1,58 @@+from dataclasses import dataclass, field+++@dataclass+class ZendutyEndpointConfig:+ name: str+ # Path relative to https://www.zenduty.com. Team-nested paths carry a `{team_id}`+ # placeholder resolved per parent team during fan-out.+ path: str+ # When True, the endpoint lives under `/api/account/teams/{team_id}/...`, so the transport+ # first lists every team and then walks the child collection once per team, tagging each+ # row with the parent team's id.+ team_nested: bool = False+ primary_keys: list[str] = field(default_factory=lambda: ["unique_id"])+ should_sync_default: bool = True+ page_size: int = 100+++# The field injected into every fan-out child row so the parent team is recoverable and the+# composite primary key stays unique table-wide (a child id is only unique within its team).+PARENT_TEAM_ID_FIELD = "_zenduty_team_id"+++def _team_nested(name: str, path: str) -> ZendutyEndpointConfig:+ # Child ids are only guaranteed unique within their parent team, so include the parent id in+ # the key — otherwise a merge multi-matches duplicate ids across teams (see the skill's OOM note).+ return ZendutyEndpointConfig(+ name=name,+ path=path,+ team_nested=True,+ primary_keys=[PARENT_TEAM_ID_FIELD, "unique_id"],+ )+++# Endpoint catalog. Paths are relative to https://www.zenduty.com. Every path here was confirmed to+# be a real route against the live API (real routes return a 403 "Invalid or Inactive Token" JSON body+# on a bad token; unknown routes return 404). `incidents` is the documented account-level list route;+# our unauthenticated probe was blocked by Zenduty's WAF (HTTP 209), so its exact response shape is+# handled defensively (see `_extract_items_and_next`). The set mirrors the streams a reliability team+# actually warehouses from an incident-management/on-call platform.+ZENDUTY_ENDPOINTS: dict[str, ZendutyEndpointConfig] = {+ # Account-level (top-level) collections.+ "teams": ZendutyEndpointConfig(name="teams", path="/api/account/teams/"),+ "account_members": ZendutyEndpointConfig(name="account_members", path="/api/account/members/"),+ "incidents": ZendutyEndpointConfig(name="incidents", path="/api/incidents/"),+ # Team-nested collections (fan out over every team).+ "services": _team_nested("services", "/api/account/teams/{team_id}/services/"),+ "escalation_policies": _team_nested("escalation_policies", "/api/account/teams/{team_id}/escalation_policies/"),+ "schedules": _team_nested("schedules", "/api/account/teams/{team_id}/schedules/"),+ "team_members": _team_nested("team_members", "/api/account/teams/{team_id}/members/"),+ "roles": _team_nested("roles", "/api/account/teams/{team_id}/roles/"),+ "postmortems": _team_nested("postmortems", "/api/account/teams/{team_id}/postmortem/"),+ "maintenance_windows": _team_nested("maintenance_windows", "/api/account/teams/{team_id}/maintenance/"),+ "slas": _team_nested("slas", "/api/account/teams/{team_id}/sla/"),+ "tags": _team_nested("tags", "/api/account/teams/{team_id}/tags/"),+}++ENDPOINTS = tuple(ZENDUTY_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/source.pyindex 8fac184cac45..a4ccb0078d01 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/source.py@@ -1,19 +1,42 @@-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 ZendutySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.zenduty.settings import (+ ENDPOINTS,+ ZENDUTY_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zenduty.zenduty import (+ ZendutyResumeConfig,+ probe_credentials,+ zenduty_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ZendutySource(SimpleSource[ZendutySourceConfig]):+class ZendutySource(ResumableSource[ZendutySourceConfig, ZendutyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ZENDUTY@@ -24,7 +47,96 @@ class ZendutySource(SimpleSource[ZendutySourceConfig]):name=SchemaExternalDataSourceType.ZENDUTY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Zenduty",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Zenduty API key to automatically pull your Zenduty incident-management and on-call data into the PostHog Data warehouse.++Create an API key in your Zenduty account under **Account Settings → Access → API Keys** (account owners and admins only). The key is account-scoped and read access is enough for syncing.""",iconPath="/static/services/zenduty.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/zenduty",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.zenduty.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Zenduty returns 403 (not 401) with `{"error": "Invalid or Inactive Token"}` for a bad token,+ # which surfaces as a requests HTTPError when `_fetch_page` calls `raise_for_status()`. No retry+ # can satisfy a credential problem. Match the stable status text + base host, not the path/query.+ return {+ "403 Client Error: Forbidden for url: https://www.zenduty.com": "Your Zenduty API key is invalid or inactive. Create a new API key in your Zenduty account settings, then reconnect.",+ "401 Client Error: Unauthorized for url: https://www.zenduty.com": "Your Zenduty API key is invalid or inactive. Create a new API key in your Zenduty account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: ZendutySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = ZENDUTY_ENDPOINTS[endpoint]+ # Full refresh only: Zenduty does not clearly document a universal server-side+ # updated-since filter, so we don't advertise incremental sync (a client-side cursor+ # that still walks every page is not incremental — it just costs the same as a full+ # refresh). Config resources are small and mutable state (incident status) is best+ # picked up by re-syncing.+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) 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: ZendutySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ status = probe_credentials(config.api_key)++ if status == 200:+ return True, None+ # Zenduty returns 403 for an invalid/inactive token (there is no 401 path), so a 403 here is+ # a genuine bad key rather than a valid-token-missing-scope situation.+ if status in (401, 403):+ return False, "Your Zenduty API key is invalid or inactive."+ return False, "Could not validate your Zenduty API key. Please check the key and try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZendutyResumeConfig]:+ return ResumableSourceManager[ZendutyResumeConfig](inputs, ZendutyResumeConfig)++ def source_for_pipeline(+ self,+ config: ZendutySourceConfig,+ resumable_source_manager: ResumableSourceManager[ZendutyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return zenduty_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/tests/test_zenduty.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/tests/test_zenduty.pynew file mode 100644index 000000000000..79767624a89c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/tests/test_zenduty.py@@ -0,0 +1,250 @@+from typing import Any++import pytest+from unittest import mock+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.zenduty import zenduty+from products.warehouse_sources.backend.temporal.data_imports.sources.zenduty.zenduty import (+ ZendutyResumeConfig,+ ZendutyRetryableError,+ _extract_items_and_next,+ _fetch_page,+ get_rows,+ probe_credentials,+)+++class TestExtractItemsAndNext:+ def test_paginated_envelope_returns_results_and_next(self) -> None:+ data = {"count": 2, "next": "https://www.zenduty.com/api/incidents/?page=2", "results": [{"a": 1}, {"a": 2}]}+ rows, next_url = _extract_items_and_next(data)+ assert rows == [{"a": 1}, {"a": 2}]+ assert next_url == "https://www.zenduty.com/api/incidents/?page=2"++ def test_last_page_has_null_next(self) -> None:+ rows, next_url = _extract_items_and_next({"next": None, "results": [{"a": 1}]})+ assert rows == [{"a": 1}]+ assert next_url is None++ def test_bare_list_returns_no_next(self) -> None:+ # Smaller team-nested collections come back as a bare array with no pagination envelope.+ rows, next_url = _extract_items_and_next([{"a": 1}, {"a": 2}])+ assert rows == [{"a": 1}, {"a": 2}]+ assert next_url is None++ @parameterized.expand(+ [+ ("empty_results", {"results": []}, [], None),+ ("null_results", {"results": None}, [], None),+ ("single_object", {"unique_id": "x"}, [{"unique_id": "x"}], None),+ ("unexpected_type", "nope", [], None),+ ]+ )+ def test_edge_shapes(self, _name: str, data: Any, expected_rows: list, expected_next: Any) -> None:+ assert _extract_items_and_next(data) == (expected_rows, expected_next)+++class TestFetchPage:+ def _response(self, status_code: int, json_value: Any = None, raises_json: bool = False) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.text = "body"+ if raises_json:+ response.json.side_effect = ValueError("not json")+ else:+ response.json.return_value = json_value+ response.headers = {}+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} Client Error", response=response) if status_code >= 400 else None+ )+ return response++ def test_success_returns_parsed_json(self) -> None:+ session = MagicMock()+ session.get.return_value = self._response(200, {"results": []})+ assert _fetch_page(session, "https://www.zenduty.com/api/incidents/", {}, MagicMock()) == {"results": []}++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_transient_status_raises_retryable(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = self._response(status_code)+ # Retry wrapper re-raises the last error after exhausting attempts.+ with pytest.raises(ZendutyRetryableError):+ _fetch_page(session, "https://www.zenduty.com/api/incidents/", {}, MagicMock())++ def test_non_json_2xx_is_retryable(self) -> None:+ # Zenduty's WAF answered our unauthenticated probe with a non-JSON "Blocked" body (HTTP 209);+ # treat an unparseable 2xx as transient rather than crashing the sync.+ session = MagicMock()+ session.get.return_value = self._response(209, raises_json=True)+ with pytest.raises(ZendutyRetryableError):+ _fetch_page(session, "https://www.zenduty.com/api/incidents/", {}, MagicMock())++ def test_forbidden_raises_http_error(self) -> None:+ session = MagicMock()+ session.get.return_value = self._response(403)+ with pytest.raises(requests.HTTPError):+ _fetch_page(session, "https://www.zenduty.com/api/account/teams/", {}, MagicMock())++ @parameterized.expand(+ [+ ("other_host", "https://evil.example.com/api/incidents/"),+ ("plain_http", "http://www.zenduty.com/api/incidents/"),+ ("host_suffix_trick", "https://www.zenduty.com.evil.example.com/api/incidents/"),+ ]+ )+ def test_non_zenduty_url_is_refused_without_a_request(self, _name: str, url: str) -> None:+ # Requests carry the account API key, so a tampered `next` URL or poisoned resume+ # checkpoint must never be fetched.+ session = MagicMock()+ with pytest.raises(ValueError):+ _fetch_page(session, url, {}, MagicMock())+ session.get.assert_not_called()++ def test_redirect_is_refused(self) -> None:+ # A redirect off the validated origin would re-send the API key wherever it points.+ session = MagicMock()+ session.get.return_value = self._response(302)+ with pytest.raises(ValueError):+ _fetch_page(session, "https://www.zenduty.com/api/incidents/", {}, MagicMock())+ assert session.get.call_args.kwargs["allow_redirects"] is False+++class _FakeResumableManager:+ def __init__(self, state: ZendutyResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ZendutyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ZendutyResumeConfig | None:+ return self._state++ def save_state(self, data: ZendutyResumeConfig) -> None:+ self.saved.append(data)+++def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], endpoint: str) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ return pages[url]++ monkeypatch.setattr(zenduty, "_fetch_page", fake_fetch)+ monkeypatch.setattr(zenduty, "make_tracked_session", lambda: MagicMock())++ rows: list[dict] = []+ for page in get_rows(api_key="tok", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=manager): # type: ignore[arg-type]+ rows.extend(page)+ return rows+++class TestGetRowsTopLevel:+ def test_follows_next_across_pages(self, monkeypatch: Any) -> None:+ first = "https://www.zenduty.com/api/incidents/?page_size=100"+ second = "https://www.zenduty.com/api/incidents/?page=2"+ pages = {+ first: {"results": [{"unique_id": "1"}], "next": second},+ second: {"results": [{"unique_id": "2"}], "next": None},+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "incidents")+ assert rows == [{"unique_id": "1"}, {"unique_id": "2"}]++ def test_saves_state_after_each_page_except_last(self, monkeypatch: Any) -> None:+ first = "https://www.zenduty.com/api/incidents/?page_size=100"+ second = "https://www.zenduty.com/api/incidents/?page=2"+ pages = {+ first: {"results": [{"unique_id": "1"}], "next": second},+ second: {"results": [{"unique_id": "2"}], "next": None},+ }+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, pages, "incidents")+ assert [(s.next_url, s.team_id) for s in manager.saved] == [(second, None)]++ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:+ resume_url = "https://www.zenduty.com/api/incidents/?page=3"+ pages = {resume_url: {"results": [{"unique_id": "9"}], "next": None}}+ manager = _FakeResumableManager(ZendutyResumeConfig(next_url=resume_url))+ rows = _collect(manager, monkeypatch, pages, "incidents")+ assert rows == [{"unique_id": "9"}]++ def test_poisoned_next_url_is_never_persisted(self, monkeypatch: Any) -> None:+ first = "https://www.zenduty.com/api/incidents/?page_size=100"+ pages = {first: {"results": [{"unique_id": "1"}], "next": "https://evil.example.com/steal"}}+ manager = _FakeResumableManager()+ with pytest.raises(ValueError):+ _collect(manager, monkeypatch, pages, "incidents")+ assert manager.saved == []+++class TestGetRowsFanOut:+ def _team_pages(self) -> dict[str, Any]:+ teams_url = "https://www.zenduty.com/api/account/teams/?page_size=100"+ return {teams_url: {"results": [{"unique_id": "team-a"}, {"unique_id": "team-b"}], "next": None}}++ def test_walks_each_team_and_injects_parent_id(self, monkeypatch: Any) -> None:+ pages = self._team_pages()+ pages["https://www.zenduty.com/api/account/teams/team-a/services/?page_size=100"] = {+ "results": [{"unique_id": "svc-1"}],+ "next": None,+ }+ pages["https://www.zenduty.com/api/account/teams/team-b/services/?page_size=100"] = {+ "results": [{"unique_id": "svc-2"}],+ "next": None,+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "services")+ # Each child row carries the parent team's id so the composite key stays unique table-wide.+ assert rows == [+ {"unique_id": "svc-1", "_zenduty_team_id": "team-a"},+ {"unique_id": "svc-2", "_zenduty_team_id": "team-b"},+ ]++ def test_checkpoints_next_team_when_a_team_completes(self, monkeypatch: Any) -> None:+ pages = self._team_pages()+ pages["https://www.zenduty.com/api/account/teams/team-a/services/?page_size=100"] = {+ "results": [{"unique_id": "svc-1"}],+ "next": None,+ }+ pages["https://www.zenduty.com/api/account/teams/team-b/services/?page_size=100"] = {+ "results": [{"unique_id": "svc-2"}],+ "next": None,+ }+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, pages, "services")+ # After team-a completes, state points at team-b's start so a resume skips team-a entirely.+ assert [(s.next_url, s.team_id) for s in manager.saved] == [(None, "team-b")]++ def test_resume_skips_completed_teams(self, monkeypatch: Any) -> None:+ pages = self._team_pages()+ # Only team-b's collection is provided; if the loop tried team-a it would KeyError.+ pages["https://www.zenduty.com/api/account/teams/team-b/services/?page_size=100"] = {+ "results": [{"unique_id": "svc-2"}],+ "next": None,+ }+ manager = _FakeResumableManager(ZendutyResumeConfig(next_url=None, team_id="team-b"))+ rows = _collect(manager, monkeypatch, pages, "services")+ assert rows == [{"unique_id": "svc-2", "_zenduty_team_id": "team-b"}]++ def test_no_teams_yields_nothing(self, monkeypatch: Any) -> None:+ teams_url = "https://www.zenduty.com/api/account/teams/?page_size=100"+ rows = _collect(_FakeResumableManager(), monkeypatch, {teams_url: {"results": [], "next": None}}, "services")+ assert rows == []+++class TestProbeCredentials:+ @parameterized.expand([("ok", 200), ("forbidden_bad_token", 403), ("server_error", 500)])+ def test_returns_status_code(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code)+ with mock.patch.object(zenduty, "make_tracked_session", return_value=session):+ assert probe_credentials("tok") == status_code++ def test_connection_failure_returns_none(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ with mock.patch.object(zenduty, "make_tracked_session", return_value=session):+ assert probe_credentials("tok") is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/tests/test_zenduty_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/tests/test_zenduty_source.pynew file mode 100644index 000000000000..279fb0100dca--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/tests/test_zenduty_source.py@@ -0,0 +1,142 @@+from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.zenduty import source as zenduty_source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.zenduty.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.zenduty.source import ZendutySource+from products.warehouse_sources.backend.temporal.data_imports.sources.zenduty.zenduty import ZendutyResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestZendutySourceConfig:+ def test_source_type(self) -> None:+ assert ZendutySource().source_type == ExternalDataSourceType.ZENDUTY++ def test_config_basics(self) -> None:+ config = ZendutySource().get_source_config+ assert config.label == "Zenduty"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ # Ship visible with a soft "new" label — never unreleasedSource.+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/zenduty"++ def test_single_password_api_key_field(self) -> None:+ fields = ZendutySource().get_source_config.fields+ assert len(fields) == 1+ field = fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "api_key"+ assert field.required is True+ assert field.type == SourceFieldInputConfigType.PASSWORD+++class TestZendutyGetSchemas:+ def test_returns_every_endpoint(self) -> None:+ schemas = ZendutySource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_all_endpoints_are_full_refresh(self) -> None:+ # Zenduty exposes no confirmed universal server-side updated-since filter, so nothing is+ # advertised as incremental — a client-side cursor is not incremental.+ schemas = ZendutySource().get_schemas(MagicMock(), team_id=1)+ assert all(s.supports_incremental is False and s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_names_filter(self) -> None:+ schemas = ZendutySource().get_schemas(MagicMock(), team_id=1, names=["incidents", "services"])+ assert {s.name for s in schemas} == {"incidents", "services"}+++class TestZendutyValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ # Zenduty returns 403 (not 401) for a bad/inactive token — reject even at source-create.+ ("forbidden_is_bad_token", 403, False),+ ("unauthorized_rejected", 401, False),+ ("connection_failure_rejected", None, False),+ ("unexpected_status_rejected", 500, False),+ ]+ )+ def test_status_mapping(self, _name: str, probe_status: int | None, expected_ok: bool) -> None:+ with mock.patch.object(zenduty_source_module, "probe_credentials", return_value=probe_status):+ ok, error = ZendutySource().validate_credentials(MagicMock(api_key="tok"), team_id=1)+ assert ok is expected_ok+ assert (error is None) is expected_ok+++class TestZendutyNonRetryableErrors:+ @parameterized.expand(+ [+ ("forbidden", "403 Client Error: Forbidden for url: https://www.zenduty.com/api/account/teams/"),+ ("unauthorized", "401 Client Error: Unauthorized for url: https://www.zenduty.com/api/incidents/"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = ZendutySource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://www.zenduty.com/api/incidents/"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://www.zenduty.com/api/incidents/"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = ZendutySource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestZendutyResumableAndPipeline:+ def test_resumable_manager_bound_to_resume_config(self) -> None:+ manager = ZendutySource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ZendutyResumeConfig++ @parameterized.expand(+ [+ # Top-level endpoints key on the object's own id...+ ("incidents", ["unique_id"]),+ ("teams", ["unique_id"]),+ # ...fan-out children key on parent team + child id, unique table-wide.+ ("services", ["_zenduty_team_id", "unique_id"]),+ ("schedules", ["_zenduty_team_id", "unique_id"]),+ ]+ )+ def test_source_for_pipeline_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:+ inputs = MagicMock()+ inputs.schema_name = endpoint+ response = ZendutySource().source_for_pipeline(+ MagicMock(api_key="tok"), resumable_source_manager=MagicMock(), inputs=inputs+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_keys+ # No partitioning until the stable creation-date column is confirmed per endpoint.+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestZendutyCanonicalDescriptions:+ def test_descriptions_keyed_by_endpoint_name(self) -> None:+ descriptions = ZendutySource().get_canonical_descriptions()+ # Every documented key must be a real endpoint so enrichment binds to the right table.+ assert set(descriptions).issubset(set(ENDPOINTS))+ assert "incidents" in descriptions+ assert descriptions["incidents"]["columns"]["unique_id"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ # Static endpoint catalog → the source opts into the public-docs Supported tables list.+ assert ZendutySource().lists_tables_without_credentials is True+ tables = ZendutySource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/zenduty.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/zenduty.mdxnew file mode 100644index 000000000000..7c0883dc5cbb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/zenduty.mdx@@ -0,0 +1,53 @@+---+title: Linking Zenduty as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: Zenduty+beta: true+---++import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'+import SyncModes from '../_snippets/sync-modes.mdx'+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'+import AlphaRelease from '../_snippets/alpha-release.mdx'++<AlphaRelease />++Sync your Zenduty incident-management and on-call data into PostHog to analyze incident volume, response times (MTTA/MTTR), and on-call load across your teams alongside the rest of your product data.++## Prerequisites++You need a Zenduty account and an account-scoped API key. API keys can only be created by account owners and admins.++## Adding a data source++<SourceSetupIntro />++You need an **API key**:++1. In Zenduty, go to **Account Settings → Access → API Keys**.+2. Create a new key (or copy an existing one). The key is account-scoped, and read access is enough for syncing.+3. Paste it into the **API key** field when connecting the source in PostHog.++## Sync modes++<SyncModes />++Zenduty tables sync with full refresh. Zenduty's API does not expose a reliable universal "updated since" filter, so each sync re-reads the current state — which keeps mutable fields (like incident status) up to date.++## Configuration++<SourceParameters />++## Supported tables++Zenduty organizes most resources under a team, so the team-scoped tables below (services, escalation policies, schedules, and so on) carry a `_zenduty_team_id` column identifying the parent team.++<SourceTables />++## Troubleshooting++**"Your Zenduty API key is invalid or inactive."** — the key was mistyped, revoked, or belongs to a deactivated account. Generate a fresh key in **Account Settings → Access → API Keys** and reconnect.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/zenduty.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/zenduty.pynew file mode 100644index 000000000000..5024eb64fcf2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenduty/zenduty.py@@ -0,0 +1,257 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode, urlsplit++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.zenduty.settings import (+ PARENT_TEAM_ID_FIELD,+ ZENDUTY_ENDPOINTS,+ ZendutyEndpointConfig,+)++ZENDUTY_BASE_URL = "https://www.zenduty.com"+REQUEST_TIMEOUT_SECONDS = 60+++class ZendutyRetryableError(Exception):+ pass+++class ZendutyResumeConfig:+ # The next page URL (DRF returns absolute `next` URLs that already carry the page cursor).+ next_url: str | None = None+ # For team-nested (fan-out) endpoints, the team whose child collection was in progress. On+ # resume we skip teams already fully walked and pick this one back up at `next_url`.+ team_id: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Token {api_key}",+ "Accept": "application/json",+ }+++def _initial_url(path: str, page_size: int) -> str:+ # `page_size` only steers the first request; DRF may cap or ignore it, after which we simply+ # follow the server's `next` links.+ return f"{ZENDUTY_BASE_URL}{path}?{urlencode({'page_size': page_size})}"+++def _ensure_zenduty_url(url: str) -> str:+ """Require an HTTPS www.zenduty.com URL. Every request carries the account API key, so a+ pagination `next` URL (or a poisoned resume checkpoint) pointing anywhere else would leak the+ key and let the worker be steered at arbitrary/internal hosts."""+ parts = urlsplit(url)+ if parts.scheme != "https" or parts.netloc != "www.zenduty.com":+ raise ValueError(f"Refusing non-Zenduty pagination URL: {url}")+ return url+++def _extract_items_and_next(data: Any) -> tuple[list[dict[str, Any]], str | None]:+ """Normalize a Zenduty list response into (rows, next_url).++ Zenduty is Django REST framework, so collections come back either as a page-number envelope+ (`{"count", "next", "previous", "results"}`) or, for smaller team-nested collections, as a bare+ JSON array. Handle both, plus a lone object, so a per-endpoint pagination difference can't drop rows.+ """+ if isinstance(data, list):+ return [row for row in data if isinstance(row, dict)], None+ if isinstance(data, dict):+ if "results" in data:+ results = data.get("results") or []+ rows = [row for row in results if isinstance(row, dict)] if isinstance(results, list) else []+ next_url = data.get("next")+ return rows, next_url if isinstance(next_url, str) else None+ # A single resource object (not expected for list routes, but keep it lossless).+ return [data], None+ return [], None+++@retry(+ retry=retry_if_exception_type((ZendutyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:+ # Redirects are refused: following one off the validated origin would re-send the API key+ # to wherever the response points.+ response = session.get(+ _ensure_zenduty_url(url), headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False+ )++ if 300 <= response.status_code < 400:+ raise ValueError(+ f"Zenduty returned an unexpected redirect: status={response.status_code}, "+ f"location={response.headers.get('Location')}, url={url}"+ )++ # 429 (rate limited) and 5xx are transient; retry them.+ if response.status_code == 429 or response.status_code >= 500:+ raise ZendutyRetryableError(f"Zenduty API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Zenduty API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ try:+ return response.json()+ except ValueError:+ # A 2xx that isn't JSON (e.g. a WAF interstitial). Treat as transient rather than crashing+ # the sync on a body we can't parse.+ raise ZendutyRetryableError(f"Zenduty returned a non-JSON body: status={response.status_code}, url={url}")+++def _with_team_id(row: dict[str, Any], team_id: str) -> dict[str, Any]:+ return {**row, PARENT_TEAM_ID_FIELD: team_id}+++def _list_team_ids(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger, page_size: int+) -> list[str]:+ """Enumerate every team's `unique_id` — the parents fan-out endpoints iterate over."""+ url: str | None = _initial_url(ZENDUTY_ENDPOINTS["teams"].path, page_size)+ team_ids: list[str] = []+ while url:+ data = _fetch_page(session, url, headers, logger)+ rows, next_url = _extract_items_and_next(data)+ for row in rows:+ unique_id = row.get("unique_id")+ if isinstance(unique_id, str) and unique_id:+ team_ids.append(unique_id)+ url = _ensure_zenduty_url(next_url) if next_url else None+ return team_ids+++def _paginate_top_level(+ session: requests.Session,+ headers: dict[str, str],+ config: ZendutyEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZendutyResumeConfig],+ resume: ZendutyResumeConfig | None,+ page_size: int,+) -> Iterator[list[dict[str, Any]]]:+ url = resume.next_url if (resume and resume.next_url) else _initial_url(config.path, page_size)+ while True:+ data = _fetch_page(session, url, headers, logger)+ rows, next_url = _extract_items_and_next(data)+ if rows:+ yield rows+ if not next_url:+ break+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge+ # dedupes on the primary key. Advance the URL before the next fetch to avoid re-looping it.+ # Validate before saving so an off-origin URL never lands in the resume checkpoint.+ resumable_source_manager.save_state(ZendutyResumeConfig(next_url=_ensure_zenduty_url(next_url)))+ url = next_url+++def _paginate_fan_out(+ session: requests.Session,+ headers: dict[str, str],+ config: ZendutyEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZendutyResumeConfig],+ resume: ZendutyResumeConfig | None,+ page_size: int,+) -> Iterator[list[dict[str, Any]]]:+ team_ids = _list_team_ids(session, headers, logger, page_size)+ if not team_ids:+ return++ start_index = 0+ resume_url: str | None = None+ if resume and resume.team_id and resume.team_id in team_ids:+ start_index = team_ids.index(resume.team_id)+ resume_url = resume.next_url++ for idx in range(start_index, len(team_ids)):+ team_id = team_ids[idx]+ url = (+ resume_url+ if (idx == start_index and resume_url)+ else _initial_url(config.path.format(team_id=team_id), page_size)+ )+ while True:+ data = _fetch_page(session, url, headers, logger)+ rows, next_url = _extract_items_and_next(data)+ if rows:+ yield [_with_team_id(row, team_id) for row in rows]+ if next_url:+ resumable_source_manager.save_state(+ ZendutyResumeConfig(next_url=_ensure_zenduty_url(next_url), team_id=team_id)+ )+ url = next_url+ continue+ # Team done — checkpoint at the next team's start so a resume skips completed teams+ # instead of re-walking them.+ if idx + 1 < len(team_ids):+ resumable_source_manager.save_state(ZendutyResumeConfig(next_url=None, team_id=team_ids[idx + 1]))+ break+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZendutyResumeConfig],+ page_size: int = 100,+) -> Iterator[list[dict[str, Any]]]:+ config = ZENDUTY_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across pages so urllib3 keeps the connection alive.+ session = make_tracked_session()++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.team_nested:+ yield from _paginate_fan_out(session, headers, config, logger, resumable_source_manager, resume, page_size)+ else:+ yield from _paginate_top_level(session, headers, config, logger, resumable_source_manager, resume, page_size)+++def zenduty_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZendutyResumeConfig],+ page_size: int = 100,+) -> SourceResponse:+ config = ZENDUTY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ page_size=page_size,+ ),+ primary_keys=config.primary_keys,+ # No partitioning: Zenduty's per-resource creation-timestamp field names aren't verified+ # against a live account, and partitioning on an absent field fails the sync. Partitioning+ # can be added later once the stable creation-date column is confirmed per endpoint.+ )+++def probe_credentials(api_key: str) -> int | None:+ """Cheap probe of the account teams collection. Returns the HTTP status code, or None on a+ connection failure. Zenduty returns 403 with `{"error": "Invalid or Inactive Token"}` for a bad+ token (there is no 401), and 200 for a valid one."""+ url = _initial_url(ZENDUTY_ENDPOINTS["teams"].path, page_size=1)+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)+ except Exception:+ return None+ return response.status_code