: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): add mailgun logs, list members, allowlist and subaccounts tables (#115459)
Tom Owers6c9487dc1b97
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex b23f8926d370..2b5986cdfddd 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -768,7 +768,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/mailersend.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/mailjet.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/mailosaur.pydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 1d2f6d6eddfd..27cc8c63c184 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -5376,10 +5376,10 @@ Diffed against: <https://documentation.mailgun.com/docs/mailgun/api-reference/se- [x] `GET /v3/{domain}/stats/total and GET /v3/stats/total` — time-bucketed sent/delivered/opened/bounced counts per domain and account (high) — deprecated Stats API, covered by `metrics` and `domain_metrics` from the Metrics API instead- [x] `GET /v3/{domain}/tags/{tag}/stats and /stats/aggregates` — per-tag performance; tags are synced but carry no metrics without these (high) — deprecated, covered by `tag_metrics` from the Metrics API instead- [x] `GET /v3/{domain}/aggregates/devices, /providers, /countries` — device, mailbox provider and country breakdown dimensions for engagement (high) — deprecated, covered by `recipient_provider_metrics` and `country_metrics` from the Metrics API; the Metrics API documents no device dimension, so devices stay uncovered-- [ ] `GET /v3/lists/{list_address}/members` — mailing list membership join table; mailing_lists gives only the list headers (high)-- [ ] `POST /v1/analytics/logs` — the v1 log query API, richer and longer-retained than the v3 events feed already synced (high)-- [ ] `GET /v3/{domain}/whitelists (allowlist)` — allowlist entries completing the suppression picture alongside bounces/complaints/unsubscribes (medium)-- [ ] `GET /v5/accounts/subaccounts` — lookup resolving subaccount ids for multi-tenant sending (medium)+- [x] `GET /v3/lists/{list_address}/members` — mailing list membership join table; mailing_lists gives only the list headers (high) — synced as `mailing_list_members` from the paged `/v3/lists/{list_address}/members/pages` route+- [x] `POST /v1/analytics/logs` — the v1 log query API, richer and longer-retained than the v3 events feed already synced (high) — synced as incremental `logs`; it reads the same plan-bounded event store as `events`, so retention is not longer, but it is account-wide with no per-domain fan-out+- [x] `GET /v3/{domain}/whitelists (allowlist)` — allowlist entries completing the suppression picture alongside bounces/complaints/unsubscribes (medium) — synced as `allowlist`+- [x] `GET /v5/accounts/subaccounts` — lookup resolving subaccount ids for multi-tenant sending (medium) — synced as `subaccounts`- [ ] `GET /v1/bounce-classification/domains/{domain}/events and /stats` — classified bounce reasons, far more analyzable than raw bounce rows (medium)- [ ] `GET /v3/{domain}/templates/{name}/versions and /v4/templates/{name}/versions` — template version lookup resolving the version referenced on sends (medium)- [ ] `POST /v1/analytics/usage-metrics` — account usage/consumption metrics for cost attribution (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/canonical_descriptions.pyindex ae1da98e5e0c..98557e87ed90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/canonical_descriptions.py@@ -145,6 +145,17 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created_at": "Time the unsubscribe was recorded.",},},+ "allowlist": {+ "description": "An address or domain on a sending domain's allowlist, which Mailgun never adds to the bounce list.",+ "docs_url": "https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/allowlist/get-v3--domainid--whitelists",+ "columns": {+ "domain": "The sending domain the allowlist entry belongs to.",+ "value": "The allowlisted email address or domain.",+ "type": "Whether the entry is an address or a domain.",+ "reason": "The reason given when the entry was added.",+ "createdAt": "Time the entry was added.",+ },+ },"mailing_lists": {"description": "A mailing list configured on the Mailgun account, addressable by a single list address.","docs_url": "https://documentation.mailgun.com/docs/mailgun/api-reference/openapi-final/tag/Mailing-Lists/",@@ -157,6 +168,17 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created_at": "Time the mailing list was created.",},},+ "mailing_list_members": {+ "description": "A member of a mailing list on the Mailgun account.",+ "docs_url": "https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/mailing-lists/get-lists-list_address-members-pages",+ "columns": {+ "list_address": "The address of the mailing list the member belongs to.",+ "address": "The member's email address.",+ "name": "The member's display name.",+ "vars": "Custom variables stored on the member.",+ "subscribed": "Whether the member is subscribed to the list.",+ },+ },"tags": {"description": "A tag used to categorize and track messages for a domain in Mailgun.","docs_url": "https://documentation.mailgun.com/docs/mailgun/api-reference/openapi-final/tag/Tags/",@@ -179,6 +201,41 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"version": "The version details of the template's stored content.",},},+ "subaccounts": {+ "description": "A subaccount under the Mailgun account, used to separate sending for different teams or customers.",+ "docs_url": "https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/subaccounts/get-v5-accounts-subaccounts",+ "columns": {+ "id": "Unique identifier for the subaccount.",+ "name": "The name of the subaccount.",+ "status": "Whether the subaccount is open, disabled or closed.",+ "features": "The features enabled on the subaccount.",+ "created_at": "Time the subaccount was created.",+ "updated_at": "Time the subaccount was last updated.",+ },+ },+ "logs": {+ "description": "A message event from the account-wide Logs API, such as an accepted, delivered, failed, opened or clicked message.",+ "docs_url": "https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/logs/post-v1-analytics-logs",+ "columns": {+ "id": "Unique identifier for the log event.",+ "event": "The type of event, such as accepted, delivered, failed, opened or clicked.",+ "timestamp": "Time the event happened.",+ "domain": "The sending domain the event belongs to.",+ "account": "The account (or subaccount) the event belongs to.",+ "recipient": "The recipient email address.",+ "recipient-domain": "The domain of the recipient email address.",+ "recipient-provider": "The recipient's mailbox provider.",+ "message": "Headers and size of the message the event is about.",+ "delivery-status": "SMTP delivery details for delivered and failed events.",+ "severity": "Whether a failure is temporary or permanent.",+ "reason": "Why a message failed or was suppressed.",+ "tags": "The tags on the message.",+ "user-variables": "Custom variables attached to the message.",+ "geolocation": "Location of the recipient for open and click events.",+ "client-info": "Mail client and device of the recipient for open and click events.",+ "url": "The link the recipient clicked, for click events.",+ },+ },"metrics": {"description": "Daily sending, delivery and engagement metrics for the whole Mailgun account.","docs_url": _METRICS_DOCS_URL,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.pyindex 5cf8b898133c..4805473c4486 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py@@ -26,6 +26,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.settings import (+ LOGS_ENDPOINT,+ LOGS_PATH,MAILGUN_ENDPOINTS,MAILGUN_METRICS_ENDPOINTS,METRICS,@@ -70,6 +72,11 @@ METRICS_REFRESH_DAYS = 2# Backstop for a Metrics API that ignores `skip` and keeps serving full pages for one day. Sized# far above the distinct values any breakdown dimension reaches in a day.MAX_METRICS_ROWS_PER_DAY = 1_000_000+# The Logs API caps `limit` at 100.+LOGS_PAGE_SIZE = 100+# Mailgun keeps logs for its plan's event retention, at most 30 days on standard plans, so a+# full refresh asks for the longest window any account can still hold.+LOGS_LOOKBACK_DAYS = 30class MailgunRetryableError(Exception):@@ -80,15 +87,22 @@ class MailgunRetryableError(Exception):@dataclasses.dataclass(frozen=False)class MailgunResumeConfig:- # URL of the next page to fetch for the in-flight chain (None = start the next domain).+ # URL of the next page to fetch for the in-flight chain (None = start the next parent).next_url: Optional[str] = None- # Domain the in-flight chain belongs to, injected into each row of the resumed pages.+ # Domain (or mailing list address, for list-scoped endpoints) 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.+ # Domains (or mailing list addresses) not yet started, in fan-out order.pending_domains: list[str] = dataclasses.field(default_factory=list)# Metrics tables: ISO date of the next daily window to query, and the offset within it.metrics_day: Optional[str] = Nonemetrics_skip: int = 0+ # Logs table: the ISO window the run reads and the token of its next page. The window is+ # fixed per run because a page token only belongs to the query that issued it. An exhausted+ # window is saved with start equal to end.+ logs_start: Optional[str] = None+ logs_end: Optional[str] = None+ logs_token: Optional[str] = Nonedef base_url_for_region(region: str) -> str:@@ -155,12 +169,14 @@ def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:return f"{base_url}{path}?{urlencode(clean_params)}"-def _endpoint_path(config: MailgunEndpointConfig, domain: Optional[str]) -> str:- if not config.domain_scoped:+def _endpoint_path(config: MailgunEndpointConfig, parent: Optional[str]) -> str:+ if not config.domain_scoped and not config.list_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=""))+ if parent is None:+ raise ValueError(f"Mailgun endpoint {config.name} requires a {'domain' if config.domain_scoped else 'list'}")+ if config.list_scoped:+ return config.path.format(list_address=quote(parent, safe=""))+ return config.path.format(domain=quote(parent, safe=""))def _initial_url(@@ -226,6 +242,9 @@ def _normalize_row(config: MailgunEndpointConfig, domain: Optional[str], item: d# 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.list_scoped:+ # Members are only unique within their list, and the list isn't on the member row.+ row["list_address"] = domainif config.name == "events":row["timestamp"] = _epoch_to_datetime(row.get("timestamp"))return row@@ -311,6 +330,22 @@ def get_domain_names(api_key: str, base_url: str, logger: FilteringBoundLogger)skip += config.page_size+def get_mailing_list_addresses(api_key: str, base_url: str, logger: FilteringBoundLogger) -> list[str]:+ config = MAILGUN_ENDPOINTS["mailing_lists"]+ addresses: list[str] = []+ url = _initial_url(base_url, config, None)+ seen_urls: set[str] = set()++ while url is not None and url not in seen_urls and len(seen_urls) < MAX_PAGES_PER_CHAIN:+ seen_urls.add(url)+ data = _fetch_page(url, api_key, logger)+ items = data.get("items") or []+ addresses.extend(item["address"] for item in items if item.get("address"))+ url = _next_page_url(config, url, data, len(items))++ return addresses++# Mailgun keys are scoped to one region, so a good key checked against the wrong region is# rejected exactly like a bad key. Naming both leaves something to act on either way.INVALID_KEY_ERROR = (@@ -376,6 +411,10 @@ def get_rows(pending_domains = get_domain_names(api_key, base_url, logger)current_domain = Nonecurrent_url = None+ elif config.list_scoped:+ pending_domains = get_mailing_list_addresses(api_key, base_url, logger)+ current_domain = None+ current_url = Noneelse:pending_domains = []current_domain = None@@ -430,7 +469,7 @@ def get_rows(resumable_source_manager.save_state(MailgunResumeConfig(pending_domains=pending_domains))continue- items = data.get("items") or []+ items = data.get(config.data_key) or []if items:yield [_normalize_row(config, current_domain, item) for item in items]@@ -448,6 +487,9 @@ def get_rows(pending_domains=pending_domains,))+ if not items:+ # A fan-out over many empty lists or domains yields nothing for a long stretch.+ resumable_source_manager.safe_point()def _to_date(value: Any) -> Optional[date]:@@ -554,6 +596,87 @@ def get_metrics_rows(resumable_source_manager.safe_point()+def _parse_log_timestamp(value: Any) -> Any:+ """Parse a Logs API `@timestamp` (ISO 8601, or RFC 2822 as a fallback); unparseable values pass+ through unchanged."""+ if not isinstance(value, str):+ return value+ try:+ parsed = datetime.fromisoformat(value)+ except ValueError:+ return _parse_rfc2822(value)+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)+++def _logs_row(item: dict[str, Any]) -> dict[str, Any]:+ row = dict(item)+ # Renamed so the incremental cursor and partition key don't depend on how the pipeline+ # normalizes the leading `@`.+ row["timestamp"] = _parse_log_timestamp(row.pop("@timestamp", None))+ return row+++def _logs_request_body(start: datetime, end: datetime, token: Optional[str]) -> dict[str, Any]:+ pagination: dict[str, Any] = {"sort": "timestamp:asc", "limit": LOGS_PAGE_SIZE}+ if token is not None:+ pagination["token"] = token+ return {"start": format_datetime(start), "end": format_datetime(end), "pagination": pagination}+++def get_logs_rows(+ api_key: str,+ region: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MailgunResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ """Walk the account-wide Logs API across one time window, oldest first."""+ url = f"{base_url_for_region(region)}{LOGS_PATH}"++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and resume_config.logs_start is not None and resume_config.logs_end is not None:+ start = datetime.fromisoformat(resume_config.logs_start)+ end = datetime.fromisoformat(resume_config.logs_end)+ token = resume_config.logs_token+ logger.debug(f"Mailgun: resuming {LOGS_ENDPOINT} at start={start}, end={end}, token={token}")+ else:+ now = datetime.now(UTC)+ # Logs come from the same eventually consistent store as the Events API.+ end = now - timedelta(seconds=EVENTS_CONSISTENCY_LAG_SECONDS)+ start = now - timedelta(days=LOGS_LOOKBACK_DAYS)+ if should_use_incremental_field:+ begin = _to_epoch(db_incremental_field_last_value)+ if begin is not None:+ start = max(start, datetime.fromtimestamp(begin, tz=UTC))+ token = None++ seen_tokens: set[str] = set()++ while start < end:+ data = _fetch_page(url, api_key, logger, json_body=_logs_request_body(start, end, token))+ items = data.get("items") or []+ next_token = (data.get("pagination") or {}).get("next")+ if token is not None:+ seen_tokens.add(token)++ if not items or not next_token or next_token == token or next_token in seen_tokens:+ start, token = end, None+ elif len(seen_tokens) >= MAX_PAGES_PER_CHAIN:+ logger.warning(f"Mailgun: stopping {LOGS_ENDPOINT} because the chain exceeded {MAX_PAGES_PER_CHAIN} pages")+ start, token = end, None+ else:+ token = next_token++ resumable_source_manager.save_state(+ MailgunResumeConfig(logs_start=start.isoformat(), logs_end=end.isoformat(), logs_token=token)+ )+ if items:+ yield [_logs_row(item) for item in items]+ else:+ resumable_source_manager.safe_point()++# Mailgun posts `{"signature": {...}, "event-data": {...}}`; `event-data` is the same event# object the Events API returns in its `items` array.WEBHOOK_PAYLOAD_EVENT_KEY = "event-data"@@ -864,6 +987,27 @@ def mailgun_source(partition_keys=["time"],)+ if endpoint == LOGS_ENDPOINT:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_logs_rows(+ api_key=api_key,+ region=region,+ 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,+ ),+ # Log ids come from the same account-wide event store as webhook event ids.+ primary_keys=["id"],+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="day",+ partition_keys=["timestamp"],+ )+config = MAILGUN_ENDPOINTS[endpoint]return SourceResponse(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.pyindex 94e75baef2e4..14aaf12cae03 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py@@ -7,17 +7,21 @@ from products.warehouse_sources.backend.types import IncrementalField, IncrementPaginationStyle = Literal["paging", "skip"]-@dataclass+@dataclass(frozen=True)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: strdomain_scoped: bool = False+ # Fans out over every mailing list on the account, with a `{list_address}` placeholder in the path.+ list_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+ # Response key that holds the page's rows.+ data_key: str = "items"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@@ -28,9 +32,9 @@ class MailgunEndpointConfig:# Of these list endpoints, only the Events API exposes a server-side timestamp filter (`begin`/`end`# epoch seconds with `ascending=yes`), so it's the only one 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.+# suppressions, the allowlist, mailing lists and their members, tags, templates, and subaccounts+# have no updated-at filter — full refresh only. Domain-scoped rows get a `domain` column injected+# so primary keys stay unique across domains, and list-scoped rows a `list_address` column.MAILGUN_ENDPOINTS: dict[str, MailgunEndpointConfig] = {"domains": MailgunEndpointConfig(name="domains",@@ -84,12 +88,27 @@ MAILGUN_ENDPOINTS: dict[str, MailgunEndpointConfig] = {partition_key="created_at",partition_format="month",),+ "allowlist": MailgunEndpointConfig(+ name="allowlist",+ path="/v3/{domain}/whitelists",+ domain_scoped=True,+ page_size=1000,+ # `value` is the allowlisted address or domain, unique within a sending domain.+ primary_keys=["domain", "value"],+ ),"mailing_lists": MailgunEndpointConfig(name="mailing_lists",path="/v3/lists/pages",page_size=100,primary_keys=["address"],),+ "mailing_list_members": MailgunEndpointConfig(+ name="mailing_list_members",+ path="/v3/lists/{list_address}/members/pages",+ list_scoped=True,+ page_size=100,+ primary_keys=["list_address", "address"],+ ),"tags": MailgunEndpointConfig(name="tags",path="/v3/{domain}/tags",@@ -108,8 +127,28 @@ MAILGUN_ENDPOINTS: dict[str, MailgunEndpointConfig] = {# Template names are unique per domain; list items aren't guaranteed an `id`.primary_keys=["domain", "name"],),+ "subaccounts": MailgunEndpointConfig(+ name="subaccounts",+ path="/v5/accounts/subaccounts",+ pagination="skip",+ page_size=1000,+ data_key="subaccounts",+ primary_keys=["id"],+ ),}+LOGS_ENDPOINT = "logs"+LOGS_PATH = "/v1/analytics/logs"++LOGS_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+]+METRICS_PATH = "/v1/analytics/metrics"# Sending metrics requested from the Metrics API, as named in Mailgun's metric and rate@@ -178,10 +217,11 @@ METRICS_INCREMENTAL_FIELDS: list[IncrementalField] = [},]-ENDPOINTS = tuple(MAILGUN_ENDPOINTS.keys()) + tuple(MAILGUN_METRICS_ENDPOINTS.keys())+ENDPOINTS = tuple(MAILGUN_ENDPOINTS.keys()) + tuple(MAILGUN_METRICS_ENDPOINTS.keys()) + (LOGS_ENDPOINT,)INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {**{name: config.incremental_fields for name, config in MAILGUN_ENDPOINTS.items() if config.incremental_fields},+ LOGS_ENDPOINT: LOGS_INCREMENTAL_FIELDS,**dict.fromkeys(MAILGUN_METRICS_ENDPOINTS, METRICS_INCREMENTAL_FIELDS),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.pyindex 04c33f281cf9..76ebde8e6ca6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py@@ -1,6 +1,7 @@import timefrom collections.abc import Iterablefrom datetime import UTC, date, datetime, timedelta+from email.utils import parsedate_to_datetimefrom typing import Any, castfrom urllib.parse import parse_qs, urlsplit@@ -23,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun imfrom products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun import (FORBIDDEN_ERROR,INVALID_KEY_ERROR,+ LOGS_LOOKBACK_DAYS,METRICS_PAGE_SIZE,UNREACHABLE_ERROR,MailgunResumeConfig,@@ -509,6 +511,127 @@ class TestMetricsRows:assert result.requests[0].json()["pagination"]["skip"] == METRICS_PAGE_SIZE+def _driver() -> SourceDriver:+ return SourceDriver(MailgunSource(), MailgunSourceConfig(api_key="key-123", region="us"))+++def _log_item(event_id: str) -> dict[str, Any]:+ return {"id": event_id, "event": "delivered", "@timestamp": "2024-07-08T12:30:00.250Z", "domain": {"name": "a.com"}}+++class TestLogsRows:+ def test_follows_page_tokens_until_an_empty_page(self):+ pages = {+ None: {"items": [_log_item("e1"), _log_item("e2")], "pagination": {"next": "t1"}},+ "t1": {"items": [_log_item("e3")], "pagination": {"next": "t2"}},+ "t2": {"items": [], "pagination": {"next": "t3"}},+ }++ result = _driver().run(+ "logs", lambda request: ScriptedResponse(json=pages[request.json()["pagination"].get("token")])+ )++ assert result.raised is None+ assert {request.path for request in result.requests} == {"/v1/analytics/logs"}+ bodies = [request.json() for request in result.requests]+ assert [body["pagination"].get("token") for body in bodies] == [None, "t1", "t2"]+ assert {(body["start"], body["end"]) for body in bodies} == {(bodies[0]["start"], bodies[0]["end"])}+ assert {body["pagination"]["sort"] for body in bodies} == {"timestamp:asc"}+ assert [row["id"] for row in result.rows] == ["e1", "e2", "e3"]+ assert "@timestamp" not in result.rows[0]+ assert result.rows[0]["timestamp"] == datetime(2024, 7, 8, 12, 30, 0, 250000, tzinfo=UTC)++ @pytest.mark.parametrize(+ "watermark_days_ago, expected_start_days_ago",+ [+ (None, LOGS_LOOKBACK_DAYS),+ (2, 2),+ # A watermark older than Mailgun's retention starts at the lookback edge instead.+ (LOGS_LOOKBACK_DAYS + 30, LOGS_LOOKBACK_DAYS),+ ],+ )+ def test_window_starts_at_the_watermark_or_the_lookback(self, watermark_days_ago, expected_start_days_ago):+ now = datetime.now(UTC)+ watermark = None if watermark_days_ago is None else now - timedelta(days=watermark_days_ago)++ result = _driver().run(+ "logs",+ lambda _request: ScriptedResponse(json={"items": [], "pagination": {}}),+ incremental_field="timestamp" if watermark else None,+ db_incremental_field_last_value=watermark,+ )++ assert result.raised is None+ start = parsedate_to_datetime(result.requests[0].json()["start"])+ assert abs(start - (now - timedelta(days=expected_start_days_ago))) < timedelta(minutes=1)++ @pytest.mark.parametrize(+ "resume_token, saved_start, expected_tokens",+ [+ ("t5", "2024-07-01T00:00:00+00:00", ["t5"]),+ # An exhausted window has nothing left to read.+ (None, "2024-07-08T00:00:00+00:00", []),+ ],+ )+ def test_resume_reuses_the_saved_window_and_token(self, resume_token, saved_start, expected_tokens):+ resume_state = MailgunResumeConfig(+ logs_start=saved_start, logs_end="2024-07-08T00:00:00+00:00", logs_token=resume_token+ )++ result = _driver().run(+ "logs",+ lambda _request: ScriptedResponse(json={"items": [], "pagination": {}}),+ resume_state=resume_state,+ )++ assert result.raised is None+ bodies = [request.json() for request in result.requests]+ assert [body["pagination"].get("token") for body in bodies] == expected_tokens+ for body in bodies:+ assert parsedate_to_datetime(body["start"]) == datetime(2024, 7, 1, tzinfo=UTC)+ assert parsedate_to_datetime(body["end"]) == datetime(2024, 7, 8, tzinfo=UTC)+++class TestFanOutEndpoints:+ def test_mailing_list_members_fan_out_over_every_list(self):+ lists_next = f"{US_BASE}/v3/lists/pages?page=next&address=b%40lists.example.com&limit=100"++ def respond(request: RecordedRequest) -> ScriptedResponse:+ if request.path == "/v3/lists/pages":+ if request.param("page") == "next":+ return ScriptedResponse(json=_paging_page([], None))+ lists = [{"address": "[email protected]"}, {"address": "[email protected]"}]+ return ScriptedResponse(json=_paging_page(lists, lists_next))+ if request.path == "/v3/lists/a%40lists.example.com/members/pages" and request.param("page") is None:+ members = [{"address": "[email protected]", "subscribed": True}]+ return ScriptedResponse(json=_paging_page(members, f"{request.url}&page=next&address=x%40example.com"))+ return ScriptedResponse(json=_paging_page([], None))++ result = _driver().run("mailing_list_members", respond)++ assert result.raised is None+ assert [(row["list_address"], row["address"]) for row in result.rows] == [+ ("[email protected]", "[email protected]")+ ]+ assert "/v3/lists/b%40lists.example.com/members/pages" in result.paths++ def test_subaccounts_read_their_own_response_key_across_skip_pages(self):+ page_size = MAILGUN_ENDPOINTS["subaccounts"].page_size++ def respond(request: RecordedRequest) -> ScriptedResponse:+ count = page_size if request.param("skip") == "0" else 1+ skip = int(request.param("skip") or 0)+ return ScriptedResponse(+ json={"subaccounts": [{"id": f"sub-{skip + i}"} for i in range(count)], "total": page_size + 1}+ )++ result = _driver().run("subaccounts", respond)++ assert result.raised is None+ assert result.params("skip") == ["0", str(page_size)]+ assert len(result.rows) == page_size + 1++class TestMailgunSourceResponse:def test_webhook_endpoint_yields_nothing_until_the_webhook_is_live(self):webhook_manager = mock.MagicMock()