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(warehouse-sources): add mailerlite activity and membership tables (#114904)

Tom Owers3b0823048e0d
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 f759a0aa738d..8bfb439a5e34 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
@@ -5330,10 +5330,10 @@ Today (10): `automations`, `campaigns`, `fields`, `forms_embedded`, `forms_popup
Diffed against: <https://developers.mailerlite.com/llms.txt>
-- [ ] `GET /api/campaigns/{campaign_id}/reports/subscriber-activity` — per-subscriber opens, clicks and bounces — the core campaign analytics table (high)
-- [ ] `GET /api/groups/{group_id}/subscribers` — group membership join table for the groups and subscribers we already sync (high)
-- [ ] `GET /api/automations/{automation_id}/activity` — subscribers flowing through each automation, the automation-side event stream (high)
-- [ ] `GET /api/segments/{segment_id}/subscribers` — segment membership join table (high)
+- [x] `GET /api/campaigns/{campaign_id}/reports/subscriber-activity` — per-subscriber opens, clicks and bounces — the core campaign analytics table (high)
+- [x] `GET /api/groups/{group_id}/subscribers` — group membership join table for the groups and subscribers we already sync (high)
+- [x] `GET /api/automations/{automation_id}/activity` — subscribers flowing through each automation, the automation-side event stream (high)
+- [x] `GET /api/segments/{segment_id}/subscribers` — segment membership join table (high)
- [ ] `GET /api/ecommerce/shops/{shop_id}/orders` — purchase transactions — the highest-value analytical object in the e-commerce API (high)
- [ ] `GET /api/ecommerce/shops` — lookup resolving shop ids for every e-commerce record (high)
- [ ] `GET /api/ecommerce/shops/{shop_id}/customers` — shop customers linked to subscribers, joins revenue to email (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py
index 83a2bcccf036..f64aa4b892c5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py
@@ -107,7 +107,7 @@ def _build_parent_resource(
path_format_values: Mapping[str, str],
page_size_param: str | None,
parent_endpoint_extra: Endpoint | None,
- parent_data_map: Callable[[dict[str, Any]], dict[str, Any]] | None,
+ parent_data_map: Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]] | None,
) -> EndpointResource:
# page_size_param=None is for APIs whose list endpoints take no page-size param at all
# (unpaginated, full-collection responses) — sending one would be an undocumented param.
@@ -308,7 +308,7 @@ def build_dependent_resource(
parent_endpoint_extra: Endpoint | None = None,
child_endpoint_extra: Endpoint | None = None,
child_params_extra: dict[str, Any] | None = None,
- parent_data_map: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
+ parent_data_map: Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]] | None = None,
page_size_param: str | None = "limit",
resume_hook: Callable[[dict[str, Any] | None], None] | None = None,
initial_paginator_state: dict[str, Any] | None = None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/api_inventory.md
index 139e28df82fa..f4c85acec67c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/api_inventory.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/api_inventory.md
@@ -30,6 +30,27 @@ conservative (follow `links.next`, yield rows verbatim, merge on `id`).
| forms_promotion | /forms/promotion | page number | id | created_at |
| webhooks | /webhooks | page number | id | created_at |
+### Fan-out endpoints
+
+Each child is fetched once per parent row from the parent list, so the parent id is part of the
+primary key. A 404 on a child (parent deleted mid-sync) is skipped.
+
+| Schema | Path | Parent | Pagination | Primary key | Partition key |
+| ---------------------------- | ---------------------------------------------------- | ------------------------- | ----------- | ----------------- | ------------- |
+| campaign_subscriber_activity | /campaigns/{campaign_id}/reports/subscriber-activity | campaigns (status `sent`) | page number | campaign_id, id | (none) |
+| group_subscribers | /groups/{group_id}/subscribers | groups | cursor | group_id, id | created_at |
+| segment_subscribers | /segments/{segment_id}/subscribers | segments | cursor | segment_id, id | created_at |
+| automation_activity | /automations/{automation_id}/activity | automations × status | page number | automation_id, id | (none) |
+
+- `campaign_subscriber_activity` sends `include=subscriber`; without it a row carries only its
+ counts. Reports exist only for sent campaigns, so the parent list is filtered to `sent`.
+- The membership endpoints default `filter[status]` to `active`, so they hold active members only.
+- `automation_activity` requires `filter[status]` and takes one value per request, so each
+ automation is fetched four times (`active`, `completed`, `canceled`, `failed`). Its `date`
+ field moves as a run progresses, so the table is not partitioned.
+- The `filter[date_from]` / `filter[date_to]` filters on automation activity don't apply to the
+ `active` status, so the table stays full refresh like the rest of the source.
+
## Pagination
All list endpoints wrap rows in `{"data": [...], "links": {...}, "meta": {...}}`. Both the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/canonical_descriptions.py
index 35545c7e359d..b109fb39a287 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/canonical_descriptions.py
@@ -152,4 +152,52 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "Time the webhook was last updated.",
},
},
+ "campaign_subscriber_activity": {
+ "description": "One row per recipient of a sent MailerLite campaign, with that recipient's opens and clicks.",
+ "docs_url": "https://developers.mailerlite.com/api/campaigns#get-subscribers-activity-of-a-sent-campaign",
+ "columns": {
+ "id": "Unique identifier for the recipient's activity record.",
+ "campaign_id": "The ID of the sent campaign the activity belongs to.",
+ "opens_count": "The number of times the recipient opened the campaign.",
+ "clicks_count": "The number of times the recipient clicked a link in the campaign.",
+ "subscriber": "The subscriber who received the campaign.",
+ },
+ },
+ "group_subscribers": {
+ "description": "Active subscribers in each MailerLite group, one row per group and subscriber.",
+ "docs_url": "https://developers.mailerlite.com/api/groups#get-subscribers-belonging-to-a-group",
+ "columns": {
+ "id": "Unique identifier for the subscriber.",
+ "group_id": "The ID of the group the subscriber belongs to.",
+ "email": "The subscriber's email address.",
+ "status": "Subscription status of the subscriber.",
+ "created_at": "Time the subscriber was created.",
+ },
+ },
+ "segment_subscribers": {
+ "description": "Active subscribers that match each MailerLite segment, one row per segment and subscriber.",
+ "docs_url": "https://developers.mailerlite.com/api/segments",
+ "columns": {
+ "id": "Unique identifier for the subscriber.",
+ "segment_id": "The ID of the segment the subscriber matches.",
+ "email": "The subscriber's email address.",
+ "status": "Subscription status of the subscriber.",
+ "created_at": "Time the subscriber was created.",
+ },
+ },
+ "automation_activity": {
+ "description": "A subscriber's run through a MailerLite automation, whether active, completed, canceled or failed.",
+ "docs_url": "https://developers.mailerlite.com/api/automations#get-the-subscriber-activity-for-an-automation",
+ "columns": {
+ "id": "Unique identifier for the automation run.",
+ "automation_id": "The ID of the automation the run belongs to.",
+ "status": "Status of the run (Active, Completed, Canceled or Failed).",
+ "date": "Time of the run's latest status.",
+ "reason": "Why the run was canceled or failed, if applicable.",
+ "reason_description": "A readable explanation of the reason.",
+ "stepRuns": "The automation steps the run has gone through.",
+ "currentStep": "The automation step the run is on.",
+ "nextStep": "The automation step the run moves to next.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/mailerlite.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/mailerlite.py
index 9c05d11d2621..15e26984bca0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/mailerlite.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/mailerlite.py
@@ -21,9 +21,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
JSONResponsePaginator,
)
+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
@@ -33,21 +37,25 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite
API_VERSION_HEADERS,
MAILERLITE_ENDPOINTS,
MAILERLITE_V1,
+ PAGE_SIZE,
WEBHOOK_SCHEMA_NAMES,
+ MailerLiteEndpointConfig,
)
MAILERLITE_BASE_URL = "https://connect.mailerlite.com/api"
-# MailerLite caps list endpoints at 100 rows per page; default is 25.
-PAGE_SIZE = 100
-
WEBHOOK_NAME = "PostHog Data warehouse"
[email protected](frozen=True)
class MailerLiteResumeConfig:
# Absolute next-page URL returned by the API (carries the cursor / page number and limit).
- next_url: str
+ next_url: str | None = None
+ # Fan-out endpoints resume per parent — see
+ # `common.rest_source.__init__._make_paginate_dependent_resource`.
+ completed: list[str] | None = None
+ current: str | None = None
+ child_state: dict[str, Any] | None = None
class MailerLiteNextUrlPaginator(JSONResponsePaginator):
@@ -71,6 +79,87 @@ class MailerLiteNextUrlPaginator(JSONResponsePaginator):
self._next_url = None
+def _client_config(api_key: str, api_version: str) -> ClientConfig:
+ # `v1` predates version pinning and sends no header (the exact behaviour existing syncs run
+ # under); newer versions pin MailerLite's `X-Version` header so responses stay on a fixed shape.
+ headers = {"Accept": "application/json"}
+ version_header = API_VERSION_HEADERS.get(api_version)
+ if version_header is not None:
+ headers["X-Version"] = version_header
+
+ return {
+ "base_url": MAILERLITE_BASE_URL,
+ # Auth (Bearer) goes through the framework auth config so its value is redacted from
+ # logs and raised errors; only the non-secret headers are set here.
+ "headers": headers,
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": MailerLiteNextUrlPaginator(),
+ # Pin every request — including a seeded resume URL — to the MailerLite host so a
+ # tampered pagination/resume link can't exfiltrate the Authorization header (SSRF).
+ "allowed_hosts": [],
+ }
+
+
+def _fanout_source(
+ endpoint_config: MailerLiteEndpointConfig,
+ client_config: ClientConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[MailerLiteResumeConfig],
+) -> SourceResponse:
+ fanout = endpoint_config.fanout
+ assert fanout is not None
+
+ initial_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and (resume.completed or resume.current):
+ initial_state = {
+ "completed": resume.completed or [],
+ "current": resume.current,
+ "child_state": resume.child_state,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(
+ MailerLiteResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+
+ # Paginators hold per-walk state, so each hop gets its own. The child is set explicitly
+ # because a path ending in a placeholder would otherwise default to a single-page fetch.
+ resource = build_dependent_resource(
+ endpoint_configs=MAILERLITE_ENDPOINTS,
+ child_endpoint=endpoint_config.name,
+ fanout=fanout,
+ client_config=client_config,
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra={"paginator": MailerLiteNextUrlPaginator(), "data_selector": "data"},
+ child_endpoint_extra={"paginator": MailerLiteNextUrlPaginator(), "data_selector": "data"},
+ parent_data_map=endpoint_config.parent_data_map,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_state,
+ )
+
+ return SourceResponse(
+ name=endpoint_config.name,
+ items=lambda: resource,
+ primary_keys=endpoint_config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
def mailerlite_source(
api_key: str,
endpoint: str,
@@ -82,26 +171,13 @@ def mailerlite_source(
api_version: str = MAILERLITE_V1,
) -> SourceResponse:
endpoint_config = MAILERLITE_ENDPOINTS[endpoint]
+ client_config = _client_config(api_key, api_version)
- # `v1` predates version pinning and sends no header (the exact behaviour existing syncs run
- # under); newer versions pin MailerLite's `X-Version` header so responses stay on a fixed shape.
- headers = {"Accept": "application/json"}
- version_header = API_VERSION_HEADERS.get(api_version)
- if version_header is not None:
- headers["X-Version"] = version_header
+ if endpoint_config.fanout is not None:
+ return _fanout_source(endpoint_config, client_config, team_id, job_id, resumable_source_manager)
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": MAILERLITE_BASE_URL,
- # Auth (Bearer) goes through the framework auth config so its value is redacted from
- # logs and raised errors; only the non-secret headers are set here.
- "headers": headers,
- "auth": {"type": "bearer", "token": api_key},
- "paginator": MailerLiteNextUrlPaginator(),
- # Pin every request — including a seeded resume URL — to the MailerLite host so a
- # tampered pagination/resume link can't exfiltrate the Authorization header (SSRF).
- "allowed_hosts": [],
- },
+ "client": client_config,
"resources": [
{
"name": endpoint,
@@ -119,7 +195,7 @@ def mailerlite_source(
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
- if resume is not None:
+ if resume is not None and 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/mailerlite/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/settings.py
index ce9df70456bf..19b5ec4a39f8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/settings.py
@@ -1,21 +1,51 @@
-from dataclasses import dataclass
-from typing import Optional
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from typing import Any, Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
+
+# MailerLite caps list endpoints at 100 rows per page; default is 25.
+PAGE_SIZE = 100
-@dataclass
+
+@dataclass(frozen=True)
class MailerLiteEndpointConfig:
name: str
path: str
# Stable datetime field used for partitioning. Must be a created-style field that
# never changes after a row is written (never updated_at). `None` disables partitioning.
partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ fanout: Optional[DependentEndpointConfig] = None
+ # Runs on each fan-out parent row before the child binds to it; a list return explodes the row.
+ parent_data_map: Optional[Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]] = None
+ page_size: int = PAGE_SIZE
+ # Unused (every endpoint is full refresh); kept so the config satisfies FanoutEndpointLike.
+ incremental_fields: list[Any] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+
+
+# A parent deleted between the parent listing and its child fetch answers 404; ignoring it keeps
+# the fan-out going instead of failing the whole table.
+_CHILD_404_IGNORE: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+
+# `filter[status]` is required on the automation activity endpoint and takes one value per
+# request, so each automation row fans out into one parent row per status.
+AUTOMATION_ACTIVITY_STATUSES: tuple[str, ...] = ("active", "completed", "canceled", "failed")
+
+
+def _explode_automation_statuses(automation: dict[str, Any]) -> list[dict[str, Any]]:
+ return [{**automation, "activity_status": status} for status in AUTOMATION_ACTIVITY_STATUSES]
# MailerLite's current API (https://connect.mailerlite.com/api) exposes no server-side
# timestamp filter on any list endpoint, so every endpoint is full-refresh only. See
# api_inventory.md for the verification notes. All list responses are flat JSON objects
# wrapped in `{"data": [...], "links": {...}, "meta": {...}}` and paginate by following
-# `links.next` (cursor for subscribers, page number for the rest).
+# `links.next` (cursor for subscriber lists, page number for the rest).
MAILERLITE_ENDPOINTS: dict[str, MailerLiteEndpointConfig] = {
"subscribers": MailerLiteEndpointConfig(
name="subscribers",
@@ -68,6 +98,74 @@ MAILERLITE_ENDPOINTS: dict[str, MailerLiteEndpointConfig] = {
path="/webhooks",
partition_key="created_at",
),
+ "campaign_subscriber_activity": MailerLiteEndpointConfig(
+ name="campaign_subscriber_activity",
+ path="/campaigns/{campaign_id}/reports/subscriber-activity",
+ # Activity rows carry no creation timestamp of their own.
+ partition_key=None,
+ primary_keys=["campaign_id", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="campaigns",
+ resolve_param="campaign_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "campaign_id"},
+ # Reports only exist for sent campaigns, and the campaign list defaults to `ready`.
+ parent_params={"filter[status]": "sent"},
+ # Without `include=subscriber` a row holds only its counts, not who they belong to.
+ child_params={"include": "subscriber"},
+ child_response_actions=_CHILD_404_IGNORE,
+ ),
+ ),
+ # Membership endpoints default `filter[status]` to `active`, so these tables hold active
+ # members only, matching what the MailerLite app shows for a group or segment.
+ "group_subscribers": MailerLiteEndpointConfig(
+ name="group_subscribers",
+ path="/groups/{group_id}/subscribers",
+ partition_key="created_at",
+ primary_keys=["group_id", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="groups",
+ resolve_param="group_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "group_id"},
+ child_response_actions=_CHILD_404_IGNORE,
+ ),
+ ),
+ "segment_subscribers": MailerLiteEndpointConfig(
+ name="segment_subscribers",
+ path="/segments/{segment_id}/subscribers",
+ partition_key="created_at",
+ primary_keys=["segment_id", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="segments",
+ resolve_param="segment_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "segment_id"},
+ child_response_actions=_CHILD_404_IGNORE,
+ ),
+ ),
+ "automation_activity": MailerLiteEndpointConfig(
+ name="automation_activity",
+ path="/automations/{automation_id}/activity?filter[status]={activity_status}",
+ # `date` can move as a subscriber advances through the automation, so it isn't stable.
+ partition_key=None,
+ primary_keys=["automation_id", "id"],
+ parent_data_map=_explode_automation_statuses,
+ fanout=DependentEndpointConfig(
+ parent_name="automations",
+ resolve_param="automation_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "automation_id"},
+ child_params={
+ "activity_status": {"type": "resolve", "resource": "automations", "field": "activity_status"}
+ },
+ child_response_actions=_CHILD_404_IGNORE,
+ ),
+ ),
}
ENDPOINTS = tuple(MAILERLITE_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/source.py
index 97b82a3f4d36..b6ac4baa87c7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/source.py
@@ -181,6 +181,9 @@ Copy the `secret` from the response into the field below. MailerLite never retur
api_version: str | None = None,
) -> tuple[bool, str | None]:
endpoint_config = MAILERLITE_ENDPOINTS.get(schema_name) if schema_name else None
+ if endpoint_config is not None and endpoint_config.fanout is not None:
+ # A fan-out path needs a parent id, so probe the parent list the child is reached through.
+ endpoint_config = MAILERLITE_ENDPOINTS[endpoint_config.fanout.parent_name]
path = endpoint_config.path if endpoint_config else "/subscribers"
return validate_mailerlite_credentials(config.api_key, path)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py
index 4375fa46aafb..b4669d61a01f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py
@@ -1,6 +1,7 @@
import json
from collections.abc import Iterable
from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
import pytest
from unittest.mock import MagicMock, patch
@@ -139,6 +140,100 @@ class TestPagination:
_run("subscribers", manager, [])
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlsplit(url).query)
+
+
+class TestFanout:
+ @pytest.mark.parametrize(
+ ("endpoint", "parent_path", "child_path", "parent_key", "expected_parent_query", "expected_child_query"),
+ [
+ (
+ "campaign_subscriber_activity",
+ "/campaigns",
+ "/campaigns/c1/reports/subscriber-activity",
+ "campaign_id",
+ {"limit": ["100"], "filter[status]": ["sent"]},
+ {"limit": ["100"], "include": ["subscriber"]},
+ ),
+ (
+ "group_subscribers",
+ "/groups",
+ "/groups/c1/subscribers",
+ "group_id",
+ {"limit": ["100"]},
+ {"limit": ["100"]},
+ ),
+ (
+ "segment_subscribers",
+ "/segments",
+ "/segments/c1/subscribers",
+ "segment_id",
+ {"limit": ["100"]},
+ {"limit": ["100"]},
+ ),
+ ],
+ )
+ def test_walks_every_child_page_and_tags_rows_with_the_parent(
+ self,
+ endpoint: str,
+ parent_path: str,
+ child_path: str,
+ parent_key: str,
+ expected_parent_query: dict[str, list[str]],
+ expected_child_query: dict[str, list[str]],
+ ) -> None:
+ child_next = f"{MAILERLITE_BASE_URL}{child_path}?cursor=abc"
+ responses = [
+ _page([{"id": "c1"}], None),
+ _page([{"id": "a1"}], child_next),
+ _page([{"id": "a2"}], None),
+ ]
+
+ batches, sent_urls, _ = _run(endpoint, _make_manager(), responses)
+
+ assert [row for batch in batches for row in batch] == [
+ {"id": "a1", parent_key: "c1"},
+ {"id": "a2", parent_key: "c1"},
+ ]
+ assert urlsplit(sent_urls[0]).path == f"/api{parent_path}"
+ assert _query(sent_urls[0]) == expected_parent_query
+ assert urlsplit(sent_urls[1]).path == f"/api{child_path}"
+ assert _query(sent_urls[1]) == expected_child_query
+ assert sent_urls[2] == child_next
+
+ def test_automation_activity_requests_each_status(self) -> None:
+ # One page per status for the single automation, each answering one activity row.
+ responses = [_page([{"id": "au1"}], None)] + [
+ _page([{"id": f"run-{status}", "status": status.title()}], None)
+ for status in ("active", "completed", "canceled", "failed")
+ ]
+
+ batches, sent_urls, _ = _run("automation_activity", _make_manager(), responses)
+
+ assert [urlsplit(url).path for url in sent_urls[1:]] == ["/api/automations/au1/activity"] * 4
+ assert [_query(url)["filter[status]"] for url in sent_urls[1:]] == [
+ ["active"],
+ ["completed"],
+ ["canceled"],
+ ["failed"],
+ ]
+ rows = [row for batch in batches for row in batch]
+ assert {row["automation_id"] for row in rows} == {"au1"}
+ assert "activity_status" not in rows[0]
+
+ def test_resume_skips_completed_parents(self) -> None:
+ manager = _make_manager(MailerLiteResumeConfig(completed=["/groups/g1/subscribers"]))
+ responses = [_page([{"id": "g1"}, {"id": "g2"}], None), _page([{"id": "s1"}], None)]
+
+ batches, sent_urls, _ = _run("group_subscribers", manager, responses)
+
+ assert [urlsplit(url).path for url in sent_urls] == ["/api/groups", "/api/groups/g2/subscribers"]
+ assert batches == [[{"id": "s1", "group_id": "g2"}]]
+ saved = manager.save_state.call_args.args[0]
+ assert saved.completed == ["/groups/g1/subscribers", "/groups/g2/subscribers"]
+
+
class TestRetry:
def test_chunked_encoding_error_eventually_reraises(self) -> None:
manager = _make_manager()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py
index 115f2293f335..1489fd544fee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py
@@ -40,6 +40,23 @@ class TestMailerLiteSourceClass:
):
assert MailerLiteSource().validate_credentials(_config(), team_id=1) == probe_result
+ @pytest.mark.parametrize(
+ ("schema_name", "expected_path"),
+ [
+ ("campaigns", "/campaigns"),
+ ("campaign_subscriber_activity", "/campaigns"),
+ ("automation_activity", "/automations"),
+ ],
+ )
+ def test_validate_credentials_probes_a_listable_path(self, schema_name: str, expected_path: str) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.source.validate_mailerlite_credentials",
+ return_value=(True, None),
+ ) as probe:
+ MailerLiteSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)
+
+ probe.assert_called_once_with("test-key", expected_path)
+
def test_default_version_is_v2(self) -> None:
source = MailerLiteSource()
assert source.default_version == MAILERLITE_V2