:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement flexmail import source (#69331)
Tom Owers93f8f0d192d7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 119829c37e7e..3c0614245401 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -163,6 +163,7 @@ the row lists both.| finnworlds | HTTP | requests | ✅ || fleetio | HTTP | requests | ✅ || firehydrant | HTTP | requests | ✅ |+| flexmail | HTTP | requests | ✅ || float_app | HTTP | requests | ✅ || front | HTTP | requests | ✅ || fulcrum | HTTP | requests | ✅ |@@ -519,7 +520,6 @@ doesn't conflict with concurrent PRs.- feishu- firebase- firebolt-- flexmail- flexport- flowlu- formbricksdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/canonical_descriptions.pynew file mode 100644index 000000000000..7daa92462e3c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/canonical_descriptions.py@@ -0,0 +1,80 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Table and column descriptions taken from the official Flexmail API reference+# (https://api.flexmail.eu/documentation/).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "contacts": {+ "description": "A contact in your Flexmail account, with their email address, name, language, and custom field values.",+ "docs_url": "https://api.flexmail.eu/documentation/#get-/contacts",+ "columns": {+ "id": "Unique identifier of the contact.",+ "email": "The contact's email address.",+ "first_name": "The contact's first name.",+ "name": "The contact's last name.",+ "language": "The language the contact wants to receive emails in.",+ "custom_fields": "The contact's values for the account's custom fields, keyed by custom field placeholder.",+ },+ },+ "custom_fields": {+ "description": "A custom field configured for contacts in your Flexmail account (free text, multiple choice, numeric, or date).",+ "docs_url": "https://api.flexmail.eu/documentation/#get-/custom-fields",+ "columns": {+ "id": "Unique identifier of the custom field.",+ "type": "The type of the custom field: free_text, multiple_choice, numeric, or date.",+ "placeholder": "The placeholder used to reference the custom field in messages and contact payloads.",+ "name": "The display name of the custom field.",+ },+ },+ "interests": {+ "description": "An interest contacts can subscribe to, used to segment your audience by topic.",+ "docs_url": "https://api.flexmail.eu/documentation/#get-/interests",+ "columns": {+ "id": "Unique identifier of the interest.",+ "name": "The internal name of the interest as used in the Flexmail account.",+ "visibility": "Whether the interest is public (visible to contacts) or private.",+ "label": "How the interest is shown to your contacts.",+ "description": "An optional extra description shown to your contacts for context.",+ },+ },+ "opt_in_forms": {+ "description": "An active opt-in form contacts can use to subscribe to your communications.",+ "docs_url": "https://api.flexmail.eu/documentation/#get-/opt-in-forms",+ "columns": {+ "id": "Unique identifier of the opt-in form.",+ "name": "The display name of the opt-in form.",+ "language": "The language of the opt-in form.",+ "created_at": "The timestamp when the opt-in form was created.",+ },+ },+ "preferences": {+ "description": "A communication preference contacts can subscribe to, such as a newsletter.",+ "docs_url": "https://api.flexmail.eu/documentation/#get-/preferences",+ "columns": {+ "id": "Unique identifier of the preference.",+ "title": "How the preference is shown in the Flexmail UI to you.",+ "label": "How the preference is shown to your contacts.",+ "description": "An optional extra description shown to your contacts for context.",+ },+ },+ "segments": {+ "description": "An active segment: a saved set of conditions grouping contacts for targeting campaigns.",+ "docs_url": "https://api.flexmail.eu/documentation/#get-/segments",+ "columns": {+ "id": "Unique identifier of the segment.",+ "parent_id": "The identifier of the segment's parent. Absent if the segment has no parent.",+ "name": "A human readable name for the segment.",+ "number_of_contacts": "The number of contacts in this segment.",+ "last_campaign_date": "The date when a campaign was last sent to this segment. Absent if no campaign has ever been sent.",+ },+ },+ "sources": {+ "description": "A source describing where contacts originated, such as a signup form or import.",+ "docs_url": "https://api.flexmail.eu/documentation/#get-/sources",+ "columns": {+ "id": "Unique identifier of the source.",+ "name": "The name of the source.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/flexmail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/flexmail.pynew file mode 100644index 000000000000..d9522c41d29b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/flexmail.py@@ -0,0 +1,182 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.settings import FLEXMAIL_ENDPOINTS++FLEXMAIL_BASE_URL = "https://api.flexmail.eu"+# List endpoints accept a `limit` of up to 500; the largest page minimises round trips against the+# 60 requests/minute rate limit.+PAGE_SIZE = 500+REQUEST_TIMEOUT_SECONDS = 60+# Cheap list endpoint used to confirm the credentials are genuine. Personal access tokens are+# account-wide, so one probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/sources"+++class FlexmailRetryableError(Exception):+ pass+++class FlexmailResumeConfig:+ # Offset of the next page to fetch. Flexmail paginates with `limit`/`offset` query params, so a+ # crashed full-refresh sync resumes from the page after the last one yielded; merge dedupes the+ # re-pulled page on `id`. `0` means start from the first page.+ offset: int = 0+++def _make_session(account_id: str, personal_access_token: str) -> requests.Session:+ # HTTP Basic auth: account ID as username, personal access token as password.+ session = make_tracked_session(headers={"Accept": "application/json"}, redact_values=(personal_access_token,))+ session.auth = (account_id, personal_access_token)+ return session+++def _extract_items(data: dict[str, Any]) -> list[dict[str, Any]]:+ # Flexmail responses follow HAL: records sit in `_embedded.item`, which is omitted when the+ # collection is empty. Per-item `_links` are navigation noise, not data, so we drop them.+ embedded = data.get("_embedded")+ items = embedded.get("item") if isinstance(embedded, dict) else None+ if not isinstance(items, list):+ return []+ return [{k: v for k, v in item.items() if k != "_links"} if isinstance(item, dict) else item for item in items]+++@retry(+ retry=retry_if_exception_type((FlexmailRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(6),+ # Rate limiting is a fixed 60 requests/minute cycle, so the backoff must be able to span a full+ # minute before giving up.+ wait=wait_exponential_jitter(initial=5, max=70),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ params: dict[str, Any] | None,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(+ f"{FLEXMAIL_BASE_URL}{path}",+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise FlexmailRetryableError(f"Flexmail API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Flexmail API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ if not isinstance(data, dict):+ raise FlexmailRetryableError(f"Flexmail returned an unexpected payload for {path}: {type(data).__name__}")++ return data+++def get_rows(+ account_id: str,+ personal_access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FlexmailResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = FLEXMAIL_ENDPOINTS[endpoint]+ session = _make_session(account_id, personal_access_token)++ if not config.paginated:+ # Segments, opt-in forms and custom fields return the full collection in one response.+ data = _fetch_page(session, config.path, None, logger)+ items = _extract_items(data)+ if items:+ yield items+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume else 0+ if resume and resume.offset:+ logger.debug(f"Flexmail: resuming {endpoint} from offset {offset}")++ while True:+ data = _fetch_page(session, config.path, {"limit": PAGE_SIZE, "offset": offset}, logger)+ items = _extract_items(data)+ if items:+ yield items++ # The collection envelope carries `total`; we've reached the end once the next offset passes+ # it (or the page came back empty, e.g. rows deleted mid-sync shrank the collection).+ total = data.get("total")+ next_offset = offset + PAGE_SIZE+ if not items or not isinstance(total, int) or next_offset >= total:+ break++ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(FlexmailResumeConfig(offset=next_offset))+ offset = next_offset+++def flexmail_source(+ account_id: str,+ personal_access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FlexmailResumeConfig],+) -> SourceResponse:+ config = FLEXMAIL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ account_id=account_id,+ personal_access_token=personal_access_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(+ account_id: str, personal_access_token: str, path: str = DEFAULT_PROBE_PATH+) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the credentials.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = _make_session(account_id, personal_access_token)+ try:+ response = session.get(f"{FLEXMAIL_BASE_URL}{path}", params={"limit": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Flexmail: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Flexmail returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(account_id: str, personal_access_token: str) -> tuple[bool, str | None]:+ status, message = check_access(account_id, personal_access_token)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Flexmail account ID or personal access token"+ return False, message or "Could not validate Flexmail credentials"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/settings.pynew file mode 100644index 000000000000..39f7bfed86bf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/settings.py@@ -0,0 +1,30 @@+from dataclasses import dataclass, field+++@dataclass+class FlexmailEndpointConfig:+ path: str+ # `paginated` marks endpoints that accept `limit`/`offset` and wrap results in the HAL+ # collection envelope (`total`/`limit`/`offset`); the rest return the full collection at once.+ paginated: bool = True+ # Flexmail identifiers are account-unique (integers or UUIDs depending on the resource), so+ # `id` is a safe primary key for every endpoint.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Flexmail REST API (https://api.flexmail.eu) list endpoints. All are full-refresh only: no list+# endpoint accepts a server-side timestamp filter (contacts only filter on `email`, custom fields+# on `type`/`language`), so there is no incremental cursor to advance. Contact sub-resources+# (interest subscriptions, preferences, sources per contact) are deliberately not fanned out —+# at 60 requests/minute per account, one request per contact is impractical for real accounts.+FLEXMAIL_ENDPOINTS: dict[str, FlexmailEndpointConfig] = {+ "contacts": FlexmailEndpointConfig(path="/contacts"),+ "custom_fields": FlexmailEndpointConfig(path="/custom-fields", paginated=False),+ "interests": FlexmailEndpointConfig(path="/interests"),+ "opt_in_forms": FlexmailEndpointConfig(path="/opt-in-forms", paginated=False),+ "preferences": FlexmailEndpointConfig(path="/preferences"),+ "segments": FlexmailEndpointConfig(path="/segments", paginated=False),+ "sources": FlexmailEndpointConfig(path="/sources"),+}++ENDPOINTS = tuple(FLEXMAIL_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/source.pyindex a157aee647f7..35ccdc5c3305 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.flexmail import (+ FlexmailResumeConfig,+ flexmail_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.settings import (+ ENDPOINTS,+ FLEXMAIL_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FlexmailSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FlexmailSource(SimpleSource[FlexmailSourceConfig]):+class FlexmailSource(ResumableSource[FlexmailSourceConfig, FlexmailResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FLEXMAIL@@ -24,7 +47,96 @@ class FlexmailSource(SimpleSource[FlexmailSourceConfig]):name=SchemaExternalDataSourceType.FLEXMAIL,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Flexmail",- iconPath="/static/services/flexmail.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Flexmail account ID and personal access token to pull your email marketing data into the PostHog Data warehouse.++You can create a personal access token under **Settings → API → Personal access tokens** in [Flexmail](https://app.flexmail.eu). The token grants read access to your contacts, interests, custom fields, preferences, segments, sources, and opt-in forms.+""",+ iconPath="/static/services/flexmail.png",+ docsUrl="https://posthog.com/docs/cdp/sources/flexmail",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="personal_access_token",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.flexmail.eu": "Your Flexmail account ID or personal access token is invalid or has been revoked. Generate a new token under Settings → API → Personal access tokens, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.flexmail.eu": "Your Flexmail personal access token does not have access to this data. Check the token's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: FlexmailSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Flexmail's list endpoints expose no server-side+ # timestamp filter, so there is no incremental cursor to advance.+ 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: FlexmailSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # Personal access tokens are account-wide, so a single probe validates access to every schema.+ return validate_credentials(config.account_id, config.personal_access_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FlexmailResumeConfig]:+ return ResumableSourceManager[FlexmailResumeConfig](inputs, FlexmailResumeConfig)++ def source_for_pipeline(+ self,+ config: FlexmailSourceConfig,+ resumable_source_manager: ResumableSourceManager[FlexmailResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in FLEXMAIL_ENDPOINTS:+ raise ValueError(f"Unknown Flexmail schema '{inputs.schema_name}'")++ return flexmail_source(+ account_id=config.account_id,+ personal_access_token=config.personal_access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail.pynew file mode 100644index 000000000000..b890cfd9f48f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail.py@@ -0,0 +1,295 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail import flexmail+from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.flexmail import (+ PAGE_SIZE,+ FlexmailResumeConfig,+ FlexmailRetryableError,+ check_access,+ flexmail_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.settings import (+ ENDPOINTS,+ FLEXMAIL_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = flexmail._fetch_page.__wrapped__ # type: ignore[attr-defined]+++def _envelope(items: list[dict], total: int, offset: int = 0) -> dict[str, Any]:+ return {"total": total, "limit": PAGE_SIZE, "offset": offset, "_embedded": {"item": items}}+++class _FakeResumableManager:+ def __init__(self, state: FlexmailResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[FlexmailResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> FlexmailResumeConfig | None:+ return self._state++ def save_state(self, data: FlexmailResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[int | None, dict[str, Any]],+ endpoint: str = "contacts",+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, params: dict | None, logger: Any) -> dict[str, Any]:+ offset = params["offset"] if params is not None else None+ return pages[offset]++ monkeypatch.setattr(flexmail, "_fetch_page", fake_fetch)+ monkeypatch.setattr(flexmail, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ account_id="12345",+ personal_access_token="flexmail-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: _envelope([{"id": 1}, {"id": 2}], total=2)})+ assert rows == [{"id": 1}, {"id": 2}]+ # total is within the first page, so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_offset_pagination_until_total(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ first_page = [{"id": i} for i in range(PAGE_SIZE)]+ pages: dict[int | None, dict[str, Any]] = {+ 0: _envelope(first_page, total=PAGE_SIZE + 1),+ PAGE_SIZE: _envelope([{"id": 999}], total=PAGE_SIZE + 1, offset=PAGE_SIZE),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1+ # State is saved after the first page (offset advances by the page size), then we stop.+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(FlexmailResumeConfig(offset=PAGE_SIZE))+ # The initial (offset=0) page must never be fetched on resume.+ pages: dict[int | None, dict[str, Any]] = {+ PAGE_SIZE: _envelope([{"id": 5}], total=PAGE_SIZE + 1, offset=PAGE_SIZE)+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 5}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: _envelope([], total=0)})+ assert rows == []+ assert manager.saved == []++ def test_empty_page_mid_collection_stops(self, monkeypatch: Any) -> None:+ # Rows deleted mid-sync can shrink the collection; an empty page must terminate the loop+ # even when `total` still claims more rows.+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: _envelope([], total=PAGE_SIZE * 2)})+ assert rows == []+ assert manager.saved == []++ def test_missing_embedded_key_yields_nothing(self, monkeypatch: Any) -> None:+ # HAL omits `_embedded` entirely for empty collections.+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: {"total": 0, "limit": PAGE_SIZE, "offset": 0}})+ assert rows == []++ def test_links_are_stripped_from_rows(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ items = [{"id": 1, "email": "[email protected]", "_links": {"self": {"href": "/contacts/1"}}}]+ rows = self._collect(manager, monkeypatch, {0: _envelope(items, total=1)})+ assert rows == [{"id": 1, "email": "[email protected]"}]++ @parameterized.expand([("segments",), ("opt_in_forms",), ("custom_fields",)])+ def test_unpaginated_endpoint_fetches_once_and_never_saves_state(self, endpoint: str) -> None:+ manager = _FakeResumableManager()+ rows = self._collect_unpaginated(manager, endpoint)+ assert rows == [{"id": "u-1"}]+ assert manager.saved == []++ @staticmethod+ def _collect_unpaginated(manager: _FakeResumableManager, endpoint: str) -> list[dict]:+ calls: list[dict | None] = []++ def fake_fetch(session: Any, path: str, params: dict | None, logger: Any) -> dict[str, Any]:+ calls.append(params)+ return {"_embedded": {"item": [{"id": "u-1"}]}}++ with (+ patch.object(flexmail, "_fetch_page", fake_fetch),+ patch.object(flexmail, "make_tracked_session", return_value=MagicMock()),+ ):+ rows: list[dict] = []+ for batch in get_rows(+ account_id="12345",+ personal_access_token="flexmail-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ # A single request with no pagination params.+ assert calls == [None]+ return rows+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else _envelope([], total=0)+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(FlexmailRetryableError):+ _fetch_page_unwrapped(session, "/contacts", {"limit": PAGE_SIZE, "offset": 0}, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/contacts", {"limit": PAGE_SIZE, "offset": 0}, MagicMock())++ def test_success_returns_body(self) -> None:+ body = _envelope([{"id": 1}], total=1)+ session = self._session_returning(200, body)+ assert _fetch_page_unwrapped(session, "/contacts", {"limit": PAGE_SIZE, "offset": 0}, MagicMock()) == body++ def test_non_dict_body_is_retryable(self) -> None:+ session = self._session_returning(200, [{"id": 1}])+ with pytest.raises(FlexmailRetryableError):+ _fetch_page_unwrapped(session, "/contacts", {"limit": PAGE_SIZE, "offset": 0}, MagicMock())++ def test_pagination_params_are_sent(self) -> None:+ session = self._session_returning(200)+ _fetch_page_unwrapped(session, "/sources", {"limit": PAGE_SIZE, "offset": 500}, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": PAGE_SIZE, "offset": 500}+++class TestCheckAccess:+ @staticmethod+ def _session(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Flexmail returned HTTP 500"),+ ]+ )+ @patch(f"{flexmail.__name__}.make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_session.return_value = self._session(response)+ assert check_access("12345", "flexmail-token") == (expected_status, expected_message)++ @patch(f"{flexmail.__name__}.make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session(requests.ConnectionError("boom"))+ status, message = check_access("12345", "flexmail-token")+ assert status == 0+ assert message is not None and "boom" in message++ @patch(f"{flexmail.__name__}.make_tracked_session")+ def test_probe_uses_basic_auth(self, mock_session: MagicMock) -> None:+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ session = self._session(response)+ mock_session.return_value = session+ check_access("12345", "flexmail-token")+ assert session.auth == ("12345", "flexmail-token")++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Flexmail account ID or personal access token"),+ ("forbidden", 403, False, "Invalid Flexmail account ID or personal access token"),+ ("server_error", 500, False, "Flexmail returned HTTP 500"),+ ]+ )+ @patch(f"{flexmail.__name__}.make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_session.return_value = self._session(response)+ assert validate_credentials("12345", "flexmail-token") == (expected_valid, expected_message)+++class TestFlexmailSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = flexmail_source(+ account_id="12345",+ personal_access_token="flexmail-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # No stable creation timestamp exists on most resources, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in FLEXMAIL_ENDPOINTS.values())+ assert set(FLEXMAIL_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail_source.pynew file mode 100644index 000000000000..9491e0d26587--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail_source.py@@ -0,0 +1,139 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.flexmail import FlexmailResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.source import FlexmailSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FlexmailSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestFlexmailSource:+ def setup_method(self) -> None:+ self.source = FlexmailSource()+ self.team_id = 123+ self.config = FlexmailSourceConfig(account_id="12345", personal_access_token="flexmail-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.FLEXMAIL++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Flexmail"+ assert config.label == "Flexmail"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/flexmail"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["account_id", "personal_access_token"]++ def test_personal_access_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "personal_access_token"+ )+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The base URL is hardcoded and the account ID only selects the Flexmail account the token+ # already belongs to, so there is no non-secret field an editor could retarget to exfiltrate+ # a preserved token to another host.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ 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_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["contacts"])+ assert len(schemas) == 1+ assert schemas[0].name == "contacts"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.flexmail.eu/contacts?limit=500&offset=0",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.flexmail.eu/sources?limit=500&offset=0"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.flexmail.eu/contacts",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://api.flexmail.eu/segments",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.source.validate_credentials")+ def test_validate_credentials_delegates_with_credentials(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in flexmail.validate_credentials; here we only assert+ # the source probes with the configured credentials and returns the delegate's verdict.+ mock_validate.return_value = (False, "Invalid Flexmail account ID or personal access token")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("12345", "flexmail-token")+ assert result == (False, "Invalid Flexmail account ID or personal access token")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is FlexmailResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.source.flexmail_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "contacts"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["account_id"] == "12345"+ assert kwargs["personal_access_token"] == "flexmail-token"+ assert kwargs["endpoint"] == "contacts"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Flexmail schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ def test_canonical_descriptions_cover_known_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 522f5b01afba..83bb36561791 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1284,7 +1284,8 @@ class FleetioSourceConfig(config.Config):@config.configclass FlexmailSourceConfig(config.Config):- pass+ account_id: str+ personal_access_token: str@config.config