: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 zendesk_sunshine import source (#72662)
Tom Owersd420b78c5eb5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex c092614fed33..af5a0f5ca2ae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -564,6 +564,7 @@ the row lists both.| zapier_supported_storage | HTTP | requests | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ || zendesk_sell | HTTP | requests | ✅ |+| zendesk_sunshine | HTTP | requests + `rest_source.RESTClient` | ✅ || zenduty | HTTP | requests | ✅ || zenloop | HTTP | requests | ✅ || zep | HTTP | requests | ✅ |@@ -1003,7 +1004,6 @@ doesn't conflict with concurrent PRs.- youtube_data- zapsign- zellify-- zendesk_sunshine- zenefits- zenloop- zoho_analyticsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zendesksunshine.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zendesksunshine.pyindex 8a663940f0ca..d7cd60201e6f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zendesksunshine.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zendesksunshine.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass ZendeskSunshineSourceConfig(config.Config):- pass+ subdomain: str+ api_key: str+ email_address: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/canonical_descriptions.pynew file mode 100644index 000000000000..c3e5ea98609f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/canonical_descriptions.py@@ -0,0 +1,68 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "object_types": {+ "description": "A legacy custom object type: a user-defined data model (key plus JSON schema) that legacy object records are validated against.",+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects-api/resource_types/",+ "columns": {+ "key": "Unique, user-defined identifier for the object type.",+ "schema": "JSON schema describing the object type's properties and which of them are required.",+ "created_at": "When the object type was created.",+ "updated_at": "When the object type was last updated.",+ },+ },+ "object_records": {+ "description": "A legacy custom object record: an instance of a legacy object type holding the record's data in its attributes.",+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects-api/resources/",+ "columns": {+ "id": "Unique identifier of the record, assigned automatically on creation.",+ "type": "Key of the legacy object type this record belongs to.",+ "external_id": "Unique, case-insensitive identifier from another system, if one was supplied on creation.",+ "attributes": "The record's data, validated against the object type's schema (up to 32 KB).",+ "type_version": "Version of the record's object type the record was validated against.",+ "created_at": "When the record was created.",+ "updated_at": "When the record was last updated.",+ },+ },+ "object_type_policies": {+ "description": "Role-based access permissions for one legacy object type: what admins, agents, and end users may create, read, update, or delete.",+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects-api/permissions/",+ "columns": {+ "object_type": "Key of the legacy object type the policy applies to.",+ "rbac": "Role-based access control rules per role (admin, agent, end_user) and operation (create, read, update, delete).",+ },+ },+ "relationship_types": {+ "description": "A legacy relationship type: defines how records of one object type relate to records of another object type or to standard Zendesk objects.",+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects-api/relationship_types/",+ "columns": {+ "key": "Unique, user-defined identifier for the relationship type.",+ "source": "Object type (or standard Zendesk object) allowed as the relationship's source.",+ "target": "Object type (or standard Zendesk object) allowed as the relationship's target.",+ "created_at": "When the relationship type was created.",+ "updated_at": "When the relationship type was last updated.",+ },+ },+ "relationship_records": {+ "description": "A legacy relationship record: an association between a source record and a target record of a given relationship type. Immutable after creation.",+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects-api/relationships/",+ "columns": {+ "id": "Unique identifier of the relationship record, assigned automatically on creation.",+ "relationship_type": "Key of the legacy relationship type this record belongs to.",+ "source": "Id of the source object record.",+ "target": "Id of the target object record.",+ "created_at": "When the relationship record was created.",+ },+ },+ "limits": {+ "description": "Account-level usage limits for legacy custom objects, with the current count against each limit.",+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects-api/limits/",+ "columns": {+ "key": "Identifier of the limit (for example the record limit).",+ "count": "Current usage counted against the limit.",+ "limit": "Maximum allowed by the account's plan.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/docs/zendesk-sunshine.md b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/docs/zendesk-sunshine.mdnew file mode 100644index 000000000000..4cefd01ed1ee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/docs/zendesk-sunshine.md@@ -0,0 +1,56 @@+---+title: Linking Zendesk Sunshine as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: ZendeskSunshine+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 />++The Zendesk Sunshine source syncs your legacy Zendesk custom objects (the Sunshine custom data API) into PostHog: object types, object records, relationship types, relationship records, permission policies, and account limits.++> **Note:** Zendesk is retiring legacy custom objects in 2026 and no new legacy objects can be created since January 15, 2026. This source reads the legacy `/api/sunshine/` API, so it is mainly useful for keeping a queryable copy of that data before Zendesk removes it. It does not cover the newer custom objects experience under the Zendesk Support API.++## Prerequisites++- A Zendesk plan that includes legacy custom objects, with legacy custom objects activated by an admin in Admin Center (Objects and rules → Custom objects).+- API token access enabled for your Zendesk account (Admin Center → Apps and integrations → APIs → Zendesk API).+- A Zendesk API token. Generate one in Admin Center under Apps and integrations → APIs → Zendesk API → Add API token.++## Adding a data source++<SourceSetupIntro />++You'll need:++1. Your Zendesk subdomain (the `yourcompany` part of `yourcompany.zendesk.com`).+2. The email address of the Zendesk user the API token belongs to.+3. The API token.++## Sync modes++<SyncModes />++Object records support incremental syncs on `updated_at`, served by Zendesk's custom object search API which filters server side. All other tables are small catalogs and sync as full refreshes.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++- **"Zendesk rejected the credentials"**: check the subdomain, email address, and API token, and confirm token access is enabled for your account. The username Zendesk expects is `[email protected]/token`; PostHog builds this for you, so enter your plain email address.+- **"The Zendesk Sunshine (legacy custom objects) API is not available"**: legacy custom objects are not activated for the account, or the plan doesn't include them. An admin can activate them in Admin Center under Objects and rules → Custom objects.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/settings.pynew file mode 100644index 000000000000..4ea7fcaa6d46--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/settings.py@@ -0,0 +1,102 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Catalog endpoints (object types, relationship types, limits) are small; a conservative+# page size keeps responses light.+DEFAULT_PAGE_SIZE = 100+# Record endpoints (`objects/records`, `relationships/records`, `objects/query`) document+# `per_page` from 1 to 1000.+RECORDS_PAGE_SIZE = 1000++# The legacy custom objects search endpoint — the only Sunshine endpoint with a server-side+# `_updated_at` range filter, so incremental object record syncs go through it.+QUERY_PATH = "objects/query"+# The query endpoint's pagination cursor grows with every page and Zendesk documents a hard+# limit of ~80 pages (the cursor exceeds the 4096-char URI limit), so re-window the+# `_updated_at` range well before that.+MAX_PAGES_PER_QUERY_WINDOW = 75+# `_updated_at`/`_created_at` range filters expect `yyyy-MM-dd HH:mm:ss.SSS`.+DEFAULT_QUERY_WINDOW_START = "1970-01-01 00:00:00.000"+++@dataclass(frozen=True)+class ZendeskSunshineEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ page_size: int = DEFAULT_PAGE_SIZE+ partition_key: str | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Single-hop fan-out: iterate `fanout_parent` and bind `resolve_field` from each parent+ # row into the `{resolve_placeholder}` in `path`.+ fanout_parent: str | None = None+ resolve_placeholder: str | None = None+ resolve_field: str | None = None+ include_from_parent: list[str] = field(default_factory=list)+ parent_field_renames: dict[str, str] = field(default_factory=dict)+ single_page: bool = False+++ZENDESK_SUNSHINE_ENDPOINTS: dict[str, ZendeskSunshineEndpointConfig] = {+ "object_types": ZendeskSunshineEndpointConfig(+ name="object_types",+ path="objects/types",+ primary_keys=["key"],+ partition_key="created_at",+ ),+ "object_records": ZendeskSunshineEndpointConfig(+ name="object_records",+ # Full-refresh path. Incremental syncs go through QUERY_PATH instead — the list+ # endpoint has no server-side timestamp filter.+ path="objects/records?type={object_type}",+ primary_keys=["id"],+ page_size=RECORDS_PAGE_SIZE,+ partition_key="created_at",+ incremental_fields=[incremental_field("updated_at")],+ fanout_parent="object_types",+ resolve_placeholder="object_type",+ resolve_field="key",+ ),+ "object_type_policies": ZendeskSunshineEndpointConfig(+ name="object_type_policies",+ path="objects/types/{object_type}/permissions",+ # The permissions endpoint returns one policy object per object type; the parent key+ # is injected as `object_type` so it doubles as the row's identity.+ primary_keys=["object_type"],+ fanout_parent="object_types",+ resolve_placeholder="object_type",+ resolve_field="key",+ include_from_parent=["key"],+ parent_field_renames={"key": "object_type"},+ single_page=True,+ ),+ "relationship_types": ZendeskSunshineEndpointConfig(+ name="relationship_types",+ path="relationships/types",+ primary_keys=["key"],+ partition_key="created_at",+ ),+ "relationship_records": ZendeskSunshineEndpointConfig(+ name="relationship_records",+ path="relationships/records?type={relationship_type}",+ primary_keys=["id"],+ page_size=RECORDS_PAGE_SIZE,+ partition_key="created_at",+ fanout_parent="relationship_types",+ resolve_placeholder="relationship_type",+ resolve_field="key",+ ),+ "limits": ZendeskSunshineEndpointConfig(+ name="limits",+ path="limits",+ primary_keys=["key"],+ ),+}++ENDPOINTS = tuple(ZENDESK_SUNSHINE_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ZENDESK_SUNSHINE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/source.pyindex d419bcedbc77..bf9450071225 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/source.py@@ -1,32 +1,164 @@-from typing import cast+import re+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 (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zendesksunshine import (ZendeskSunshineSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.zendesk_sunshine import (+ ZendeskSunshineResumeConfig,+ normalize_subdomain,+ validate_credentials as validate_zendesk_sunshine_credentials,+ zendesk_sunshine_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ZendeskSunshineSource(SimpleSource[ZendeskSunshineSourceConfig]):+class ZendeskSunshineSource(ResumableSource[ZendeskSunshineSourceConfig, ZendeskSunshineResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # The Sunshine API path (`/api/sunshine/`) carries no version token, so the unversioned+ # `supported_versions`/`default_version` defaults apply.+ api_docs_url = "https://developer.zendesk.com/api-reference/custom-data/custom-objects-api/custom-objects-api/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ZENDESKSUNSHINE+ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.canonical_descriptions import ( # noqa: PLC0415 — sibling data module, loaded only when descriptions are requested+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": (+ "Zendesk rejected the credentials. Check the subdomain, email address, and API token are correct, "+ "and that token access is enabled for your account."+ ),+ "403 Client Error: Forbidden for url": (+ "Zendesk denied access to the Sunshine API. Check that legacy custom objects are activated for "+ "your account and that the API token has access."+ ),+ "404 Client Error: Not Found for url": (+ "The Zendesk Sunshine (legacy custom objects) API was not found. Check the subdomain is correct "+ "and that legacy custom objects are activated in Admin Center."+ ),+ }++ def get_schemas(+ self,+ config: ZendeskSunshineSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # The query endpoint's `_updated_at.start` filter is inclusive, so boundary rows are+ # re-fetched on every sync; only merge mode dedupes them, hence no append support.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=("object_records",))++ def validate_credentials(+ self, config: ZendeskSunshineSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ subdomain = normalize_subdomain(config.subdomain)+ if not re.match(r"^[a-zA-Z0-9-]+$", subdomain):+ return False, "Zendesk subdomain is incorrect"++ return validate_zendesk_sunshine_credentials(config.subdomain, config.api_key, config.email_address)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZendeskSunshineResumeConfig]:+ return ResumableSourceManager[ZendeskSunshineResumeConfig](inputs, ZendeskSunshineResumeConfig)++ def source_for_pipeline(+ self,+ config: ZendeskSunshineSourceConfig,+ resumable_source_manager: ResumableSourceManager[ZendeskSunshineResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return zendesk_sunshine_source(+ subdomain=config.subdomain,+ api_key=config.api_key,+ email_address=config.email_address,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ZENDESK_SUNSHINE,category=DataWarehouseSourceCategory.CRM,label="Zendesk Sunshine",+ caption="""Import your legacy Zendesk custom objects (the Sunshine custom data API) into the PostHog Data warehouse: object types, object records, relationships, and limits.++Requires a Zendesk plan with legacy custom objects activated in Admin Center. Note that Zendesk is retiring legacy custom objects in 2026, so this source is mainly useful for keeping a copy of that data. Authenticate with your Zendesk email address and an API token (token access must be enabled for your account).""",+ keywords=["zendesk", "sunshine", "custom objects", "custom data"],iconPath="/static/services/zendesk_sunshine.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ iconClassName="rounded dark:bg-white p-[2px]",+ docsUrl="https://posthog.com/docs/cdp/sources/zendesk-sunshine",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Zendesk subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="email_address",+ label="Zendesk email address",+ type=SourceFieldInputConfigType.EMAIL,+ required=True,+ placeholder="",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine.pynew file mode 100644index 000000000000..7cb55dc588b7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine.py@@ -0,0 +1,549 @@+from collections.abc import Iterable+from datetime import UTC, datetime, timedelta, timezone+from typing import Any, Optional, cast++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Request++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.settings import (+ DEFAULT_QUERY_WINDOW_START,+ ZENDESK_SUNSHINE_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.zendesk_sunshine import (+ SunshineLinksPaginator,+ SunshineObjectQueryPaginator,+ ZendeskSunshineResumeConfig,+ _fanout_resources,+ _query_resource,+ get_base_url,+ list_object_type_keys,+ normalize_subdomain,+ to_query_datetime,+ validate_credentials,+ zendesk_sunshine_source,+)++BASE_URL = "https://nibbles.zendesk.com/api/sunshine/"+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.zendesk_sunshine"+++class _FakeResumeManager:+ def __init__(self, state: Optional[dict[str, Any]] = None) -> None:+ self._state = state+ self.saved: list[dict[str, Any]] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> Optional[ZendeskSunshineResumeConfig]:+ return ZendeskSunshineResumeConfig(state=self._state) if self._state is not None else None++ def save_state(self, data: ZendeskSunshineResumeConfig) -> None:+ self.saved.append(data.state)+++class _FakeResource:+ def __init__(self, name: str, pages: Optional[list[list[dict[str, Any]]]] = None) -> None:+ self.name = name+ self.maps: list[Any] = []+ self._pages = pages or []++ def add_map(self, fn: Any) -> "_FakeResource":+ self.maps.append(fn)+ return self++ def __iter__(self):+ return iter(self._pages)+++def _response(body: dict[str, Any]) -> mock.Mock:+ response = mock.Mock()+ response.json.return_value = body+ return response+++def _collect_pages(response: SourceResponse) -> list[list[dict[str, Any]]]:+ items = response.items()+ assert isinstance(items, Iterable)+ return cast(list[list[dict[str, Any]]], list(items))+++class TestZendeskSunshineTransport:+ @parameterized.expand(+ [+ ("bare", "nibbles", "nibbles"),+ ("full_host", "nibbles.zendesk.com", "nibbles"),+ ("url", "https://nibbles.zendesk.com/", "nibbles"),+ ("url_with_path", "https://nibbles.zendesk.com/agent", "nibbles"),+ ("mixed_case_host", "Nibbles.Zendesk.Com", "Nibbles"),+ ("whitespace", " nibbles ", "nibbles"),+ ]+ )+ def test_normalize_subdomain(self, _name: str, raw: str, expected: str) -> None:+ assert normalize_subdomain(raw) == expected++ def test_get_base_url(self) -> None:+ assert get_base_url("nibbles") == BASE_URL+ assert get_base_url("https://nibbles.zendesk.com") == BASE_URL++ @parameterized.expand(+ [+ ("none", None, None),+ ("naive_datetime_assumed_utc", datetime(2026, 1, 2, 3, 4, 5), "2026-01-02 03:04:05.000"),+ (+ "aware_datetime_converted",+ datetime(2026, 1, 2, 4, 4, 5, 500000, tzinfo=timezone(timedelta(hours=1))),+ "2026-01-02 03:04:05.500",+ ),+ ("iso_string", "2026-01-02T03:04:05.123Z", "2026-01-02 03:04:05.123"),+ ("microseconds_truncated", datetime(2026, 1, 2, 3, 4, 5, 123999, tzinfo=UTC), "2026-01-02 03:04:05.123"),+ ("garbage_string", "not-a-date", None),+ ]+ )+ def test_to_query_datetime(self, _name: str, value: Any, expected: str | None) -> None:+ assert to_query_datetime(value) == expected++ def test_links_paginator_absolutizes_relative_next(self) -> None:+ paginator = SunshineLinksPaginator(BASE_URL)+ paginator.update_state(+ _response({"data": [], "links": {"next": "/api/sunshine/objects/types?page[after]=abc"}})+ )++ assert paginator.has_next_page is True+ request = Request(method="GET", url=f"{BASE_URL}objects/types", params={"per_page": 100})+ paginator.update_request(request)+ assert request.url == "https://nibbles.zendesk.com/api/sunshine/objects/types?page[after]=abc"+ # The next link is self-contained; params must not be re-appended.+ assert request.params == {}++ def test_links_paginator_keeps_absolute_next(self) -> None:+ paginator = SunshineLinksPaginator(BASE_URL)+ next_url = f"{BASE_URL}objects/types?page[after]=abc"+ paginator.update_state(_response({"data": [], "links": {"next": next_url}}))++ request = Request(method="GET", url=f"{BASE_URL}objects/types")+ paginator.update_request(request)+ assert request.url == next_url++ def test_links_paginator_stops_on_null_next(self) -> None:+ paginator = SunshineLinksPaginator(BASE_URL)+ paginator.update_state(_response({"data": [], "links": {"next": None}}))+ assert paginator.has_next_page is False++ def test_links_paginator_resume_state_round_trip(self) -> None:+ paginator = SunshineLinksPaginator(BASE_URL)+ paginator.update_state(+ _response({"data": [], "links": {"next": "/api/sunshine/objects/types?page[after]=abc"}})+ )+ state = paginator.get_resume_state()+ assert state is not None++ resumed = SunshineLinksPaginator(BASE_URL)+ resumed.set_resume_state(state)+ request = Request(method="GET", url=f"{BASE_URL}objects/types", params={"per_page": 100})+ resumed.init_request(request)+ assert request.url == "https://nibbles.zendesk.com/api/sunshine/objects/types?page[after]=abc"++ def _query_request(self, window_start: str = DEFAULT_QUERY_WINDOW_START) -> Request:+ resource = _query_resource("product", window_start, BASE_URL)+ endpoint = resource["endpoint"]+ assert isinstance(endpoint, dict)+ return Request(+ method="POST",+ url=f"{BASE_URL}objects/query",+ params=dict(endpoint["params"] or {}),+ json=dict(endpoint["json"] or {}),+ )++ def test_query_resource_shape(self) -> None:+ resource = _query_resource("product", "2026-01-01 00:00:00.000", BASE_URL)+ endpoint = resource["endpoint"]+ assert isinstance(endpoint, dict)+ assert endpoint["method"] == "POST"+ assert endpoint["json"] == {+ "query": {"_type": {"$eq": "product"}},+ "sort_by": "_updated_at asc",+ "_updated_at": {"start": "2026-01-01 00:00:00.000"},+ }+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ def test_query_paginator_follows_next_and_keeps_window(self) -> None:+ paginator = SunshineObjectQueryPaginator(BASE_URL, DEFAULT_QUERY_WINDOW_START, max_pages_per_window=5)+ request = self._query_request()+ paginator.init_request(request)+ assert request.json["_updated_at"] == {"start": DEFAULT_QUERY_WINDOW_START}++ paginator.update_state(+ _response(+ {+ "data": [{"id": "1", "updated_at": "2026-01-01T00:00:00.000Z"}],+ "links": {"next": "/api/sunshine/objects/query?per_page=1000&cursor=abc"},+ }+ ),+ data=[{"id": "1", "updated_at": "2026-01-01T00:00:00.000Z"}],+ )+ paginator.update_request(request)++ assert request.url == "https://nibbles.zendesk.com/api/sunshine/objects/query?per_page=1000&cursor=abc"+ assert request.json["_updated_at"] == {"start": DEFAULT_QUERY_WINDOW_START}++ def test_query_paginator_rewindows_before_page_cap(self) -> None:+ paginator = SunshineObjectQueryPaginator(BASE_URL, DEFAULT_QUERY_WINDOW_START, max_pages_per_window=2)+ request = self._query_request()+ paginator.init_request(request)++ page1 = [{"id": "1", "updated_at": "2026-01-01T00:00:00.000Z"}]+ paginator.update_state(_response({"data": page1, "links": {"next": "/q?cursor=a"}}), data=page1)+ paginator.update_request(request)++ page2 = [{"id": "2", "updated_at": "2026-02-03T04:05:06.789Z"}]+ paginator.update_state(_response({"data": page2, "links": {"next": "/q?cursor=b"}}), data=page2)+ paginator.update_request(request)++ # Window re-anchored on the newest updated_at; pagination restarts at the query URL.+ assert request.url == f"{BASE_URL}objects/query?per_page=1000"+ assert request.json["_updated_at"] == {"start": "2026-02-03 04:05:06.789"}+ assert paginator.has_next_page is True++ def test_query_paginator_raises_when_window_cannot_advance(self) -> None:+ window_start = "2026-01-01 00:00:00.000"+ paginator = SunshineObjectQueryPaginator(BASE_URL, window_start, max_pages_per_window=1)+ page = [{"id": "1", "updated_at": "2026-01-01T00:00:00.000Z"}]++ with pytest.raises(ValueError, match="cannot advance"):+ paginator.update_state(_response({"data": page, "links": {"next": "/q?cursor=a"}}), data=page)++ def test_query_paginator_raises_when_no_timestamp_to_rewindow_from(self) -> None:+ paginator = SunshineObjectQueryPaginator(BASE_URL, DEFAULT_QUERY_WINDOW_START, max_pages_per_window=1)+ page = [{"id": "1"}]++ with pytest.raises(ValueError, match="re-window"):+ paginator.update_state(_response({"data": page, "links": {"next": "/q?cursor=a"}}), data=page)++ def test_query_paginator_stops_naturally_at_page_cap_without_next(self) -> None:+ paginator = SunshineObjectQueryPaginator(BASE_URL, DEFAULT_QUERY_WINDOW_START, max_pages_per_window=1)+ page = [{"id": "1", "updated_at": "2026-01-01T00:00:00.000Z"}]+ paginator.update_state(_response({"data": page, "links": {"next": None}}), data=page)+ assert paginator.has_next_page is False++ def test_query_paginator_resume_state_round_trip(self) -> None:+ paginator = SunshineObjectQueryPaginator(BASE_URL, "2026-01-01 00:00:00.000", max_pages_per_window=10)+ page = [{"id": "1", "updated_at": "2026-01-05T00:00:00.000Z"}]+ paginator.update_state(_response({"data": page, "links": {"next": "/q?cursor=a"}}), data=page)++ state = paginator.get_resume_state()+ assert state is not None+ assert state["window_start"] == "2026-01-01 00:00:00.000"+ assert state["pages_in_window"] == 1++ resumed = SunshineObjectQueryPaginator(BASE_URL, DEFAULT_QUERY_WINDOW_START, max_pages_per_window=10)+ resumed.set_resume_state(state)+ request = self._query_request()+ resumed.init_request(request)+ assert request.url == "https://nibbles.zendesk.com/q?cursor=a"+ # The resumed request keeps the saved window, not the constructor default.+ assert request.json["_updated_at"] == {"start": "2026-01-01 00:00:00.000"}++ def test_fanout_resources_resolve_parent_key_into_path(self) -> None:+ endpoint_config = ZENDESK_SUNSHINE_ENDPOINTS["relationship_records"]+ parent_config = ZENDESK_SUNSHINE_ENDPOINTS["relationship_types"]+ parent, child = _fanout_resources(endpoint_config, parent_config, BASE_URL)+ assert isinstance(parent, dict) and isinstance(child, dict)++ assert parent["name"] == "relationship_types"+ child_endpoint = child["endpoint"]+ assert isinstance(child_endpoint, dict)+ assert child_endpoint["path"] == "relationships/records?type={relationship_type}"+ child_params = child_endpoint["params"]+ assert child_params is not None+ assert child_params["relationship_type"] == {+ "type": "resolve",+ "resource": "relationship_types",+ "field": "key",+ }+ assert child_params["per_page"] == 1000++ def test_fanout_resources_policies_are_single_page(self) -> None:+ endpoint_config = ZENDESK_SUNSHINE_ENDPOINTS["object_type_policies"]+ parent_config = ZENDESK_SUNSHINE_ENDPOINTS["object_types"]+ _parent, child = _fanout_resources(endpoint_config, parent_config, BASE_URL)+ assert isinstance(child, dict)++ child_endpoint = child["endpoint"]+ assert isinstance(child_endpoint, dict)+ assert "per_page" not in (child_endpoint["params"] or {})+ assert child["include_from_parent"] == ["key"]++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "rejected the credentials"),+ ("forbidden", 403, False, "not available"),+ ("not_found", 404, False, "not available"),+ ("teapot", 418, False, "unexpected response"),+ ]+ )+ def test_validate_credentials_status_mapping(+ self, _name: str, status_code: int, expected_valid: bool, message_fragment: str | None+ ) -> None:+ session = mock.MagicMock()+ session.get.return_value = mock.Mock(status_code=status_code)++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ is_valid, message = validate_credentials("nibbles", "token", "[email protected]")++ assert is_valid is expected_valid+ if message_fragment is None:+ assert message is None+ else:+ assert message is not None and message_fragment in message+ assert session.get.call_args.kwargs["auth"] == ("[email protected]/token", "token")++ def test_list_object_type_keys_follows_pagination(self) -> None:+ session = mock.MagicMock()+ page1 = mock.Mock(status_code=200)+ page1.json.return_value = {+ "data": [{"key": "product"}, {"key": "order"}],+ "links": {"next": "/api/sunshine/objects/types?page[after]=abc"},+ }+ page2 = mock.Mock(status_code=200)+ page2.json.return_value = {"data": [{"key": "shipment"}], "links": {"next": None}}+ session.get.side_effect = [page1, page2]++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ keys = list_object_type_keys("nibbles", "token", "[email protected]")++ assert keys == ["product", "order", "shipment"]+ second_call = session.get.call_args_list[1]+ assert second_call.args[0] == "https://nibbles.zendesk.com/api/sunshine/objects/types?page[after]=abc"+ assert second_call.kwargs["params"] is None+++class TestZendeskSunshineSourceResponses:+ def _fake_rest_api_resources(self, config: dict[str, Any], *args: Any, **kwargs: Any) -> list[_FakeResource]:+ return [_FakeResource(resource["name"]) for resource in config["resources"]]++ @parameterized.expand(+ [+ ("object_types", ["key"], ["created_at"]),+ ("object_records", ["id"], ["created_at"]),+ ("object_type_policies", ["object_type"], None),+ ("relationship_types", ["key"], ["created_at"]),+ ("relationship_records", ["id"], ["created_at"]),+ ("limits", ["key"], None),+ ]+ )+ def test_source_response_shape(+ self, endpoint: str, expected_primary_keys: list[str], expected_partition_keys: list[str] | None+ ) -> None:+ with (+ mock.patch(+ f"{MODULE}.rest_api_resource",+ side_effect=lambda config, *a, **k: _FakeResource(config["resources"][0]["name"]),+ ),+ mock.patch(f"{MODULE}.rest_api_resources", side_effect=self._fake_rest_api_resources),+ ):+ response = zendesk_sunshine_source(+ subdomain="nibbles",+ api_key="token",+ email_address="[email protected]",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_FakeResumeManager(), # type: ignore[arg-type]+ )++ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ assert response.sort_mode == "asc"+ assert response.partition_keys == expected_partition_keys+ if expected_partition_keys:+ assert response.partition_mode == "datetime"++ def test_policies_rows_carry_object_type_from_parent(self) -> None:+ with mock.patch(f"{MODULE}.rest_api_resources", side_effect=self._fake_rest_api_resources):+ response = zendesk_sunshine_source(+ subdomain="nibbles",+ api_key="token",+ email_address="[email protected]",+ endpoint="object_type_policies",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_FakeResumeManager(), # type: ignore[arg-type]+ )++ resource = response.items()+ assert isinstance(resource, _FakeResource)+ assert len(resource.maps) == 1+ row = resource.maps[0]({"_object_types_key": "product", "rbac": {"admin": {"read": True}}})+ assert row == {"object_type": "product", "rbac": {"admin": {"read": True}}}+++class TestZendeskSunshineIncrementalObjectRecords:+ def _run(+ self,+ manager: _FakeResumeManager,+ db_incremental_field_last_value: Any = None,+ type_keys: Optional[list[str]] = None,+ pages_by_type: Optional[dict[str, list[list[dict[str, Any]]]]] = None,+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:+ pages_by_type = pages_by_type or {}++ def fake_rest_api_resource(config: dict[str, Any], *args: Any, **kwargs: Any) -> _FakeResource:+ type_key = config["resources"][0]["endpoint"]["json"]["query"]["_type"]["$eq"]+ return _FakeResource("object_records", pages_by_type.get(type_key, [[{"id": f"{type_key}-row"}]]))++ with (+ mock.patch(f"{MODULE}.list_object_type_keys", return_value=type_keys or ["alpha", "beta"]),+ mock.patch(f"{MODULE}.rest_api_resource", side_effect=fake_rest_api_resource) as mock_resource,+ ):+ response = zendesk_sunshine_source(+ subdomain="nibbles",+ api_key="token",+ email_address="[email protected]",+ endpoint="object_records",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager, # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ pages = _collect_pages(response)+ return pages, mock_resource++ def test_fresh_run_walks_every_type_and_checkpoints(self) -> None:+ manager = _FakeResumeManager()+ pages, mock_resource = self._run(manager)++ assert pages == [[{"id": "alpha-row"}], [{"id": "beta-row"}]]+ assert mock_resource.call_count == 2+ for call, type_key in zip(mock_resource.call_args_list, ["alpha", "beta"]):+ body = call.args[0]["resources"][0]["endpoint"]["json"]+ assert body["query"] == {"_type": {"$eq": type_key}}+ assert body["_updated_at"] == {"start": DEFAULT_QUERY_WINDOW_START}++ # A checkpoint lands after each completed type; the final one marks both done.+ assert manager.saved[-1]["completed"] == ["alpha", "beta"]+ assert manager.saved[-1]["current"] is None+ assert manager.saved[-1]["child_state"] is None++ def test_watermark_seeds_query_window(self) -> None:+ manager = _FakeResumeManager()+ _pages, mock_resource = self._run(+ manager, db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)+ )+ body = mock_resource.call_args_list[0].args[0]["resources"][0]["endpoint"]["json"]+ assert body["_updated_at"] == {"start": "2026-01-02 03:04:05.000"}++ def test_resume_skips_completed_types_and_seeds_child_state(self) -> None:+ child_state = {"next_url": f"{BASE_URL}q?cursor=x", "window_start": "2025-06-01 00:00:00.000"}+ manager = _FakeResumeManager(+ state={+ "window_start": "2025-06-01 00:00:00.000",+ "completed": ["alpha"],+ "current": "beta",+ "child_state": child_state,+ }+ )+ pages, mock_resource = self._run(+ manager,+ # A newer watermark must NOT reshape the window mid-job: the saved window wins, so+ # types that had not started when the previous attempt died keep their history.+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),+ )++ assert pages == [[{"id": "beta-row"}]]+ mock_resource.assert_called_once()+ call = mock_resource.call_args+ body = call.args[0]["resources"][0]["endpoint"]["json"]+ assert body["query"] == {"_type": {"$eq": "beta"}}+ assert body["_updated_at"] == {"start": "2025-06-01 00:00:00.000"}+ assert call.kwargs["initial_paginator_state"] == child_state+++class TestZendeskSunshineFrameworkIntegration:+ """Drive the real rest_source framework against a mocked HTTP layer.++ Guards the declarative wiring the mocked tests can't: that the resolve placeholder+ binds into the path (including the query-string form), that fan-out children inherit+ parent fields, and that the incremental query POSTs the expected body.+ """++ def _source_response(self, endpoint: str, manager: _FakeResumeManager, **kwargs: Any) -> Any:+ return zendesk_sunshine_source(+ subdomain="nibbles",+ api_key="token",+ email_address="[email protected]",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ )++ def test_relationship_records_fanout_binds_type_into_query_string(self, requests_mock: Any) -> None:+ requests_mock.get(+ f"{BASE_URL}relationships/types",+ json={"data": [{"key": "order_rel"}], "links": {"next": None}},+ )+ requests_mock.get(+ f"{BASE_URL}relationships/records",+ json={"data": [{"id": "r1", "relationship_type": "order_rel"}], "links": {"next": None}},+ )++ response = self._source_response("relationship_records", _FakeResumeManager())+ rows = [row for page in _collect_pages(response) for row in page]++ assert rows == [{"id": "r1", "relationship_type": "order_rel"}]+ records_request = next(r for r in requests_mock.request_history if "relationships/records" in r.path)+ assert records_request.qs["type"] == ["order_rel"]+ assert records_request.qs["per_page"] == ["1000"]++ def test_policies_fanout_resolves_path_and_injects_parent_key(self, requests_mock: Any) -> None:+ requests_mock.get(+ f"{BASE_URL}objects/types",+ json={"data": [{"key": "product"}], "links": {"next": None}},+ )+ requests_mock.get(+ f"{BASE_URL}objects/types/product/permissions",+ json={"data": {"rbac": {"admin": {"read": True}}}},+ )++ response = self._source_response("object_type_policies", _FakeResumeManager())+ rows = [row for page in _collect_pages(response) for row in page]++ assert rows == [{"rbac": {"admin": {"read": True}}, "object_type": "product"}]++ def test_incremental_object_records_posts_windowed_query(self, requests_mock: Any) -> None:+ requests_mock.get(+ f"{BASE_URL}objects/types",+ json={"data": [{"key": "product"}], "links": {"next": None}},+ )+ requests_mock.post(+ f"{BASE_URL}objects/query",+ json={"data": [{"id": "1", "updated_at": "2026-01-05T00:00:00.000Z"}], "links": {"next": None}},+ )++ manager = _FakeResumeManager()+ response = self._source_response(+ "object_records",+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ )+ rows = [row for page in _collect_pages(response) for row in page]++ assert rows == [{"id": "1", "updated_at": "2026-01-05T00:00:00.000Z"}]+ query_request = next(r for r in requests_mock.request_history if r.method == "POST")+ assert query_request.json() == {+ "query": {"_type": {"$eq": "product"}},+ "sort_by": "_updated_at asc",+ "_updated_at": {"start": "2026-01-02 03:04:05.000"},+ }+ assert query_request.qs["per_page"] == ["1000"]+ # The completed type is checkpointed so a retry skips it.+ assert manager.saved[-1]["completed"] == ["product"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine_source.pynew file mode 100644index 000000000000..3e38ff1e1810--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine_source.py@@ -0,0 +1,167 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zendesksunshine import (+ ZendeskSunshineSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.source import (+ ZendeskSunshineSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.zendesk_sunshine import (+ ZendeskSunshineResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestZendeskSunshineSource:+ def setup_method(self) -> None:+ self.source = ZendeskSunshineSource()+ self.team_id = 123+ self.config = ZendeskSunshineSourceConfig(+ subdomain="nibbles", api_key="zendesk-token", email_address="[email protected]"+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ZENDESKSUNSHINE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "ZendeskSunshine"+ assert config.label == "Zendesk Sunshine"+ assert config.category == DataWarehouseSourceCategory.CRM+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/zendesk_sunshine.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/zendesk-sunshine"+ # A finished source ships visible; the scaffold's unreleasedSource flag must stay gone.+ assert not config.unreleasedSource++ def test_source_config_fields(self) -> None:+ config = self.source.get_source_config+ fields = {f.name: f for f in config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields) == {"subdomain", "api_key", "email_address"}+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD+ assert fields["api_key"].secret is True+ assert fields["subdomain"].secret is False+ assert fields["email_address"].type == SourceFieldInputConfigType.EMAIL+ assert all(f.required for f in fields.values())++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_incremental_semantics(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ # Only object records have a server-side timestamp filter (the `objects/query`+ # endpoint's `_updated_at` range); everything else is full refresh.+ assert schemas["object_records"].supports_incremental is True+ # The inclusive `_updated_at.start` window re-fetches boundary rows each sync, so only+ # merge (which dedupes on `id`) is offered — append would duplicate those rows.+ assert schemas["object_records"].supports_append is False+ assert [f["field"] for f in schemas["object_records"].incremental_fields] == ["updated_at"]++ for name in ("object_types", "object_type_policies", "relationship_types", "relationship_records", "limits"):+ assert schemas[name].supports_incremental is False, name+ assert schemas[name].incremental_fields == [], name++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["object_records"])+ assert [s.name for s in schemas] == ["object_records"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://nibbles.zendesk.com/api/sunshine/objects/types",+ "403 Client Error: Forbidden for url: https://nibbles.zendesk.com/api/sunshine/objects/records",+ "404 Client Error: Not Found for url: https://nibbles.zendesk.com/api/sunshine/objects/types",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ def test_non_retryable_errors_ignore_transient_failures(self) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ transient = "HTTP 500 for https://nibbles.zendesk.com/api/sunshine/objects/types"+ assert not any(key in transient for key in non_retryable)++ @pytest.mark.parametrize("bad_subdomain", ["bad domain", "sub.domain!", ""])+ def test_validate_credentials_rejects_invalid_subdomain_without_http(self, bad_subdomain: str) -> None:+ config = ZendeskSunshineSourceConfig(+ subdomain=bad_subdomain, api_key="zendesk-token", email_address="[email protected]"+ )+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.source.validate_zendesk_sunshine_credentials"+ ) as mock_validate:+ is_valid, message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert message == "Zendesk subdomain is incorrect"+ mock_validate.assert_not_called()++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.source.validate_zendesk_sunshine_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)++ result = self.source.validate_credentials(self.config, self.team_id)++ assert result == (True, None)+ mock_validate.assert_called_once_with("nibbles", "zendesk-token", "[email protected]")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is ZendeskSunshineResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.source.zendesk_sunshine_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "object_records"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["subdomain"] == "nibbles"+ assert kwargs["api_key"] == "zendesk-token"+ assert kwargs["email_address"] == "[email protected]"+ assert kwargs["endpoint"] == "object_records"+ 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:00Z"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.source.zendesk_sunshine_source"+ )+ def test_source_for_pipeline_omits_watermark_when_not_incremental(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "object_records"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/zendesk_sunshine.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/zendesk_sunshine.pynew file mode 100644index 000000000000..e697a284f348--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/zendesk_sunshine.py@@ -0,0 +1,477 @@+import re+import dataclasses+from collections.abc import Callable, Iterable, Iterator+from typing import Any, Optional+from urllib.parse import urlencode, urljoin++from dateutil import parser as dateutil_parser+from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+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,+ rest_api_resources,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ rename_parent_fields,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponsePaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.settings import (+ DEFAULT_PAGE_SIZE,+ DEFAULT_QUERY_WINDOW_START,+ MAX_PAGES_PER_QUERY_WINDOW,+ QUERY_PATH,+ RECORDS_PAGE_SIZE,+ ZENDESK_SUNSHINE_ENDPOINTS,+ ZendeskSunshineEndpointConfig,+)+++class ZendeskSunshineResumeConfig:+ """Generic resume envelope.++ `state` holds whichever checkpoint shape the endpoint produces: a paginator snapshot for+ top-level endpoints, the framework's `{completed, current, child_state}` fan-out shape for+ dependent endpoints, or the incremental object records loop's shape (which adds+ `window_start`). Each schema syncs as its own job, so the shapes never share a Redis key.+ """++ state: dict[str, Any]+++def normalize_subdomain(subdomain: str) -> str:+ """Reduce whatever the user entered to the bare Zendesk subdomain label.++ Users frequently paste the full host ("nibbles.zendesk.com") or a URL+ ("https://nibbles.zendesk.com/") into the subdomain field; without normalizing, the+ base URL would carry a doubled host.+ """+ subdomain = subdomain.strip()+ if "://" in subdomain:+ subdomain = subdomain.split("://", 1)[1]+ subdomain = subdomain.split("/", 1)[0]+ return re.sub(r"\.zendesk\.com$", "", subdomain, flags=re.IGNORECASE)+++def get_base_url(subdomain: str) -> str:+ return f"https://{normalize_subdomain(subdomain)}.zendesk.com/api/sunshine/"+++def to_query_datetime(value: Any) -> str | None:+ """Format a watermark or record timestamp as the `yyyy-MM-dd HH:mm:ss.SSS` (UTC) string+ the query endpoint's `_updated_at` range filter expects."""+ if value is None:+ return None+ if isinstance(value, str):+ try:+ value = dateutil_parser.parse(value)+ except (ValueError, OverflowError):+ return None+ normalized = coerce_datetime_to_utc(value)+ if normalized is None:+ return None+ return normalized.strftime("%Y-%m-%d %H:%M:%S.") + f"{normalized.microsecond // 1000:03d}"+++class SunshineLinksPaginator(JSONResponsePaginator):+ """Follows the `links.next` URL Sunshine list endpoints return, absolutized against the+ account's base URL (the docs don't guarantee whether the link is absolute or relative)."""++ def __init__(self, base_url: str) -> None:+ super().__init__(next_url_path="links.next")+ self._base_url = base_url++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if self._has_next_page and self._next_url:+ self._next_url = urljoin(self._base_url, self._next_url)+++class SunshineObjectQueryPaginator(SunshineLinksPaginator):+ """Cursor pagination for the POST `objects/query` search endpoint.++ Follows `links.next` like the other Sunshine endpoints, but this endpoint's cursor grows+ with every page and Zendesk rejects it past ~80 pages. Results are requested sorted+ `_updated_at asc`, so before hitting the cap we re-window: restart the query with+ `_updated_at.start` set to the newest `updated_at` seen so far. Boundary rows are+ re-fetched (the range start is inclusive) and deduped by the merge on `id`.+ """++ def __init__(+ self,+ base_url: str,+ window_start: str,+ page_size: int = RECORDS_PAGE_SIZE,+ max_pages_per_window: int = MAX_PAGES_PER_QUERY_WINDOW,+ ) -> None:+ super().__init__(base_url)+ self._query_url = urljoin(base_url, QUERY_PATH)+ self._page_size = page_size+ self._window_start = window_start+ self._max_pages_per_window = max_pages_per_window+ self._pages_in_window = 0+ self._last_updated_at: Optional[str] = None++ def init_request(self, request: Request) -> None:+ super().init_request(request)+ self._apply_window(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ for row in data or []:+ # Rows arrive sorted `_updated_at asc`, so the last timestamped row is the max.+ if isinstance(row, dict) and row.get("updated_at"):+ self._last_updated_at = row["updated_at"]+ self._pages_in_window += 1+ if self._has_next_page and self._pages_in_window >= self._max_pages_per_window:+ next_start = to_query_datetime(self._last_updated_at)+ if next_start is None:+ raise ValueError(+ "Zendesk Sunshine query pagination reached the per-window page limit but no row "+ "carried a usable `updated_at` to re-window from"+ )+ if next_start == self._window_start:+ raise ValueError(+ f"Zendesk Sunshine query window cannot advance: every row shares updated_at {next_start}"+ )+ self._window_start = next_start+ self._next_url = f"{self._query_url}?{urlencode({'per_page': self._page_size})}"+ self._pages_in_window = 0++ def update_request(self, request: Request) -> None:+ super().update_request(request)+ self._apply_window(request)++ def _apply_window(self, request: Request) -> None:+ if request.json is None:+ request.json = {}+ request.json["_updated_at"] = {"start": self._window_start}++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ state = super().get_resume_state()+ if state is None:+ return None+ return {**state, "window_start": self._window_start, "pages_in_window": self._pages_in_window}++ def set_resume_state(self, state: dict[str, Any]) -> None:+ super().set_resume_state(state)+ window_start = state.get("window_start")+ if window_start:+ self._window_start = window_start+ self._pages_in_window = int(state.get("pages_in_window") or 0)+++def _client_config(subdomain: str, api_key: str, email_address: str) -> ClientConfig:+ return {+ "base_url": get_base_url(subdomain),+ "auth": {+ "type": "http_basic",+ # Zendesk API token auth requires the `{email}/token` username form.+ "username": f"{email_address}/token",+ "password": api_key,+ },+ "headers": {"Accept": "application/json"},+ # Pin pagination `links.next` URLs to the account's own host.+ "allowed_hosts": [],+ }+++def _top_level_resource(endpoint_config: ZendeskSunshineEndpointConfig, base_url: str) -> EndpointResource:+ return {+ "name": endpoint_config.name,+ "table_name": endpoint_config.name,+ "write_disposition": "replace",+ "endpoint": {+ "path": endpoint_config.path,+ "params": {"per_page": endpoint_config.page_size},+ "paginator": SunshineLinksPaginator(base_url),+ "data_selector": "data",+ },+ "table_format": "delta",+ }+++def _fanout_resources(+ endpoint_config: ZendeskSunshineEndpointConfig,+ parent_config: ZendeskSunshineEndpointConfig,+ base_url: str,+) -> list[str | EndpointResource]:+ if endpoint_config.resolve_placeholder is None or endpoint_config.resolve_field is None:+ raise ValueError(f"Endpoint {endpoint_config.name} is not configured for fan-out")++ child_params: dict[str, Any] = {+ endpoint_config.resolve_placeholder: {+ "type": "resolve",+ "resource": parent_config.name,+ "field": endpoint_config.resolve_field,+ },+ }+ child_endpoint: Endpoint = {+ "path": endpoint_config.path,+ "params": child_params,+ "data_selector": "data",+ }+ if endpoint_config.single_page:+ child_endpoint["paginator"] = SinglePagePaginator()+ else:+ child_params["per_page"] = endpoint_config.page_size+ child_endpoint["paginator"] = SunshineLinksPaginator(base_url)++ child_resource: EndpointResource = {+ "name": endpoint_config.name,+ "table_name": endpoint_config.name,+ "write_disposition": "replace",+ "include_from_parent": endpoint_config.include_from_parent,+ "endpoint": child_endpoint,+ "table_format": "delta",+ }+ return [_top_level_resource(parent_config, base_url), child_resource]+++def _query_resource(object_type_key: str, window_start: str, base_url: str) -> EndpointResource:+ return {+ "name": "object_records",+ "table_name": "object_records",+ "write_disposition": {"disposition": "merge", "strategy": "upsert"},+ "endpoint": {+ "method": "POST",+ "path": QUERY_PATH,+ "params": {"per_page": RECORDS_PAGE_SIZE},+ "json": {+ "query": {"_type": {"$eq": object_type_key}},+ "sort_by": "_updated_at asc",+ "_updated_at": {"start": window_start},+ },+ "paginator": SunshineObjectQueryPaginator(base_url, window_start),+ "data_selector": "data",+ },+ "table_format": "delta",+ }+++def _load_resume_state(+ resumable_source_manager: ResumableSourceManager[ZendeskSunshineResumeConfig],+) -> Optional[dict[str, Any]]:+ if not resumable_source_manager.can_resume():+ return None+ loaded = resumable_source_manager.load_state()+ return loaded.state if loaded is not None else None+++def _make_resume_hook(+ resumable_source_manager: ResumableSourceManager[ZendeskSunshineResumeConfig],+) -> Callable[[Optional[dict[str, Any]]], None]:+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's something to resume to; the Redis TTL handles cleanup.+ if state:+ resumable_source_manager.save_state(ZendeskSunshineResumeConfig(state=state))++ return save_checkpoint+++def list_object_type_keys(subdomain: str, api_key: str, email_address: str) -> list[str]:+ """Fetch every legacy object type key, following `links.next` pagination."""+ base_url = get_base_url(subdomain)+ session = make_tracked_session(redact_values=(api_key,), headers={"Accept": "application/json"})+ session.auth = (f"{email_address}/token", api_key)++ keys: list[str] = []+ url: Optional[str] = urljoin(base_url, "objects/types")+ params: Optional[dict[str, Any]] = {"per_page": DEFAULT_PAGE_SIZE}+ while url:+ response = session.get(url, params=params, timeout=60)+ response.raise_for_status()+ body = response.json() or {}+ keys.extend(item["key"] for item in body.get("data") or [] if isinstance(item, dict) and item.get("key"))+ next_url = (body.get("links") or {}).get("next")+ url = urljoin(base_url, next_url) if next_url else None+ params = None # the next link already carries the query params+ return keys+++def _object_records_incremental(+ subdomain: str,+ api_key: str,+ email_address: str,+ team_id: int,+ job_id: str,+ db_incremental_field_last_value: Optional[Any],+ resumable_source_manager: ResumableSourceManager[ZendeskSunshineResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Incremental object records: one `objects/query` walk per object type.++ The framework's declarative fan-out can't drive a POST body, so this mirrors its resume+ shape by hand: completed types are skipped, and the in-progress type resumes from its+ saved paginator snapshot.+ """+ base_url = get_base_url(subdomain)+ client_config = _client_config(subdomain, api_key, email_address)++ resume_state = _load_resume_state(resumable_source_manager) or {}+ # Pin the query window across retries: the pipeline advances the incremental watermark+ # per batch, so recomputing the window mid-job would skip history for types that hadn't+ # started syncing when the previous attempt died.+ window_start = (+ resume_state.get("window_start")+ or to_query_datetime(db_incremental_field_last_value)+ or DEFAULT_QUERY_WINDOW_START+ )+ completed: set[str] = set(resume_state.get("completed") or [])+ current_key = resume_state.get("current")+ current_child_state = resume_state.get("child_state")++ def save_checkpoint(current: Optional[str], child_state: Optional[dict[str, Any]]) -> None:+ resumable_source_manager.save_state(+ ZendeskSunshineResumeConfig(+ state={+ "window_start": window_start,+ "completed": sorted(completed),+ "current": current,+ "child_state": child_state,+ }+ )+ )++ for type_key in list_object_type_keys(subdomain, api_key, email_address):+ if type_key in completed:+ continue+ initial_paginator_state = current_child_state if type_key == current_key else None++ def child_resume_hook(paginator_state: Optional[dict[str, Any]], _key: str = type_key) -> None:+ save_checkpoint(_key, paginator_state)++ config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {},+ "resources": [_query_resource(type_key, window_start, base_url)],+ }+ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=child_resume_hook,+ initial_paginator_state=initial_paginator_state,+ )+ yield from resource++ completed.add(type_key)+ save_checkpoint(None, None)+++def zendesk_sunshine_source(+ subdomain: str,+ api_key: str,+ email_address: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[ZendeskSunshineResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = ZENDESK_SUNSHINE_ENDPOINTS[endpoint]+ base_url = get_base_url(subdomain)+ items: Callable[[], Iterable[Any]]++ if endpoint_config.name == "object_records" and should_use_incremental_field:++ def incremental_items() -> Iterator[list[dict[str, Any]]]:+ return _object_records_incremental(+ subdomain,+ api_key,+ email_address,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resumable_source_manager,+ )++ items = incremental_items+ elif endpoint_config.fanout_parent is not None:+ parent_config = ZENDESK_SUNSHINE_ENDPOINTS[endpoint_config.fanout_parent]+ config: RESTAPIConfig = {+ "client": _client_config(subdomain, api_key, email_address),+ "resource_defaults": {},+ "resources": _fanout_resources(endpoint_config, parent_config, base_url),+ }+ resources = rest_api_resources(+ config,+ team_id,+ job_id,+ None,+ resume_hook=_make_resume_hook(resumable_source_manager),+ initial_paginator_state=_load_resume_state(resumable_source_manager),+ )+ child = next(r for r in resources if r.name == endpoint_config.name)+ dependent_resource = child.add_map(+ rename_parent_fields(parent_config.name, endpoint_config.parent_field_renames)+ )+ items = lambda: dependent_resource # noqa: E731+ else:+ top_level_config: RESTAPIConfig = {+ "client": _client_config(subdomain, api_key, email_address),+ "resource_defaults": {},+ "resources": [_top_level_resource(endpoint_config, base_url)],+ }+ resource = rest_api_resource(+ top_level_config,+ team_id,+ job_id,+ None,+ resume_hook=_make_resume_hook(resumable_source_manager),+ initial_paginator_state=_load_resume_state(resumable_source_manager),+ )+ items = lambda: resource # noqa: E731++ response = SourceResponse(+ name=endpoint_config.name,+ items=items,+ primary_keys=list(endpoint_config.primary_keys),+ sort_mode="asc",+ )+ if endpoint_config.partition_key:+ response.partition_count = 1+ response.partition_size = 1+ response.partition_mode = "datetime"+ response.partition_format = "week"+ response.partition_keys = [endpoint_config.partition_key]+ return response+++def validate_credentials(subdomain: str, api_key: str, email_address: str) -> tuple[bool, str | None]:+ session = make_tracked_session(redact_values=(api_key,), headers={"Accept": "application/json"})+ response = session.get(+ urljoin(get_base_url(subdomain), "objects/types"),+ params={"per_page": 1},+ auth=(f"{email_address}/token", api_key),+ timeout=30,+ )+ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, (+ "Zendesk rejected the credentials. Check the subdomain, email address, and API token are correct, "+ "and that token access is enabled for your account."+ )+ if response.status_code in (403, 404):+ return False, (+ "The Zendesk Sunshine (legacy custom objects) API is not available for this account. "+ "Check that legacy custom objects are activated in Admin Center and that your plan supports them."+ )+ return False, f"Zendesk Sunshine returned an unexpected response (HTTP {response.status_code})"