: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 iterable import source (#61588)
Tom Owers947b3f5c8884
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 0b364fa97af3..6e59de5ec691 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -84,6 +84,7 @@ the row lists both.| greenhouse | HTTP | requests | ✅ || hubspot | HTTP | requests | ✅ || intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |+| iterable | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ || launchdarkly | HTTP | requests | ✅ || linear | HTTP | requests | ✅ |@@ -199,7 +200,6 @@ doesn't conflict with concurrent PRs.- google_drive- helpscout-- iterable- jira- kafka- leverdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 341c45f0eb73..1950e39a19b2 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -473,7 +473,8 @@ class IntercomSourceConfig(config.Config):@config.configclass IterableSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")@config.configdiff --git a/posthog/temporal/data_imports/sources/iterable/api_inventory.md b/posthog/temporal/data_imports/sources/iterable/api_inventory.mdnew file mode 100644index 000000000000..14b1e9ec8d6f--- /dev/null+++ b/posthog/temporal/data_imports/sources/iterable/api_inventory.md@@ -0,0 +1,50 @@+# Iterable API inventory++Reference for the `iterable` data warehouse source. Iterable is a cross-channel marketing+automation platform (email, SMS, push, in-app). REST/JSON API.++- **Docs:** <https://api.iterable.com/api/docs> (US), <https://api.eu.iterable.com/api/docs> (EU)+- **Base URLs:** `https://api.iterable.com` (US), `https://api.eu.iterable.com` (EU). A key only+ works against the data center that issued it.+- **Auth:** `Api-Key: <server-side key>` header. (JWT-enabled keys use `Authorization: Bearer <jwt>`+ — not currently supported here.)+- **Rate limits:** ~100 req/s for most list endpoints; the Export API is far stricter+ (~4 req/min per project, max 4 concurrent exports per org). Returns `429` when exceeded.+- **Errors:** JSON envelope `{"code": "...", "msg": "...", "params": {...}}`. `401 BadApiKey`,+ `403`, `404`, `429 RateLimitExceeded`, `5xx`.++## Implemented endpoints (full refresh)++| Schema | Path | Data key | Primary key |+| --------------- | ------------------- | -------------- | ------------ |+| `campaigns` | `/api/campaigns` | `campaigns` | `id` |+| `channels` | `/api/channels` | `channels` | `id` |+| `lists` | `/api/lists` | `lists` | `id` |+| `message_types` | `/api/messageTypes` | `messageTypes` | `id` |+| `templates` | `/api/templates` | `templates` | `templateId` |++These return their full result set in a single response wrapped under the named array. The+transport still follows `nextPageUrl` if present (with a `MAX_PAGES` safety cap) so the source+keeps working if Iterable paginates large result sets in the future.++## Incremental / partitioning notes++- **No verified server-side timestamp filter.** Per the implementing-warehouse-sources skill, a+ client-side cursor that re-reads every page each run is not real incremental, so all endpoints+ ship full refresh. Airbyte/Fivetran sync `templates` incrementally on `updatedAt` (via the+ `startDateTime`/`endDateTime` params) and `users` on `profileUpdatedAt`, but those filters+ could not be curl-verified without live credentials. Revisit once a key is available.+- **No partition key.** Iterable timestamps (`createdAt`, `updatedAt`) are epoch **milliseconds**.+ The datetime partitioner (`pipelines/pipeline/utils.py`) treats integer partition values as+ epoch **seconds** (`datetime.fromtimestamp`), so partitioning on these fields would map every+ row into far-future buckets (and overflow). Skipped rather than ship an unstable/broken config.++## Deferred (not implemented)++- **Export API** (`/api/export/data.json`, `/api/export/userEvents`) — the high-volume event and+ user streams (email/push/SMS/in-app sends, opens, clicks, bounces, purchases, custom events,+ `users`). Async jobId polling + NDJSON streaming + strict 4 req/min rate limit + adaptive+ date-range slicing. Needs live-credential verification before implementing.+- **Webhooks** — Iterable supports system webhooks for realtime events, but they're configured+ in the UI only (not programmatically), and the payload shapes need verification, so no+ `WebhookSource` integration is included yet.diff --git a/posthog/temporal/data_imports/sources/iterable/iterable.py b/posthog/temporal/data_imports/sources/iterable/iterable.pynew file mode 100644index 000000000000..3cf1052761d3--- /dev/null+++ b/posthog/temporal/data_imports/sources/iterable/iterable.py@@ -0,0 +1,164 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlparse++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.iterable.settings import ITERABLE_ENDPOINTS++# Iterable is region-locked: a key issued in one data center only works against that data center.+ITERABLE_BASE_URLS: dict[str, str] = {+ "us": "https://api.iterable.com",+ "eu": "https://api.eu.iterable.com",+}++REQUEST_TIMEOUT_SECONDS = 60+# Safety bound on the pagination loop. Iterable's list endpoints normally return everything in a+# single response, but if one ever starts returning `nextPageUrl` we don't want an unbounded scan.+MAX_PAGES = 10_000+++class IterableRetryableError(Exception):+ pass+++class IterableResumeConfig:+ next_url: str+++def base_url_for_region(region: str | None) -> str:+ return ITERABLE_BASE_URLS.get((region or "us").lower(), ITERABLE_BASE_URLS["us"])+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Api-Key": api_key,+ "Accept": "application/json",+ }+++def validate_credentials(api_key: str, region: str | None) -> bool:+ # `/api/channels` is a cheap, low-cardinality endpoint that requires a valid server-side key.+ url = f"{base_url_for_region(region)}/api/channels"+ # `redact_values` masks the key in logs and sample capture: the sampler's name-based scrubber+ # doesn't recognise Iterable's `Api-Key` header, so the value would otherwise be captured raw.+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(url, timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def _is_same_origin(base_url: str, url: str) -> bool:+ base = urlparse(base_url)+ target = urlparse(url)+ return (target.scheme, target.netloc) == (base.scheme, base.netloc)+++def _resolve_next_url(base_url: str, next_page: Any) -> str | None:+ """Normalize the `nextPageUrl` value from a response body into an absolute URL.++ Absolute URLs are only followed when they point at the selected Iterable base URL.+ The session carries the `Api-Key` header, so a `nextPageUrl` aimed at another host+ (e.g. an attacker-controlled value echoed back in a response) would leak the key —+ such off-host pages stop pagination instead.+ """+ if not next_page or not isinstance(next_page, str):+ return None+ if next_page.startswith("http://") or next_page.startswith("https://"):+ return next_page if _is_same_origin(base_url, next_page) else None+ return f"{base_url}{next_page}" if next_page.startswith("/") else f"{base_url}/{next_page}"+++def get_rows(+ api_key: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[IterableResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = ITERABLE_ENDPOINTS[endpoint]+ base_url = base_url_for_region(region)+ # `redact_values` masks the key in logs and sample capture: the sampler's name-based scrubber+ # doesn't recognise Iterable's `Api-Key` header, so the value would otherwise be captured raw.+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and _is_same_origin(base_url, resume_config.next_url):+ url: str | None = resume_config.next_url+ logger.debug(f"Iterable: resuming {endpoint} from URL: {url}")+ else:+ # Either no resume state, or it points off-host (corrupted/poisoned) — start from the top.+ # The session carries the `Api-Key` header, so we never follow a resumed off-host URL.+ url = f"{base_url}{config.path}"++ @retry(+ retry=retry_if_exception_type((IterableRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_url: str) -> dict[str, Any]:+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise IterableRetryableError(+ f"Iterable API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"Iterable API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ pages = 0+ while url is not None:+ data = fetch_page(url)+ items = data.get(config.data_key, [])++ next_url = _resolve_next_url(base_url, data.get("nextPageUrl"))++ if items:+ yield items+ # Save state AFTER yielding so a crash re-yields the last batch (merge dedupes on the+ # primary key) rather than skipping it.+ if next_url is not None:+ resumable_source_manager.save_state(IterableResumeConfig(next_url=next_url))++ pages += 1+ if pages >= MAX_PAGES:+ logger.warning(f"Iterable: hit MAX_PAGES={MAX_PAGES} cap for endpoint={endpoint}; stopping pagination")+ break++ url = next_url+++def iterable_source(+ api_key: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[IterableResumeConfig],+) -> SourceResponse:+ config = ITERABLE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=[config.primary_key],+ )diff --git a/posthog/temporal/data_imports/sources/iterable/settings.py b/posthog/temporal/data_imports/sources/iterable/settings.pynew file mode 100644index 000000000000..d63b017b6235--- /dev/null+++ b/posthog/temporal/data_imports/sources/iterable/settings.py@@ -0,0 +1,35 @@+from dataclasses import dataclass, field++from products.data_warehouse.backend.types import IncrementalField+++@dataclass+class IterableEndpointConfig:+ name: str+ path: str+ data_key: str # JSON key the result array is nested under in the response body+ primary_key: str = "id"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++# Iterable's list endpoints return their full result set in a single response wrapped under a+# named array (e.g. `{"campaigns": [...]}`). None of them expose a server-side timestamp filter+# (`startDateTime`/`updatedAt[after]`/etc.) we can verify, so every endpoint is full refresh —+# an "incremental" sync would still have to read every row each run. The higher-volume+# event/user streams live behind Iterable's async Export API (jobId polling, 4 req/min limit)+# and are intentionally deferred until that behavior can be verified against live credentials.+ITERABLE_ENDPOINTS: dict[str, IterableEndpointConfig] = {+ "campaigns": IterableEndpointConfig(name="campaigns", path="/api/campaigns", data_key="campaigns"),+ "channels": IterableEndpointConfig(name="channels", path="/api/channels", data_key="channels"),+ "lists": IterableEndpointConfig(name="lists", path="/api/lists", data_key="lists"),+ "message_types": IterableEndpointConfig(name="message_types", path="/api/messageTypes", data_key="messageTypes"),+ "templates": IterableEndpointConfig(+ name="templates", path="/api/templates", data_key="templates", primary_key="templateId"+ ),+}++ENDPOINTS = tuple(ITERABLE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ITERABLE_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/iterable/source.py b/posthog/temporal/data_imports/sources/iterable/source.pyindex e1d46d1544f7..79bc4c0e6222 100644--- a/posthog/temporal/data_imports/sources/iterable/source.py+++ b/posthog/temporal/data_imports/sources/iterable/source.py@@ -1,29 +1,133 @@-from typing import cast+from typing import Optional, castfrom 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, ResumableSourcefrom 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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import IterableSourceConfig+from posthog.temporal.data_imports.sources.iterable.iterable import (+ IterableResumeConfig,+ iterable_source,+ validate_credentials as validate_iterable_credentials,+)+from posthog.temporal.data_imports.sources.iterable.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class IterableSource(SimpleSource[IterableSourceConfig]):+class IterableSource(ResumableSource[IterableSourceConfig, IterableResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ITERABLE+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": (+ "Iterable rejected the API key. Make sure you're using a server-side API key from the "+ "matching data center (US or EU) and reconnect."+ ),+ "403 Client Error": (+ "The Iterable API key doesn't have permission for this endpoint. Grant the key access to "+ "the resources you're syncing and reconnect."+ ),+ }++ def get_schemas(+ self,+ config: IterableSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ 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: IterableSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_iterable_credentials(config.api_key, config.region):+ return True, None++ return False, "Invalid Iterable API key for the selected data center"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[IterableResumeConfig]:+ return ResumableSourceManager[IterableResumeConfig](inputs, IterableResumeConfig)++ def source_for_pipeline(+ self,+ config: IterableSourceConfig,+ resumable_source_manager: ResumableSourceManager[IterableResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return iterable_source(+ api_key=config.api_key,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ITERABLE,label="Iterable",+ caption="""Enter your Iterable API key to pull your Iterable data into the PostHog Data warehouse.++Create a **server-side** API key with read permissions in your [Iterable integrations settings](https://app.iterable.com/settings/apiKeys). Client-side (Mobile/Browser/JWT) keys are not supported.++Make sure the data center below matches the one that issued your key (US or EU).""",iconPath="/static/services/iterable.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/iterable",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Data center",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.iterable.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api.eu.iterable.com)", value="eu"),+ ],+ ),+ ],+ ),unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/posthog/temporal/data_imports/sources/iterable/tests/test_iterable.py b/posthog/temporal/data_imports/sources/iterable/tests/test_iterable.pynew file mode 100644index 000000000000..3da33ca3814f--- /dev/null+++ b/posthog/temporal/data_imports/sources/iterable/tests/test_iterable.py@@ -0,0 +1,197 @@+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.iterable.iterable import (+ IterableResumeConfig,+ _get_headers,+ _resolve_next_url,+ base_url_for_region,+ get_rows,+ iterable_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.iterable.settings import ITERABLE_ENDPOINTS++MODULE = "posthog.temporal.data_imports.sources.iterable.iterable"+++def _make_response(status_code: int = 200, body: dict[str, Any] | None = None) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.json.return_value = body or {}+ response.text = ""+ return response+++def _make_manager(resume_state: IterableResumeConfig | 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+++class TestBaseUrlForRegion:+ @pytest.mark.parametrize(+ "region, expected",+ [+ ("us", "https://api.iterable.com"),+ ("US", "https://api.iterable.com"),+ ("eu", "https://api.eu.iterable.com"),+ ("EU", "https://api.eu.iterable.com"),+ (None, "https://api.iterable.com"),+ ("unknown", "https://api.iterable.com"),+ ],+ )+ def test_base_url_for_region(self, region: str | None, expected: str) -> None:+ assert base_url_for_region(region) == expected+++class TestHeaders:+ def test_uses_api_key_header(self) -> None:+ headers = _get_headers("secret-key")+ assert headers["Api-Key"] == "secret-key"+ assert headers["Accept"] == "application/json"+ # Iterable uses the `Api-Key` header, not `Authorization`.+ assert "Authorization" not in headers+++class TestResolveNextUrl:+ @pytest.mark.parametrize(+ "next_page, expected",+ [+ ("https://api.iterable.com/api/campaigns?page=2", "https://api.iterable.com/api/campaigns?page=2"),+ ("/api/campaigns?page=2", "https://api.iterable.com/api/campaigns?page=2"),+ ("api/campaigns?page=2", "https://api.iterable.com/api/campaigns?page=2"),+ (None, None),+ ("", None),+ (123, None),+ # Off-host absolute URLs must not be followed — the session carries the Api-Key header.+ ("https://evil.com/api/campaigns?page=2", None),+ ("http://api.iterable.com/api/campaigns?page=2", None),+ ("https://api.iterable.com.evil.com/api/campaigns", None),+ ],+ )+ def test_resolve_next_url(self, next_page: Any, expected: str | None) -> None:+ assert _resolve_next_url("https://api.iterable.com", next_page) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_status_code_mapping(self, mock_session, status_code: int, expected: bool) -> None:+ mock_session.return_value.get.return_value = _make_response(status_code=status_code)+ assert validate_credentials("key", "us") is expected++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_network_error_is_invalid(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key", "us") is False++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_uses_region_base_url(self, mock_session) -> None:+ mock_session.return_value.get.return_value = _make_response(status_code=200)+ validate_credentials("key", "eu")+ called_url = mock_session.return_value.get.call_args.args[0]+ assert called_url == "https://api.eu.iterable.com/api/channels"+++class TestGetRows:+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_single_page_yields_items_without_saving_state(self, mock_session) -> None:+ mock_session.return_value.get.return_value = _make_response(body={"campaigns": [{"id": 1}, {"id": 2}]})+ manager = _make_manager()++ batches = list(get_rows("key", "us", "campaigns", mock.MagicMock(), manager))++ assert batches == [[{"id": 1}, {"id": 2}]]+ manager.save_state.assert_not_called()++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_empty_response_yields_nothing(self, mock_session) -> None:+ mock_session.return_value.get.return_value = _make_response(body={"campaigns": []})+ manager = _make_manager()++ batches = list(get_rows("key", "us", "campaigns", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_follows_next_page_url_and_saves_state_after_yield(self, mock_session) -> None:+ first = _make_response(body={"campaigns": [{"id": 1}], "nextPageUrl": "/api/campaigns?page=2"})+ second = _make_response(body={"campaigns": [{"id": 2}]})+ mock_session.return_value.get.side_effect = [first, second]+ manager = _make_manager()++ batches = list(get_rows("key", "us", "campaigns", mock.MagicMock(), manager))++ assert batches == [[{"id": 1}], [{"id": 2}]]+ # State is saved once — after the first page yields, pointing at the resolved next URL.+ manager.save_state.assert_called_once_with(+ IterableResumeConfig(next_url="https://api.iterable.com/api/campaigns?page=2")+ )+ # Second request follows the resolved next URL.+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls == ["https://api.iterable.com/api/campaigns", "https://api.iterable.com/api/campaigns?page=2"]++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_resumes_from_saved_state(self, mock_session) -> None:+ mock_session.return_value.get.return_value = _make_response(body={"campaigns": [{"id": 9}]})+ manager = _make_manager(+ resume_state=IterableResumeConfig(next_url="https://api.iterable.com/api/campaigns?page=5")+ )++ list(get_rows("key", "us", "campaigns", mock.MagicMock(), manager))++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert first_url == "https://api.iterable.com/api/campaigns?page=5"++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_off_host_resume_state_restarts_from_top(self, mock_session) -> None:+ # A resume URL pointing at another host (corrupted/poisoned state) must not be requested+ # with the Api-Key header — pagination restarts from the endpoint's base URL instead.+ mock_session.return_value.get.return_value = _make_response(body={"campaigns": [{"id": 9}]})+ manager = _make_manager(resume_state=IterableResumeConfig(next_url="https://evil.com/api/campaigns?page=5"))++ list(get_rows("key", "us", "campaigns", mock.MagicMock(), manager))++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert first_url == "https://api.iterable.com/api/campaigns"++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_uses_endpoint_data_key(self, mock_session) -> None:+ mock_session.return_value.get.return_value = _make_response(body={"templates": [{"templateId": 7}]})+ manager = _make_manager()++ batches = list(get_rows("key", "us", "templates", mock.MagicMock(), manager))++ assert batches == [[{"templateId": 7}]]+++class TestIterableSource:+ @pytest.mark.parametrize(+ "endpoint, expected_pk",+ [+ ("campaigns", "id"),+ ("channels", "id"),+ ("lists", "id"),+ ("message_types", "id"),+ ("templates", "templateId"),+ ],+ )+ def test_source_response_primary_keys(self, endpoint: str, expected_pk: str) -> None:+ response = iterable_source("key", "us", endpoint, mock.MagicMock(), _make_manager())+ assert response.name == endpoint+ assert response.primary_keys == [expected_pk]+ assert response.primary_keys == [ITERABLE_ENDPOINTS[endpoint].primary_key]diff --git a/posthog/temporal/data_imports/sources/iterable/tests/test_iterable_source.py b/posthog/temporal/data_imports/sources/iterable/tests/test_iterable_source.pynew file mode 100644index 000000000000..75314abbf2ac--- /dev/null+++ b/posthog/temporal/data_imports/sources/iterable/tests/test_iterable_source.py@@ -0,0 +1,131 @@+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 IterableSourceConfig+from posthog.temporal.data_imports.sources.iterable.iterable import IterableResumeConfig+from posthog.temporal.data_imports.sources.iterable.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.iterable.source import IterableSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestIterableSource:+ def setup_method(self):+ self.source = IterableSource()+ self.team_id = 123+ self.config = IterableSourceConfig(api_key="fake-key", region="us")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.ITERABLE++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Iterable"+ assert config.label == "Iterable"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/iterable.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key", "region"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_region_field_offers_us_and_eu(self):+ config = self.source.get_source_config+ region_field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig))+ assert region_field.name == "region"+ assert region_field.defaultValue == "us"+ assert {option.value for option in region_field.options} == {"us", "eu"}++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.iterable.com/api/campaigns",+ "403 Client Error: Forbidden for url: https://api.eu.iterable.com/api/templates",+ ],+ )+ def test_non_retryable_errors_match_auth_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)++ @pytest.mark.parametrize(+ "transient_error",+ [+ "500 Server Error for url: https://api.iterable.com/api/campaigns",+ "429 Client Error: Too Many Requests for url: https://api.iterable.com/api/campaigns",+ "Connection aborted: ReadTimeout for url: https://api.iterable.com/api/campaigns",+ ],+ )+ def test_non_retryable_errors_does_not_match_transient(self, transient_error):+ # Transient failures (5xx / 429 / timeouts) must stay retryable, not permanently fail the job.+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in transient_error for key in non_retryable_errors)++ def test_get_schemas_covers_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_get_schemas_are_full_refresh(self):+ # No Iterable list endpoint exposes a verified server-side timestamp filter,+ # so everything is full refresh (no incremental / append).+ for schema in self.source.get_schemas(self.config, self.team_id):+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == INCREMENTAL_FIELDS[schema.name] == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["campaigns"])+ assert len(schemas) == 1+ assert schemas[0].name == "campaigns"++ 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, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Iterable API key for the selected data center"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.iterable.source.validate_iterable_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ 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+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.api_key, self.config.region)++ 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 IterableResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.iterable.source.iterable_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_iterable_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "campaigns"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_iterable_source.assert_called_once()+ kwargs = mock_iterable_source.call_args.kwargs+ assert kwargs["api_key"] == "fake-key"+ assert kwargs["region"] == "us"+ assert kwargs["endpoint"] == "campaigns"+ assert kwargs["resumable_source_manager"] is manager