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): add mailgun metrics api tables (#114906)

Tom Owersd623ad55797a
diff --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.md
index f8ee3419565c..e0876016b1e1 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
@@ -5373,10 +5373,10 @@ Today (8): `bounces`, `complaints`, `domains`, `events`, `mailing_lists`, `tags`
Diffed against: <https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/metrics/post-v1-analytics-metrics>
-- [ ] `POST /v1/analytics/metrics` — the modern aggregated metrics API — Mailgun's headline deliverability numbers (high)
-- [ ] `GET /v3/{domain}/stats/total and GET /v3/stats/total` — time-bucketed sent/delivered/opened/bounced counts per domain and account (high)
-- [ ] `GET /v3/{domain}/tags/{tag}/stats and /stats/aggregates` — per-tag performance; tags are synced but carry no metrics without these (high)
-- [ ] `GET /v3/{domain}/aggregates/devices, /providers, /countries` — device, mailbox provider and country breakdown dimensions for engagement (high)
+- [x] `POST /v1/analytics/metrics` — the modern aggregated metrics API — Mailgun's headline deliverability numbers (high) — synced as daily `metrics`, `domain_metrics`, `tag_metrics`, `country_metrics` and `recipient_provider_metrics`
+- [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)
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.py
index 51e39755105f..ae1da98e5e0c 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
@@ -9,6 +9,49 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
CanonicalDescriptions,
)
+_METRICS_DOCS_URL = (
+ "https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/metrics/post-v1-analytics-metrics"
+)
+
+_METRICS_COLUMNS: dict[str, str] = {
+ "time": "Start of the UTC day the metrics cover.",
+ "accepted_count": "Messages Mailgun accepted for delivery.",
+ "processed_count": "Messages Mailgun processed, including ones it suppressed.",
+ "sent_count": "Messages Mailgun attempted to deliver.",
+ "delivered_count": "Messages the recipient's mail server accepted.",
+ "failed_count": "Messages that failed to deliver, temporarily or permanently.",
+ "temporary_failed_count": "Delivery attempts that failed temporarily and may be retried.",
+ "permanent_failed_count": "Messages that failed to deliver permanently.",
+ "bounced_count": "Messages that bounced.",
+ "hard_bounces_count": "Messages that bounced permanently.",
+ "soft_bounces_count": "Messages that bounced temporarily.",
+ "opened_count": "Opens of delivered messages.",
+ "unique_opened_count": "Delivered messages opened at least once.",
+ "clicked_count": "Clicks on tracked links.",
+ "unique_clicked_count": "Delivered messages with at least one tracked link clicked.",
+ "unsubscribed_count": "Recipients who unsubscribed.",
+ "complained_count": "Recipients who reported a message as spam.",
+ "delivered_rate": "Delivered messages as a percentage of sent messages.",
+ "opened_rate": "Opens as a percentage of delivered messages.",
+ "unique_opened_rate": "Unique opens as a percentage of delivered messages.",
+ "clicked_rate": "Clicks as a percentage of delivered messages.",
+ "unique_clicked_rate": "Unique clicks as a percentage of delivered messages.",
+ "unsubscribed_rate": "Unsubscribes as a percentage of delivered messages.",
+ "complained_rate": "Spam complaints as a percentage of delivered messages.",
+ "bounce_rate": "Bounces as a percentage of processed messages.",
+ "permanent_fail_rate": "Permanent failures as a percentage of processed messages.",
+ "delayed_rate": "Messages not delivered on the first attempt as a percentage of delivered messages.",
+}
+
+
+def _breakdown_columns(dimension: str, label: str) -> dict[str, str]:
+ return {
+ **_METRICS_COLUMNS,
+ dimension: f"The {label} the metrics are grouped by.",
+ f"{dimension}_display_value": f"The {label} in display form.",
+ }
+
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"domains": {
"description": "A sending domain configured on the Mailgun account.",
@@ -136,4 +179,29 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"version": "The version details of the template's stored content.",
},
},
+ "metrics": {
+ "description": "Daily sending, delivery and engagement metrics for the whole Mailgun account.",
+ "docs_url": _METRICS_DOCS_URL,
+ "columns": _METRICS_COLUMNS,
+ },
+ "domain_metrics": {
+ "description": "Daily sending, delivery and engagement metrics for each sending domain.",
+ "docs_url": _METRICS_DOCS_URL,
+ "columns": _breakdown_columns("domain", "sending domain"),
+ },
+ "tag_metrics": {
+ "description": "Daily sending, delivery and engagement metrics for each message tag.",
+ "docs_url": _METRICS_DOCS_URL,
+ "columns": _breakdown_columns("tag", "message tag"),
+ },
+ "country_metrics": {
+ "description": "Daily engagement metrics for each country, from the IP of the opening or clicking recipient. Non-engagement counts fall under Unknown.",
+ "docs_url": _METRICS_DOCS_URL,
+ "columns": _breakdown_columns("country", "ISO 3166 country code"),
+ },
+ "recipient_provider_metrics": {
+ "description": "Daily sending, delivery and engagement metrics for each recipient mailbox provider, such as Gmail or Outlook 365.",
+ "docs_url": _METRICS_DOCS_URL,
+ "columns": _breakdown_columns("recipient_provider", "recipient mailbox provider"),
+ },
}
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.py
index 4f395fddc926..5cf8b898133c 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
@@ -1,8 +1,8 @@
import time
import dataclasses
from collections.abc import AsyncIterable, Iterable, Iterator
-from datetime import UTC, date, datetime
-from email.utils import parsedate_to_datetime
+from datetime import UTC, date, datetime, timedelta
+from email.utils import format_datetime, parsedate_to_datetime
from typing import Any, Optional
from urllib.parse import parse_qs, quote, urlencode, urlsplit, urlunsplit
@@ -27,9 +27,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.settings import (
MAILGUN_ENDPOINTS,
+ MAILGUN_METRICS_ENDPOINTS,
+ METRICS,
+ METRICS_PATH,
WEBHOOK_EVENTS_ENDPOINT,
WEBHOOK_TYPES,
MailgunEndpointConfig,
+ MailgunMetricsEndpointConfig,
)
REGION_BASE_URLS = {
@@ -56,6 +60,16 @@ EVENTS_CONSISTENCY_LAG_SECONDS = 30 * 60
# seen-URL guard below can't catch. Sized far above any real page count (the largest paging
# endpoint fetches 1000 rows a page) so it only trips on a runaway.
MAX_PAGES_PER_CHAIN = 100_000
+# The Metrics API caps `limit` at 1000 for any dimension other than `time`.
+METRICS_PAGE_SIZE = 1000
+# Mailgun keeps daily metrics for one year.
+METRICS_LOOKBACK_DAYS = 365
+# A day's counts keep moving until Mailgun's event store settles, so incremental syncs re-read
+# the days just before the watermark and merge over them.
+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
class MailgunRetryableError(Exception):
@@ -64,7 +78,7 @@ class MailgunRetryableError(Exception):
self.retry_after = retry_after
[email protected](frozen=False)
class MailgunResumeConfig:
# URL of the next page to fetch for the in-flight chain (None = start the next domain).
next_url: Optional[str] = None
@@ -72,6 +86,9 @@ class MailgunResumeConfig:
current_domain: Optional[str] = None
# Domains 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] = None
+ metrics_skip: int = 0
def base_url_for_region(region: str) -> str:
@@ -220,15 +237,27 @@ def _normalize_row(config: MailgunEndpointConfig, domain: Optional[str], item: d
wait=_retry_wait,
reraise=True,
)
-def _fetch_page(url: str, api_key: str, logger: FilteringBoundLogger) -> dict[str, Any]:
+def _fetch_page(
+ url: str, api_key: str, logger: FilteringBoundLogger, json_body: Optional[dict[str, Any]] = None
+) -> 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,
- )
+ session = make_tracked_session()
+ if json_body is None:
+ response = session.get(
+ url,
+ auth=("api", api_key),
+ headers={"Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ else:
+ response = session.post(
+ url,
+ auth=("api", api_key),
+ headers={"Accept": "application/json"},
+ json=json_body,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
if response.status_code == 429 or response.status_code >= 500:
raise MailgunRetryableError(
@@ -421,6 +450,110 @@ def get_rows(
)
+def _to_date(value: Any) -> Optional[date]:
+ if isinstance(value, datetime):
+ return (value if value.tzinfo is None else value.astimezone(UTC)).date()
+ if isinstance(value, date):
+ return value
+ if isinstance(value, str):
+ try:
+ return _to_date(datetime.fromisoformat(value))
+ except ValueError:
+ return None
+ return None
+
+
+def _parse_rfc2822(value: Any) -> Any:
+ """Parse the Metrics API's RFC 2822 `time` dimension; unparseable values pass through unchanged."""
+ if not isinstance(value, str):
+ return value
+ try:
+ return parsedate_to_datetime(value).astimezone(UTC)
+ except (TypeError, ValueError):
+ return value
+
+
+def _metrics_request_body(config: MailgunMetricsEndpointConfig, day: date, skip: int) -> dict[str, Any]:
+ start = datetime.combine(day, datetime.min.time(), tzinfo=UTC)
+ dimensions = ["time", config.dimension] if config.dimension else ["time"]
+ return {
+ "start": format_datetime(start),
+ "end": format_datetime(start + timedelta(days=1) - timedelta(seconds=1)),
+ "resolution": "day",
+ "dimensions": dimensions,
+ "metrics": list(METRICS),
+ # Within a single day the breakdown dimension is unique, so sorting on it keeps
+ # skip/limit pages stable.
+ "pagination": {"sort": f"{dimensions[-1]}:asc", "skip": skip, "limit": METRICS_PAGE_SIZE},
+ }
+
+
+def _metrics_row(item: dict[str, Any]) -> dict[str, Any]:
+ row: dict[str, Any] = dict(item.get("metrics") or {})
+ for dimension in item.get("dimensions") or []:
+ name = dimension.get("dimension")
+ if not name:
+ continue
+ if name == "time":
+ row["time"] = _parse_rfc2822(dimension.get("value"))
+ else:
+ row[name] = dimension.get("value")
+ row[f"{name}_display_value"] = dimension.get("display_value")
+ return row
+
+
+def get_metrics_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,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk the Metrics API one UTC day at a time, oldest first.
+
+ One day per request keeps every page deterministic, since `time` and the breakdown dimension
+ together are unique only within a day."""
+ config = MAILGUN_METRICS_ENDPOINTS[endpoint]
+ url = f"{base_url_for_region(region)}{METRICS_PATH}"
+ today = datetime.now(UTC).date()
+
+ day = today - timedelta(days=METRICS_LOOKBACK_DAYS - 1)
+ if should_use_incremental_field:
+ last_day = _to_date(db_incremental_field_last_value)
+ if last_day is not None:
+ day = max(day, last_day - timedelta(days=METRICS_REFRESH_DAYS))
+ skip = 0
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None and resume_config.metrics_day is not None:
+ day = date.fromisoformat(resume_config.metrics_day)
+ skip = resume_config.metrics_skip
+ logger.debug(f"Mailgun: resuming {endpoint} at day={day}, skip={skip}")
+
+ while day <= today:
+ data = _fetch_page(url, api_key, logger, json_body=_metrics_request_body(config, day, skip))
+ items = data.get("items") or []
+
+ if len(items) < METRICS_PAGE_SIZE:
+ day, skip = day + timedelta(days=1), 0
+ elif skip + METRICS_PAGE_SIZE >= MAX_METRICS_ROWS_PER_DAY:
+ logger.warning(
+ f"Mailgun: stopping {endpoint} for {day} after {MAX_METRICS_ROWS_PER_DAY} rows; "
+ "the Metrics API kept returning full pages"
+ )
+ day, skip = day + timedelta(days=1), 0
+ else:
+ skip += METRICS_PAGE_SIZE
+
+ resumable_source_manager.save_state(MailgunResumeConfig(metrics_day=day.isoformat(), metrics_skip=skip))
+ if items:
+ yield [_metrics_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"
@@ -710,6 +843,27 @@ def mailgun_source(
if endpoint == WEBHOOK_EVENTS_ENDPOINT:
return mailgun_webhook_source(webhook_source_manager, endpoint)
+ if endpoint in MAILGUN_METRICS_ENDPOINTS:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_metrics_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,
+ ),
+ primary_keys=MAILGUN_METRICS_ENDPOINTS[endpoint].primary_keys,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=["time"],
+ )
+
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.py
index f3a8402b7bef..94e75baef2e4 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
@@ -26,8 +26,8 @@ class MailgunEndpointConfig:
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,
+# 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.
@@ -110,10 +110,79 @@ MAILGUN_ENDPOINTS: dict[str, MailgunEndpointConfig] = {
),
}
-ENDPOINTS = tuple(MAILGUN_ENDPOINTS.keys())
+METRICS_PATH = "/v1/analytics/metrics"
+
+# Sending metrics requested from the Metrics API, as named in Mailgun's metric and rate
+# definitions. Rates come back as strings.
+METRICS: tuple[str, ...] = (
+ "accepted_count",
+ "processed_count",
+ "sent_count",
+ "delivered_count",
+ "failed_count",
+ "temporary_failed_count",
+ "permanent_failed_count",
+ "bounced_count",
+ "hard_bounces_count",
+ "soft_bounces_count",
+ "opened_count",
+ "unique_opened_count",
+ "clicked_count",
+ "unique_clicked_count",
+ "unsubscribed_count",
+ "complained_count",
+ "delivered_rate",
+ "opened_rate",
+ "unique_opened_rate",
+ "clicked_rate",
+ "unique_clicked_rate",
+ "unsubscribed_rate",
+ "complained_rate",
+ "bounce_rate",
+ "permanent_fail_rate",
+ "delayed_rate",
+)
+
+
+@dataclass(frozen=True)
+class MailgunMetricsEndpointConfig:
+ name: str
+ # Metrics API dimension each daily row breaks down by. None gives account-wide totals.
+ dimension: Optional[str] = None
+
+ @property
+ def primary_keys(self) -> list[str]:
+ return ["time", self.dimension] if self.dimension else ["time"]
+
+
+# Daily rollups from the Metrics API, which replaces the deprecated /v3 stats, tag stats and
+# aggregates endpoints. The request takes a start/end window, so every table can sync
+# incrementally on its daily `time` bucket.
+MAILGUN_METRICS_ENDPOINTS: dict[str, MailgunMetricsEndpointConfig] = {
+ config.name: config
+ for config in (
+ MailgunMetricsEndpointConfig(name="metrics"),
+ MailgunMetricsEndpointConfig(name="domain_metrics", dimension="domain"),
+ MailgunMetricsEndpointConfig(name="tag_metrics", dimension="tag"),
+ MailgunMetricsEndpointConfig(name="country_metrics", dimension="country"),
+ MailgunMetricsEndpointConfig(name="recipient_provider_metrics", dimension="recipient_provider"),
+ )
+}
+
+METRICS_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+ENDPOINTS = tuple(MAILGUN_ENDPOINTS.keys()) + tuple(MAILGUN_METRICS_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
- name: config.incremental_fields for name, config in MAILGUN_ENDPOINTS.items() if config.incremental_fields
+ **{name: config.incremental_fields for name, config in MAILGUN_ENDPOINTS.items() if config.incremental_fields},
+ **dict.fromkeys(MAILGUN_METRICS_ENDPOINTS, METRICS_INCREMENTAL_FIELDS),
}
# Webhook-only table fed by Mailgun's pushed event stream. It deliberately does not feed the
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.py
index 164874fb8452..04c33f281cf9 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
@@ -11,9 +11,19 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import WebhookCreationResult
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ RecordedRequest,
+ ScriptedResponse,
+ SourceDriver,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mailgun import (
+ MailgunSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun import mailgun as mailgun_module
from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun import (
FORBIDDEN_ERROR,
INVALID_KEY_ERROR,
+ METRICS_PAGE_SIZE,
UNREACHABLE_ERROR,
MailgunResumeConfig,
MailgunRetryableError,
@@ -37,6 +47,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.se
WEBHOOK_EVENTS_ENDPOINT,
WEBHOOK_TYPES,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.source import MailgunSource
US_BASE = "https://api.mailgun.net"
POSTHOG_URL = "https://us.posthog.com/public/webhooks/abc"
@@ -384,6 +395,120 @@ class TestGetRows:
assert [row["address"] for batch in batches for row in batch] == ["[email protected]"]
+def _metrics_item(day: date, tag: str) -> dict[str, Any]:
+ return {
+ "dimensions": [
+ {"dimension": "time", "value": f"{day.strftime('%a, %d %b %Y')} 00:00:00 +0000", "display_value": ""},
+ {"dimension": "tag", "value": tag, "display_value": tag.title()},
+ ],
+ "metrics": {"delivered_count": 3, "opened_rate": "66.67"},
+ }
+
+
+def _request_day(request: RecordedRequest) -> date:
+ return datetime.strptime(request.json()["start"], "%a, %d %b %Y %H:%M:%S %z").date()
+
+
+# Short enough for the driver's request limit; production walks a full year of days.
+METRICS_LOOKBACK_DAYS = 20
+
+
+class TestMetricsRows:
+ @pytest.fixture(autouse=True)
+ def _short_lookback(self):
+ with mock.patch.object(mailgun_module, "METRICS_LOOKBACK_DAYS", METRICS_LOOKBACK_DAYS):
+ yield
+
+ @staticmethod
+ def _driver() -> SourceDriver:
+ return SourceDriver(MailgunSource(), MailgunSourceConfig(api_key="key-123", region="us"))
+
+ def test_walks_one_day_per_request_and_pages_within_a_busy_day(self):
+ today = datetime.now(UTC).date()
+ busy_day = today - timedelta(days=10)
+
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ body = request.json()
+ if _request_day(request) != busy_day:
+ return ScriptedResponse(json={"items": []})
+ count = METRICS_PAGE_SIZE if body["pagination"]["skip"] == 0 else 2
+ return ScriptedResponse(json={"items": [_metrics_item(busy_day, f"tag-{i}") for i in range(count)]})
+
+ result = self._driver().run("tag_metrics", respond)
+
+ assert result.raised is None
+ assert {request.method for request in result.requests} == {"POST"}
+ assert {request.path for request in result.requests} == {"/v1/analytics/metrics"}
+ days = [_request_day(request) for request in result.requests]
+ assert days[0] == today - timedelta(days=METRICS_LOOKBACK_DAYS - 1)
+ assert days[-1] == today
+ assert len(days) == METRICS_LOOKBACK_DAYS + 1
+ busy_requests = [request.json() for request in result.requests if _request_day(request) == busy_day]
+ assert [body["pagination"]["skip"] for body in busy_requests] == [0, METRICS_PAGE_SIZE]
+ assert busy_requests[0]["dimensions"] == ["time", "tag"]
+ assert busy_requests[0]["pagination"]["sort"] == "tag:asc"
+ assert len(result.rows) == METRICS_PAGE_SIZE + 2
+ assert result.rows[0] == {
+ "delivered_count": 3,
+ "opened_rate": "66.67",
+ "time": datetime.combine(busy_day, datetime.min.time(), tzinfo=UTC),
+ "tag": "tag-0",
+ "tag_display_value": "Tag-0",
+ }
+
+ @pytest.mark.parametrize(
+ "watermark_days_ago, expected_first_day_ago",
+ [
+ (5, 7),
+ # A watermark older than the lookback starts at the lookback edge instead.
+ (METRICS_LOOKBACK_DAYS + 30, METRICS_LOOKBACK_DAYS - 1),
+ ],
+ )
+ def test_incremental_sync_starts_shortly_before_the_watermark(self, watermark_days_ago, expected_first_day_ago):
+ today = datetime.now(UTC).date()
+ watermark = datetime.combine(today - timedelta(days=watermark_days_ago), datetime.min.time(), tzinfo=UTC)
+
+ result = self._driver().run(
+ "metrics",
+ lambda _request: ScriptedResponse(json={"items": []}),
+ incremental_field="time",
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert result.raised is None
+ days = [_request_day(request) for request in result.requests]
+ assert days[0] == today - timedelta(days=expected_first_day_ago)
+ assert days[-1] == today
+ assert result.requests[0].json()["dimensions"] == ["time"]
+
+ def test_a_day_that_never_stops_returning_full_pages_moves_on_at_the_row_cap(self):
+ today = datetime.now(UTC).date()
+ full_page = ScriptedResponse(
+ json={"items": [_metrics_item(today, f"tag-{i}") for i in range(METRICS_PAGE_SIZE)]}
+ )
+
+ with mock.patch.object(mailgun_module, "MAX_METRICS_ROWS_PER_DAY", METRICS_PAGE_SIZE):
+ result = self._driver().run("tag_metrics", lambda _request: full_page)
+
+ assert result.raised is None
+ assert len(result.requests) == METRICS_LOOKBACK_DAYS
+ assert {request.json()["pagination"]["skip"] for request in result.requests} == {0}
+
+ def test_resume_continues_from_the_saved_day_and_offset(self):
+ today = datetime.now(UTC).date()
+
+ result = self._driver().run(
+ "domain_metrics",
+ lambda _request: ScriptedResponse(json={"items": []}),
+ resume_state=MailgunResumeConfig(metrics_day=today.isoformat(), metrics_skip=METRICS_PAGE_SIZE),
+ )
+
+ assert result.raised is None
+ assert len(result.requests) == 1
+ assert _request_day(result.requests[0]) == today
+ assert result.requests[0].json()["pagination"]["skip"] == METRICS_PAGE_SIZE
+
+
class TestMailgunSourceResponse:
def test_webhook_endpoint_yields_nothing_until_the_webhook_is_live(self):
webhook_manager = mock.MagicMock()