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 Mailgun source (#62654)

Tom Owersfae098d7a07e
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 42509fdfe040..c597086b148a 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.
| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
| mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |
| mailerlite | HTTP | requests | ✅ |
+| mailgun | HTTP | requests | ✅ |
| mailjet | HTTP | requests | ✅ |
| meta_ads | HTTP | requests | ✅ |
| mixpanel | HTTP | requests | ✅ |
@@ -253,7 +254,6 @@ doesn't conflict with concurrent PRs.
- lattice
- lever
- lightspeed_retail
-- mailgun
- marketo
- matomo
- microsoft_teams
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index eb60b9a2e727..ce344c86b49b 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -791,7 +791,8 @@ class MailerLiteSourceConfig(config.Config):
@config.config
class MailgunSourceConfig(config.Config):
- pass
+ api_key: str
+ region: Literal["us", "eu"] = config.value(default="us")
@config.config
diff --git a/posthog/temporal/data_imports/sources/mailgun/mailgun.py b/posthog/temporal/data_imports/sources/mailgun/mailgun.py
new file mode 100644
index 000000000000..291541dfc790
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailgun/mailgun.py
@@ -0,0 +1,339 @@
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from email.utils import parsedate_to_datetime
+from typing import Any, Optional
+from urllib.parse import parse_qs, quote, urlencode, urlsplit, urlunsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, 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.mailgun.settings import MAILGUN_ENDPOINTS, MailgunEndpointConfig
+
+REGION_BASE_URLS = {
+ "us": "https://api.mailgun.net",
+ "eu": "https://api.eu.mailgun.net",
+}
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+MAX_RETRY_AFTER_SECONDS = 120
+# Mailgun events are eventually consistent — the docs recommend treating the trailing
+# ~30 minutes as incomplete. Bounding `end` keeps the incremental watermark behind the
+# consistency horizon so late-arriving events aren't skipped on the next sync.
+EVENTS_CONSISTENCY_LAG_SECONDS = 30 * 60
+
+
+class MailgunRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None):
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class MailgunResumeConfig:
+ # URL of the next page to fetch for the in-flight chain (None = start the next domain).
+ next_url: Optional[str] = None
+ # Domain the in-flight chain belongs to, injected into each row of the resumed pages.
+ current_domain: Optional[str] = None
+ # Domains not yet started, in fan-out order.
+ pending_domains: list[str] = dataclasses.field(default_factory=list)
+
+
+def base_url_for_region(region: str) -> str:
+ return REGION_BASE_URLS.get(region.lower(), REGION_BASE_URLS["us"])
+
+
+def _to_epoch(value: Any) -> Optional[int]:
+ """Coerce an incremental cursor value to UNIX epoch seconds for the `begin` filter."""
+ if value is None or isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ return int(value)
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return int(dt.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ try:
+ return int(float(value))
+ except (TypeError, ValueError):
+ return None
+
+
+def _epoch_to_datetime(value: Any) -> Any:
+ """Convert Mailgun's float-epoch event timestamps into timezone-aware datetimes.
+
+ Raw floats can't be used for datetime partitioning or DateTime incremental cursors,
+ so the column is normalized; unparseable values pass through unchanged."""
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ return datetime.fromtimestamp(value, tz=UTC)
+ return value
+
+
+def _parse_retry_after(value: str | None) -> float | None:
+ if not value:
+ return None
+ try:
+ return max(float(value), 0)
+ except ValueError:
+ pass
+ try:
+ retry_at = parsedate_to_datetime(value)
+ return max((retry_at - datetime.now(UTC)).total_seconds(), 0)
+ except (TypeError, ValueError):
+ return None
+
+
+_exponential_wait = wait_exponential_jitter(initial=1, max=60)
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ exception = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exception, MailgunRetryableError) and exception.retry_after is not None:
+ return min(exception.retry_after, MAX_RETRY_AFTER_SECONDS)
+ return _exponential_wait(retry_state)
+
+
+def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:
+ clean_params = {key: value for key, value in params.items() if value is not None}
+ if not clean_params:
+ return f"{base_url}{path}"
+ return f"{base_url}{path}?{urlencode(clean_params)}"
+
+
+def _endpoint_path(config: MailgunEndpointConfig, domain: Optional[str]) -> str:
+ if not config.domain_scoped:
+ return config.path
+ if domain is None:
+ raise ValueError(f"Mailgun endpoint {config.name} requires a domain")
+ return config.path.format(domain=quote(domain, safe=""))
+
+
+def _initial_url(
+ base_url: str,
+ config: MailgunEndpointConfig,
+ domain: Optional[str],
+ begin: Optional[int] = None,
+) -> Optional[str]:
+ params: dict[str, Any] = {"limit": config.page_size}
+
+ if config.pagination == "skip":
+ params["skip"] = 0
+
+ if config.name == "events":
+ # Ascending creation order keeps fetched pages stable and lets the incremental
+ # watermark advance monotonically.
+ params["ascending"] = "yes"
+ end = int(time.time()) - EVENTS_CONSISTENCY_LAG_SECONDS
+ if begin is not None and begin >= end:
+ # Watermark is already inside the consistency lag window; nothing safe to fetch.
+ return None
+ params["begin"] = begin
+ params["end"] = end
+
+ return _build_url(base_url, _endpoint_path(config, domain), params)
+
+
+def _increment_skip(current_url: str, page_size: int) -> str:
+ scheme, netloc, path, query, fragment = urlsplit(current_url)
+ params = {key: values[-1] for key, values in parse_qs(query).items()}
+ try:
+ skip = int(params.get("skip", "0"))
+ except ValueError:
+ skip = 0
+ params["skip"] = str(skip + page_size)
+ return urlunsplit((scheme, netloc, path, urlencode(params), fragment))
+
+
+def _next_page_url(
+ config: MailgunEndpointConfig, current_url: str, data: dict[str, Any], items_count: int
+) -> Optional[str]:
+ if config.pagination == "skip":
+ if items_count < config.page_size:
+ return None
+ return _increment_skip(current_url, config.page_size)
+
+ # Paging-style endpoints terminate with an empty `items` page; the `next` URL of that
+ # empty page would just return another empty page (or, for events, later events that
+ # are out of this sync's scope).
+ if items_count == 0:
+ return None
+ next_url = (data.get("paging") or {}).get("next")
+ return next_url or None
+
+
+def _normalize_row(config: MailgunEndpointConfig, domain: Optional[str], item: dict[str, Any]) -> dict[str, Any]:
+ row = dict(item)
+ if config.domain_scoped:
+ # Rows from different sending domains can collide on their natural key (e.g. the
+ # same suppressed address), so the fan-out domain is part of every primary key.
+ row["domain"] = domain
+ if config.name == "events":
+ row["timestamp"] = _epoch_to_datetime(row.get("timestamp"))
+ return row
+
+
+@retry(
+ retry=retry_if_exception_type((MailgunRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+)
+def _fetch_page(url: str, api_key: str, logger: FilteringBoundLogger) -> dict[str, Any]:
+ # Mailgun auth is HTTP basic with the literal username "api" and the private API key
+ # as the password. Rate limits are plan-dependent; 429s honor Retry-After when present.
+ response = make_tracked_session().get(
+ url,
+ auth=("api", api_key),
+ headers={"Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MailgunRetryableError(
+ f"Mailgun API error (retryable): status={response.status_code}, url={url}",
+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),
+ )
+
+ if not response.ok:
+ logger.error(f"Mailgun API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_domain_names(api_key: str, base_url: str, logger: FilteringBoundLogger) -> list[str]:
+ config = MAILGUN_ENDPOINTS["domains"]
+ names: list[str] = []
+ skip = 0
+
+ while True:
+ url = _build_url(base_url, config.path, {"limit": config.page_size, "skip": skip})
+ data = _fetch_page(url, api_key, logger)
+ items = data.get("items") or []
+ names.extend(item["name"] for item in items if item.get("name"))
+
+ if len(items) < config.page_size:
+ return names
+
+ skip += config.page_size
+
+
+def validate_credentials(api_key: str, region: str) -> bool:
+ """Confirm the private API key is valid for the region. A 1-item domain listing is a cheap probe."""
+ try:
+ response = make_tracked_session().get(
+ f"{base_url_for_region(region)}/v4/domains",
+ params={"limit": 1},
+ auth=("api", api_key),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailgunResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = MAILGUN_ENDPOINTS[endpoint]
+ base_url = base_url_for_region(region)
+
+ begin: Optional[int] = None
+ if should_use_incremental_field and (incremental_field is None or incremental_field == "timestamp"):
+ begin = _to_epoch(db_incremental_field_last_value)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if resume_config is not None:
+ pending_domains = list(resume_config.pending_domains)
+ current_domain = resume_config.current_domain
+ current_url = resume_config.next_url
+ logger.debug(
+ f"Mailgun: resuming {endpoint}. url={current_url}, domain={current_domain}, pending={len(pending_domains)}"
+ )
+ elif config.domain_scoped:
+ pending_domains = get_domain_names(api_key, base_url, logger)
+ current_domain = None
+ current_url = None
+ else:
+ pending_domains = []
+ current_domain = None
+ current_url = _initial_url(base_url, config, None, begin)
+
+ while current_url is not None or pending_domains:
+ if current_url is None:
+ current_domain = pending_domains.pop(0)
+ current_url = _initial_url(base_url, config, current_domain, begin)
+ if current_url is None:
+ current_domain = None
+ resumable_source_manager.save_state(MailgunResumeConfig(pending_domains=pending_domains))
+ continue
+
+ data = _fetch_page(current_url, api_key, logger)
+ items = data.get("items") or []
+
+ if items:
+ yield [_normalize_row(config, current_domain, item) for item in items]
+
+ current_url = _next_page_url(config, current_url, data, len(items))
+ if current_url is None:
+ current_domain = None
+
+ # Save after yielding so a crash re-yields the last batch (merge dedupes on
+ # primary key) instead of skipping it.
+ resumable_source_manager.save_state(
+ MailgunResumeConfig(
+ next_url=current_url,
+ current_domain=current_domain,
+ pending_domains=pending_domains,
+ )
+ )
+
+
+def mailgun_source(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailgunResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = MAILGUN_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ region=region,
+ 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,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=list(config.primary_keys),
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format=config.partition_format if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/mailgun/settings.py b/posthog/temporal/data_imports/sources/mailgun/settings.py
new file mode 100644
index 000000000000..0a2152970fe5
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailgun/settings.py
@@ -0,0 +1,115 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+PaginationStyle = Literal["paging", "skip"]
+
+
+@dataclass
+class MailgunEndpointConfig:
+ name: str
+ # Path relative to the regional API host. Contains a `{domain}` placeholder for
+ # domain-scoped endpoints, which fan out over every sending domain on the account.
+ path: str
+ domain_scoped: bool = False
+ # "paging" endpoints return opaque next/previous URLs in a `paging` object and
+ # terminate with an empty `items` page; "skip" endpoints use limit/skip offsets.
+ pagination: PaginationStyle = "paging"
+ page_size: int = 100
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style
+ # field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ partition_format: Optional[PartitionFormat] = None
+
+
+# Only the Events API exposes a server-side timestamp filter (`begin`/`end` epoch seconds
+# with `ascending=yes`), so it's the only endpoint advertised as incremental. Domains,
+# suppressions, mailing lists, tags, and templates have no updated-at filter — full
+# refresh only. Domain-scoped rows get a `domain` column injected so primary keys stay
+# unique across domains.
+MAILGUN_ENDPOINTS: dict[str, MailgunEndpointConfig] = {
+ "domains": MailgunEndpointConfig(
+ name="domains",
+ path="/v4/domains",
+ pagination="skip",
+ page_size=1000,
+ primary_keys=["id"],
+ ),
+ "events": MailgunEndpointConfig(
+ name="events",
+ path="/v3/{domain}/events",
+ domain_scoped=True,
+ # Events API caps pages at 300 items.
+ page_size=300,
+ primary_keys=["domain", "id"],
+ partition_key="timestamp",
+ partition_format="day",
+ incremental_fields=[
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "bounces": MailgunEndpointConfig(
+ name="bounces",
+ path="/v3/{domain}/bounces",
+ domain_scoped=True,
+ page_size=1000,
+ primary_keys=["domain", "address"],
+ partition_key="created_at",
+ partition_format="month",
+ ),
+ "complaints": MailgunEndpointConfig(
+ name="complaints",
+ path="/v3/{domain}/complaints",
+ domain_scoped=True,
+ page_size=1000,
+ primary_keys=["domain", "address"],
+ partition_key="created_at",
+ partition_format="month",
+ ),
+ "unsubscribes": MailgunEndpointConfig(
+ name="unsubscribes",
+ path="/v3/{domain}/unsubscribes",
+ domain_scoped=True,
+ page_size=1000,
+ primary_keys=["domain", "address"],
+ partition_key="created_at",
+ partition_format="month",
+ ),
+ "mailing_lists": MailgunEndpointConfig(
+ name="mailing_lists",
+ path="/v3/lists/pages",
+ page_size=100,
+ primary_keys=["address"],
+ ),
+ "tags": MailgunEndpointConfig(
+ name="tags",
+ path="/v3/{domain}/tags",
+ domain_scoped=True,
+ page_size=100,
+ primary_keys=["domain", "tag"],
+ ),
+ "templates": MailgunEndpointConfig(
+ name="templates",
+ path="/v3/{domain}/templates",
+ domain_scoped=True,
+ page_size=100,
+ # Template names are unique per domain; list items aren't guaranteed an `id`.
+ primary_keys=["domain", "name"],
+ ),
+}
+
+ENDPOINTS = tuple(MAILGUN_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in MAILGUN_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/mailgun/source.py b/posthog/temporal/data_imports/sources/mailgun/source.py
index 730727e992ca..ccdaa6ea9458 100644
--- a/posthog/temporal/data_imports/sources/mailgun/source.py
+++ b/posthog/temporal/data_imports/sources/mailgun/source.py
@@ -1,29 +1,133 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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 MailgunSourceConfig
+from posthog.temporal.data_imports.sources.mailgun.mailgun import (
+ MailgunResumeConfig,
+ mailgun_source,
+ validate_credentials as validate_mailgun_credentials,
+)
+from posthog.temporal.data_imports.sources.mailgun.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MailgunSource(SimpleSource[MailgunSourceConfig]):
+class MailgunSource(ResumableSource[MailgunSourceConfig, MailgunResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MAILGUN
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.mailgun.net": "Mailgun authentication failed. Please check your private API key.",
+ "401 Client Error: Unauthorized for url: https://api.eu.mailgun.net": "Mailgun authentication failed. Please check your private API key and that the EU region is correct for your account.",
+ "403 Client Error: Forbidden for url: https://api.mailgun.net": "Mailgun denied access. Please check that your API key has the required permissions.",
+ "403 Client Error: Forbidden for url: https://api.eu.mailgun.net": "Mailgun denied access. Please check that your API key has the required permissions.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.MAILGUN,
label="Mailgun",
+ caption="""Enter your Mailgun private API key to pull your Mailgun data into the PostHog Data warehouse.
+
+You can find your private API key in the [Mailgun dashboard](https://app.mailgun.com/settings/api_security) under **Settings → API security**. Pick the region that matches where your Mailgun account is hosted.
+
+Note: Mailgun only retains events for a limited period (1 day on free plans, up to 30 days on paid plans), so the initial events sync is bounded by your plan's retention.""",
iconPath="/static/services/mailgun.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/mailgun",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Private API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (api.mailgun.net)", value="us"),
+ SourceFieldSelectConfigOption(label="EU (api.eu.mailgun.net)", value="eu"),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: MailgunSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint in INCREMENTAL_FIELDS,
+ supports_append=endpoint in INCREMENTAL_FIELDS,
+ incremental_fields=INCREMENTAL_FIELDS.get(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: MailgunSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_mailgun_credentials(config.api_key, config.region):
+ return True, None
+
+ return False, "Invalid Mailgun API key or region"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MailgunResumeConfig]:
+ return ResumableSourceManager[MailgunResumeConfig](inputs, MailgunResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MailgunSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MailgunResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return mailgun_source(
+ api_key=config.api_key,
+ region=config.region,
+ 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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun.py b/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun.py
new file mode 100644
index 000000000000..f07032baf1ec
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun.py
@@ -0,0 +1,507 @@
+import time
+from datetime import UTC, date, datetime, timedelta
+from typing import Any
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.mailgun.mailgun import (
+ MAX_RETRY_AFTER_SECONDS,
+ MailgunResumeConfig,
+ MailgunRetryableError,
+ _epoch_to_datetime,
+ _increment_skip,
+ _initial_url,
+ _next_page_url,
+ _normalize_row,
+ _parse_retry_after,
+ _retry_wait,
+ _to_epoch,
+ base_url_for_region,
+ get_domain_names,
+ get_rows,
+ mailgun_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.mailgun.settings import ENDPOINTS, MAILGUN_ENDPOINTS
+
+US_BASE = "https://api.mailgun.net"
+
+
+def _make_manager(resume_state: MailgunResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.json.return_value = payload
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.headers = {}
+ return response
+
+
+def _paging_page(items: list[dict[str, Any]], next_url: str | None) -> dict[str, Any]:
+ paging: dict[str, Any] = {"first": "f", "last": "l"}
+ if next_url is not None:
+ paging["next"] = next_url
+ return {"items": items, "paging": paging}
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlsplit(url).query)
+
+
+class TestHelpers:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (1700000000, 1700000000),
+ (1700000000.9, 1700000000),
+ ("1700000000", 1700000000),
+ ("1700000000.5", 1700000000),
+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),
+ (date(2023, 11, 15), int(datetime(2023, 11, 15, tzinfo=UTC).timestamp())),
+ ("not-a-number", None),
+ (True, None),
+ ],
+ )
+ def test_to_epoch_values(self, value, expected):
+ assert _to_epoch(value) == expected
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (1521472262.908181, datetime.fromtimestamp(1521472262.908181, tz=UTC)),
+ (1521472262, datetime.fromtimestamp(1521472262, tz=UTC)),
+ (None, None),
+ ("not-a-timestamp", "not-a-timestamp"),
+ (True, True),
+ ],
+ )
+ def test_epoch_to_datetime(self, value, expected):
+ assert _epoch_to_datetime(value) == expected
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ ("", None),
+ ("30", 30.0),
+ ("0", 0.0),
+ ("-5", 0.0),
+ ("garbage", None),
+ ],
+ )
+ def test_parse_retry_after(self, value, expected):
+ assert _parse_retry_after(value) == expected
+
+ def test_parse_retry_after_http_date(self):
+ retry_at = datetime.now(UTC) + timedelta(seconds=60)
+ result = _parse_retry_after(retry_at.strftime("%a, %d %b %Y %H:%M:%S GMT"))
+ assert result is not None
+ assert 0 < result <= 61
+
+ @pytest.mark.parametrize(
+ "region, expected",
+ [
+ ("us", "https://api.mailgun.net"),
+ ("eu", "https://api.eu.mailgun.net"),
+ ("EU", "https://api.eu.mailgun.net"),
+ ("unknown", "https://api.mailgun.net"),
+ ],
+ )
+ def test_base_url_for_region(self, region, expected):
+ assert base_url_for_region(region) == expected
+
+ def test_retry_wait_honors_retry_after(self):
+ retry_state = mock.MagicMock()
+ retry_state.outcome.exception.return_value = MailgunRetryableError("rate limited", retry_after=42)
+ assert _retry_wait(retry_state) == 42
+
+ def test_retry_wait_caps_retry_after(self):
+ retry_state = mock.MagicMock()
+ retry_state.outcome.exception.return_value = MailgunRetryableError("rate limited", retry_after=9999)
+ assert _retry_wait(retry_state) == MAX_RETRY_AFTER_SECONDS
+
+ def test_retry_wait_falls_back_to_exponential(self):
+ retry_state = mock.MagicMock()
+ retry_state.outcome.exception.return_value = MailgunRetryableError("server error")
+ retry_state.attempt_number = 1
+ wait = _retry_wait(retry_state)
+ assert 0 <= wait <= 61
+
+
+class TestInitialUrl:
+ def test_events_url_includes_ascending_begin_and_end(self):
+ url = _initial_url(US_BASE, MAILGUN_ENDPOINTS["events"], "example.com", begin=1700000000)
+
+ assert url is not None
+ assert url.startswith(f"{US_BASE}/v3/example.com/events?")
+ query = _query(url)
+ assert query["limit"] == ["300"]
+ assert query["ascending"] == ["yes"]
+ assert query["begin"] == ["1700000000"]
+ assert int(query["end"][0]) <= int(time.time()) - 30 * 60
+
+ def test_events_url_without_begin_on_full_refresh(self):
+ url = _initial_url(US_BASE, MAILGUN_ENDPOINTS["events"], "example.com", begin=None)
+
+ assert url is not None
+ query = _query(url)
+ assert "begin" not in query
+ assert query["ascending"] == ["yes"]
+
+ def test_events_url_is_none_when_watermark_inside_lag_window(self):
+ assert _initial_url(US_BASE, MAILGUN_ENDPOINTS["events"], "example.com", begin=int(time.time())) is None
+
+ def test_domain_is_url_quoted_in_path(self):
+ url = _initial_url(US_BASE, MAILGUN_ENDPOINTS["bounces"], "ex/ample.com")
+ assert url is not None
+ assert "/v3/ex%2Fample.com/bounces" in url
+
+ def test_skip_endpoint_starts_at_zero(self):
+ url = _initial_url(US_BASE, MAILGUN_ENDPOINTS["domains"], None)
+ assert url is not None
+ query = _query(url)
+ assert query["skip"] == ["0"]
+ assert query["limit"] == ["1000"]
+
+ def test_domain_scoped_endpoint_without_domain_raises(self):
+ with pytest.raises(ValueError):
+ _initial_url(US_BASE, MAILGUN_ENDPOINTS["events"], None)
+
+ @pytest.mark.parametrize("endpoint", ["bounces", "complaints", "unsubscribes", "tags", "templates"])
+ def test_full_refresh_endpoints_have_no_time_filters(self, endpoint):
+ url = _initial_url(US_BASE, MAILGUN_ENDPOINTS[endpoint], "example.com", begin=1700000000)
+ assert url is not None
+ query = _query(url)
+ assert "begin" not in query
+ assert "ascending" not in query
+
+
+class TestPagination:
+ def test_increment_skip(self):
+ url = _increment_skip(f"{US_BASE}/v4/domains?limit=1000&skip=0", 1000)
+ assert _query(url)["skip"] == ["1000"]
+
+ def test_increment_skip_without_existing_skip_param(self):
+ url = _increment_skip(f"{US_BASE}/v4/domains?limit=1000", 1000)
+ assert _query(url)["skip"] == ["1000"]
+
+ def test_skip_pagination_stops_on_partial_page(self):
+ config = MAILGUN_ENDPOINTS["domains"]
+ assert _next_page_url(config, f"{US_BASE}/v4/domains?limit=1000&skip=0", {}, config.page_size - 1) is None
+
+ def test_skip_pagination_continues_on_full_page(self):
+ config = MAILGUN_ENDPOINTS["domains"]
+ next_url = _next_page_url(config, f"{US_BASE}/v4/domains?limit=1000&skip=0", {}, config.page_size)
+ assert next_url is not None
+ assert _query(next_url)["skip"] == ["1000"]
+
+ def test_paging_stops_on_empty_items(self):
+ config = MAILGUN_ENDPOINTS["events"]
+ data = _paging_page([], "https://api.mailgun.net/v3/example.com/events/next-token")
+ assert _next_page_url(config, "current", data, 0) is None
+
+ def test_paging_follows_next_url_when_items_present(self):
+ config = MAILGUN_ENDPOINTS["events"]
+ data = _paging_page([{"id": "a"}], "https://api.mailgun.net/v3/example.com/events/next-token")
+ assert _next_page_url(config, "current", data, 1) == "https://api.mailgun.net/v3/example.com/events/next-token"
+
+ def test_paging_stops_when_next_missing(self):
+ config = MAILGUN_ENDPOINTS["events"]
+ data = _paging_page([{"id": "a"}], None)
+ assert _next_page_url(config, "current", data, 1) is None
+
+
+class TestNormalizeRow:
+ def test_injects_domain_for_domain_scoped_endpoints(self):
+ row = _normalize_row(MAILGUN_ENDPOINTS["bounces"], "example.com", {"address": "[email protected]"})
+ assert row == {"address": "[email protected]", "domain": "example.com"}
+
+ def test_converts_event_timestamp_to_datetime(self):
+ row = _normalize_row(MAILGUN_ENDPOINTS["events"], "example.com", {"id": "x", "timestamp": 1521472262.9})
+ assert row["timestamp"] == datetime.fromtimestamp(1521472262.9, tz=UTC)
+ assert row["domain"] == "example.com"
+
+ def test_leaves_account_level_rows_untouched(self):
+ row = _normalize_row(MAILGUN_ENDPOINTS["mailing_lists"], None, {"address": "[email protected]"})
+ assert row == {"address": "[email protected]"}
+
+ def test_does_not_mutate_original_item(self):
+ item = {"id": "x", "timestamp": 1521472262.9}
+ _normalize_row(MAILGUN_ENDPOINTS["events"], "example.com", item)
+ assert item == {"id": "x", "timestamp": 1521472262.9}
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ mock_session.return_value.get.return_value = _response({}, status_code)
+
+ assert validate_credentials("key", "us") is expected
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_validate_credentials_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key", "us") is False
+
+ @pytest.mark.parametrize(
+ "region, expected_host",
+ [
+ ("us", "https://api.mailgun.net/v4/domains"),
+ ("eu", "https://api.eu.mailgun.net/v4/domains"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_validate_credentials_targets_region_host(self, mock_session, region, expected_host):
+ mock_session.return_value.get.return_value = _response({}, 200)
+
+ validate_credentials("key", region)
+
+ assert mock_session.return_value.get.call_args.args[0] == expected_host
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_validate_credentials_uses_basic_auth(self, mock_session):
+ mock_session.return_value.get.return_value = _response({}, 200)
+
+ validate_credentials("key-123", "us")
+
+ assert mock_session.return_value.get.call_args.kwargs["auth"] == ("api", "key-123")
+
+
+class TestGetDomainNames:
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_collects_names_across_skip_pages(self, mock_session):
+ page_size = MAILGUN_ENDPOINTS["domains"].page_size
+ full_page = {"items": [{"name": f"domain-{i}.com"} for i in range(page_size)]}
+ partial_page = {"items": [{"name": "last.com"}]}
+ mock_session.return_value.get.side_effect = [_response(full_page), _response(partial_page)]
+
+ names = get_domain_names("key", US_BASE, mock.MagicMock())
+
+ assert len(names) == page_size + 1
+ assert names[-1] == "last.com"
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert _query(second_url)["skip"] == [str(page_size)]
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_skips_items_without_a_name(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"items": [{"name": "a.com"}, {"id": "no-name"}]})
+
+ assert get_domain_names("key", US_BASE, mock.MagicMock()) == ["a.com"]
+
+
+class TestGetRows:
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_account_level_endpoint_paginates_via_paging_next(self, mock_session):
+ next_url = f"{US_BASE}/v3/lists/pages?limit=100&page=next&address=b%40x.com"
+ mock_session.return_value.get.side_effect = [
+ _response(_paging_page([{"address": "[email protected]"}, {"address": "[email protected]"}], next_url)),
+ _response(_paging_page([], next_url)),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "us", "mailing_lists", mock.MagicMock(), manager))
+
+ assert [row["address"] for batch in batches for row in batch] == ["[email protected]", "[email protected]"]
+ # State saved after the yielded batch and again when the chain terminates.
+ saved_states = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved_states[0].next_url == next_url
+ assert saved_states[-1].next_url is None
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_domains_endpoint_uses_skip_pagination(self, mock_session):
+ page_size = MAILGUN_ENDPOINTS["domains"].page_size
+ full_page = {"items": [{"id": f"id-{i}", "name": f"d{i}.com"} for i in range(page_size)]}
+ partial_page = {"items": [{"id": "id-last", "name": "last.com"}]}
+ mock_session.return_value.get.side_effect = [_response(full_page), _response(partial_page)]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "us", "domains", mock.MagicMock(), manager))
+
+ assert sum(len(batch) for batch in batches) == page_size + 1
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert _query(second_url)["skip"] == [str(page_size)]
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_domain_scoped_endpoint_fans_out_over_domains(self, mock_session):
+ domains_page = {"items": [{"name": "a.com"}, {"name": "b.com"}]}
+ a_events = _paging_page([{"id": "e1", "timestamp": 1700000000.5}], f"{US_BASE}/v3/a.com/events/next")
+ a_empty = _paging_page([], None)
+ b_events = _paging_page([{"id": "e2", "timestamp": 1700000100.5}], f"{US_BASE}/v3/b.com/events/next")
+ b_empty = _paging_page([], None)
+ mock_session.return_value.get.side_effect = [
+ _response(domains_page),
+ _response(a_events),
+ _response(a_empty),
+ _response(b_events),
+ _response(b_empty),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "us", "events", mock.MagicMock(), manager))
+
+ rows = [row for batch in batches for row in batch]
+ assert [(row["id"], row["domain"]) for row in rows] == [("e1", "a.com"), ("e2", "b.com")]
+ assert rows[0]["timestamp"] == datetime.fromtimestamp(1700000000.5, tz=UTC)
+
+ first_events_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert first_events_url.startswith(f"{US_BASE}/v3/a.com/events?")
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_incremental_run_passes_begin_from_watermark(self, mock_session):
+ domains_page = {"items": [{"name": "a.com"}]}
+ empty = _paging_page([], None)
+ mock_session.return_value.get.side_effect = [_response(domains_page), _response(empty)]
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "key",
+ "us",
+ "events",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC),
+ incremental_field="timestamp",
+ )
+ )
+
+ events_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert _query(events_url)["begin"] == ["1700000000"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_incremental_watermark_inside_lag_window_skips_fetch(self, mock_session):
+ domains_page = {"items": [{"name": "a.com"}, {"name": "b.com"}]}
+ mock_session.return_value.get.side_effect = [_response(domains_page)]
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "key",
+ "us",
+ "events",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=int(time.time()),
+ incremental_field="timestamp",
+ )
+ )
+
+ assert batches == []
+ # Only the domain listing was fetched; both domains were skipped.
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_resumes_mid_chain_without_relisting_domains(self, mock_session):
+ resume_url = f"{US_BASE}/v3/a.com/events/page-token"
+ resume = MailgunResumeConfig(next_url=resume_url, current_domain="a.com", pending_domains=["b.com"])
+ a_empty = _paging_page([{"id": "e9", "timestamp": 1700000000.0}], None)
+ b_page = _paging_page([], None)
+ mock_session.return_value.get.side_effect = [_response(a_empty), _response(b_page)]
+
+ manager = _make_manager(resume)
+ batches = list(get_rows("key", "us", "events", mock.MagicMock(), manager))
+
+ # First request goes straight to the saved page URL — no /v4/domains listing.
+ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url
+ rows = [row for batch in batches for row in batch]
+ assert [(row["id"], row["domain"]) for row in rows] == [("e9", "a.com")]
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_resume_with_completed_state_yields_nothing(self, mock_session):
+ manager = _make_manager(MailgunResumeConfig(next_url=None, current_domain=None, pending_domains=[]))
+
+ batches = list(get_rows("key", "us", "events", mock.MagicMock(), manager))
+
+ assert batches == []
+ mock_session.return_value.get.assert_not_called()
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_state_saved_after_each_yielded_batch(self, mock_session):
+ domains_page = {"items": [{"name": "a.com"}]}
+ next_url = f"{US_BASE}/v3/a.com/bounces?page=next&address=x"
+ page_one = _paging_page([{"address": "[email protected]", "created_at": "Fri, 21 Oct 2011 11:02:55 GMT"}], next_url)
+ page_two = _paging_page([], None)
+ mock_session.return_value.get.side_effect = [_response(domains_page), _response(page_one), _response(page_two)]
+
+ manager = _make_manager()
+ list(get_rows("key", "us", "bounces", mock.MagicMock(), manager))
+
+ saved_states = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved_states[0].next_url == next_url
+ assert saved_states[0].current_domain == "a.com"
+ assert saved_states[-1].next_url is None
+ assert saved_states[-1].pending_domains == []
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_non_ok_response_raises(self, mock_session):
+ response = _response({}, 401)
+ response.raise_for_status.side_effect = Exception("401 Client Error")
+ response.text = "unauthorized"
+ mock_session.return_value.get.return_value = response
+
+ manager = _make_manager()
+ with pytest.raises(Exception, match="401 Client Error"):
+ list(get_rows("key", "us", "mailing_lists", mock.MagicMock(), manager))
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ @mock.patch("tenacity.nap.time.sleep", return_value=None)
+ def test_retries_on_429_then_succeeds(self, _mock_sleep, mock_session):
+ rate_limited = _response({}, 429)
+ rate_limited.headers = {"Retry-After": "1"}
+ ok_page = _response(_paging_page([{"address": "[email protected]"}], None))
+ empty_page = _response(_paging_page([], None))
+ mock_session.return_value.get.side_effect = [rate_limited, ok_page, empty_page]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "us", "mailing_lists", mock.MagicMock(), manager))
+
+ assert [row["address"] for batch in batches for row in batch] == ["[email protected]"]
+
+
+class TestMailgunSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = MAILGUN_ENDPOINTS[endpoint]
+ response = mailgun_source("key", "us", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ assert response.partition_format == config.partition_format
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_domain_scoped_endpoints_have_domain_in_primary_key(self, endpoint):
+ config = MAILGUN_ENDPOINTS[endpoint]
+ if config.domain_scoped:
+ assert "domain" in config.primary_keys
+
+ @pytest.mark.parametrize("config", list(MAILGUN_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key in {"timestamp", "created_at"}
diff --git a/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun_source.py b/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun_source.py
new file mode 100644
index 000000000000..c2168d50afbf
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun_source.py
@@ -0,0 +1,160 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import MailgunSourceConfig
+from posthog.temporal.data_imports.sources.mailgun.mailgun import MailgunResumeConfig
+from posthog.temporal.data_imports.sources.mailgun.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.mailgun.source import MailgunSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestMailgunSource:
+ def setup_method(self):
+ self.source = MailgunSource()
+ self.team_id = 123
+ self.config = MailgunSourceConfig(api_key="key-123", region="us")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.MAILGUN
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Mailgun"
+ assert config.label == "Mailgun"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/mailgun.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_key", "region"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ def test_region_field_is_select_with_us_default(self):
+ config = self.source.get_source_config
+ region_field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "region")
+ assert region_field.required is True
+ assert region_field.defaultValue == "us"
+ assert [option.value for option in region_field.options] == ["us", "eu"]
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.mailgun.net/v3/example.com/events?limit=300",
+ "401 Client Error: Unauthorized for url: https://api.eu.mailgun.net/v4/domains?limit=1000",
+ "403 Client Error: Forbidden for url: https://api.mailgun.net/v3/example.com/bounces",
+ "403 Client Error: Forbidden for url: https://api.eu.mailgun.net/v3/lists/pages",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.mailgun.net/v3/example.com/events",
+ "429 Client Error: Too Many Requests for url: https://api.mailgun.net/v3/example.com/events",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only the Events API exposes a server-side timestamp filter.
+ assert incremental == {"events"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["events"].incremental_fields == INCREMENTAL_FIELDS["events"]
+ assert schemas["events"].supports_append is True
+
+ @pytest.mark.parametrize("endpoint", [e for e in ENDPOINTS if e != "events"])
+ def test_full_refresh_schemas_have_no_incremental_fields(self, endpoint):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas[endpoint].incremental_fields == []
+ assert schemas[endpoint].supports_incremental is False
+ assert schemas[endpoint].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["events"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "events"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Mailgun API key or region"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.source.validate_mailgun_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key, self.config.region)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MailgunResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.source.mailgun_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_mailgun_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "events"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ inputs.incremental_field = "timestamp"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_mailgun_source.assert_called_once()
+ kwargs = mock_mailgun_source.call_args.kwargs
+ assert kwargs["api_key"] == "key-123"
+ assert kwargs["region"] == "us"
+ assert kwargs["endpoint"] == "events"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+ assert kwargs["incremental_field"] == "timestamp"
+
+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.source.mailgun_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_mailgun_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "bounces"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_mailgun_source.call_args.kwargs["db_incremental_field_last_value"] is None