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): add iterable campaign metrics, list members and export tables (#111890)

Tom Owers748850afc1dc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 1c9a3df37a98..39f47aa96bfc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4444,23 +4444,23 @@ Note: IP2WHOIS's Domain WHOIS product is literally one endpoint: GET https://api
## Iterable — **thin**
-Today (5): `campaigns`, `channels`, `lists`, `message_types`, `templates`
+Today (7 + Export API): `campaigns`, `campaign_metrics`, `channels`, `lists`, `list_users`, `message_types`, `templates`, plus one Export API table per `dataTypeName` (`email_send`, `email_open`, ..., `users`)
Diffed against: <https://api.iterable.com/api-docs>
-- [ ] `GET /api/campaigns/metrics` — the headline campaign performance metrics (sends, opens, clicks, bounces, unsubs) — none of it is synced today (high)
-- [ ] `GET /api/export/userEvents and /api/export/data.json` — the actual message events (emailSend/Open/Click/Bounce, push, SMS, purchases, custom events) and the users table — the core analytical dataset (high)
-- [ ] `GET /api/lists/getUsers` — list membership junction resolving the lists we already sync to users (high)
+- [x] `GET /api/campaigns/metrics` — the headline campaign performance metrics (sends, opens, clicks, bounces, unsubs) — none of it is synced today (high). Added as `campaign_metrics` (lifetime totals, batched over `campaigns`).
+- [x] `GET /api/export/userEvents and /api/export/data.json` — the actual message events (emailSend/Open/Click/Bounce, push, SMS, purchases, custom events) and the users table — the core analytical dataset (high). `/api/export/data.json` added as one table per `dataTypeName` (`email_send`, `email_open`, ..., `custom_event`, `purchase`, `users`), with append sync on `createdAt` / `profileUpdatedAt`. `/api/export/userEvents` skipped: it needs an `email` or `userId` per call, and the same events are in the `data.json` tables.
+- [x] `GET /api/lists/getUsers` — list membership junction resolving the lists we already sync to users (high). Added as `list_users` (fan-out over `lists`).
- [ ] `GET /api/journeys` — lookup resolving workflow/journey IDs that appear on campaigns and events (medium)
- [ ] `GET /api/experiments, /api/experiments/metrics, /api/experiments/{id}/variants` — A/B test definitions and per-variant results for campaigns we sync (medium)
- [ ] `GET /api/catalogs and /api/catalogs/{catalogName}/items` — catalog item lookup used for personalization and recommendations (medium)
-- [ ] `GET /api/users/getSentMessages` — per-user message history for cohort-level send analysis (medium)
+- [ ] `GET /api/users/getSentMessages` — per-user message history for cohort-level send analysis (medium) — skipped: it needs an `email` or `userId` per call, so a table would cost one request per user, and the same sends are in the `email_send`, `push_send` and `sms_send` export tables.
- [ ] `GET /api/campaigns/recurring/{id}/childCampaigns` — lookup linking recurring parent campaigns to their child sends (medium)
- [ ] `GET /api/metadata and /api/metadata/{table}` — key-value metadata tables used as lookups in templates (low)
- [ ] `GET /api/snippets` — reusable template snippets referenced by templates we sync (low)
- [ ] `GET /api/embedded-messaging/messages` — embedded message inventory for the embedded channel (low)
-Note: Swagger JSON is public and unauthenticated at https://api.iterable.com/api-docs (52 GET paths). The source's own products/warehouse_sources/backend/temporal/data_imports/sources/iterable/api_inventory.md explicitly defers the Export API (async jobId polling, NDJSON streaming, ~4 req/min limit) — that deferral is why the source is 5 config tables with zero metrics or events. EU keys need api.eu.iterable.com.
+Note: Swagger JSON is public and unauthenticated at https://api.iterable.com/api-docs (52 GET paths). The Export API tables use the synchronous `/api/export/data.json` NDJSON stream in 30-day windows, paced for its ~4 req/min limit, rather than the async jobId flow. EU keys need api.eu.iterable.com.
## JamfPro — **thin**
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/api_inventory.md
index b5579b6b7e48..09961f29c169 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/api_inventory.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/api_inventory.md
@@ -27,24 +27,48 @@ These return their full result set in a single response wrapped under the named
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.
+## Fan-out endpoints (full refresh)
+
+| Schema | Path | Response | Primary key |
+| ------------------ | ------------------------------------------------------ | ----------------------------- | ----------------- |
+| `campaign_metrics` | `/api/campaigns/metrics?campaignId=…` (100 ids a call) | CSV, one row per campaign | `id` |
+| `list_users` | `/api/lists/getUsers?listId=…` (one call per list) | Plain text, one user per line | `listId`, `email` |
+
+`campaign_metrics` returns lifetime totals. `startDateTime`/`endDateTime` change the aggregation
+window rather than filtering rows, so there is no incremental mode.
+
+## Export API endpoints (full refresh or append)
+
+`/api/export/data.json?dataTypeName=…&startDateTime=…&endDateTime=…` streams NDJSON. One table per
+`dataTypeName` (every documented type except `unknownSession`): events filter on `createdAt`, the
+`users` table on `profileUpdatedAt`. The source walks 30-day windows, waits 15 seconds between
+requests (the limit is about 4 a minute per project), and stores the next window start as its resume
+state. The cursor field is parsed from `yyyy-MM-dd HH:mm:ss +00:00` into a datetime so it can drive
+incremental sync and (for events) monthly partitioning.
+
+- Rows carry no unique id, so the tables support append, not merge.
+- First sync and full refresh start 365 days back.
+- Tables start disabled because they share the project's export rate limit.
+
## 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
+- **No verified server-side timestamp filter on the list endpoints.** Per the
+ implementing-warehouse-sources skill, a client-side cursor that re-reads every page each run is
+ not real incremental, so the list 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**.
+- **No partition key on the list endpoints.** Iterable timestamps (`createdAt`, `updatedAt`) are epoch **milliseconds**.
The datetime partitioner (`pipelines/core/partitioning.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.
+- **Per-user endpoints** (`/api/export/userEvents`, `/api/users/getSentMessages`) — both need an
+ `email` or `userId` on every call, so a table would mean one request per user. The same events
+ and sends are in the Export API tables above.
+- **Async export jobs** (`/api/export/start`) — the synchronous `data.json` stream covers the same
+ data types without job polling.
- **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/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/canonical_descriptions.py
index 3e6029d0e542..a4c8babe2429 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/canonical_descriptions.py
@@ -81,4 +81,40 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updatedAt": "Time at which the template was last updated, as a Unix timestamp.",
},
},
+ "campaign_metrics": {
+ "description": "Lifetime performance metrics for an Iterable campaign, such as sends, opens, clicks, bounces and unsubscribes.",
+ "docs_url": "https://api.iterable.com/api/docs#campaigns_metrics",
+ "columns": {
+ "id": "Identifier of the campaign the metrics belong to. Joins to `campaigns.id`.",
+ },
+ },
+ "list_users": {
+ "description": "Membership of Iterable lists: one row per user in each list.",
+ "docs_url": "https://api.iterable.com/api/docs#lists_getLists_0",
+ "columns": {
+ "listId": "Identifier of the list. Joins to `lists.id`.",
+ "email": "Email of the list member, or the userId for a user without an email.",
+ },
+ },
+ "users": {
+ "description": "User profiles in the Iterable project, from the Export API.",
+ "docs_url": "https://api.iterable.com/api/docs#export_exportDataJson",
+ "columns": {
+ "email": "The user's email address.",
+ "userId": "The user's userId, when set.",
+ "profileUpdatedAt": "Time at which the user's profile was last updated.",
+ "signupDate": "Time at which the user signed up.",
+ },
+ },
+ "email_send": {
+ "description": "One row per email Iterable sent, from the Export API.",
+ "docs_url": "https://api.iterable.com/api/docs#export_exportDataJson",
+ "columns": {
+ "createdAt": "Time at which the email was sent.",
+ "email": "Email address of the recipient.",
+ "campaignId": "Identifier of the campaign that sent the email. Joins to `campaigns.id`.",
+ "templateId": "Identifier of the template used. Joins to `templates.templateId`.",
+ "messageId": "Identifier of the sent message, shared by its open, click and bounce events.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/iterable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/iterable.py
index 1ae7d933e12f..02e3a103cd30 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/iterable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/iterable.py
@@ -1,10 +1,19 @@
-import dataclasses
+import io
+import csv
+import time
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
from urllib.parse import urlparse
+import orjson
+import requests
from requests import Response
+from posthog.dataclasses import frozen
+
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.http.transport import BoundedRetry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
@@ -15,7 +24,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.iterable.settings import ITERABLE_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.iterable.settings import (
+ CAMPAIGN_METRICS,
+ DEFAULT_EXPORT_LOOKBACK_DAYS,
+ FAN_OUT_PRIMARY_KEYS,
+ ITERABLE_ENDPOINTS,
+ ITERABLE_EXPORT_ENDPOINTS,
+ LIST_USERS,
+ IterableExportEndpointConfig,
+)
# Iterable is region-locked: a key issued in one data center only works against that data center.
ITERABLE_BASE_URLS: dict[str, str] = {
@@ -27,19 +44,38 @@ ITERABLE_BASE_URLS: dict[str, str] = {
# single response, but if one ever starts returning `nextPageUrl` we don't want an unbounded scan.
MAX_PAGES = 10_000
+CHUNK_SIZE = 5000
+REQUEST_TIMEOUT = 300
+EXPORT_WINDOW = timedelta(days=30)
+# The Export API allows about 4 requests a minute per project.
+EXPORT_REQUEST_INTERVAL_SECONDS = 15
+CAMPAIGN_METRICS_BATCH_SIZE = 100
+
+# The export and metrics endpoints have per-minute rate limits, so a 429 needs a much longer
+# backoff than the default transport retry gives.
+RATE_LIMITED_RETRY = BoundedRetry(
+ total=5,
+ backoff_factor=30,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=frozenset(["GET"]),
+ raise_on_status=False,
+)
+
+@frozen
class IterableResumeConfig:
- next_url: str
+ next_url: str | None = None
+ # ISO start of the next export window to fetch.
+ export_window_start: str | None = None
def base_url_for_region(region: str | None) -> str:
return ITERABLE_BASE_URLS.get((region or "us").lower(), ITERABLE_BASE_URLS["us"])
-def _probe_headers(api_key: str) -> dict[str, str]:
+def _api_key_headers(api_key: str) -> dict[str, str]:
# The Api-Key credential rides in a header the tracked session's name-based scrubber doesn't
- # know, so the probe session masks it by value via `redact_values`.
+ # know, so sessions using it mask it by value via `redact_values`.
return {"Api-Key": api_key, "Accept": "application/json"}
@@ -49,7 +85,7 @@ def validate_credentials(api_key: str, region: str | None) -> bool:
ok, _status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,)),
url,
- headers=_probe_headers(api_key),
+ headers=_api_key_headers(api_key),
)
return ok
@@ -106,6 +142,200 @@ class IterableNextPagePaginator(BaseNextUrlPaginator):
self._has_next_page = False
+def _parse_iterable_datetime(value: Any) -> Any:
+ """Parse an export timestamp such as ``2024-01-31 18:04:05 +00:00`` into an aware datetime.
+
+ Anything that does not parse is returned unchanged.
+ """
+ if not isinstance(value, str):
+ return value
+ try:
+ parsed = datetime.fromisoformat(value.strip().replace(" +", "+").replace(" -", "-"))
+ except ValueError:
+ return value
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+
+
+def _to_datetime(value: Any) -> datetime | None:
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime(value.year, value.month, value.day, tzinfo=UTC)
+ if isinstance(value, str) and value.strip():
+ parsed = _parse_iterable_datetime(value.replace("Z", "+00:00"))
+ return parsed if isinstance(parsed, datetime) else None
+ return None
+
+
+def _format_export_datetime(value: datetime) -> str:
+ return value.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S +00:00")
+
+
+@frozen
+class ExportWindow:
+ start: datetime
+ end: datetime
+
+
+def _export_windows(start: datetime, end: datetime) -> Iterator[ExportWindow]:
+ window_start = start
+ while window_start < end:
+ window_end = min(window_start + EXPORT_WINDOW, end)
+ yield ExportWindow(start=window_start, end=window_end)
+ window_start = window_end
+
+
+def _stream_export_window(
+ session: requests.Session,
+ base_url: str,
+ config: IterableExportEndpointConfig,
+ window: ExportWindow,
+) -> Iterator[list[dict[str, Any]]]:
+ params = {
+ "dataTypeName": config.data_type_name,
+ "startDateTime": _format_export_datetime(window.start),
+ "endDateTime": _format_export_datetime(window.end),
+ }
+ with session.get(
+ f"{base_url}/api/export/data.json", params=params, timeout=REQUEST_TIMEOUT, stream=True
+ ) as response:
+ response.raise_for_status()
+ batch: list[dict[str, Any]] = []
+ for line in response.iter_lines():
+ if not line:
+ continue
+ row = orjson.loads(line)
+ if config.cursor_field in row:
+ row[config.cursor_field] = _parse_iterable_datetime(row[config.cursor_field])
+ batch.append(row)
+ if len(batch) >= CHUNK_SIZE:
+ yield batch
+ batch = []
+ if batch:
+ yield batch
+
+
+def _iter_export(
+ session: requests.Session,
+ base_url: str,
+ config: IterableExportEndpointConfig,
+ manager: ResumableSourceManager[IterableResumeConfig],
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ end = datetime.now(UTC)
+ start = _to_datetime(db_incremental_field_last_value) or end - timedelta(days=DEFAULT_EXPORT_LOOKBACK_DAYS)
+ if manager.can_resume():
+ resume = manager.load_state()
+ resume_start = _to_datetime(resume.export_window_start) if resume else None
+ if resume_start is not None:
+ start = resume_start
+
+ for index, window in enumerate(_export_windows(start, end)):
+ if index > 0:
+ time.sleep(EXPORT_REQUEST_INTERVAL_SECONDS)
+ # Hold back one batch so the next window's cursor is staged before the window's last
+ # batch is yielded: the pipeline then commits it only once the whole window is written.
+ pending: list[dict[str, Any]] | None = None
+ for batch in _stream_export_window(session, base_url, config, window):
+ if pending is not None:
+ yield pending
+ pending = batch
+ if window.end < end:
+ manager.save_state(IterableResumeConfig(export_window_start=window.end.isoformat()))
+ if pending is not None:
+ yield pending
+ else:
+ manager.safe_point()
+
+
+def _get_ids(session: requests.Session, base_url: str, path: str, data_key: str) -> list[Any]:
+ response = session.get(f"{base_url}{path}", timeout=REQUEST_TIMEOUT)
+ response.raise_for_status()
+ return [item["id"] for item in response.json().get(data_key, []) if item.get("id") is not None]
+
+
+def _iter_list_users(session: requests.Session, base_url: str) -> Iterator[list[dict[str, Any]]]:
+ for list_id in _get_ids(session, base_url, "/api/lists", "lists"):
+ with session.get(
+ f"{base_url}/api/lists/getUsers", params={"listId": list_id}, timeout=REQUEST_TIMEOUT, stream=True
+ ) as response:
+ response.raise_for_status()
+ batch: list[dict[str, Any]] = []
+ # One identifier per line: the email, or the userId for users without one.
+ for line in response.iter_lines():
+ user = line.decode("utf-8").strip()
+ if not user:
+ continue
+ batch.append({"listId": list_id, "email": user})
+ if len(batch) >= CHUNK_SIZE:
+ yield batch
+ batch = []
+ if batch:
+ yield batch
+
+
+def _parse_campaign_metrics_csv(text: str) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for row in csv.DictReader(io.StringIO(text)):
+ record: dict[str, Any] = {key: (value if value != "" else None) for key, value in row.items() if key}
+ # Cast the id so it joins to the integer `campaigns.id`.
+ campaign_id = record.get("id")
+ if isinstance(campaign_id, str) and campaign_id.isdigit():
+ record["id"] = int(campaign_id)
+ rows.append(record)
+ return rows
+
+
+def _iter_campaign_metrics(session: requests.Session, base_url: str) -> Iterator[list[dict[str, Any]]]:
+ campaign_ids = _get_ids(session, base_url, "/api/campaigns", "campaigns")
+ for offset in range(0, len(campaign_ids), CAMPAIGN_METRICS_BATCH_SIZE):
+ batch_ids = campaign_ids[offset : offset + CAMPAIGN_METRICS_BATCH_SIZE]
+ response = session.get(
+ f"{base_url}/api/campaigns/metrics",
+ params=[("campaignId", campaign_id) for campaign_id in batch_ids],
+ timeout=REQUEST_TIMEOUT,
+ )
+ response.raise_for_status()
+ rows = _parse_campaign_metrics_csv(response.text)
+ if rows:
+ yield rows
+
+
+def _make_session(api_key: str) -> requests.Session:
+ # `requests` only strips `Authorization` on a cross-host redirect, so a redirect would replay the
+ # Api-Key header to the new host.
+ return make_tracked_session(
+ retry=RATE_LIMITED_RETRY,
+ headers=_api_key_headers(api_key),
+ redact_values=(api_key,),
+ allow_redirects=False,
+ )
+
+
+def _export_source_response(
+ api_key: str,
+ base_url: str,
+ endpoint: str,
+ resumable_source_manager: ResumableSourceManager[IterableResumeConfig],
+ db_incremental_field_last_value: Any,
+) -> SourceResponse:
+ config = ITERABLE_EXPORT_ENDPOINTS[endpoint]
+ partition_key = config.cursor_field if config.partition_by_cursor else None
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _iter_export(
+ _make_session(api_key), base_url, config, resumable_source_manager, db_incremental_field_last_value
+ ),
+ primary_keys=None,
+ partition_count=1 if partition_key else None,
+ partition_size=1 if partition_key else None,
+ partition_mode="datetime" if partition_key else None,
+ partition_format="month" if partition_key else None,
+ partition_keys=[partition_key] if partition_key else None,
+ sort_mode="asc",
+ )
+
+
def iterable_source(
api_key: str,
region: str | None,
@@ -115,9 +345,31 @@ def iterable_source(
resumable_source_manager: ResumableSourceManager[IterableResumeConfig],
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
- config = ITERABLE_ENDPOINTS[endpoint]
base_url = base_url_for_region(region)
+ if endpoint in ITERABLE_EXPORT_ENDPOINTS:
+ return _export_source_response(
+ api_key, base_url, endpoint, resumable_source_manager, db_incremental_field_last_value
+ )
+
+ if endpoint == CAMPAIGN_METRICS:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _iter_campaign_metrics(_make_session(api_key), base_url),
+ primary_keys=FAN_OUT_PRIMARY_KEYS[endpoint],
+ supports_resume=False,
+ )
+
+ if endpoint == LIST_USERS:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _iter_list_users(_make_session(api_key), base_url),
+ primary_keys=FAN_OUT_PRIMARY_KEYS[endpoint],
+ supports_resume=False,
+ )
+
+ config = ITERABLE_ENDPOINTS[endpoint]
+
rest_config: RESTAPIConfig = {
"client": {
"base_url": base_url,
@@ -145,7 +397,7 @@ def iterable_source(
resume = resumable_source_manager.load_state()
# Only resume from a same-origin URL. A resume URL pointing off-host (corrupted/poisoned
# state) must not be requested with the Api-Key header — start from the top instead.
- if resume is not None and _is_same_origin(base_url, resume.next_url):
+ if resume is not None and resume.next_url and _is_same_origin(base_url, resume.next_url):
initial_paginator_state = {"next_url": resume.next_url}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/settings.py
index 875099e09703..2b0487d012ee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/settings.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass, field
-from products.warehouse_sources.backend.types import IncrementalField
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@dataclass
@@ -12,12 +12,21 @@ class IterableEndpointConfig:
incremental_fields: list[IncrementalField] = field(default_factory=list)
+@dataclass(frozen=True)
+class IterableExportEndpointConfig:
+ name: str
+ data_type_name: str # `dataTypeName` passed to `/api/export/data.json`
+ # The timestamp `startDateTime`/`endDateTime` filter on: event time for events, last profile
+ # update for users.
+ cursor_field: str = "createdAt"
+ # Event time never changes, so it is a stable partition key. `profileUpdatedAt` is not.
+ partition_by_cursor: bool = True
+
+
# 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.
+# an "incremental" sync would still have to read every row each run.
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"),
@@ -28,8 +37,111 @@ ITERABLE_ENDPOINTS: dict[str, IterableEndpointConfig] = {
),
}
-ENDPOINTS = tuple(ITERABLE_ENDPOINTS.keys())
+# Fan-out endpoints that return CSV / plain text rather than JSON, so they bypass the REST framework.
+CAMPAIGN_METRICS = "campaign_metrics"
+LIST_USERS = "list_users"
+
+FAN_OUT_PRIMARY_KEYS: dict[str, list[str]] = {
+ # One row per campaign with its lifetime metrics.
+ CAMPAIGN_METRICS: ["id"],
+ # A user can belong to many lists, so the list id is part of the key.
+ LIST_USERS: ["listId", "email"],
+}
+
+
+def _export(name: str, data_type_name: str) -> IterableExportEndpointConfig:
+ return IterableExportEndpointConfig(name=name, data_type_name=data_type_name)
+
+
+# Every `dataTypeName` the Export API documents, except `unknownSession`.
+ITERABLE_EXPORT_ENDPOINTS: dict[str, IterableExportEndpointConfig] = {
+ config.name: config
+ for config in [
+ _export("email_send", "emailSend"),
+ _export("email_open", "emailOpen"),
+ _export("email_click", "emailClick"),
+ _export("email_bounce", "emailBounce"),
+ _export("email_complaint", "emailComplaint"),
+ _export("email_send_skip", "emailSendSkip"),
+ _export("email_subscribe", "emailSubscribe"),
+ _export("email_unsubscribe", "emailUnSubscribe"),
+ _export("hosted_unsubscribe_click", "hostedUnsubscribeClick"),
+ _export("push_send", "pushSend"),
+ _export("push_open", "pushOpen"),
+ _export("push_uninstall", "pushUninstall"),
+ _export("push_bounce", "pushBounce"),
+ _export("push_send_skip", "pushSendSkip"),
+ _export("in_app_send", "inAppSend"),
+ _export("in_app_open", "inAppOpen"),
+ _export("in_app_click", "inAppClick"),
+ _export("in_app_close", "inAppClose"),
+ _export("in_app_delete", "inAppDelete"),
+ _export("in_app_delivery", "inAppDelivery"),
+ _export("in_app_send_skip", "inAppSendSkip"),
+ _export("in_app_recall", "inAppRecall"),
+ _export("inbox_session", "inboxSession"),
+ _export("inbox_message_impression", "inboxMessageImpression"),
+ _export("sms_send", "smsSend"),
+ _export("sms_bounce", "smsBounce"),
+ _export("sms_click", "smsClick"),
+ _export("sms_received", "smsReceived"),
+ _export("sms_send_skip", "smsSendSkip"),
+ _export("sms_usage_info", "smsUsageInfo"),
+ _export("web_push_send", "webPushSend"),
+ _export("web_push_click", "webPushClick"),
+ _export("web_push_send_skip", "webPushSendSkip"),
+ _export("embedded_send", "embeddedSend"),
+ _export("embedded_send_skip", "embeddedSendSkip"),
+ _export("embedded_click", "embeddedClick"),
+ _export("embedded_received", "embeddedReceived"),
+ _export("embedded_impression", "embeddedImpression"),
+ _export("embedded_session", "embeddedSession"),
+ _export("whatsapp_send", "whatsAppSend"),
+ _export("whatsapp_send_skip", "whatsAppSendSkip"),
+ _export("whatsapp_bounce", "whatsAppBounce"),
+ _export("whatsapp_click", "whatsAppClick"),
+ _export("whatsapp_received", "whatsAppReceived"),
+ _export("whatsapp_seen", "whatsAppSeen"),
+ _export("whatsapp_usage_info", "whatsAppUsageInfo"),
+ _export("journey_exit", "journeyExit"),
+ _export("purchase", "purchase"),
+ _export("custom_event", "customEvent"),
+ IterableExportEndpointConfig(
+ name="users", data_type_name="user", cursor_field="profileUpdatedAt", partition_by_cursor=False
+ ),
+ ]
+}
+
+# First sync of an export table, and every full refresh, starts this far back. Iterable has no
+# cheap way to find a project's earliest event, and walking back to its founding would spend the
+# export rate limit on empty windows.
+DEFAULT_EXPORT_LOOKBACK_DAYS = 365
+
+ENDPOINTS = (
+ *ITERABLE_ENDPOINTS.keys(),
+ CAMPAIGN_METRICS,
+ LIST_USERS,
+ *ITERABLE_EXPORT_ENDPOINTS.keys(),
+)
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
- name: config.incremental_fields for name, config in ITERABLE_ENDPOINTS.items()
+ **{name: config.incremental_fields for name, config in ITERABLE_ENDPOINTS.items()},
+ **{
+ name: [
+ {
+ "label": config.cursor_field,
+ "type": IncrementalFieldType.DateTime,
+ "field": config.cursor_field,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+ for name, config in ITERABLE_EXPORT_ENDPOINTS.items()
+ },
}
+
+# Export rows carry no unique id to merge on, so the export tables append rather than merge.
+APPEND_ONLY_ENDPOINTS = frozenset(ITERABLE_EXPORT_ENDPOINTS)
+
+# All export tables share one per-project rate limit of a few requests a minute, so they start
+# disabled and the user picks the ones they need.
+SHOULD_SYNC_DEFAULT: dict[str, bool] = dict.fromkeys(ITERABLE_EXPORT_ENDPOINTS, False)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/source.py
index 2a469ff14c05..c9531b0f407a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/source.py
@@ -29,8 +29,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.iterable.i
validate_credentials as validate_iterable_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.iterable.settings import (
+ APPEND_ONLY_ENDPOINTS,
ENDPOINTS,
INCREMENTAL_FIELDS,
+ SHOULD_SYNC_DEFAULT,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -72,7 +74,13 @@ class IterableSource(ResumableSource[IterableSourceConfig, IterableResumeConfig]
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ append_only=APPEND_ONLY_ENDPOINTS,
+ should_sync_default=SHOULD_SYNC_DEFAULT,
+ )
def validate_credentials(
self,
@@ -102,7 +110,9 @@ class IterableSource(ResumableSource[IterableSourceConfig, IterableResumeConfig]
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
- db_incremental_field_last_value=None, # every Iterable endpoint is full refresh
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
@property
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/tests/test_iterable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/tests/test_iterable.py
index 67cdd4bb14d1..45b757124699 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/tests/test_iterable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/tests/test_iterable.py
@@ -1,7 +1,9 @@
import json
+from datetime import UTC, datetime
from typing import Any
import pytest
+import time_machine
from unittest import mock
from requests import Response
@@ -9,6 +11,7 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
from products.warehouse_sources.backend.temporal.data_imports.sources.iterable.iterable import (
IterableResumeConfig,
+ _parse_iterable_datetime,
_resolve_next_url,
base_url_for_region,
iterable_source,
@@ -28,6 +31,19 @@ def _response(body: dict[str, Any]) -> Response:
return resp
+def _text_response(text: str) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp.encoding = "utf-8"
+ resp._content = text.encode()
+ resp._content_consumed = True # type: ignore[attr-defined]
+ return resp
+
+
+def _ndjson(rows: list[dict[str, Any]]) -> Response:
+ return _text_response("\n".join(json.dumps(row) for row in rows))
+
+
def _make_manager(resume_state: IterableResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -266,3 +282,205 @@ class TestIterableSource:
assert response.name == endpoint
assert response.primary_keys == [expected_pk]
assert response.primary_keys == [ITERABLE_ENDPOINTS[endpoint].primary_key]
+
+
+class TestParseIterableDatetime:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("2024-01-31 18:04:05 +00:00", datetime(2024, 1, 31, 18, 4, 5, tzinfo=UTC)),
+ ("2024-01-31 18:04:05.250 +00:00", datetime(2024, 1, 31, 18, 4, 5, 250000, tzinfo=UTC)),
+ ("2024-01-31 20:04:05 +02:00", datetime(2024, 1, 31, 18, 4, 5, tzinfo=UTC)),
+ ("2024-01-31 18:04:05", datetime(2024, 1, 31, 18, 4, 5, tzinfo=UTC)),
+ ("not a date", "not a date"),
+ (1706724245000, 1706724245000),
+ (None, None),
+ ],
+ )
+ def test_parse(self, value: Any, expected: Any) -> None:
+ assert _parse_iterable_datetime(value) == expected
+
+
[email protected](f"{MODULE}.time.sleep")
[email protected](f"{MODULE}.make_tracked_session")
+class TestExport:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(datetime(2024, 3, 1, tzinfo=UTC), tick=False):
+ yield
+
+ def test_walks_windows_from_watermark_and_stages_next_window_before_its_last_batch(
+ self, mock_session, mock_sleep
+ ) -> None:
+ session = mock_session.return_value
+ session.get.side_effect = [
+ _ndjson([{"email": "[email protected]", "createdAt": "2024-01-20 10:00:00 +00:00"}]),
+ _ndjson([{"email": "[email protected]", "createdAt": "2024-02-25 09:30:00 +00:00"}]),
+ ]
+ manager = _make_manager()
+ response = iterable_source(
+ "key",
+ "eu",
+ "email_send",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=datetime(2024, 1, 15, tzinfo=UTC),
+ )
+ events: list[str] = []
+ manager.save_state.side_effect = lambda state: events.append(f"save {state.export_window_start}")
+ batches: Any = response.items()
+ for batch in batches:
+ events.append(f"yield {batch[0]['email']}")
+
+ assert [call.args[0] for call in session.get.call_args_list] == [
+ "https://api.eu.iterable.com/api/export/data.json"
+ ] * 2
+ assert [call.kwargs["params"] for call in session.get.call_args_list] == [
+ {
+ "dataTypeName": "emailSend",
+ "startDateTime": "2024-01-15 00:00:00 +00:00",
+ "endDateTime": "2024-02-14 00:00:00 +00:00",
+ },
+ {
+ "dataTypeName": "emailSend",
+ "startDateTime": "2024-02-14 00:00:00 +00:00",
+ "endDateTime": "2024-03-01 00:00:00 +00:00",
+ },
+ ]
+ assert events == ["save 2024-02-14T00:00:00+00:00", "yield [email protected]", "yield [email protected]"]
+ mock_sleep.assert_called_once()
+
+ def test_parses_cursor_field_into_datetime(self, mock_session, mock_sleep) -> None:
+ mock_session.return_value.get.side_effect = [
+ _ndjson([{"email": "[email protected]", "profileUpdatedAt": "2024-02-20 10:00:00 +00:00"}])
+ ]
+ response = iterable_source(
+ "key",
+ "us",
+ "users",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ db_incremental_field_last_value=datetime(2024, 2, 10, tzinfo=UTC),
+ )
+
+ assert _rows(response) == [
+ {"email": "[email protected]", "profileUpdatedAt": datetime(2024, 2, 20, 10, tzinfo=UTC)}
+ ]
+
+ @pytest.mark.parametrize(
+ "last_value, resume_state, expected_start",
+ [
+ (None, None, "2023-03-02 00:00:00 +00:00"),
+ ("2024-02-20 12:00:00 +00:00", None, "2024-02-20 12:00:00 +00:00"),
+ (
+ datetime(2024, 2, 20, tzinfo=UTC),
+ IterableResumeConfig(export_window_start="2024-02-10T00:00:00+00:00"),
+ "2024-02-10 00:00:00 +00:00",
+ ),
+ ],
+ )
+ def test_first_window_start(
+ self, mock_session, mock_sleep, last_value: Any, resume_state: Any, expected_start: str
+ ) -> None:
+ session = mock_session.return_value
+ session.get.side_effect = lambda *args, **kwargs: _ndjson([])
+
+ _run_rows = _rows(
+ iterable_source(
+ "key",
+ "us",
+ "purchase",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(resume_state),
+ db_incremental_field_last_value=last_value,
+ )
+ )
+
+ assert _run_rows == []
+ assert session.get.call_args_list[0].kwargs["params"]["startDateTime"] == expected_start
+
+ def test_empty_window_reaches_safe_point(self, mock_session, mock_sleep) -> None:
+ mock_session.return_value.get.side_effect = [_ndjson([])]
+ manager = _make_manager()
+
+ rows = _rows(
+ iterable_source(
+ "key",
+ "us",
+ "email_open",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=datetime(2024, 2, 20, tzinfo=UTC),
+ )
+ )
+
+ assert rows == []
+ manager.safe_point.assert_called_once()
+ manager.save_state.assert_not_called()
+
+
[email protected](f"{MODULE}.make_tracked_session")
+class TestFanOut:
+ def test_list_users_carries_list_id_and_skips_blank_lines(self, mock_session) -> None:
+ session = mock_session.return_value
+ session.get.side_effect = [
+ _response({"lists": [{"id": 11}, {"id": 12}]}),
+ _text_response("[email protected]\n\[email protected]\n"),
+ _text_response("[email protected]\n"),
+ ]
+
+ rows = _rows(
+ iterable_source("key", "us", "list_users", team_id=1, job_id="j", resumable_source_manager=_make_manager())
+ )
+
+ assert rows == [
+ {"listId": 11, "email": "[email protected]"},
+ {"listId": 11, "email": "[email protected]"},
+ {"listId": 12, "email": "[email protected]"},
+ ]
+ assert [call.kwargs.get("params") for call in session.get.call_args_list[1:]] == [
+ {"listId": 11},
+ {"listId": 12},
+ ]
+
+ def test_campaign_metrics_batches_campaign_ids_and_parses_csv(self, mock_session) -> None:
+ session = mock_session.return_value
+ session.get.side_effect = [
+ _response({"campaigns": [{"id": i} for i in range(1, 102)]}),
+ _text_response("id,Total Email Sends,Unique Email Opens\n1,100,40\n2,50,\n"),
+ _text_response("id,Total Email Sends,Unique Email Opens\n101,7,3\n"),
+ ]
+
+ rows = _rows(
+ iterable_source(
+ "key", "us", "campaign_metrics", team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+ )
+
+ assert rows == [
+ {"id": 1, "Total Email Sends": "100", "Unique Email Opens": "40"},
+ {"id": 2, "Total Email Sends": "50", "Unique Email Opens": None},
+ {"id": 101, "Total Email Sends": "7", "Unique Email Opens": "3"},
+ ]
+ metrics_params = [call.kwargs["params"] for call in session.get.call_args_list[1:]]
+ assert metrics_params == [
+ [("campaignId", i) for i in range(1, 101)],
+ [("campaignId", 101)],
+ ]
+
+ def test_campaign_metrics_with_no_campaigns_makes_no_metrics_request(self, mock_session) -> None:
+ session = mock_session.return_value
+ session.get.side_effect = [_response({"campaigns": []})]
+
+ rows = _rows(
+ iterable_source(
+ "key", "us", "campaign_metrics", team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+ )
+
+ assert rows == []
+ assert session.get.call_count == 1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/tests/test_iterable_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/tests/test_iterable_source.py
index 671c2e18ae57..a0411dc97b2e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/tests/test_iterable_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/iterable/tests/test_iterable_source.py
@@ -4,7 +4,10 @@ from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.iterable import (
IterableSourceConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.iterable.settings import INCREMENTAL_FIELDS
+from products.warehouse_sources.backend.temporal.data_imports.sources.iterable.settings import (
+ INCREMENTAL_FIELDS,
+ ITERABLE_EXPORT_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.iterable.source import IterableSource
@@ -38,13 +41,18 @@ class TestIterableSource:
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_are_full_refresh(self):
- # No Iterable list endpoint exposes a verified server-side timestamp filter,
- # so everything is full refresh (no incremental / append).
+ def test_get_schemas_sync_modes(self):
for schema in self.source.get_schemas(self.config, self.team_id):
+ # Export rows have no unique id to merge on, so they never offer incremental merge.
assert schema.supports_incremental is False
- assert schema.supports_append is False
- assert schema.incremental_fields == INCREMENTAL_FIELDS[schema.name] == []
+ if schema.name in ITERABLE_EXPORT_ENDPOINTS:
+ assert schema.supports_append is True
+ assert schema.should_sync_default is False
+ assert schema.incremental_fields == INCREMENTAL_FIELDS[schema.name] != []
+ else:
+ assert schema.supports_append is False
+ assert schema.should_sync_default is True
+ assert schema.incremental_fields == []
@pytest.mark.parametrize(
"mock_return, expected_valid, expected_message",