: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 zenloop import source (#68560)
Tom Owerscf692836f4ca
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 93290629cee5..fa4067b91421 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -346,6 +346,7 @@ the row lists both.| wufoo | HTTP | requests | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ || zendesk_sell | HTTP | requests | ✅ |+| zenloop | HTTP | requests | ✅ || zonka_feedback | HTTP | requests | ✅ || zoom | HTTP | requests | ✅ || zuora | HTTP | requests | ✅ |diff --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 bdee3df512b9..cea3e99e887c 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@@ -3637,7 +3637,7 @@ class ZenefitsSourceConfig(config.Config):@config.configclass ZenloopSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/canonical_descriptions.pynew file mode 100644index 000000000000..28302b336688--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/canonical_descriptions.py@@ -0,0 +1,43 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Zenloop public API docs (https://docs.zenloop.com/reference).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "surveys": {+ "description": "A Zenloop survey (measurement) — an NPS or feedback questionnaire that collects answers from recipients.",+ "docs_url": "https://docs.zenloop.com/reference/get-surveys",+ "columns": {+ "id": "The unique numeric ID of the survey.",+ "public_hash_id": "The stable public hash identifier of the survey, used to scope answer queries.",+ "title": "The human-readable title of the survey.",+ "status": "The current status of the survey (e.g. draft, live, paused).",+ "type": "The survey type (e.g. the metric or question format it measures).",+ "inserted_at": "The timestamp when the survey was created.",+ "updated_at": "The timestamp when the survey was last updated.",+ },+ },+ "survey_groups": {+ "description": "A Zenloop survey group — a bundle of surveys aggregated together for combined reporting.",+ "docs_url": "https://docs.zenloop.com/reference/get-survey-groups",+ "columns": {+ "id": "The unique numeric ID of the survey group.",+ "public_hash_id": "The stable public hash identifier of the survey group.",+ "title": "The human-readable title of the survey group.",+ "status": "The current status of the survey group.",+ "inserted_at": "The timestamp when the survey group was created.",+ "updated_at": "The timestamp when the survey group was last updated.",+ },+ },+ "properties": {+ "description": "A Zenloop property — a custom metadata field attached to survey answers for segmentation and filtering.",+ "docs_url": "https://docs.zenloop.com/reference/get-properties",+ "columns": {+ "id": "The unique numeric ID of the property.",+ "name": "The name of the property.",+ "inserted_at": "The timestamp when the property was created.",+ "updated_at": "The timestamp when the property was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/settings.pynew file mode 100644index 000000000000..7b8ccab6c826--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/settings.py@@ -0,0 +1,30 @@+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class ZenloopEndpointConfig:+ name: str+ path: str+ # The list of rows lives under a named key in the response envelope+ # (e.g. {"surveys": [...], "meta": {...}}), and the key differs per endpoint.+ response_key: str+ # Zenloop object IDs are unique within an account, so `id` is a safe primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # A stable (never-rewritten) datetime field to partition by. Only set where the object+ # actually exposes a creation timestamp.+ partition_key: Optional[str] = None+++# Zenloop public API top-level list endpoints. All are full-refresh only: while Zenloop exposes+# date_from/date_to filters on some answer streams, the survey and property catalogs here have no+# reliable incremental cursor to advance, so a full refresh is the honest sync method.+ZENLOOP_ENDPOINTS: dict[str, ZenloopEndpointConfig] = {+ "surveys": ZenloopEndpointConfig(name="surveys", path="/surveys", response_key="surveys"),+ "survey_groups": ZenloopEndpointConfig(name="survey_groups", path="/survey_groups", response_key="survey_groups"),+ "properties": ZenloopEndpointConfig(name="properties", path="/properties", response_key="properties"),+}++ENDPOINTS = tuple(ZENLOOP_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/source.pyindex e4eaf457553c..94d6ed2103b1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/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 ZenloopSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.settings import (+ ENDPOINTS,+ ZENLOOP_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.zenloop import (+ ZenloopResumeConfig,+ check_access,+ zenloop_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ZenloopSource(SimpleSource[ZenloopSourceConfig]):+class ZenloopSource(ResumableSource[ZenloopSourceConfig, ZenloopResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ZENLOOP@@ -24,7 +47,95 @@ class ZenloopSource(SimpleSource[ZenloopSourceConfig]):name=SchemaExternalDataSourceType.ZENLOOP,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Zenloop",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Zenloop API token to pull your Zenloop data into the PostHog Data warehouse.++You can generate an API token under **Settings → API** in the [Zenloop app](https://app.zenloop.com/settings/api). The token inherits the generating user's account permissions and grants read access to surveys, survey groups, and properties.+""",iconPath="/static/services/zenloop.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/zenloop",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked API token surfaces as a requests HTTPError when `_fetch_page`+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop+ # the sync. Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.zenloop.com": "Your Zenloop API token is invalid or has been revoked. Generate a new token under Settings → API, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.zenloop.com": "Your Zenloop API token does not have access to this data. Check the token's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: ZenloopSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — the survey and property catalogs expose no reliable+ # server-side timestamp cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: ZenloopSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API token is account-wide, so a single probe validates access to every schema; there+ # is no per-endpoint scope to check.+ status, message = check_access(config.api_token)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Zenloop API token"+ return False, message or "Could not validate Zenloop API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZenloopResumeConfig]:+ return ResumableSourceManager[ZenloopResumeConfig](inputs, ZenloopResumeConfig)++ def source_for_pipeline(+ self,+ config: ZenloopSourceConfig,+ resumable_source_manager: ResumableSourceManager[ZenloopResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in ZENLOOP_ENDPOINTS:+ raise ValueError(f"Unknown Zenloop schema '{inputs.schema_name}'")++ return zenloop_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/tests/test_zenloop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/tests/test_zenloop.pynew file mode 100644index 000000000000..6ea570556ee2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/tests/test_zenloop.py@@ -0,0 +1,210 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.zenloop import zenloop+from products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.settings import (+ ENDPOINTS,+ ZENLOOP_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.zenloop import (+ ZenloopResumeConfig,+ ZenloopRetryableError,+ check_access,+ get_rows,+ zenloop_source,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = zenloop._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: ZenloopResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ZenloopResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ZenloopResumeConfig | None:+ return self._state++ def save_state(self, data: ZenloopResumeConfig) -> None:+ self.saved.append(data)+++def _page(items: list[dict], response_key: str = "surveys") -> dict[str, Any]:+ # The row list lives under a named key alongside a `meta` block in the real envelope.+ return {response_key: items, "meta": {"per_page": zenloop.PER_PAGE}}+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, dict], endpoint: str = "surveys"+ ) -> list[dict]:+ # Shrink the page size so a page of 2 rows counts as "full" and a shorter page terminates.+ monkeypatch.setattr(zenloop, "PER_PAGE", 2)++ def fake_fetch(session: Any, path: str, page: int, per_page: int, logger: Any) -> dict:+ return pages[page]++ monkeypatch.setattr(zenloop, "_fetch_page", fake_fetch)+ monkeypatch.setattr(zenloop, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_token="zenloop-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_short_page_yields_items_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([{"id": 1}])})+ assert rows == [{"id": 1}]+ # Page shorter than PER_PAGE, so no resume state is persisted.+ assert manager.saved == []++ def test_follows_pagination_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: _page([{"id": 1}, {"id": 2}]),+ 2: _page([{"id": 3}, {"id": 4}]),+ 3: _page([{"id": 5}]),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}]++ def test_saves_next_page_after_yielding_each_full_batch(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: _page([{"id": 1}, {"id": 2}]),+ 2: _page([{"id": 3}]),+ }+ self._collect(manager, monkeypatch, pages)+ # State is saved AFTER the full page 1 is yielded (pointing at page 2), never for the final short page.+ assert [s.next_page for s in manager.saved] == [2]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(ZenloopResumeConfig(next_page=2))+ pages = {+ # Page 1 must never be fetched on resume.+ 2: _page([{"id": 3}, {"id": 4}]),+ 3: _page([{"id": 5}]),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 3}, {"id": 4}, {"id": 5}]++ def test_empty_page_does_not_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([])})+ assert rows == []++ def test_selects_rows_under_endpoint_named_key(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {1: _page([{"id": 9}], response_key="properties")}+ rows = self._collect(manager, monkeypatch, pages, endpoint="properties")+ assert rows == [{"id": 9}]+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: dict | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body or {}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(ZenloopRetryableError):+ _fetch_page_unwrapped(session, "/surveys", 1, 50, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/surveys", 1, 50, MagicMock())++ def test_success_returns_json_body(self) -> None:+ body = _page([{"id": 1}])+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "/surveys", 1, 50, MagicMock())+ assert result == body++ def test_request_uses_page_and_per_page_params(self) -> None:+ session = self._session_returning(200, _page([]))+ _fetch_page_unwrapped(session, "/properties", 3, 50, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"page": 3, "per_page": 50}+++class TestCheckAccess:+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ monkeypatch.setattr(zenloop, "make_tracked_session", lambda **kwargs: session)+ return session++ @pytest.mark.parametrize(+ "status, ok, expected_status, expected_message",+ [+ (200, True, 200, None),+ (401, False, 401, None),+ (403, False, 403, None),+ (500, False, 500, "Zenloop returned HTTP 500"),+ ],+ )+ def test_status_mapping(+ self, status: int, ok: bool, expected_status: int, expected_message: str | None, monkeypatch: Any+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ self._patch_session(monkeypatch, response)+ assert check_access("zenloop-token") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))+ status, message = check_access("zenloop-token")+ assert status == 0+ assert message is not None and "boom" in message+++class TestZenloopSourceResponse:+ @parameterized.expand([("surveys",), ("survey_groups",), ("properties",)])+ def test_response_shape_matches_endpoint_config(self, endpoint: str) -> None:+ response = zenloop_source(+ api_token="zenloop-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # No endpoint exposes a creation-timestamp partition key, so partitioning stays off.+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in ZENLOOP_ENDPOINTS.values())+ assert set(ZENLOOP_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/tests/test_zenloop_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/tests/test_zenloop_source.pynew file mode 100644index 000000000000..7cad54fd019e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/tests/test_zenloop_source.py@@ -0,0 +1,153 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ZenloopSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.source import ZenloopSource+from products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.zenloop import ZenloopResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestZenloopSource:+ def setup_method(self) -> None:+ self.source = ZenloopSource()+ self.team_id = 123+ self.config = ZenloopSourceConfig(api_token="zenloop-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ZENLOOP++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Zenloop"+ assert config.label == "Zenloop"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/zenloop"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_token"]++ def test_api_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret token itself; the base URL is hardcoded and the account is+ # implicit in the token. There is no non-secret field that retargets where the token is sent.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["properties"])+ assert len(schemas) == 1+ assert schemas[0].name == "properties"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ # Exercises the credential-free catalog path used by the posthog.com docs.+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.zenloop.com/v1/surveys?page=1&per_page=50",+ "403 Client Error: Forbidden for url: https://api.zenloop.com/v1/properties?page=2&per_page=50",+ ],+ )+ 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)++ @pytest.mark.parametrize(+ "unrelated_error",+ [+ "500 Server Error: Internal Server Error for url: https://api.zenloop.com/v1/surveys",+ "HTTPSConnectionPool(host='api.zenloop.com', port=443): Read timed out.",+ "429 Client Error: Too Many Requests for url: https://api.zenloop.com/v1/survey_groups",+ ],+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @pytest.mark.parametrize(+ "status, expected_valid, expected_message",+ [+ (200, True, None),+ (401, False, "Invalid Zenloop API token"),+ (403, False, "Invalid Zenloop API token"),+ (500, False, "Zenloop returned HTTP 500"),+ (0, False, "Could not connect to Zenloop: boom"),+ ],+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.source.check_access")+ def test_validate_credentials(+ self,+ mock_check: mock.MagicMock,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ message = (+ "Zenloop returned HTTP 500"+ if status == 500+ else ("Could not connect to Zenloop: boom" if status == 0 else None)+ )+ mock_check.return_value = (status, message)+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)+ assert is_valid is expected_valid+ assert returned == expected_message++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.source.check_access")+ def test_validate_credentials_probes_the_account_token(self, mock_check: mock.MagicMock) -> None:+ # The API token is account-wide, so validation probes the token, not a per-schema scope.+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id, schema_name="properties")+ mock_check.assert_called_once_with("zenloop-token")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ZenloopResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.zenloop.source.zenloop_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_zenloop_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "surveys"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_zenloop_source.assert_called_once()+ kwargs = mock_zenloop_source.call_args.kwargs+ assert kwargs["api_token"] == "zenloop-token"+ assert kwargs["endpoint"] == "surveys"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Zenloop schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/zenloop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/zenloop.pynew file mode 100644index 000000000000..9b338402e633--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zenloop/zenloop.py@@ -0,0 +1,145 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++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.zenloop.settings import ZENLOOP_ENDPOINTS++ZENLOOP_BASE_URL = "https://api.zenloop.com/v1"+# Zenloop's list endpoints default to 50 rows per page; keep that size and paginate.+PER_PAGE = 50+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API token is genuine. The token inherits its user's account+# permissions, so one probe validates access to the list endpoints exposed here.+DEFAULT_PROBE_PATH = "/surveys"+++class ZenloopRetryableError(Exception):+ pass+++class ZenloopResumeConfig:+ # Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.+ next_page: int = 1+++def _headers(api_token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((ZenloopRetryableError, 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,+ path: str,+ page: int,+ per_page: int,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(+ f"{ZENLOOP_BASE_URL}{path}",+ params={"page": page, "per_page": per_page},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise ZenloopRetryableError(f"Zenloop API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Zenloop API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZenloopResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = ZENLOOP_ENDPOINTS[endpoint]+ # `redact_values` masks the token in logged URLs and captured samples.+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else 1+ if resume:+ logger.debug(f"Zenloop: resuming {endpoint} from page {page}")++ while True:+ data = _fetch_page(session, config.path, page, PER_PAGE, logger)++ # The row list is always present under its named key in the envelope; missing it means a+ # malformed response, so fail loudly rather than silently advancing past lost rows.+ items = data[config.response_key]+ if items:+ yield items++ # Zenloop exposes no reliable "has more" flag, so a short page marks the end: a page with+ # fewer than PER_PAGE rows cannot be followed by another full page.+ if len(items) < PER_PAGE:+ break++ page += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(ZenloopResumeConfig(next_page=page))+++def zenloop_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ZenloopResumeConfig],+) -> SourceResponse:+ config = ZENLOOP_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def check_access(api_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single list endpoint to validate the API token.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))+ try:+ response = session.get(f"{ZENLOOP_BASE_URL}{path}", params={"page": 1, "per_page": 5}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Zenloop: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Zenloop returned HTTP {response.status_code}"++ return 200, None