Skip to content

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

feat(data-warehouse): implement mailerlite import source (#61155)

Tom Owers2f894f997fda
diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
index 4d81dc6a2021..800a3fff4b5e 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
@@ -1122,7 +1122,7 @@
WHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,
(SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id
FROM events
- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), equals(events.mat_pp_email, 'bla'), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))
+ WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))
GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')
HAVING 1
ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESC
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 869baf2fd26a..46c31946b250 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -76,6 +76,7 @@ the row lists both.
| lever | HTTP | requests | ✅ |
| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
| mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| mailerlite | HTTP | requests | ✅ |
| mailjet | HTTP | requests | ✅ |
| meta_ads | HTTP | requests | ✅ |
| mongodb | DB protocol | pymongo | ➖ |
@@ -189,7 +190,7 @@ doesn't conflict with concurrent PRs.
- jira
- kafka
- launchdarkly
-- mailerlite
+- lever
- marketo
- microsoft_teams
- mixpanel
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 1c6652ab6193..335355796f2c 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -503,7 +503,7 @@ class MailchimpSourceConfig(config.Config):
@config.config
class MailerLiteSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/mailerlite/api_inventory.md b/posthog/temporal/data_imports/sources/mailerlite/api_inventory.md
new file mode 100644
index 000000000000..b03d1e9e7514
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailerlite/api_inventory.md
@@ -0,0 +1,54 @@
+# MailerLite API inventory
+
+Base URL: `https://connect.mailerlite.com/api` (current date-versioned API, released 2022-03-22).
+Auth: `Authorization: Bearer <api-key>` (account-wide API key; the simple API-key model has no
+granular per-resource scopes). `Accept: application/json`.
+
+## Verified with curl (2026-06-02)
+
+Without a live key only auth behavior and endpoint existence were verifiable:
+
+- `GET /subscribers` with no/invalid token → `401 {"message":"Unauthenticated."}`.
+- All endpoints below return `401` (not `404`) for an invalid token, confirming the paths exist.
+
+The response **shapes, pagination cursors, and field names below are taken from the public API
+docs** and could not be exercised against live data without credentials. Parsing is kept
+conservative (follow `links.next`, yield rows verbatim, merge on `id`).
+
+## Endpoints implemented
+
+| Schema | Path | Pagination | Primary key | Partition key |
+| --------------- | ---------------- | ----------- | ----------- | ------------- |
+| subscribers | /subscribers | cursor | id | created_at |
+| campaigns | /campaigns | page number | id | created_at |
+| groups | /groups | page number | id | created_at |
+| segments | /segments | page number | id | created_at |
+| fields | /fields | page number | id | (none) |
+| automations | /automations | page number | id | created_at |
+| forms_popup | /forms/popup | page number | id | created_at |
+| forms_embedded | /forms/embedded | page number | id | created_at |
+| forms_promotion | /forms/promotion | page number | id | created_at |
+| webhooks | /webhooks | page number | id | created_at |
+
+## Pagination
+
+All list endpoints wrap rows in `{"data": [...], "links": {...}, "meta": {...}}`. Both the
+cursor-based `subscribers` endpoint and the page-number endpoints expose an absolute next-page URL
+at `links.next` (or `null` on the last page), so a single "follow `links.next`" loop covers both.
+Page size capped at 100 (default 25); we request `limit=100`.
+
+## Incremental sync
+
+None. The current API exposes **no server-side timestamp filter** (`updated_after`, `since`, etc.)
+on any list endpoint — `created_at` / `updated_at` are returned in responses but cannot be filtered
+on. A client-side cursor would still page through the entire collection every run, so per the
+warehouse-source guidance every endpoint ships **full refresh only** (`supports_incremental=False`).
+This matches the Airbyte MailerLite connector, which is also full-refresh only.
+
+Pagination is still resumable (the source is a `ResumableSource`): the next-page URL is persisted to
+Redis after each page so Temporal can resume mid-collection after a heartbeat timeout.
+
+## Rate limits
+
+120 requests/minute globally (5/minute for bulk import/upsert, which this source does not use).
+`429` responses are retried with exponential backoff via `tenacity`.
diff --git a/posthog/temporal/data_imports/sources/mailerlite/mailerlite.py b/posthog/temporal/data_imports/sources/mailerlite/mailerlite.py
new file mode 100644
index 000000000000..e63d0044dade
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailerlite/mailerlite.py
@@ -0,0 +1,141 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.mailerlite.settings import MAILERLITE_ENDPOINTS
+
+MAILERLITE_BASE_URL = "https://connect.mailerlite.com/api"
+
+# MailerLite caps list endpoints at 100 rows per page; default is 25.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class MailerLiteRetryableError(Exception):
+ pass
+
+
+class MailerLiteResumeConfig:
+ # Absolute next-page URL returned by the API (carries the cursor / page number and limit).
+ next_url: str
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _build_initial_url(path: str) -> str:
+ return f"{MAILERLITE_BASE_URL}{path}?{urlencode({'limit': PAGE_SIZE})}"
+
+
+def validate_credentials(api_key: str, path: str = "/subscribers") -> bool:
+ """Confirm the API key is genuine with one cheap probe against a list endpoint."""
+ url = f"{MAILERLITE_BASE_URL}{path}?{urlencode({'limit': 1})}"
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailerLiteResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = MAILERLITE_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url = resume_config.next_url
+ # Guard the persisted resume URL too — only ever saved from a host-pinned `links.next`,
+ # but re-check so a tampered Redis state can't redirect our authenticated request (SSRF).
+ if not url.startswith(MAILERLITE_BASE_URL):
+ raise ValueError(f"MailerLite resume state contains an unexpected URL: {url!r}")
+ logger.debug(f"MailerLite: resuming {endpoint} from URL: {url}")
+ else:
+ url = _build_initial_url(config.path)
+
+ @retry(
+ retry=retry_if_exception_type((MailerLiteRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MailerLiteRetryableError(
+ f"MailerLite API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"MailerLite API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+
+ items = data.get("data", [])
+ if items:
+ yield items
+
+ # Both cursor (subscribers) and page-number (everything else) pagination return an
+ # absolute next-page URL in `links.next`, or `None` on the last page.
+ next_url = data.get("links", {}).get("next")
+ if not next_url:
+ break
+
+ # Only follow pagination URLs that stay on the canonical MailerLite host, so a tampered or
+ # compromised API response can't point our authenticated request at an internal address
+ # (SSRF) and leak the API key carried in the Authorization header.
+ if not isinstance(next_url, str) or not next_url.startswith(MAILERLITE_BASE_URL):
+ logger.warning(f"MailerLite: ignoring off-host pagination URL: {next_url!r}")
+ break
+
+ # Save state only after yielding the current page, so a crash re-yields the last page
+ # (merge dedupes on primary key) instead of skipping it.
+ resumable_source_manager.save_state(MailerLiteResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def mailerlite_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailerLiteResumeConfig],
+) -> SourceResponse:
+ endpoint_config = MAILERLITE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=["id"],
+ 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,
+ )
diff --git a/posthog/temporal/data_imports/sources/mailerlite/settings.py b/posthog/temporal/data_imports/sources/mailerlite/settings.py
new file mode 100644
index 000000000000..16e1a29c5292
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailerlite/settings.py
@@ -0,0 +1,73 @@
+from dataclasses import dataclass
+from typing import Optional
+
+
+@dataclass
+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
+
+
+# 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).
+MAILERLITE_ENDPOINTS: dict[str, MailerLiteEndpointConfig] = {
+ "subscribers": MailerLiteEndpointConfig(
+ name="subscribers",
+ path="/subscribers",
+ partition_key="created_at",
+ ),
+ "campaigns": MailerLiteEndpointConfig(
+ name="campaigns",
+ path="/campaigns",
+ partition_key="created_at",
+ ),
+ "groups": MailerLiteEndpointConfig(
+ name="groups",
+ path="/groups",
+ partition_key="created_at",
+ ),
+ "segments": MailerLiteEndpointConfig(
+ name="segments",
+ path="/segments",
+ partition_key="created_at",
+ ),
+ "fields": MailerLiteEndpointConfig(
+ name="fields",
+ path="/fields",
+ # Custom field definitions carry no creation timestamp, so they aren't partitioned.
+ partition_key=None,
+ ),
+ "automations": MailerLiteEndpointConfig(
+ name="automations",
+ path="/automations",
+ partition_key="created_at",
+ ),
+ "forms_popup": MailerLiteEndpointConfig(
+ name="forms_popup",
+ path="/forms/popup",
+ partition_key="created_at",
+ ),
+ "forms_embedded": MailerLiteEndpointConfig(
+ name="forms_embedded",
+ path="/forms/embedded",
+ partition_key="created_at",
+ ),
+ "forms_promotion": MailerLiteEndpointConfig(
+ name="forms_promotion",
+ path="/forms/promotion",
+ partition_key="created_at",
+ ),
+ "webhooks": MailerLiteEndpointConfig(
+ name="webhooks",
+ path="/webhooks",
+ partition_key="created_at",
+ ),
+}
+
+ENDPOINTS = tuple(MAILERLITE_ENDPOINTS.keys())
diff --git a/posthog/temporal/data_imports/sources/mailerlite/source.py b/posthog/temporal/data_imports/sources/mailerlite/source.py
index 57d8b04eb170..3369b1edf637 100644
--- a/posthog/temporal/data_imports/sources/mailerlite/source.py
+++ b/posthog/temporal/data_imports/sources/mailerlite/source.py
@@ -1,19 +1,31 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import MailerLiteSourceConfig
+from posthog.temporal.data_imports.sources.mailerlite.mailerlite import (
+ MailerLiteResumeConfig,
+ mailerlite_source,
+ validate_credentials as validate_mailerlite_credentials,
+)
+from posthog.temporal.data_imports.sources.mailerlite.settings import ENDPOINTS, MAILERLITE_ENDPOINTS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MailerLiteSource(SimpleSource[MailerLiteSourceConfig]):
+class MailerLiteSource(ResumableSource[MailerLiteSourceConfig, MailerLiteResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MAILERLITE
@@ -23,7 +35,78 @@ class MailerLiteSource(SimpleSource[MailerLiteSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.MAILER_LITE,
label="MailerLite",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your MailerLite API key to pull your MailerLite data into the PostHog Data warehouse.
+
+You can create an API key in your [MailerLite integrations settings](https://dashboard.mailerlite.com/integrations/api).""",
iconPath="/static/services/mailerlite.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/mailerlite",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Your MailerLite API key",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://connect.mailerlite.com": "Your MailerLite API key is invalid or expired. Please generate a new key and reconnect.",
+ "403 Client Error: Forbidden for url: https://connect.mailerlite.com": "Your MailerLite API key does not have the required permissions. Please check the key and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: MailerLiteSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # MailerLite exposes no server-side timestamp filter, so every endpoint is full-refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: MailerLiteSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ endpoint_config = MAILERLITE_ENDPOINTS.get(schema_name) if schema_name else None
+ path = endpoint_config.path if endpoint_config else "/subscribers"
+ if validate_mailerlite_credentials(config.api_key, path):
+ return True, None
+
+ return False, "Invalid MailerLite API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MailerLiteResumeConfig]:
+ return ResumableSourceManager[MailerLiteResumeConfig](inputs, MailerLiteResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MailerLiteSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MailerLiteResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return mailerlite_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py b/posthog/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py
new file mode 100644
index 000000000000..3af234f20474
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py
@@ -0,0 +1,201 @@
+import json
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+from requests.exceptions import HTTPError
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.mailerlite.mailerlite import (
+ MAILERLITE_BASE_URL,
+ MailerLiteResumeConfig,
+ get_rows,
+ mailerlite_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.mailerlite.settings import ENDPOINTS
+
+
+def _make_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _page(items: list[dict[str, Any]], next_url: str | None) -> dict[str, Any]:
+ return {"data": items, "links": {"next": next_url}, "meta": {}}
+
+
+def _drive_get_rows(
+ endpoint: str, manager: MagicMock, responses: list[Response]
+) -> tuple[list[list[dict[str, Any]]], list[str]]:
+ """Run get_rows against a mocked tracked session, returning (yielded_batches, fetched_urls)."""
+ fetched_urls: list[str] = []
+ response_iter = iter(responses)
+
+ def fake_get(url: str, *_args: Any, **_kwargs: Any) -> Response:
+ fetched_urls.append(url)
+ return next(response_iter)
+
+ with patch("posthog.temporal.data_imports.sources.mailerlite.mailerlite.make_tracked_session") as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.get.side_effect = fake_get
+
+ batches = list(get_rows("test-key", endpoint, MagicMock(), manager))
+ return batches, fetched_urls
+
+
+class TestGetRows:
+ def test_follows_links_next_across_pages(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ next_url = f"{MAILERLITE_BASE_URL}/subscribers?cursor=abc&limit=100"
+ responses = [
+ _make_response(_page([{"id": "1"}], next_url)),
+ _make_response(_page([{"id": "2"}], None)),
+ ]
+
+ batches, fetched_urls = _drive_get_rows("subscribers", manager, responses)
+
+ assert batches == [[{"id": "1"}], [{"id": "2"}]]
+ assert fetched_urls[0] == f"{MAILERLITE_BASE_URL}/subscribers?limit=100"
+ assert fetched_urls[1] == next_url
+
+ def test_saves_state_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ next_url_1 = f"{MAILERLITE_BASE_URL}/groups?page=2&limit=100"
+ next_url_2 = f"{MAILERLITE_BASE_URL}/groups?page=3&limit=100"
+ responses = [
+ _make_response(_page([{"id": "1"}], next_url_1)),
+ _make_response(_page([{"id": "2"}], next_url_2)),
+ _make_response(_page([{"id": "3"}], None)),
+ ]
+
+ _drive_get_rows("groups", manager, responses)
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ MailerLiteResumeConfig(next_url=next_url_1),
+ MailerLiteResumeConfig(next_url=next_url_2),
+ ]
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [_make_response(_page([{"id": "only"}], None))]
+
+ _drive_get_rows("groups", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_resume_starts_from_saved_url(self) -> None:
+ resumed_url = f"{MAILERLITE_BASE_URL}/subscribers?cursor=resumed&limit=100"
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = MailerLiteResumeConfig(next_url=resumed_url)
+ responses = [_make_response(_page([{"id": "9"}], None))]
+
+ _, fetched_urls = _drive_get_rows("subscribers", manager, responses)
+
+ assert fetched_urls == [resumed_url]
+ manager.load_state.assert_called_once()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [_make_response(_page([{"id": "1"}], None))]
+
+ _drive_get_rows("subscribers", manager, responses)
+
+ manager.load_state.assert_not_called()
+
+ def test_empty_page_yields_nothing_and_stops(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [_make_response(_page([], None))]
+
+ batches, _ = _drive_get_rows("groups", manager, responses)
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ def test_non_retryable_status_raises(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [_make_response({"message": "Not Found"}, status_code=404)]
+
+ with pytest.raises(HTTPError):
+ _drive_get_rows("groups", manager, responses)
+
+ @pytest.mark.parametrize(
+ "off_host_url",
+ [
+ "http://169.254.169.254/latest/meta-data/",
+ "https://evil.example.com/api/subscribers?cursor=abc",
+ "https://connect.mailerlite.com.evil.com/api/subscribers",
+ ],
+ )
+ def test_off_host_next_url_is_ignored(self, off_host_url: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [_make_response(_page([{"id": "1"}], off_host_url))]
+
+ batches, fetched_urls = _drive_get_rows("subscribers", manager, responses)
+
+ # The tampered next URL is dropped: we yield the first page and stop without following it.
+ assert batches == [[{"id": "1"}]]
+ assert fetched_urls == [f"{MAILERLITE_BASE_URL}/subscribers?limit=100"]
+ manager.save_state.assert_not_called()
+
+ def test_off_host_resume_url_raises(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = MailerLiteResumeConfig(next_url="http://169.254.169.254/latest/meta-data/")
+
+ with pytest.raises(ValueError, match="unexpected URL"):
+ _drive_get_rows("subscribers", manager, [])
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected"),
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ def test_status_maps_to_bool(self, status_code: int, expected: bool) -> None:
+ with patch("posthog.temporal.data_imports.sources.mailerlite.mailerlite.make_tracked_session") as MockSession:
+ MockSession.return_value.get.return_value = _make_response({}, status_code=status_code)
+ assert validate_credentials("key") is expected
+
+ def test_exception_returns_false(self) -> None:
+ with patch("posthog.temporal.data_imports.sources.mailerlite.mailerlite.make_tracked_session") as MockSession:
+ MockSession.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
+
+
+class TestMailerLiteSource:
+ def test_partitioned_endpoint_response_shape(self) -> None:
+ response = mailerlite_source("key", "subscribers", MagicMock(), MagicMock(spec=ResumableSourceManager))
+
+ assert response.name == "subscribers"
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "month"
+ assert response.partition_keys == ["created_at"]
+
+ def test_unpartitioned_endpoint_has_no_partition(self) -> None:
+ response = mailerlite_source("key", "fields", MagicMock(), MagicMock(spec=ResumableSourceManager))
+
+ assert response.partition_mode is None
+ assert response.partition_format is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_every_endpoint_builds_a_response(self, endpoint: str) -> None:
+ response = mailerlite_source("key", endpoint, MagicMock(), MagicMock(spec=ResumableSourceManager))
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
diff --git a/posthog/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py b/posthog/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py
new file mode 100644
index 000000000000..252fae7a2035
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py
@@ -0,0 +1,92 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import MailerLiteSourceConfig
+from posthog.temporal.data_imports.sources.mailerlite.mailerlite import MailerLiteResumeConfig
+from posthog.temporal.data_imports.sources.mailerlite.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.mailerlite.source import MailerLiteSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _config() -> MailerLiteSourceConfig:
+ return MailerLiteSourceConfig(api_key="test-key")
+
+
+class TestMailerLiteSourceClass:
+ def test_source_type(self) -> None:
+ assert MailerLiteSource().source_type == ExternalDataSourceType.MAILERLITE
+
+ def test_source_config_fields(self) -> None:
+ config = MailerLiteSource().get_source_config
+ assert config.label == "MailerLite"
+ assert config.unreleasedSource is not True
+ assert [field.name for field in config.fields] == ["api_key"]
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+
+ def test_get_schemas_are_all_full_refresh(self) -> None:
+ schemas = MailerLiteSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = MailerLiteSource().get_schemas(_config(), team_id=1, names=["subscribers", "groups"])
+ assert {s.name for s in schemas} == {"subscribers", "groups"}
+
+ @pytest.mark.parametrize(
+ ("valid", "expected_ok"),
+ [(True, True), (False, False)],
+ )
+ def test_validate_credentials(self, valid: bool, expected_ok: bool) -> None:
+ with patch(
+ "posthog.temporal.data_imports.sources.mailerlite.source.validate_mailerlite_credentials",
+ return_value=valid,
+ ):
+ ok, error = MailerLiteSource().validate_credentials(_config(), team_id=1)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_validate_credentials_uses_schema_path(self) -> None:
+ with patch(
+ "posthog.temporal.data_imports.sources.mailerlite.source.validate_mailerlite_credentials",
+ return_value=True,
+ ) as mock_validate:
+ MailerLiteSource().validate_credentials(_config(), team_id=1, schema_name="groups")
+ assert mock_validate.call_args.args == ("test-key", "/groups")
+
+ def test_get_non_retryable_errors_cover_auth(self) -> None:
+ errors = MailerLiteSource().get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock(spec=SourceInputs)
+ inputs.logger = MagicMock()
+ manager = MailerLiteSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MailerLiteResumeConfig
+
+ def test_source_for_pipeline_plumbing(self) -> None:
+ inputs = MagicMock(spec=SourceInputs)
+ inputs.schema_name = "subscribers"
+ inputs.logger = MagicMock()
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ with patch("posthog.temporal.data_imports.sources.mailerlite.source.mailerlite_source") as mock_source:
+ MailerLiteSource().source_for_pipeline(_config(), manager, inputs)
+ mock_source.assert_called_once_with(
+ api_key="test-key",
+ endpoint="subscribers",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ )