: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 elasticemail import source (#65650)
Tom Owers763f6a158af8
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 43295df1fb6c..f0320c6a8025 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -94,6 +94,7 @@ the row lists both.| drip | HTTP | requests | ✅ || freshdesk | HTTP | requests | ✅ || freshsales | HTTP | requests | ✅ |+| elasticemail | HTTP | requests | ✅ || elasticsearch | HTTP | requests | ✅ || eventbrite | HTTP | requests | ✅ || front | HTTP | requests | ✅ |@@ -352,7 +353,6 @@ doesn't conflict with concurrent PRs.- easypost- easypromos- ebay-- elasticemail- eloqua- emailoctopus- employment_herodiff --git a/posthog/temporal/data_imports/sources/elasticemail/canonical_descriptions.py b/posthog/temporal/data_imports/sources/elasticemail/canonical_descriptions.pynew file mode 100644index 000000000000..25786e493f8d--- /dev/null+++ b/posthog/temporal/data_imports/sources/elasticemail/canonical_descriptions.py@@ -0,0 +1,89 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Descriptions sourced from the official Elastic Email v4 API reference and SDK models. Keyed by the+# endpoint/schema name returned by `get_schemas`. Columns mirror the PascalCase JSON the API returns.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "contacts": {+ "description": "Email contacts in the account, including their subscription status and custom fields.",+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Contacts",+ "columns": {+ "Email": "Contact's email address. Unique per account.",+ "Status": "Subscription status (e.g. Active, Bounced, Unsubscribed, Transactional).",+ "FirstName": "Contact's first name.",+ "LastName": "Contact's last name.",+ "CustomFields": "Key-value map of custom contact fields defined in the account.",+ "Source": "How the contact was added (e.g. DeliveryApi, ManualInput, FileUpload).",+ "DateAdded": "Date the contact was created, in YYYY-MM-DDThh:mm:ss format.",+ "DateUpdated": "Date the contact was last changed.",+ "StatusChangeDate": "Date of the contact's last status change.",+ },+ },+ "lists": {+ "description": "Contact lists used to group contacts for campaigns.",+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Lists",+ "columns": {+ "ListName": "Name of the list.",+ "PublicListID": "Public ID code of the list (distinct from the internal listid).",+ "DateAdded": "Date the list was created, in YYYY-MM-DDThh:mm:ss format.",+ "AllowUnsubscribe": "Whether contacts are allowed to unsubscribe from this list.",+ },+ },+ "segments": {+ "description": "Dynamic contact segments defined by a rule.",+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Segments",+ "columns": {+ "Name": "Segment name.",+ "Rule": "SQL-like rule that determines which contacts belong to this segment.",+ },+ },+ "campaigns": {+ "description": "Email campaigns configured in the account.",+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Campaigns",+ "columns": {+ "Name": "Campaign name.",+ "Status": "Current campaign status (e.g. Draft, Active, Completed, Paused).",+ "Content": "Campaign email content; multiple items indicate an A/X split campaign.",+ "Recipients": "Lists and segments the campaign is sent to.",+ "Options": "Send and scheduling options for the campaign.",+ },+ },+ "templates": {+ "description": "Reusable email templates (personal and global scope).",+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Templates",+ "columns": {+ "Name": "Template name.",+ "TemplateType": "Template type (e.g. RawHTML, DragDropEditor).",+ "TemplateScope": "Template visibility: Personal or Global.",+ "Subject": "Default email subject for the template.",+ "DateAdded": "Date the template was created, in YYYY-MM-DDThh:mm:ss format.",+ },+ },+ "events": {+ "description": "Recipient-level email events (sends, opens, clicks, bounces, complaints, unsubscribes). Immutable; synced append-only.",+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Events",+ "columns": {+ "TransactionID": "ID of the transaction (send) this event belongs to.",+ "MsgID": "ID of the individual message this event belongs to.",+ "FromEmail": "From address of the email.",+ "To": "Recipient address of the email.",+ "Subject": "Subject of the email.",+ "EventType": "Type of event (Submission, Sent, Open, Click, Bounce, Complaint, Unsubscribe, FailedAttempt).",+ "EventDate": "Date the event occurred.",+ "ChannelName": "Name of the channel the email was sent through.",+ "MessageCategory": "Category of the message (e.g. Spam, BlackListed, NoMailbox, Unknown).",+ "Message": "Error message when sending failed (FailedAttempt or Bounce).",+ "IPAddress": "IP address the email was sent through.",+ "PoolName": "Name of the IP pool the email was sent through.",+ },+ },+ "suppressions": {+ "description": "Suppressed recipients (bounces, complaints, and unsubscribes) that are excluded from sends.",+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Suppressions",+ "columns": {+ "Email": "Suppressed email address.",+ "FriendlyErrorMessage": "Human-readable RFC error message for the suppression.",+ "ErrorCode": "SMTP error code associated with the suppression.",+ "DateUpdated": "Date the suppression was last changed.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/elasticemail/elasticemail.py b/posthog/temporal/data_imports/sources/elasticemail/elasticemail.pynew file mode 100644index 000000000000..0a4c69f49134--- /dev/null+++ b/posthog/temporal/data_imports/sources/elasticemail/elasticemail.py@@ -0,0 +1,240 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+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.batcher import Batcher+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.elasticemail.settings import (+ ELASTICEMAIL_ENDPOINTS,+ PAGE_SIZE,+ ElasticEmailEndpointConfig,+)++ELASTICEMAIL_BASE_URL = "https://api.elasticemail.com/v4"++# Marker carried by ElasticEmailAuthError so `get_non_retryable_errors` can match credential failures.+# Elastic Email returns these as HTTP 400 with an `{"Error": "APIKey Expired"}` style body rather than+# the more usual 401/403, so we can't match on the status line alone.+AUTH_ERROR_MARKER = "Elastic Email API authentication failed"++# A cheap, parameter-free endpoint used to confirm a key is genuine at source-create time.+VALIDATION_PATH = "/statistics"++REQUEST_TIMEOUT_SECONDS = 60+++class ElasticEmailRetryableError(Exception):+ pass+++class ElasticEmailAuthError(Exception):+ pass+++class ElasticEmailResumeConfig:+ # Next offset to request. Elastic Email paginates with limit/offset, so the offset alone is enough+ # to resume mid-endpoint; the incremental `from` window is re-derived from the stored cursor each run.+ offset: int = 0+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "X-ElasticEmail-ApiKey": api_key,+ "Accept": "application/json",+ }+++def _format_datetime(value: Any) -> str:+ """Format a datetime/date as the `YYYY-MM-DDThh:mm:ss` (UTC, no offset) shape Elastic Email expects."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S")+ return str(value)+++def _clamp_future_value_to_now(value: Any) -> Any:+ """Cap a future datetime/date cursor at now so the `from` filter never asks for impossible records."""+ now = datetime.now(UTC)+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return now if aware > now else value+ if isinstance(value, date):+ return now.date() if value > now.date() else value+ return value+++def _build_params(+ config: ElasticEmailEndpointConfig,+ offset: int,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ """Assemble the query params for one page request."""+ params: dict[str, Any] = {"limit": PAGE_SIZE, "offset": offset}+ params.update(config.extra_params)++ # Only endpoints that advertise an incremental field have a server-side `from` time filter.+ if should_use_incremental_field and config.incremental_fields and db_incremental_field_last_value:+ params["from"] = _format_datetime(_clamp_future_value_to_now(db_incremental_field_last_value))++ return params+++def _build_url(path: str, params: dict[str, Any]) -> str:+ # doseq=True expands list values (e.g. scopeType=Personal&scopeType=Global) into repeated params.+ return f"{ELASTICEMAIL_BASE_URL}{path}?{urlencode(params, doseq=True)}"+++def _is_auth_error_body(status_code: int, body: str) -> bool:+ if status_code in (401, 403):+ return True+ if status_code != 400:+ return False+ lowered = body.lower()+ return any(token in lowered for token in ("apikey", "api key", "access token", "unauthorized", "expired"))+++@retry(+ retry=retry_if_exception_type((ElasticEmailRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise ElasticEmailRetryableError(+ f"Elastic Email API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ body = response.text or ""+ # Elastic Email signals a bad/expired/under-scoped key with HTTP 400, not 401/403. Surface it as a+ # distinct, non-retryable error so the sync stops instead of hammering the API with a dead key.+ if _is_auth_error_body(response.status_code, body):+ raise ElasticEmailAuthError(f"{AUTH_ERROR_MARKER} (HTTP {response.status_code}): {body}")+ logger.error(f"Elastic Email API error: status={response.status_code}, body={body}, url={url}")+ response.raise_for_status()++ try:+ data = response.json()+ except ValueError as exc:+ # A 200 with a non-JSON body (e.g. an HTML error page from a CDN/proxy) raises JSONDecodeError,+ # which isn't a retryable type by default. Treat it as transient so the page is retried.+ raise ElasticEmailRetryableError(f"Non-JSON Elastic Email response: url={url}") from exc++ # Every v4 list endpoint returns a bare JSON array. Guard against an unexpected object payload.+ if not isinstance(data, list):+ raise ElasticEmailRetryableError(f"Unexpected Elastic Email response shape (expected list): url={url}")+ return data+++def validate_credentials(+ api_key: str, path: str = VALIDATION_PATH, extra_params: Optional[dict[str, list[str] | str]] = None+) -> bool:+ """Probe a single endpoint to confirm the key is accepted. `path` lets callers check a specific scope."""+ params: dict[str, Any] = {"limit": 1, "offset": 0, **(extra_params or {})}+ url = _build_url(path, params)+ try:+ # redact_values masks the API key in logged URLs and captured HTTP samples; the X-ElasticEmail-ApiKey+ # header name isn't in the transport's generic auth denylist, so we redact the value explicitly.+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=10)+ except requests.RequestException:+ # A transport failure (DNS, connection, timeout) isn't a credential verdict, but at source-create+ # time we can only report valid/invalid — treat an unreachable API as "can't validate" → invalid.+ return False+ if response.ok:+ return True+ return not _is_auth_error_body(response.status_code, response.text or "")+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ElasticEmailResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = ELASTICEMAIL_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page so urllib3 keeps the connection alive between requests.+ # redact_values masks the API key in logged URLs and captured HTTP samples; the X-ElasticEmail-ApiKey+ # header name isn't in the transport's generic auth denylist, so we redact the value explicitly.+ session = make_tracked_session(redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume is not None else 0+ if resume is not None:+ logger.debug(f"Elastic Email: resuming {endpoint} from offset={offset}")++ while True:+ params = _build_params(config, offset, should_use_incremental_field, db_incremental_field_last_value)+ url = _build_url(config.path, params)+ items = _fetch_page(session, url, headers, logger)++ for item in items:+ batcher.batch(item)++ offset += len(items)+ last_page = len(items) < PAGE_SIZE++ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding so a crash re-fetches from the last persisted offset rather than skipping+ # rows. Only persist when more pages remain; the final flush below needs no checkpoint.+ if not last_page:+ resumable_source_manager.save_state(ElasticEmailResumeConfig(offset=offset))++ if last_page:+ break++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def elasticemail_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ElasticEmailResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = ELASTICEMAIL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Events are fetched oldest-first (orderBy=DateAscending); the other endpoints are full refresh+ # where order does not affect correctness.+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/elasticemail/settings.py b/posthog/temporal/data_imports/sources/elasticemail/settings.pynew file mode 100644index 000000000000..d26e0c1024d5--- /dev/null+++ b/posthog/temporal/data_imports/sources/elasticemail/settings.py@@ -0,0 +1,95 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Elastic Email v4 caps each request at 1000 items and most list endpoints accept limit/offset.+# Use the max page size so we make as few round-trips as possible.+PAGE_SIZE = 1000+++@dataclass+class ElasticEmailEndpointConfig:+ name: str+ path: str+ # Keys must be unique across the whole table. Most v4 resources are keyed by their natural name+ # (the value used in the resource's `/{name}` path); events have no single id so they use a composite.+ primary_keys: list[str]+ # A STABLE creation-style field used for datetime partitioning. Never a "last updated" field, which+ # would rewrite partitions on every sync. None when the resource exposes no stable date.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Append-only resources (immutable events) are synced with the incremental `from`/`to` time filter+ # but inserted rather than merged, since they have no reliably-unique primary key.+ append_only: bool = False+ # Static query params merged into every request for this endpoint (e.g. templates require `scopeType`,+ # events force ascending order so the watermark advances correctly).+ extra_params: dict[str, list[str] | str] = field(default_factory=dict)+ should_sync_default: bool = True+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++ELASTICEMAIL_ENDPOINTS: dict[str, ElasticEmailEndpointConfig] = {+ "contacts": ElasticEmailEndpointConfig(+ name="contacts",+ path="/contacts",+ primary_keys=["Email"],+ partition_key="DateAdded",+ ),+ "lists": ElasticEmailEndpointConfig(+ name="lists",+ path="/lists",+ primary_keys=["ListName"],+ partition_key="DateAdded",+ ),+ "segments": ElasticEmailEndpointConfig(+ name="segments",+ path="/segments",+ primary_keys=["Name"],+ ),+ "campaigns": ElasticEmailEndpointConfig(+ name="campaigns",+ path="/campaigns",+ primary_keys=["Name"],+ ),+ "templates": ElasticEmailEndpointConfig(+ name="templates",+ path="/templates",+ primary_keys=["Name"],+ partition_key="DateAdded",+ # scopeType is a required query param; request both visibility scopes so all templates are returned.+ extra_params={"scopeType": ["Personal", "Global"]},+ ),+ "events": ElasticEmailEndpointConfig(+ name="events",+ path="/events",+ # A transaction fans out into multiple event rows (Sent, Open, Click, ...); the only combination+ # that is unique per row is the message + event type + timestamp. Events carry no row id.+ primary_keys=["TransactionID", "MsgID", "EventType", "EventDate"],+ partition_key="EventDate",+ append_only=True,+ incremental_fields=[_datetime_incremental_field("EventDate")],+ # Default order is DateDescending; force ascending so rows arrive oldest-first and the+ # incremental watermark advances safely (sort_mode="asc").+ extra_params={"orderBy": "DateAscending"},+ ),+ "suppressions": ElasticEmailEndpointConfig(+ name="suppressions",+ path="/suppressions",+ primary_keys=["Email"],+ ),+}++ENDPOINTS = tuple(ELASTICEMAIL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ELASTICEMAIL_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/elasticemail/source.py b/posthog/temporal/data_imports/sources/elasticemail/source.pyindex 959890d8ba94..1ec7a0c5507a 100644--- a/posthog/temporal/data_imports/sources/elasticemail/source.py+++ b/posthog/temporal/data_imports/sources/elasticemail/source.py@@ -1,20 +1,37 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,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.canonical_descriptions import CanonicalDescriptionsfrom 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.elasticemail.elasticemail import (+ ElasticEmailResumeConfig,+ elasticemail_source,+ validate_credentials as validate_elasticemail_credentials,+)+from posthog.temporal.data_imports.sources.elasticemail.settings import (+ ELASTICEMAIL_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from posthog.temporal.data_imports.sources.generated_configs import ElasticemailSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class ElasticemailSource(SimpleSource[ElasticemailSourceConfig]):+class ElasticemailSource(ResumableSource[ElasticemailSourceConfig, ElasticEmailResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ELASTICEMAIL@@ -24,8 +41,103 @@ class ElasticemailSource(SimpleSource[ElasticemailSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.ELASTICEMAIL,category=DataWarehouseSourceCategory.MARKETING___EMAIL,- label="Elasticemail",- iconPath="/static/services/elasticemail.png",- fields=cast(list[FieldType], []),+ label="Elastic Email",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Elastic Email API key to pull your Elastic Email data into the PostHog Data warehouse.++You can create an API key in your [Elastic Email account settings](https://app.elasticemail.com/marketing/settings/new/manage-api).++Grant the key read access to the data you want to sync (Contacts, Campaigns, Templates, Reports, etc.).""",+ iconPath="/static/services/elasticemail.png",+ docsUrl="https://posthog.com/docs/cdp/sources/elasticemail",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # Elastic Email rejects bad/expired/under-scoped keys with HTTP 400; `_fetch_page` raises an+ # ElasticEmailAuthError carrying this marker. Retrying can never fix a credential problem.+ "Elastic Email API authentication failed": "Your Elastic Email API key is invalid, expired, or missing the required read permissions. Create a new key in your Elastic Email account settings, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.elasticemail.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: ElasticemailSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = ELASTICEMAIL_ENDPOINTS[endpoint]+ has_incremental_field = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ # Events are immutable, so they sync append-only via the server-side `from` filter. No+ # other list endpoint exposes a server-side timestamp filter, so they are full refresh only.+ supports_incremental=False,+ supports_append=has_incremental_field and endpoint_config.append_only,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) 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: ElasticemailSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # At source-create (schema_name=None) probe a cheap generic endpoint; for a specific schema, probe+ # that endpoint's path so we surface a per-endpoint permission problem early.+ if schema_name is not None and schema_name in ELASTICEMAIL_ENDPOINTS:+ endpoint_config = ELASTICEMAIL_ENDPOINTS[schema_name]+ valid = validate_elasticemail_credentials(+ config.api_key, endpoint_config.path, endpoint_config.extra_params+ )+ else:+ valid = validate_elasticemail_credentials(config.api_key)++ if valid:+ return True, None+ return False, "Invalid Elastic Email API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ElasticEmailResumeConfig]:+ return ResumableSourceManager[ElasticEmailResumeConfig](inputs, ElasticEmailResumeConfig)++ def source_for_pipeline(+ self,+ config: ElasticemailSourceConfig,+ resumable_source_manager: ResumableSourceManager[ElasticEmailResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return elasticemail_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/posthog/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py b/posthog/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.pynew file mode 100644index 000000000000..199552fe1df1--- /dev/null+++ b/posthog/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py@@ -0,0 +1,335 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.elasticemail import elasticemail+from posthog.temporal.data_imports.sources.elasticemail.elasticemail import (+ AUTH_ERROR_MARKER,+ ElasticEmailAuthError,+ ElasticEmailResumeConfig,+ ElasticEmailRetryableError,+ _build_params,+ _build_url,+ _clamp_future_value_to_now,+ _format_datetime,+ _is_auth_error_body,+ elasticemail_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.elasticemail.settings import ELASTICEMAIL_ENDPOINTS+++class TestFormatDatetime:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00"),+ ("string_passthrough", "some-cursor", "some-cursor"),+ ]+ )+ def test_format_datetime(self, _name: str, value: Any, expected: str) -> None:+ assert _format_datetime(value) == expected++ def test_no_offset_suffix(self) -> None:+ # Elastic Email expects YYYY-MM-DDThh:mm:ss with no timezone offset.+ result = _format_datetime(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+ assert "+" not in result and "Z" not in result+++class TestClampFutureValueToNow:+ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_datetime_is_clamped(self) -> None:+ assert _clamp_future_value_to_now(datetime(2027, 2, 5, tzinfo=UTC)) == datetime(+ 2026, 6, 15, 12, 0, 0, tzinfo=UTC+ )++ @freeze_time("2026-06-15T12:00:00Z")+ def test_past_datetime_is_unchanged(self) -> None:+ value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)+ assert _clamp_future_value_to_now(value) == value++ def test_string_passthrough(self) -> None:+ assert _clamp_future_value_to_now("cursor") == "cursor"+++class TestBuildParams:+ def test_events_incremental_adds_from_filter(self) -> None:+ params = _build_params(+ ELASTICEMAIL_ENDPOINTS["events"],+ offset=0,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert params["from"] == "2026-03-04T02:58:14"+ assert params["orderBy"] == "DateAscending"+ assert params["limit"] == elasticemail.PAGE_SIZE++ def test_events_without_cursor_has_no_from(self) -> None:+ params = _build_params(+ ELASTICEMAIL_ENDPOINTS["events"],+ offset=0,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ assert "from" not in params++ def test_full_refresh_endpoint_never_adds_from(self) -> None:+ # Contacts has no server-side time filter, so a cursor value must not leak into the request.+ params = _build_params(+ ELASTICEMAIL_ENDPOINTS["contacts"],+ offset=40,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert "from" not in params+ assert params["offset"] == 40++ def test_templates_carries_required_scope_type(self) -> None:+ params = _build_params(+ ELASTICEMAIL_ENDPOINTS["templates"],+ offset=0,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert params["scopeType"] == ["Personal", "Global"]+++class TestBuildUrl:+ def test_expands_list_params_into_repeated_query(self) -> None:+ url = _build_url("/templates", {"limit": 1, "scopeType": ["Personal", "Global"]})+ assert url == "https://api.elasticemail.com/v4/templates?limit=1&scopeType=Personal&scopeType=Global"+++class TestIsAuthErrorBody:+ @parameterized.expand(+ [+ ("401", 401, "", True),+ ("403", 403, "", True),+ ("400_apikey_expired", 400, '{"Error":"APIKey Expired"}', True),+ ("400_incorrect_key", 400, '{"Error":"Incorrect API key."}', True),+ ("400_generic_bad_request", 400, '{"Error":"Invalid date range"}', False),+ ("404", 404, '{"Error":"Not found"}', False),+ ("200", 200, "[]", False),+ ]+ )+ def test_is_auth_error_body(self, _name: str, status: int, body: str, expected: bool) -> None:+ assert _is_auth_error_body(status, body) is expected+++def _make_response(status_code: int, *, json_body: Any = None, text: str | None = None) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ if json_body is not None:+ import json++ response._content = json.dumps(json_body).encode()+ elif text is not None:+ response._content = text.encode()+ return response+++class _FakeSession:+ def __init__(self, response: requests.Response) -> None:+ self._response = response+ self.requested_urls: list[str] = []++ def get(self, url: str, headers: dict[str, str], timeout: int) -> requests.Response:+ self.requested_urls.append(url)+ return self._response+++class TestFetchPage:+ # Call the undecorated body so tests exercise the status handling without tenacity's retry/backoff.+ _fetch = staticmethod(elasticemail._fetch_page.__wrapped__) # type: ignore[attr-defined]+ _url = "https://api.elasticemail.com/v4/contacts"++ def test_returns_list_on_ok(self) -> None:+ session = _FakeSession(_make_response(200, json_body=[{"Email": "[email protected]"}]))+ assert self._fetch(session, self._url, {}, MagicMock()) == [{"Email": "[email protected]"}]++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])+ def test_retryable_statuses_raise_retryable(self, _name: str, status: int) -> None:+ session = _FakeSession(_make_response(status, text="boom"))+ with pytest.raises(ElasticEmailRetryableError):+ self._fetch(session, self._url, {}, MagicMock())++ @parameterized.expand([("expired_key", 400, '{"Error":"APIKey Expired"}'), ("unauthorized", 401, "")])+ def test_auth_failures_raise_auth_error(self, _name: str, status: int, body: str) -> None:+ session = _FakeSession(_make_response(status, text=body))+ with pytest.raises(ElasticEmailAuthError) as exc:+ self._fetch(session, self._url, {}, MagicMock())+ assert AUTH_ERROR_MARKER in str(exc.value)++ def test_non_list_payload_raises_retryable(self) -> None:+ session = _FakeSession(_make_response(200, json_body={"Error": "unexpected"}))+ with pytest.raises(ElasticEmailRetryableError):+ self._fetch(session, self._url, {}, MagicMock())++ def test_non_json_body_raises_retryable(self) -> None:+ # A 200 with an HTML/proxy body must not propagate a raw JSONDecodeError past the retry layer.+ session = _FakeSession(_make_response(200, text="<html>gateway timeout</html>"))+ with pytest.raises(ElasticEmailRetryableError):+ self._fetch(session, self._url, {}, MagicMock())+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, "[]", True),+ ("expired_key", 400, '{"Error":"APIKey Expired"}', False),+ ("unauthorized", 401, "", False),+ ("forbidden", 403, "", False),+ # A non-auth error (e.g. a transient 500) should not be reported as an invalid key.+ ("server_error", 500, "boom", True),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, body: str, expected: bool) -> None:+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(+ elasticemail,+ "make_tracked_session",+ lambda **_: _FakeSession(_make_response(status, text=body)),+ )+ assert validate_credentials("key") is expected++ def test_transport_exception_is_invalid(self, monkeypatch: Any) -> None:+ class _Boom:+ def get(self, *a: Any, **k: Any) -> Any:+ raise requests.ConnectionError("down")++ monkeypatch.setattr(elasticemail, "make_tracked_session", lambda **_: _Boom())+ assert validate_credentials("key") is False+++class _FakeBatcher:+ """Yields after every page so the save-after-batch contract is testable without 2000+ rows."""++ def __init__(self, **_kwargs: Any) -> None:+ self._rows: list[dict] = []++ def batch(self, item: dict) -> None:+ self._rows.append(item)++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return len(self._rows) > 0++ def get_table(self) -> list[dict]:+ rows = self._rows+ self._rows = []+ return rows+++class _FakeManager:+ def __init__(self, state: ElasticEmailResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ElasticEmailResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ElasticEmailResumeConfig | None:+ return self._state++ def save_state(self, data: ElasticEmailResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ def _patch(self, monkeypatch: Any, pages: dict[int, list[dict]]) -> list[int]:+ requested_offsets: list[int] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> list[dict]:+ # Offset is the last query param built by _build_params/_build_url.+ offset = int(url.split("offset=")[1].split("&")[0])+ requested_offsets.append(offset)+ return pages[offset]++ monkeypatch.setattr(elasticemail, "_fetch_page", fake_fetch)+ monkeypatch.setattr(elasticemail, "Batcher", _FakeBatcher)+ monkeypatch.setattr(elasticemail, "PAGE_SIZE", 2)+ return requested_offsets++ def _collect(self, manager: _FakeManager) -> list[dict]:+ rows: list[dict] = []+ for table in get_rows(+ api_key="key",+ endpoint="contacts",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(table)+ return rows++ def test_paginates_until_short_page(self, monkeypatch: Any) -> None:+ offsets = self._patch(+ monkeypatch,+ {+ 0: [{"Email": "a"}, {"Email": "b"}],+ 2: [{"Email": "c"}, {"Email": "d"}],+ 4: [{"Email": "e"}], # short page → terminate+ },+ )+ rows = self._collect(_FakeManager())+ assert [r["Email"] for r in rows] == ["a", "b", "c", "d", "e"]+ assert offsets == [0, 2, 4]++ def test_saves_offset_after_each_non_final_page(self, monkeypatch: Any) -> None:+ self._patch(+ monkeypatch,+ {0: [{"Email": "a"}, {"Email": "b"}], 2: [{"Email": "c"}, {"Email": "d"}], 4: [{"Email": "e"}]},+ )+ manager = _FakeManager()+ self._collect(manager)+ # State is saved after the two full pages (next offsets 2 and 4); the short final page saves nothing.+ assert [s.offset for s in manager.saved] == [2, 4]++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ offsets = self._patch(monkeypatch, {2: [{"Email": "c"}, {"Email": "d"}], 4: [{"Email": "e"}]})+ rows = self._collect(_FakeManager(ElasticEmailResumeConfig(offset=2)))+ assert offsets[0] == 2+ assert [r["Email"] for r in rows] == ["c", "d", "e"]++ def test_empty_first_page_terminates(self, monkeypatch: Any) -> None:+ offsets = self._patch(monkeypatch, {0: []})+ rows = self._collect(_FakeManager())+ assert rows == []+ assert offsets == [0]+++class TestElasticemailSource:+ @parameterized.expand(+ [+ ("contacts", ["Email"], "DateAdded"),+ ("lists", ["ListName"], "DateAdded"),+ ("segments", ["Name"], None),+ ("campaigns", ["Name"], None),+ ("templates", ["Name"], "DateAdded"),+ ("events", ["TransactionID", "MsgID", "EventType", "EventDate"], "EventDate"),+ ("suppressions", ["Email"], None),+ ]+ )+ def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_key: str | None) -> None:+ response = elasticemail_source(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == "asc"+ if partition_key is None:+ assert response.partition_mode is None+ assert response.partition_keys is None+ else:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]+ assert response.partition_format == "week"diff --git a/posthog/temporal/data_imports/sources/elasticemail/tests/test_elasticemail_source.py b/posthog/temporal/data_imports/sources/elasticemail/tests/test_elasticemail_source.pynew file mode 100644index 000000000000..2c5f1b9eb8e5--- /dev/null+++ b/posthog/temporal/data_imports/sources/elasticemail/tests/test_elasticemail_source.py@@ -0,0 +1,138 @@+from types import SimpleNamespace+from typing import Any++from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.elasticemail import source as source_module+from posthog.temporal.data_imports.sources.elasticemail.elasticemail import ElasticEmailResumeConfig+from posthog.temporal.data_imports.sources.elasticemail.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.elasticemail.source import ElasticemailSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert ElasticemailSource().source_type == ExternalDataSourceType.ELASTICEMAIL++ def test_get_source_config(self) -> None:+ config = ElasticemailSource().get_source_config+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.fields is not None+ assert len(config.fields) == 1+ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+++class TestGetSchemas:+ def test_returns_all_endpoints(self) -> None:+ schemas = ElasticemailSource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_filters_by_names(self) -> None:+ schemas = ElasticemailSource().get_schemas(MagicMock(), team_id=1, names=["contacts", "events"])+ assert {s.name for s in schemas} == {"contacts", "events"}++ def test_events_are_append_only(self) -> None:+ schemas = {s.name: s for s in ElasticemailSource().get_schemas(MagicMock(), team_id=1)}+ events = schemas["events"]+ # Events are immutable and the only endpoint with a server-side time filter → append, not merge.+ assert events.supports_incremental is False+ assert events.supports_append is True+ assert [f["field"] for f in events.incremental_fields] == ["EventDate"]++ @parameterized.expand([("contacts",), ("lists",), ("segments",), ("campaigns",), ("templates",), ("suppressions",)])+ def test_non_event_endpoints_are_full_refresh(self, endpoint: str) -> None:+ schemas = {s.name: s for s in ElasticemailSource().get_schemas(MagicMock(), team_id=1)}+ schema = schemas[endpoint]+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []+++class TestValidateCredentials:+ def test_success(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(source_module, "validate_elasticemail_credentials", lambda *a, **k: True)+ valid, error = ElasticemailSource().validate_credentials(SimpleNamespace(api_key="key"), team_id=1) # type: ignore[arg-type]+ assert valid is True+ assert error is None++ def test_failure(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(source_module, "validate_elasticemail_credentials", lambda *a, **k: False)+ valid, error = ElasticemailSource().validate_credentials(SimpleNamespace(api_key="bad"), team_id=1) # type: ignore[arg-type]+ assert valid is False+ assert error == "Invalid Elastic Email API key"++ def test_per_schema_probe_uses_endpoint_path(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_validate(api_key: str, path: str = "/statistics", extra_params: Any = None) -> bool:+ captured["path"] = path+ captured["extra_params"] = extra_params+ return True++ monkeypatch.setattr(source_module, "validate_elasticemail_credentials", fake_validate)+ ElasticemailSource().validate_credentials(SimpleNamespace(api_key="key"), team_id=1, schema_name="templates") # type: ignore[arg-type]+ assert captured["path"] == "/templates"+ assert captured["extra_params"] == {"scopeType": ["Personal", "Global"]}+++class TestNonRetryableErrors:+ def test_auth_error_is_non_retryable(self) -> None:+ errors = ElasticemailSource().get_non_retryable_errors()+ observed = (+ 'ElasticEmailAuthError: Elastic Email API authentication failed (HTTP 400): {"Error":"APIKey Expired"}'+ )+ assert any(key in observed for key in errors)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.elasticemail.com', port=443): Read timed out."),+ ("server_error", "ElasticEmailRetryableError: status=500"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:+ errors = ElasticemailSource().get_non_retryable_errors()+ assert not any(key in observed for key in errors)+++class TestResumableAndCanonical:+ def test_resumable_manager_is_bound_to_resume_config(self) -> None:+ inputs = SimpleNamespace(logger=MagicMock())+ manager = ElasticemailSource().get_resumable_source_manager(inputs) # type: ignore[arg-type]+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ElasticEmailResumeConfig++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = ElasticemailSource().get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = SimpleNamespace(+ schema_name="events",+ logger=MagicMock(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00",+ )+ response = ElasticemailSource().source_for_pipeline(+ SimpleNamespace(api_key="key"), # type: ignore[arg-type]+ MagicMock(),+ inputs, # type: ignore[arg-type]+ )+ assert response.name == "events"+ assert response.primary_keys == ["TransactionID", "MsgID", "EventType", "EventDate"]diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 63e31c053e1a..69ac69a5333d 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -1002,7 +1002,7 @@ class EbaySourceConfig(config.Config):@config.configclass ElasticemailSourceConfig(config.Config):- pass+ api_key: str@config.config