Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement zuora import source (#63017)

Tom Owers63d1397340a9
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 3ef59c0368bd..e693871e7652 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -184,6 +184,7 @@ the row lists both.
| wrike | HTTP | requests | ✅ |
| zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| zoom | HTTP | requests | ✅ |
+| zuora | HTTP | requests | ✅ |
### Notes on partially-tracked sources
@@ -310,7 +311,6 @@ doesn't conflict with concurrent PRs.
- youtube_analytics
- zoho_crm
- zoominfo
-- zuora
---
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 88720d0fea30..c385a70abe9f 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -1442,7 +1442,17 @@ class ZoomSourceConfig(config.Config):
@config.config
class ZuoraSourceConfig(config.Config):
- pass
+ client_id: str
+ client_secret: str
+ environment: Literal[
+ "us_production",
+ "us_api_sandbox",
+ "us_cloud_production",
+ "us_cloud_sandbox",
+ "eu_production",
+ "eu_sandbox",
+ "central_sandbox",
+ ] = config.value(default="us_production")
def get_config_for_source(source: ExternalDataSourceType):
diff --git a/posthog/temporal/data_imports/sources/zuora/settings.py b/posthog/temporal/data_imports/sources/zuora/settings.py
new file mode 100644
index 000000000000..baad0c8d47dd
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/zuora/settings.py
@@ -0,0 +1,45 @@
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+# Region/environment-specific REST hosts — credentials only work against
+# their tenant's environment.
+ZUORA_ENVIRONMENT_HOSTS: dict[str, str] = {
+ "us_production": "https://rest.zuora.com",
+ "us_api_sandbox": "https://rest.apisandbox.zuora.com",
+ "us_cloud_production": "https://rest.na.zuora.com",
+ "us_cloud_sandbox": "https://rest.sandbox.na.zuora.com",
+ "eu_production": "https://rest.eu.zuora.com",
+ "eu_sandbox": "https://rest.sandbox.eu.zuora.com",
+ "central_sandbox": "https://rest.test.zuora.com",
+}
+
+# Object Query pages cap at 99 records.
+PAGE_SIZE = 99
+
+# Every Object Query object filters server-side on updateddate (lowercase in
+# filters, camelCase in rows) — all streams are honestly incremental.
+_UPDATED_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "updatedDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updatedDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+# Stream name -> Object Query path segment under /object-query/.
+ZUORA_ENDPOINTS: dict[str, str] = {
+ "accounts": "accounts",
+ "subscriptions": "subscriptions",
+ "invoices": "invoices",
+ "payments": "payments",
+ "credit_memos": "credit-memos",
+ "refunds": "refunds",
+ "products": "products",
+ "orders": "orders",
+}
+
+ENDPOINTS = tuple(ZUORA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: list(_UPDATED_DATE_INCREMENTAL_FIELDS) for name in ZUORA_ENDPOINTS
+}
diff --git a/posthog/temporal/data_imports/sources/zuora/source.py b/posthog/temporal/data_imports/sources/zuora/source.py
index 6f7668a04d8e..6ecb71b05da8 100644
--- a/posthog/temporal/data_imports/sources/zuora/source.py
+++ b/posthog/temporal/data_imports/sources/zuora/source.py
@@ -1,29 +1,143 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import ZuoraSourceConfig
+from posthog.temporal.data_imports.sources.zuora.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.zuora.zuora import (
+ ZuoraResumeConfig,
+ validate_credentials as validate_zuora_credentials,
+ zuora_source,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ZuoraSource(SimpleSource[ZuoraSourceConfig]):
+class ZuoraSource(ResumableSource[ZuoraSourceConfig, ZuoraResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ZUORA
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "400 Client Error: Bad Request for url: https://rest.": "Zuora rejected the request. If this occurs while connecting, check your client ID and client secret (and that they match the selected environment).",
+ "401 Client Error: Unauthorized for url: https://rest.": "Zuora authentication failed. Please check your client ID and client secret (and that they match the selected environment).",
+ "403 Client Error: Forbidden for url: https://rest.": "Zuora denied access. Please check that the OAuth client's user has permission for this object.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ZUORA,
label="Zuora",
+ caption="""Connect your Zuora tenant to pull your subscription billing data into the PostHog Data warehouse.
+
+A Zuora admin can create an OAuth client under Settings > Administration > Manage Users (the client inherits the user's permissions). Pick the environment that matches your tenant — credentials only work against their own environment.""",
iconPath="/static/services/zuora.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/zuora",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="us_production",
+ options=[
+ SourceFieldSelectConfigOption(label="US Production", value="us_production"),
+ SourceFieldSelectConfigOption(label="US API Sandbox", value="us_api_sandbox"),
+ SourceFieldSelectConfigOption(label="US Cloud Production", value="us_cloud_production"),
+ SourceFieldSelectConfigOption(label="US Cloud Sandbox", value="us_cloud_sandbox"),
+ SourceFieldSelectConfigOption(label="EU Production", value="eu_production"),
+ SourceFieldSelectConfigOption(label="EU Sandbox", value="eu_sandbox"),
+ SourceFieldSelectConfigOption(label="Central Sandbox", value="central_sandbox"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_secret",
+ label="Client secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: ZuoraSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: ZuoraSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_zuora_credentials(config.environment, config.client_id, config.client_secret):
+ return True, None
+
+ return False, "Invalid Zuora credentials. Check the client ID, client secret, and environment."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZuoraResumeConfig]:
+ return ResumableSourceManager[ZuoraResumeConfig](inputs, ZuoraResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ZuoraSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ZuoraResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return zuora_source(
+ environment=config.environment,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/posthog/temporal/data_imports/sources/zuora/tests/test_zuora.py b/posthog/temporal/data_imports/sources/zuora/tests/test_zuora.py
new file mode 100644
index 000000000000..44fddcbf6a73
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/zuora/tests/test_zuora.py
@@ -0,0 +1,176 @@
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+
+from posthog.temporal.data_imports.sources.zuora.settings import ENDPOINTS, ZUORA_ENDPOINTS, ZUORA_ENVIRONMENT_HOSTS
+from posthog.temporal.data_imports.sources.zuora.zuora import (
+ ZuoraResumeConfig,
+ _base_url,
+ get_rows,
+ validate_credentials,
+ zuora_source,
+)
+
+_MODULE = "posthog.temporal.data_imports.sources.zuora.zuora"
+
+
+def _make_manager(resume_state: ZuoraResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(body: Any, status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = body
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ return resp
+
+
+def _token_response() -> mock.MagicMock:
+ return _response({"access_token": "tok-1", "token_type": "bearer", "expires_in": 3599})
+
+
+class TestBaseUrl:
+ @pytest.mark.parametrize("environment, expected", list(ZUORA_ENVIRONMENT_HOSTS.items()))
+ def test_environment_hosts(self, environment, expected):
+ assert _base_url(environment) == expected
+
+ def test_invalid_environment_raises(self):
+ with pytest.raises(ValueError):
+ _base_url("nope")
+
+
+class TestValidateCredentials:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_valid_credentials_mint_a_token(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+
+ assert validate_credentials("us_production", "cid", "sec") is True
+ call = mock_session.return_value.post.call_args
+ assert call.args[0] == "https://rest.zuora.com/oauth/token"
+ assert call.kwargs["data"] == {"grant_type": "client_credentials", "client_id": "cid", "client_secret": "sec"}
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_credentials(self, mock_session):
+ response = _response({}, status_code=401)
+ response.raise_for_status.side_effect = requests.HTTPError("401", response=requests.Response())
+ mock_session.return_value.post.return_value = response
+
+ assert validate_credentials("us_production", "cid", "bad") is False
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_network_error_propagates(self, mock_session):
+ # A transient network failure must not be reported as invalid credentials.
+ mock_session.return_value.post.side_effect = requests.ConnectionError("boom")
+
+ with pytest.raises(requests.ConnectionError):
+ validate_credentials("us_production", "cid", "sec")
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_sandbox_environment_uses_sandbox_host(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+
+ validate_credentials("eu_sandbox", "cid", "sec")
+
+ assert mock_session.return_value.post.call_args.args[0] == "https://rest.sandbox.eu.zuora.com/oauth/token"
+
+
+class TestGetRows:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_paginates_with_next_page_cursor(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"id": "a1"}], "nextPage": "cur-1"}),
+ _response({"data": [{"id": "a2"}], "nextPage": None}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("us_production", "cid", "sec", "accounts", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["a1", "a2"]
+ first_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert first_url.startswith("https://rest.zuora.com/object-query/accounts?")
+ assert "pageSize=99" in first_url
+ assert "sort%5B%5D=updateddate.ASC" in first_url
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert "cursor=cur-1" in second_url
+ # The cursor encodes the full query context, so the original params are dropped.
+ assert "pageSize" not in second_url
+ assert "sort%5B%5D" not in second_url
+ assert [call.args[0].cursor for call in manager.save_state.call_args_list] == ["cur-1"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_passes_updateddate_gt_filter(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _response({"data": [], "nextPage": None})
+
+ list(
+ get_rows(
+ "us_production",
+ "cid",
+ "sec",
+ "invoices",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "filter%5B%5D=updateddate.GT%3A2024-01-02T03%3A04%3A05Z" in url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_saved_cursor(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _response({"data": [{"id": "a9"}], "nextPage": None})
+
+ manager = _make_manager(ZuoraResumeConfig(cursor="cur-9"))
+ list(get_rows("us_production", "cid", "sec", "accounts", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "cursor=cur-9" in url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_mid_sync_401_re_mints_token(self, mock_session):
+ mock_session.return_value.post.side_effect = [_token_response(), _token_response()]
+ mock_session.return_value.get.side_effect = [
+ _response({}, status_code=401),
+ _response({"data": [{"id": "a1"}], "nextPage": None}),
+ ]
+
+ batches = list(get_rows("us_production", "cid", "sec", "accounts", mock.MagicMock(), _make_manager()))
+
+ assert [row["id"] for batch in batches for row in batch] == ["a1"]
+ assert mock_session.return_value.post.call_count == 2
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_hyphenated_object_paths(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _response({"data": [], "nextPage": None})
+
+ list(get_rows("us_production", "cid", "sec", "credit_memos", mock.MagicMock(), _make_manager()))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "/object-query/credit-memos?" in url
+
+
+class TestZuoraSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ response = zuora_source("us_production", "cid", "sec", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # Pages are requested sorted ascending by updateddate.
+ assert response.sort_mode == "asc"
+
+ def test_all_endpoints_have_paths(self):
+ assert set(ENDPOINTS) == set(ZUORA_ENDPOINTS.keys())
diff --git a/posthog/temporal/data_imports/sources/zuora/tests/test_zuora_source.py b/posthog/temporal/data_imports/sources/zuora/tests/test_zuora_source.py
new file mode 100644
index 000000000000..fa4268eb3369
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/zuora/tests/test_zuora_source.py
@@ -0,0 +1,140 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import ZuoraSourceConfig
+from posthog.temporal.data_imports.sources.zuora.settings import ENDPOINTS, INCREMENTAL_FIELDS, ZUORA_ENVIRONMENT_HOSTS
+from posthog.temporal.data_imports.sources.zuora.source import ZuoraSource
+from posthog.temporal.data_imports.sources.zuora.zuora import ZuoraResumeConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestZuoraSource:
+ def setup_method(self):
+ self.source = ZuoraSource()
+ self.team_id = 123
+ self.config = ZuoraSourceConfig(environment="us_production", client_id="cid", client_secret="sec")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.ZUORA
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Zuora"
+ assert config.label == "Zuora"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/zuora.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["environment", "client_id", "client_secret"]
+
+ def test_environment_field_covers_all_hosts(self):
+ config = self.source.get_source_config
+ env_field = next(f for f in config.fields if f.name == "environment")
+ assert isinstance(env_field, SourceFieldSelectConfig)
+ assert env_field.defaultValue == "us_production"
+ assert {option.value for option in env_field.options} == set(ZUORA_ENVIRONMENT_HOSTS.keys())
+
+ def test_client_secret_field_is_secret_password(self):
+ config = self.source.get_source_config
+ secret_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret"
+ )
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert secret_field.secret is True
+ assert secret_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "400 Client Error: Bad Request for url: https://rest.zuora.com/oauth/token",
+ "401 Client Error: Unauthorized for url: https://rest.sandbox.eu.zuora.com/oauth/token",
+ "403 Client Error: Forbidden for url: https://rest.zuora.com/object-query/accounts",
+ ],
+ )
+ def test_non_retryable_errors_match_known_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ def test_non_retryable_errors_does_not_match_server_errors(self):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ error = "500 Server Error for url: https://rest.zuora.com/object-query/accounts"
+ assert not any(key in error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # Every Object Query object filters server-side on updateddate.
+ assert all(schema.supports_incremental for schema in schemas)
+ assert all([f["field"] for f in schema.incremental_fields] == ["updatedDate"] for schema in schemas)
+ assert {schema.name: schema.incremental_fields for schema in schemas} == INCREMENTAL_FIELDS
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["invoices"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "invoices"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid",
+ [
+ (True, True),
+ (False, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.zuora.source.validate_zuora_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ if not expected_valid:
+ assert "Invalid Zuora credentials" in (error_message or "")
+ mock_validate.assert_called_once_with("us_production", "cid", "sec")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ZuoraResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.zuora.source.zuora_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_zuora_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "invoices"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_zuora_source.assert_called_once()
+ kwargs = mock_zuora_source.call_args.kwargs
+ assert kwargs["environment"] == "us_production"
+ assert kwargs["client_id"] == "cid"
+ assert kwargs["client_secret"] == "sec"
+ assert kwargs["endpoint"] == "invoices"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.zuora.source.zuora_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_zuora_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "accounts"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_zuora_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/zuora/zuora.py b/posthog/temporal/data_imports/sources/zuora/zuora.py
new file mode 100644
index 000000000000..dc549edc14c6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/zuora/zuora.py
@@ -0,0 +1,175 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.zuora.settings import PAGE_SIZE, ZUORA_ENDPOINTS, ZUORA_ENVIRONMENT_HOSTS
+
+REQUEST_TIMEOUT_SECONDS = 60
+# Zuora recommends exponential backoff; limits are generous (50k RPM) but
+# concurrency-capped.
+MAX_RETRY_ATTEMPTS = 5
+
+
+class ZuoraRetryableError(Exception):
+ pass
+
+
+class ZuoraResumeConfig:
+ # The nextPage cursor of the next unfetched Object Query page.
+ cursor: str
+
+
+def _get_session(client_secret: str) -> requests.Session:
+ return make_tracked_session(redact_values=(client_secret,))
+
+
+def _base_url(environment: str) -> str:
+ host = ZUORA_ENVIRONMENT_HOSTS.get(environment)
+ if host is None:
+ raise ValueError(f"Invalid Zuora environment: {environment}")
+ return host
+
+
+def _mint_token(session: requests.Session, environment: str, client_id: str, client_secret: str) -> str:
+ """Exchange client credentials for a bearer token (~1h lifetime)."""
+ response = session.post(
+ f"{_base_url(environment)}/oauth/token",
+ data={"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ return response.json()["access_token"]
+
+
+def _format_timestamp(value: Any) -> str:
+ """Format an incremental cursor for the updateddate.GT filter (ISO 8601 UTC)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00Z")
+ return str(value)
+
+
+def validate_credentials(environment: str, client_id: str, client_secret: str) -> bool:
+ """Confirm the OAuth client credentials are valid by minting a token."""
+ try:
+ _mint_token(_get_session(client_secret), environment, client_id, client_secret)
+ return True
+ except requests.HTTPError:
+ # A rejected token request means the credentials are wrong. Let other
+ # failures (network/DNS/timeout) propagate so they aren't misreported
+ # to the user as invalid credentials.
+ return False
+
+
+def get_rows(
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ZuoraResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ path_segment = ZUORA_ENDPOINTS[endpoint]
+ session = _get_session(client_secret)
+ base_url = _base_url(environment)
+ token = _mint_token(session, environment, client_id, client_secret)
+
+ @retry(
+ retry=retry_if_exception_type((ZuoraRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=2, max=90),
+ reraise=True,
+ )
+ def fetch(url: str) -> dict[str, Any]:
+ nonlocal token
+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Tokens last ~1h; re-mint once if one expires mid-sync.
+ if response.status_code == 401:
+ token = _mint_token(session, environment, client_id, client_secret)
+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ZuoraRetryableError(f"Zuora API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Zuora API error: status={response.status_code}, body={response.text[:500]}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ # Filters use lowercase field names (updateddate); rows come back camelCase
+ # (updatedDate). Ascending sort lets the pipeline commit the watermark
+ # progressively as pages complete.
+ params: list[tuple[str, Any]] = [("pageSize", PAGE_SIZE), ("sort[]", "updateddate.ASC")]
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ params.append(("filter[]", f"updateddate.GT:{_format_timestamp(db_incremental_field_last_value)}"))
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume_config.cursor if resume_config is not None else None
+ if resume_config is not None:
+ logger.debug(f"Zuora: resuming {endpoint} from saved cursor")
+
+ while True:
+ # The cursor encodes the full query context (pageSize/sort/filter), so
+ # send it alone — repeating the original params risks a 400.
+ page_params = [("cursor", cursor)] if cursor else params
+ url = f"{base_url}/object-query/{path_segment}?{urlencode(page_params)}"
+ body = fetch(url)
+ items = body.get("data") or []
+ rows = [row for row in items if isinstance(row, dict)]
+
+ if rows:
+ yield rows
+
+ cursor = body.get("nextPage") or None
+ if not cursor:
+ return
+
+ # Save state AFTER yielding so a crash re-yields the in-flight page
+ # (merge dedupes on primary key).
+ resumable_source_manager.save_state(ZuoraResumeConfig(cursor=cursor))
+
+
+def zuora_source(
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ZuoraResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ environment=environment,
+ client_id=client_id,
+ client_secret=client_secret,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=["id"],
+ partition_count=1,
+ partition_size=1,
+ # Pages are requested sorted ascending by updateddate.
+ sort_mode="asc",
+ )