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(emailoctopus): add campaign report and list tag tables (#107280)

Tom Owerse227eda5ee8a
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 611f22e788e2..a31a07908749 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
@@ -2842,14 +2842,14 @@ Note: Official spec is large (277 paths); the ConvAI surface is the bulk of it.
## EmailOctopus — gaps
-Today (3): `campaigns`, `contacts`, `lists`
+Today (7): `campaign_report_links`, `campaign_report_summaries`, `campaign_reports`, `campaigns`, `contacts`, `list_tags`, `lists`
Diffed against: <https://emailoctopus.com/api-documentation/v2>
-- [ ] `/campaigns/{campaign_id}/reports/summary` — headline campaign metrics (sent, opened, clicked, bounced, complained, unsubscribed) — currently no campaign performance data at all (high)
-- [ ] `/campaigns/{campaign_id}/reports?status={sent|opened|clicked|bounced|complained|unsubscribed|not-opened|not-clicked}` — per-contact campaign engagement events, the join between campaigns and contacts (high)
-- [ ] `/campaigns/{campaign_id}/reports/links` — per-link click breakdown for a campaign (medium)
-- [ ] `/lists/{list_id}/tags` — tag lookup resolving the tags carried on the contacts we already sync (medium)
+- [x] `/campaigns/{campaign_id}/reports/summary` — headline campaign metrics (sent, opened, clicked, bounced, complained, unsubscribed) — currently no campaign performance data at all (high)
+- [x] `/campaigns/{campaign_id}/reports?status={sent|opened|clicked|bounced|complained|unsubscribed|not-opened|not-clicked}` — per-contact campaign engagement events, the join between campaigns and contacts (high)
+- [x] `/campaigns/{campaign_id}/reports/links` — per-link click breakdown for a campaign (medium)
+- [x] `/lists/{list_id}/tags` — tag lookup resolving the tags carried on the contacts we already sync (medium)
Note: The docs URL serves the raw OpenAPI 3.1 JSON directly. The v2 API GET surface is only lists, campaigns, contacts and the campaign reports — contacts are already synced via /lists/{list_id}/contacts, so list membership is covered. Automations are write-only (POST queue), so there is nothing to sync there.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/canonical_descriptions.py
index 8a20ac205a56..cb8d561cceb8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/canonical_descriptions.py
@@ -47,4 +47,46 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"last_updated_at": "ISO 8601 timestamp of when the contact was last updated.",
},
},
+ "campaign_reports": {
+ "description": "Per-contact engagement events for a campaign, materialized one row per (campaign, status, contact). Each documented report status is fetched separately and the status is attached to the row.",
+ "docs_url": "https://emailoctopus.com/api-documentation/v2",
+ "columns": {
+ "campaign_id": "Identifier of the campaign the report covers.",
+ "status": "Report status the row belongs to: sent, opened, clicked, bounced, complained, unsubscribed, not-opened or not-clicked.",
+ "contact_id": "Identifier of the contact the event relates to.",
+ "contact_email_address": "Email address of the contact the event relates to.",
+ "occurred_at": "ISO 8601 timestamp of when the event occurred.",
+ },
+ },
+ "campaign_report_summaries": {
+ "description": "Headline performance metrics for a campaign, one row per campaign that has started sending.",
+ "docs_url": "https://emailoctopus.com/api-documentation/v2",
+ "columns": {
+ "id": "Identifier of the campaign the summary covers.",
+ "sent": "Number of contacts the campaign was sent to.",
+ "bounced": "Bounce counts, split into hard and soft bounces.",
+ "opened": "Open counts, split into total opens and unique openers.",
+ "clicked": "Click counts, split into total clicks and unique clickers.",
+ "complained": "Number of contacts who marked the campaign as spam.",
+ "unsubscribed": "Number of contacts who unsubscribed from the campaign.",
+ },
+ },
+ "campaign_report_links": {
+ "description": "Click performance of each link in a campaign, one row per (campaign, link URL).",
+ "docs_url": "https://emailoctopus.com/api-documentation/v2",
+ "columns": {
+ "campaign_id": "Identifier of the campaign the link appeared in.",
+ "url": "Destination URL of the link.",
+ "clicked_total": "Number of total clicks on the link.",
+ "clicked_unique": "Number of contacts who clicked the link at least once.",
+ },
+ },
+ "list_tags": {
+ "description": "Tags defined on a list, one row per (list, tag). Resolves the tags carried on contact rows.",
+ "docs_url": "https://emailoctopus.com/api-documentation/v2",
+ "columns": {
+ "list_id": "Identifier of the list the tag is defined on.",
+ "tag": "Name of the tag.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/emailoctopus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/emailoctopus.py
index c948f41b6d46..006ba4197aef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/emailoctopus.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/emailoctopus.py
@@ -1,5 +1,5 @@
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
@@ -11,15 +11,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
JSONResponsePaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
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.emailoctopus.settings import (
- CONTACT_STATUSES,
EMAILOCTOPUS_ENDPOINTS,
EmailOctopusEndpointConfig,
+ EmailOctopusFanOut,
)
EMAILOCTOPUS_BASE_URL = "https://api.emailoctopus.com"
@@ -47,14 +52,14 @@ def _base_url_for_version(api_version: str) -> str:
return _BASE_URL_BY_VERSION.get(api_version, EMAILOCTOPUS_BASE_URL)
[email protected](frozen=True)
class EmailOctopusResumeConfig:
# Full next-page URL returned by the API (`paging.next.url`). Followed verbatim so the original
# query string — including any incremental time filter — is preserved across a resume. None means
# "start this list at its first page".
next_url: str | None = None
- # Legacy fan-out bookmark fields. The contacts fan-out is now a composed set of single-hop
- # dependent resources whose retries re-fetch (the [list_id, id] merge key dedupes), so these are
+ # Legacy fan-out bookmark fields. Fan-out endpoints are now composed sets of single-hop
+ # dependent resources whose retries re-fetch (the composite merge key dedupes), so these are
# no longer written. They are kept — with defaults — so any state persisted by the previous
# implementation still deserializes via ``dataclass(**saved)`` on resume.
list_id: str | None = None
@@ -73,8 +78,17 @@ def _format_incremental_value(value: Any) -> str:
return str(value)
-def _build_contact_params(status: str, incremental_field: str | None, filter_value: str | None) -> dict[str, Any]:
- params: dict[str, Any] = {"limit": PAGE_SIZE, "status": status}
+def _build_child_params(
+ fanout: EmailOctopusFanOut,
+ status: str | None,
+ incremental_field: str | None,
+ filter_value: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if fanout.paginated:
+ params["limit"] = PAGE_SIZE
+ if status is not None:
+ params["status"] = status
if incremental_field and filter_value:
# Server-side incremental filter, e.g. last_updated_at.gte=2024-01-19T12:14:28Z.
params[f"{incremental_field}.gte"] = filter_value
@@ -95,15 +109,43 @@ def _client_config(api_key: str, base_url: str) -> ClientConfig:
"base_url": base_url,
"headers": _HEADERS,
"auth": {"type": "bearer", "token": api_key},
+ # Pin every request to the API host and refuse redirects: the bearer header carries the
+ # customer's API key, so a spoofed `paging.next.url` or a cross-origin 3xx must not carry
+ # that credential off-host (SSRF). `allowed_hosts=[]` means "same host as base_url only",
+ # and covers paginator and resume URLs, both of which this source follows verbatim.
+ "allowed_hosts": [],
+ "allow_redirects": False,
}
-def _rename_list_id(row: dict[str, Any]) -> dict[str, Any]:
- # `include_from_parent=["id"]` injects the parent list's id as `_lists_id`; expose it as `list_id`
- # so contact rows carry the exact same field the previous implementation attached.
- if "_lists_id" in row:
- row["list_id"] = row.pop("_lists_id")
- return row
+def _rename_parent_id(fanout: EmailOctopusFanOut) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ # `include_from_parent=["id"]` injects the parent's id as `_<parent>_id`; expose it under the
+ # name the endpoint's own path parameter uses, e.g. `list_id` or `campaign_id`.
+ injected_key = f"_{fanout.parent}_id"
+
+ def _mapper(row: dict[str, Any]) -> dict[str, Any]:
+ if injected_key in row:
+ row[fanout.param] = row.pop(injected_key)
+ return row
+
+ return _mapper
+
+
+def _parent_status_filter(allowed: tuple[str, ...]) -> Callable[[dict[str, Any]], bool]:
+ def _predicate(row: dict[str, Any]) -> bool:
+ return row.get("status") in allowed
+
+ return _predicate
+
+
+def _attach_status(status: str) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ # The reports endpoint states the status once on the envelope, which `data_selector` drops, so
+ # the rows of each status walk have to carry it themselves to stay distinguishable.
+ def _mapper(row: dict[str, Any]) -> dict[str, Any]:
+ row["status"] = status
+ return row
+
+ return _mapper
def _top_level_resource(
@@ -152,7 +194,7 @@ def _top_level_resource(
)
-def _contacts_items(
+def _fan_out_items(
api_key: str,
base_url: str,
config: EmailOctopusEndpointConfig,
@@ -162,58 +204,71 @@ def _contacts_items(
db_incremental_field_last_value: Any,
incremental_field: str | None,
) -> Iterator[list[dict[str, Any]]]:
- """Fan out over every list and contact status, attaching each contact's `list_id`.
+ """Fan out over every parent row, attaching each child row's parent id.
- Contacts are nested under lists and the API returns one status at a time, so each status is its
- own single-hop parent(lists)->child(contacts) fan-out; the results are concatenated. A list
- deleted between enumeration and the child fetch 404s, which is ignored per (list, status) via
- `response_actions` rather than failing the whole sync. The [list_id, id] merge key keeps a single
- row per contact across statuses and dedupes any rows re-fetched on a retry.
+ Endpoints nested under a list or a campaign are driven as a single-hop parent->child fan-out.
+ An endpoint that serves one status per request gets one such fan-out per status, concatenated.
+ A parent deleted between enumeration and the child fetch 404s, which is ignored per (parent,
+ status) via `response_actions` rather than failing the whole sync.
"""
+ fanout = config.fanout
+ assert fanout is not None
+
filter_field = incremental_field if should_use_incremental_field else None
filter_value = (
_format_incremental_value(db_incremental_field_last_value)
if should_use_incremental_field and db_incremental_field_last_value and incremental_field
else None
)
+ parent_path = EMAILOCTOPUS_ENDPOINTS[fanout.parent].path
- for status in CONTACT_STATUSES:
- contact_params: dict[str, Any] = {
- "list_id": {"type": "resolve", "resource": "lists", "field": "id"},
- **_build_contact_params(status, filter_field, filter_value),
+ for status in fanout.statuses or (None,):
+ child_name = f"{config.name}_{status}" if status is not None else config.name
+ child_params: dict[str, Any] = {
+ fanout.param: {"type": "resolve", "resource": fanout.parent, "field": "id"},
+ **_build_child_params(fanout, status, filter_field, filter_value),
+ }
+ child_endpoint: Endpoint = {
+ "path": config.path,
+ "params": child_params,
+ "data_selector": "$" if fanout.single_object else "data",
+ "paginator": JSONResponsePaginator(next_url_path=_NEXT_URL_PATH)
+ if fanout.paginated
+ else SinglePagePaginator(),
+ # A parent deleted mid-fan-out 404s; treat it as an empty result for this (parent,
+ # status) and move on instead of failing the sync.
+ "response_actions": [{"status_code": 404, "action": "ignore"}],
}
+ child_resource: EndpointResource = {"name": child_name, "endpoint": child_endpoint}
+ if fanout.attach_parent_id:
+ child_resource["include_from_parent"] = ["id"]
+
rest_config: RESTAPIConfig = {
"client": _client_config(api_key, base_url),
"resource_defaults": {},
"resources": [
{
- "name": "lists",
+ "name": fanout.parent,
"endpoint": {
- "path": "/lists",
+ "path": parent_path,
"params": {"limit": PAGE_SIZE},
"data_selector": "data",
"paginator": JSONResponsePaginator(next_url_path=_NEXT_URL_PATH),
},
},
- {
- "name": f"contacts_{status}",
- "include_from_parent": ["id"],
- "endpoint": {
- "path": config.path,
- "params": contact_params,
- "data_selector": "data",
- "paginator": JSONResponsePaginator(next_url_path=_NEXT_URL_PATH),
- # A list deleted mid-fan-out 404s; treat it as an empty result for this
- # (list, status) and move on instead of failing the sync.
- "response_actions": [{"status_code": 404, "action": "ignore"}],
- },
- },
+ child_resource,
],
}
resources = rest_api_resources(rest_config, team_id, job_id, None)
- child = next(r for r in resources if getattr(r, "name", None) == f"contacts_{status}")
- child.add_map(_rename_list_id)
+ by_name = {getattr(r, "name", None): r for r in resources}
+ if fanout.parent_statuses:
+ by_name[fanout.parent].add_filter(_parent_status_filter(fanout.parent_statuses))
+ child = by_name[child_name]
+ if fanout.attach_parent_id:
+ child.add_map(_rename_parent_id(fanout))
+ if fanout.inject_status and status is not None:
+ child.add_map(_attach_status(status))
yield from child
@@ -231,8 +286,8 @@ def emailoctopus_source(
endpoint_config = EMAILOCTOPUS_ENDPOINTS[endpoint]
base_url = _base_url_for_version(api_version)
- if endpoint_config.fan_out_over_lists:
- items: Any = lambda: _contacts_items(
+ if endpoint_config.fanout is not None:
+ items: Any = lambda: _fan_out_items(
api_key,
base_url,
endpoint_config,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/settings.py
index eba653fef41d..502dee528a6e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/settings.py
@@ -4,10 +4,36 @@ from typing import Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
+class EmailOctopusFanOut:
+ """How a child endpoint is driven from the rows of a parent endpoint."""
+
+ # Endpoint whose rows supply the path parameter, e.g. "lists" or "campaigns".
+ parent: str
+ # Path placeholder to resolve, and the column the parent id is attached to on child rows.
+ param: str
+ # Statuses the endpoint serves one at a time, each needing its own paginated walk. Empty means
+ # the endpoint takes no status.
+ statuses: tuple[str, ...] = ()
+ # Whether the status the request asked for has to be attached to the rows. The reports endpoint
+ # returns it once on the envelope rather than on each row.
+ inject_status: bool = False
+ # Whether child rows need the parent id attached. False when the response already carries it.
+ attach_parent_id: bool = True
+ # Whether the endpoint accepts `limit` / `starting_after`. False means it returns the whole
+ # collection in one response, so sending a page-size param would be undocumented.
+ paginated: bool = True
+ # Whether the response body is itself the row rather than a `data` collection.
+ single_object: bool = False
+ # Parent statuses worth fanning out over. Empty means every parent row.
+ parent_statuses: tuple[str, ...] = ()
+
+
+@dataclass(frozen=True)
class EmailOctopusEndpointConfig:
name: str
- # Path on the v2 API. For fan-out endpoints this is a template with a `{list_id}` placeholder.
+ # Path on the v2 API. For fan-out endpoints this is a template with a `{list_id}` or
+ # `{campaign_id}` placeholder.
path: str
incremental_fields: list[IncrementalField]
# A stable creation-time field used for datetime partitioning. Never `last_updated_at`,
@@ -15,9 +41,8 @@ class EmailOctopusEndpointConfig:
partition_key: Optional[str] = None
primary_keys: list[str] = field(default_factory=lambda: ["id"])
should_sync_default: bool = True
- # Fan out one paginated request per synced list, materializing each list's contacts. When True,
- # `path` is a template with a `{list_id}` placeholder and rows carry their `list_id`.
- fan_out_over_lists: bool = False
+ # Set when the endpoint is nested under a parent resource and has to be fanned out over it.
+ fanout: Optional[EmailOctopusFanOut] = None
# EmailOctopus contacts carry a status and the API returns only `subscribed` contacts unless asked
@@ -26,6 +51,26 @@ class EmailOctopusEndpointConfig:
# latest status.
CONTACT_STATUSES = ("subscribed", "unsubscribed", "pending")
+# The campaign reports endpoint requires a status and serves one per request, so every documented
+# status gets its own walk. `not-opened` and `not-clicked` are the complements of `opened` and
+# `clicked` within `sent`; they are synced too so the table answers "who ignored this campaign"
+# without a second query.
+CAMPAIGN_REPORT_STATUSES = (
+ "sent",
+ "opened",
+ "clicked",
+ "bounced",
+ "complained",
+ "unsubscribed",
+ "not-opened",
+ "not-clicked",
+)
+
+# Only campaigns that have started sending have report data. Skipping drafts and errored campaigns
+# keeps the fan-out proportional to what actually went out, and avoids a per-draft request whose
+# rejection we could not tell apart from a genuinely malformed one.
+REPORTABLE_CAMPAIGN_STATUSES = ("sending", "sent")
+
def _datetime_field(name: str) -> IncrementalField:
return {
@@ -58,12 +103,72 @@ EMAILOCTOPUS_ENDPOINTS: dict[str, EmailOctopusEndpointConfig] = {
path="/lists/{list_id}/contacts",
partition_key="created_at",
primary_keys=["list_id", "id"],
- fan_out_over_lists=True,
+ fanout=EmailOctopusFanOut(parent="lists", param="list_id", statuses=CONTACT_STATUSES),
incremental_fields=[
_datetime_field("last_updated_at"),
_datetime_field("created_at"),
],
),
+ # Per-contact engagement events for a campaign — the join between campaigns and contacts.
+ # Off by default: it is the only table whose size scales with campaigns x contacts, and with no
+ # server-side time filter every sync is a full refresh of that whole product.
+ "campaign_reports": EmailOctopusEndpointConfig(
+ name="campaign_reports",
+ path="/campaigns/{campaign_id}/reports",
+ partition_key="occurred_at",
+ # The endpoint documents no per-event id. A contact appears once per status in the
+ # per-contact reading of the response; if it instead returns one row per raw event, repeat
+ # events for a contact collapse into the latest. The table is full refresh either way, so
+ # this key never has to reconcile rows across syncs.
+ primary_keys=["campaign_id", "status", "contact_id"],
+ should_sync_default=False,
+ # No server-side timestamp filter on the reports endpoint, so full refresh only.
+ incremental_fields=[],
+ fanout=EmailOctopusFanOut(
+ parent="campaigns",
+ param="campaign_id",
+ statuses=CAMPAIGN_REPORT_STATUSES,
+ inject_status=True,
+ parent_statuses=REPORTABLE_CAMPAIGN_STATUSES,
+ ),
+ ),
+ # Headline metrics for a campaign: one row per campaign, returned as a bare object.
+ "campaign_report_summaries": EmailOctopusEndpointConfig(
+ name="campaign_report_summaries",
+ path="/campaigns/{campaign_id}/reports/summary",
+ incremental_fields=[],
+ fanout=EmailOctopusFanOut(
+ parent="campaigns",
+ param="campaign_id",
+ # The summary body already carries the campaign id as `id`.
+ attach_parent_id=False,
+ paginated=False,
+ single_object=True,
+ parent_statuses=REPORTABLE_CAMPAIGN_STATUSES,
+ ),
+ ),
+ # Click totals per link in a campaign. The URL is what identifies a link — the endpoint exposes
+ # no link id — so it carries the key alongside the campaign.
+ "campaign_report_links": EmailOctopusEndpointConfig(
+ name="campaign_report_links",
+ path="/campaigns/{campaign_id}/reports/links",
+ primary_keys=["campaign_id", "url"],
+ incremental_fields=[],
+ fanout=EmailOctopusFanOut(
+ parent="campaigns",
+ param="campaign_id",
+ paginated=False,
+ parent_statuses=REPORTABLE_CAMPAIGN_STATUSES,
+ ),
+ ),
+ # Tag lookup resolving the tags carried on contact rows. A tag is named, not given an id.
+ "list_tags": EmailOctopusEndpointConfig(
+ name="list_tags",
+ path="/lists/{list_id}/tags",
+ primary_keys=["list_id", "tag"],
+ incremental_fields=[],
+ fanout=EmailOctopusFanOut(parent="lists", param="list_id"),
+ ),
}
ENDPOINTS = tuple(EMAILOCTOPUS_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus.py
index a2efe533e428..3d4fb217109a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus.py
@@ -13,15 +13,27 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.emailoctop
EMAILOCTOPUS_BASE_URL as BASE,
EmailOctopusResumeConfig,
_base_url_for_version,
- _build_contact_params,
+ _build_child_params,
_format_incremental_value,
emailoctopus_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.emailoctopus.settings import (
+ CAMPAIGN_REPORT_STATUSES,
EMAILOCTOPUS_ENDPOINTS,
+ EmailOctopusFanOut,
)
+
+def _fanout(endpoint: str) -> EmailOctopusFanOut:
+ fanout = EMAILOCTOPUS_ENDPOINTS[endpoint].fanout
+ assert fanout is not None
+ return fanout
+
+
+CONTACTS_FANOUT = _fanout("contacts")
+LINKS_FANOUT = _fanout("campaign_report_links")
+
# RESTClient builds its session via make_tracked_session in the rest_client module.
CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
# validate_credentials builds its own tracked session in the emailoctopus module.
@@ -112,15 +124,20 @@ class TestFormatIncrementalValue:
assert result.endswith("Z")
-class TestBuildContactParams:
+class TestBuildChildParams:
def test_status_only_when_no_incremental(self) -> None:
- params = _build_contact_params("subscribed", incremental_field=None, filter_value=None)
+ params = _build_child_params(CONTACTS_FANOUT, "subscribed", incremental_field=None, filter_value=None)
assert params == {"limit": 100, "status": "subscribed"}
def test_no_filter_when_value_missing(self) -> None:
- params = _build_contact_params("pending", incremental_field="created_at", filter_value=None)
+ params = _build_child_params(CONTACTS_FANOUT, "pending", incremental_field="created_at", filter_value=None)
assert "created_at.gte" not in params
+ def test_unpaginated_endpoint_sends_no_page_size(self) -> None:
+ # /campaigns/{id}/reports/links documents no limit/starting_after, so sending one would be
+ # an undocumented param on a request that always returns the whole collection.
+ assert _build_child_params(LINKS_FANOUT, None, incremental_field=None, filter_value=None) == {}
+
@parameterized.expand(
[
("last_updated", "last_updated_at", "last_updated_at.gte"),
@@ -128,7 +145,9 @@ class TestBuildContactParams:
]
)
def test_server_side_filter(self, _name: str, field: str, expected_param: str) -> None:
- params = _build_contact_params("subscribed", incremental_field=field, filter_value="2026-01-01T00:00:00Z")
+ params = _build_child_params(
+ CONTACTS_FANOUT, "subscribed", incremental_field=field, filter_value="2026-01-01T00:00:00Z"
+ )
assert params[expected_param] == "2026-01-01T00:00:00Z"
assert params["status"] == "subscribed"
@@ -226,6 +245,50 @@ class TestTopLevelPagination:
manager.save_state.assert_called_once_with(EmailOctopusResumeConfig(next_url=next_url))
+class TestHostPinning:
+ @parameterized.expand(
+ [
+ ("top_level", "lists", f"{BASE}/lists"),
+ ("fan_out_child", "list_tags", f"{BASE}/lists/L1/tags"),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_off_host_next_url_is_refused_before_the_request_goes_out(
+ self, _name: str, endpoint: str, paged_url: str, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ # Every request carries the customer's API key as a bearer header, and this source follows
+ # `paging.next.url` verbatim. A spoofed next URL must be refused before the credential
+ # leaves the process.
+ evil_url = "https://evil.example.com/lists?starting_after=cur1"
+ _wire(
+ session,
+ {
+ f"{BASE}/lists": _resp(
+ {
+ "data": [{"id": "L1"}],
+ "paging": {"next": {"url": evil_url if endpoint == "lists" else None}},
+ }
+ ),
+ paged_url: _resp({"data": [{"tag": "vip"}], "paging": {"next": {"url": evil_url}}}),
+ },
+ )
+
+ with pytest.raises(ValueError, match="disallowed host"):
+ _rows(_source(endpoint, _make_manager()))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_off_host_resume_url_is_refused(self, MockSession) -> None:
+ session = MockSession.return_value
+ # Resume state is read back from Redis, so a poisoned cursor is seeded straight into the
+ # paginator. Host pinning covers that seed too.
+ evil_url = "https://evil.example.com/campaigns?starting_after=cur5"
+ _wire(session, {evil_url: _resp({"data": [], "paging": {"next": None}})})
+
+ with pytest.raises(ValueError, match="disallowed host"):
+ _rows(_source("campaigns", _make_manager(EmailOctopusResumeConfig(next_url=evil_url))))
+
+
class TestContactsFanOut:
def _one_list_pages(self, contacts: dict[str, list[dict[str, Any]]]) -> dict[str, Any]:
pages: dict[str, Any] = {f"{BASE}/lists": _resp({"data": [{"id": "L1"}], "paging": {"next": None}})}
@@ -318,20 +381,170 @@ class TestContactsFanOut:
_rows(_source("contacts", _make_manager()))
+class TestCampaignReportsFanOut:
+ def _pages(
+ self,
+ campaigns: list[dict[str, Any]],
+ rows_by_status: dict[str, list[dict[str, Any]]] | None = None,
+ campaign_id: str = "C1",
+ ) -> dict[str, Any]:
+ pages: dict[str, Any] = {f"{BASE}/campaigns": _resp({"data": campaigns, "paging": {"next": None}})}
+ for status in CAMPAIGN_REPORT_STATUSES:
+ pages[f"{BASE}/campaigns/{campaign_id}/reports?status={status}"] = _resp(
+ {"status": status, "data": (rows_by_status or {}).get(status, []), "paging": {"next": None}}
+ )
+ return pages
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_attaches_campaign_id_and_the_requested_status(self, MockSession) -> None:
+ session = MockSession.return_value
+ # The envelope states the status once and `data_selector` drops it, so without the attach
+ # step the eight walks would be indistinguishable in the table.
+ _wire(
+ session,
+ self._pages(
+ [{"id": "C1", "status": "sent"}],
+ {"opened": [{"contact_id": "ct1", "occurred_at": "2026-01-02T03:04:05+00:00"}]},
+ ),
+ )
+ rows = _rows(_source("campaign_reports", _make_manager()))
+ assert rows == [
+ {
+ "contact_id": "ct1",
+ "occurred_at": "2026-01-02T03:04:05+00:00",
+ "campaign_id": "C1",
+ "status": "opened",
+ }
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_requests_every_documented_status(self, MockSession) -> None:
+ session = MockSession.return_value
+ calls: list[tuple[str, Any]] = []
+ _wire(session, self._pages([{"id": "C1", "status": "sent"}]), calls)
+
+ _rows(_source("campaign_reports", _make_manager()))
+
+ requested = {params["status"] for url, params in calls if "/reports" in url}
+ assert requested == set(CAMPAIGN_REPORT_STATUSES)
+
+ @parameterized.expand([("draft",), ("error",)])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_skips_campaigns_that_never_sent(self, campaign_status: str, MockSession) -> None:
+ session = MockSession.return_value
+ calls: list[tuple[str, Any]] = []
+ # A campaign that never sent has no report. Fanning out over it would spend eight requests
+ # per sync on a rejection we could not tell apart from a genuinely malformed one.
+ _wire(session, self._pages([{"id": "C1", "status": campaign_status}]), calls)
+
+ rows = _rows(_source("campaign_reports", _make_manager()))
+
+ assert rows == []
+ assert not [url for url, _ in calls if "/reports" in url]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_deleted_campaign_is_skipped(self, MockSession) -> None:
+ session = MockSession.return_value
+ pages = self._pages([{"id": "C1", "status": "sent"}, {"id": "GONE", "status": "sent"}])
+ for status in CAMPAIGN_REPORT_STATUSES:
+ pages[f"{BASE}/campaigns/GONE/reports?status={status}"] = _resp({}, status=404)
+ pages[f"{BASE}/campaigns/C1/reports?status=sent"] = _resp(
+ {"status": "sent", "data": [{"contact_id": "ct1"}], "paging": {"next": None}}
+ )
+ _wire(session, pages)
+
+ rows = _rows(_source("campaign_reports", _make_manager()))
+ assert rows == [{"contact_id": "ct1", "campaign_id": "C1", "status": "sent"}]
+
+
+class TestUnpaginatedCampaignFanOuts:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_summary_yields_the_bare_response_body_as_one_row(self, MockSession) -> None:
+ session = MockSession.return_value
+ # The summary is a bare object rather than a `data` collection, and already carries the
+ # campaign id as `id`, so no parent id is attached on top.
+ _wire(
+ session,
+ {
+ f"{BASE}/campaigns": _resp({"data": [{"id": "C1", "status": "sent"}], "paging": {"next": None}}),
+ f"{BASE}/campaigns/C1/reports/summary": _resp(
+ {"id": "C1", "sent": 200, "opened": {"total": 110, "unique": 85}}
+ ),
+ },
+ )
+ rows = _rows(_source("campaign_report_summaries", _make_manager()))
+ assert rows == [{"id": "C1", "sent": 200, "opened": {"total": 110, "unique": 85}}]
+ assert "campaign_id" not in rows[0]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_links_attach_campaign_id_and_stop_after_one_page(self, MockSession) -> None:
+ session = MockSession.return_value
+ calls: list[tuple[str, Any]] = []
+ # The links endpoint takes no pagination params and returns no `paging` block; a next-URL
+ # paginator would have nothing to follow, so the walk must terminate on the first response.
+ _wire(
+ session,
+ {
+ f"{BASE}/campaigns": _resp({"data": [{"id": "C1", "status": "sent"}], "paging": {"next": None}}),
+ f"{BASE}/campaigns/C1/reports/links": _resp(
+ {"data": [{"url": "https://example.com/promo-1", "clicked_total": 10, "clicked_unique": 7}]}
+ ),
+ },
+ calls,
+ )
+ rows = _rows(_source("campaign_report_links", _make_manager()))
+ assert rows == [
+ {
+ "url": "https://example.com/promo-1",
+ "clicked_total": 10,
+ "clicked_unique": 7,
+ "campaign_id": "C1",
+ }
+ ]
+ assert len([url for url, _ in calls if url.endswith("/links")]) == 1
+
+
+class TestListTagsFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_attaches_list_id_and_follows_pagination(self, MockSession) -> None:
+ session = MockSession.return_value
+ next_url = f"{BASE}/lists/L1/tags?limit=100&starting_after=cur1"
+ _wire(
+ session,
+ {
+ f"{BASE}/lists": _resp({"data": [{"id": "L1"}], "paging": {"next": None}}),
+ f"{BASE}/lists/L1/tags": _resp({"data": [{"tag": "vip"}], "paging": {"next": {"url": next_url}}}),
+ next_url: _resp({"data": [{"tag": "beta"}], "paging": {"next": None}}),
+ },
+ )
+ rows = _rows(_source("list_tags", _make_manager()))
+ assert rows == [{"tag": "vip", "list_id": "L1"}, {"tag": "beta", "list_id": "L1"}]
+
+
class TestSourceResponse:
@parameterized.expand(
[
- ("lists", ["id"]),
- ("campaigns", ["id"]),
- ("contacts", ["list_id", "id"]),
+ ("lists", ["id"], "created_at"),
+ ("campaigns", ["id"], "created_at"),
+ ("contacts", ["list_id", "id"], "created_at"),
+ ("campaign_reports", ["campaign_id", "status", "contact_id"], "occurred_at"),
+ ("campaign_report_summaries", ["id"], None),
+ ("campaign_report_links", ["campaign_id", "url"], None),
+ ("list_tags", ["list_id", "tag"], None),
]
)
- def test_primary_keys_and_partitioning(self, endpoint: str, expected_pks: list[str]) -> None:
+ def test_primary_keys_and_partitioning(
+ self, endpoint: str, expected_pks: list[str], partition_key: str | None
+ ) -> None:
response = _source(endpoint, _make_manager())
assert response.name == endpoint
assert response.primary_keys == expected_pks
assert response.sort_mode == "asc"
- assert response.partition_mode == "datetime"
- assert response.partition_format == "week"
- assert response.partition_keys == [EMAILOCTOPUS_ENDPOINTS[endpoint].partition_key]
- assert EMAILOCTOPUS_ENDPOINTS[endpoint].partition_key == "created_at"
+ assert EMAILOCTOPUS_ENDPOINTS[endpoint].partition_key == partition_key
+ if partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "week"
+ assert response.partition_keys == [partition_key]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus_source.py
index ffb698de4d42..31aab7f28b74 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus_source.py
@@ -18,13 +18,25 @@ def _config() -> Any:
class TestEmailOctopusGetSchemas:
def test_returns_all_endpoints(self) -> None:
names = {s.name for s in EmailOctopusSource().get_schemas(_config(), team_id=1)}
- assert names == {"lists", "campaigns", "contacts"}
+ assert names == {
+ "lists",
+ "campaigns",
+ "contacts",
+ "campaign_reports",
+ "campaign_report_summaries",
+ "campaign_report_links",
+ "list_tags",
+ }
@parameterized.expand(
[
("lists", False),
("campaigns", False),
("contacts", True),
+ ("campaign_reports", False),
+ ("campaign_report_summaries", False),
+ ("campaign_report_links", False),
+ ("list_tags", False),
]
)
def test_incremental_support(self, endpoint: str, supports_incremental: bool) -> None: