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 moengage import source (#107252)

Tom Owers03b9fe1b9db2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 26bc99498e72..2a51c8d13ba9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -475,6 +475,7 @@ the row lists both.
| mistral_ai | HTTP | requests | ✅ |
| mixmax | HTTP | requests | ✅ |
| mixpanel | HTTP | requests | ✅ |
+| moengage | HTTP | requests + `rest_source.RESTClient` | ✅ |
| mollie | HTTP | requests | ✅ |
| monday | HTTP (GraphQL) | requests | ✅ |
| mongodb | DB protocol | pymongo | ➖ |
@@ -1218,7 +1219,6 @@ doesn't conflict with concurrent PRs.
- miro
- missive
- mode
-- moengage
- moesif
- monaco
- moneybird
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moengage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moengage.py
index e65aaca1f449..f2991b5f1d4a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moengage.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moengage.py
@@ -1,9 +1,14 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
class MoEngageSourceConfig(config.Config):
- pass
+ workspace_id: str
+ api_key: str
+ data_center: Literal["01", "02", "03", "04", "05", "06", "101"] = config.value(default="01")
+ start_date: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/canonical_descriptions.py
new file mode 100644
index 000000000000..3bc1d414721d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/canonical_descriptions.py
@@ -0,0 +1,59 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_REPORT_COLUMNS = {
+ "id": "Surrogate key hashed from the row's identity dimensions.",
+ "campaign_id": "Identifier of the campaign the stats belong to.",
+ "platform": "Platform the users engaged on (for example ANDROID, IOS, WEB).",
+ "locale": "Locale breakdown of the stats, or all_locales for the campaign total.",
+ "variation": "Campaign variation the stats belong to, or all_variations for the campaign total. Control groups appear as campaign_control_group and global_control_group.",
+ "attempted": "Number of messages MoEngage attempted to send.",
+ "sent": "Number of messages sent.",
+ "failed": "Number of messages that failed to send.",
+ "impression": "Number of impressions recorded for the campaign.",
+ "click": "Number of clicks recorded for the campaign.",
+ "ctr": "Click-through rate for the campaign.",
+ "delivery_rate": "Share of attempted messages that were delivered.",
+ "sent_rate": "Share of attempted messages that were sent.",
+ "failure_rate": "Share of attempted messages that failed.",
+ "conversion_goal_stats": "Conversions, conversion rate, and uplift per configured conversion goal.",
+ "delivery_funnel": "Delivery funnel counts, from reachable users in the segment through to impressions.",
+ "failure_breakdown": "Failure counts broken down by reason.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "campaigns": {
+ "description": "Campaigns in the MoEngage workspace, across channels, with their status, delivery type, and configuration details.",
+ "docs_url": "https://www.moengage.com/docs/api/get-campaign-details/search-campaigns-v5",
+ "columns": {
+ "id": "Unique identifier of the campaign document. With campaign versioning enabled, each published revision has its own id.",
+ "campaign_id": "Stable campaign identifier shared by every version of the campaign.",
+ "status": "Current status of the campaign (for example ACTIVE, SCHEDULED, STOPPED).",
+ "channel": "Channel the campaign sends on (PUSH, EMAIL, or SMS).",
+ "campaign_delivery_type": "How the campaign is delivered (for example ONE_TIME, PERIODIC, EVENT_TRIGGERED).",
+ "created_by": "Email address of the user who created the campaign.",
+ "created_at": "When the campaign was created, in the workspace timezone.",
+ "updated_at": "When the campaign was last updated, in the workspace timezone.",
+ "basic_details": "Campaign name, platforms, tags, and other channel-specific setup details.",
+ "connector": "Delivery connector the campaign sends through (for example the email provider).",
+ },
+ },
+ "campaign_report": {
+ "description": "Per-campaign performance stats aggregated over the trailing 30 days, broken down by platform, locale, and variation. The whole table refreshes on every sync.",
+ "docs_url": "https://www.moengage.com/docs/api/stats-report",
+ "columns": {
+ **_REPORT_COLUMNS,
+ "start_date": "First day of the reported window.",
+ "end_date": "Last day of the reported window.",
+ },
+ },
+ "daily_campaign_report": {
+ "description": "Per-campaign performance stats for a single day, broken down by platform, locale, and variation. One row per campaign, day, platform, locale, and variation.",
+ "docs_url": "https://www.moengage.com/docs/api/stats-report",
+ "columns": {
+ **_REPORT_COLUMNS,
+ "date": "Day the stats cover, in the workspace timezone.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/moengage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/moengage.py
new file mode 100644
index 000000000000..66f777fcffcd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/moengage.py
@@ -0,0 +1,531 @@
+import uuid
+import hashlib
+from collections.abc import Callable, Iterator
+from datetime import UTC, date, datetime, timedelta
+from functools import partial
+from typing import Any, Optional
+
+from requests import Request, Response
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.settings import (
+ ATTRIBUTION_TYPE,
+ DEFAULT_BACKFILL_DAYS,
+ MAX_BACKFILL_DAYS,
+ MAX_RETRY_ATTEMPTS,
+ METRIC_TYPE,
+ MOENGAGE_DATA_CENTERS,
+ MOENGAGE_ENDPOINTS,
+ REPORT_WINDOW_DAYS,
+ REQUEST_TIMEOUT_SECONDS,
+ SEARCH_PAGE_SIZE,
+ STATS_PAGE_SIZE,
+)
+
+START_DATE_TOO_OLD_ERROR = (
+ f"Start date can't be more than {MAX_BACKFILL_DAYS // 365} years ago. Pick a more recent date."
+)
+
+
+@frozen
+class MoEngageResumeConfig:
+ # Campaign search checkpoint: {"page": <next 1-indexed page>}.
+ search_state: dict | None = None
+ # Daily report checkpoint: {"start": "YYYY-MM-DD"}, the first day not yet fully yielded. The
+ # within-day stats offset is deliberately not saved: replaying a whole day costs at most a few
+ # request sets and merge dedupes the overlap on the synthesized `id`.
+ report_day_state: dict | None = None
+
+
+def moengage_base_url(data_center: str) -> str:
+ # The value is interpolated into the hostname, so anything outside the fixed data-center set is
+ # refused rather than sent: "01.evil.com" would otherwise retarget the credential.
+ if data_center not in MOENGAGE_DATA_CENTERS:
+ raise ValueError(f"Unknown MoEngage data center: {data_center!r}")
+ return f"https://api-{data_center}.moengage.com"
+
+
+class MoEngageSearchPaginator(BasePaginator):
+ """Page-number pagination inside the V5 search POST body.
+
+ The response carries no total count, so the terminal page is the one that returns fewer
+ campaigns than the requested limit. Every POST also needs a fresh Idempotency-Key header:
+ reusing one would make MoEngage replay the first page's response for every page.
+ """
+
+ def __init__(self, limit: int = SEARCH_PAGE_SIZE) -> None:
+ super().__init__()
+ self._limit = limit
+ self._page = 1
+
+ def _apply(self, request: Request) -> None:
+ if request.json is None:
+ request.json = {}
+ request.json["page"] = self._page
+ request.json["limit"] = self._limit
+ request.headers["Idempotency-Key"] = str(uuid.uuid4())
+
+ def init_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if data is not None and len(data) >= self._limit:
+ self._page += 1
+ self._has_next_page = True
+ else:
+ self._has_next_page = False
+
+ def update_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"page": self._page} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ page = state.get("page")
+ if page is not None:
+ self._page = int(page)
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return f"MoEngageSearchPaginator(page={self._page}, limit={self._limit})"
+
+
+class MoEngageStatsPaginator(BasePaginator):
+ """Offset pagination inside the campaign-stats POST body.
+
+ The response reports current_page/total_pages; an empty `data` object or the last page stops
+ the walk. When the page counters are missing from a response, a page holding fewer campaigns
+ than the limit is treated as terminal so the walk can never loop on one offset.
+ """
+
+ def __init__(self, limit: int = STATS_PAGE_SIZE) -> None:
+ super().__init__()
+ self._limit = limit
+ self._offset = 0
+
+ def _apply(self, request: Request) -> None:
+ if request.json is None:
+ request.json = {}
+ request.json["offset"] = self._offset
+ request.json["limit"] = self._limit
+
+ def init_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ body = response.json()
+ except Exception:
+ body = None
+ # A response that fails to parse is treated as terminal, matching the paginator's other
+ # termination signals; a response that parses but isn't the documented object shape (e.g. a
+ # bare list or null) is a broken contract, not an empty page, so it must not be mistaken for
+ # sync completion.
+ if body is not None and not isinstance(body, dict):
+ raise ValueError(f"Expected a MoEngage stats object response, got {type(body).__name__}")
+ if not isinstance(body, dict):
+ self._has_next_page = False
+ return
+ stats = body.get("data") or {}
+ current_page = body.get("current_page")
+ total_pages = body.get("total_pages")
+ if not stats:
+ self._has_next_page = False
+ elif isinstance(current_page, int) and isinstance(total_pages, int):
+ self._has_next_page = current_page < total_pages
+ else:
+ self._has_next_page = len(stats) >= self._limit
+ if self._has_next_page:
+ self._offset += self._limit
+
+ def update_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def __str__(self) -> str:
+ return f"MoEngageStatsPaginator(offset={self._offset}, limit={self._limit})"
+
+
+def _row_id(*parts: Any) -> str:
+ """Deterministic surrogate id for a report row.
+
+ Hashes only the identity dimensions (never the metric values), so a row whose metrics get
+ restated between runs keeps the same id and merge updates it in place.
+ """
+ joined = "|".join("\x00" if p is None else str(p) for p in parts)
+ return hashlib.sha256(joined.encode()).hexdigest()
+
+
+def _explode_stats(window_columns: dict[str, Any], data_item: dict[str, Any]) -> list[dict[str, Any]]:
+ """Flatten one campaign-stats response into rows.
+
+ The response's `data` is an object keyed by campaign id, each holding a list of entries whose
+ platforms/locales/variations nest the metrics. One row per (campaign, platform, locale,
+ variation) with the flat performance metrics spread as columns; the goal, funnel and failure
+ groups keep dynamic keys (goal names, failure reasons) so they stay nested.
+ """
+ rows: list[dict[str, Any]] = []
+ for campaign_id, entries in data_item.items():
+ if not isinstance(entries, list):
+ continue
+ # The entry list is undocumented and observed with a single element; the index joins the id
+ # so a second element can never silently collide with the first.
+ for index, entry in enumerate(entries):
+ platforms = (entry or {}).get("platforms") or {}
+ for platform, platform_data in platforms.items():
+ locales = (platform_data or {}).get("locales") or {}
+ for locale, locale_data in locales.items():
+ variations = (locale_data or {}).get("variations") or {}
+ for variation, stats in variations.items():
+ stats = stats or {}
+ row: dict[str, Any] = dict(stats.get("performance_stats") or {})
+ row.update(
+ {
+ "id": _row_id(
+ campaign_id,
+ *window_columns.values(),
+ index,
+ platform,
+ locale,
+ variation,
+ ),
+ "campaign_id": campaign_id,
+ **window_columns,
+ "platform": platform,
+ "locale": locale,
+ "variation": variation,
+ "conversion_goal_stats": stats.get("conversion_goal_stats"),
+ "delivery_funnel": stats.get("delivery_funnel"),
+ "failure_breakdown": stats.get("failure_breakdown"),
+ }
+ )
+ rows.append(row)
+ return rows
+
+
+def _stats_body(start_date: date, end_date: date) -> dict[str, Any]:
+ return {
+ "request_id": str(uuid.uuid4()),
+ "start_date": start_date.isoformat(),
+ "end_date": end_date.isoformat(),
+ "attribution_type": ATTRIBUTION_TYPE,
+ "metric_type": METRIC_TYPE,
+ }
+
+
+def parse_iso_date(value: str) -> date:
+ # Accept a bare date or a full timestamp; only the calendar day matters for the fan-out.
+ return date.fromisoformat(value.strip()[:10])
+
+
+def start_date_error(start_date: str, today: Optional[date] = None) -> Optional[str]:
+ """Why a configured start date is unusable, or None if it's fine.
+
+ Rejects a date reaching back further than `MAX_BACKFILL_DAYS`: the daily report fans out one
+ request set per calendar day, so an unbounded lookback (e.g. `0001-01-01`) would turn one sync
+ into hundreds of thousands of requests. Syntax is validated separately by the caller.
+ """
+ floor = (today or datetime.now(UTC).date()) - timedelta(days=MAX_BACKFILL_DAYS)
+ if parse_iso_date(start_date) < floor:
+ return START_DATE_TOO_OLD_ERROR
+ return None
+
+
+def _as_date(value: Any) -> date:
+ # datetime subclasses date, so it has to be tested first.
+ if isinstance(value, datetime):
+ return (value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)).date()
+ if isinstance(value, date):
+ return value
+ return parse_iso_date(str(value))
+
+
+def _previous_sync_floor(
+ last_synced_at: Optional[datetime],
+ db_incremental_field_last_value: Optional[Any],
+ db_incremental_field_last_value_before_lookback: Optional[Any],
+) -> Optional[date]:
+ """First day the previous successful sync leaves to re-read, or None when that is unknown.
+
+ That sync scanned every day up to its own start, so only the lookback the pipeline applied to
+ the watermark needs a re-read, measured back from that start.
+ """
+ if (
+ last_synced_at is None
+ or not isinstance(db_incremental_field_last_value, date)
+ or not isinstance(db_incremental_field_last_value_before_lookback, date)
+ ):
+ return None
+ lookback = db_incremental_field_last_value_before_lookback - db_incremental_field_last_value
+ return _as_date(last_synced_at - lookback)
+
+
+def _report_days(
+ db_incremental_field_last_value: Optional[Any],
+ today: date,
+ configured_start: Optional[date],
+ resume_from: Optional[date],
+ previous_sync_floor: Optional[date] = None,
+) -> list[date]:
+ """Resolve the days the daily report requests, oldest first.
+
+ An incremental run continues from the watermark (already shifted back by the pipeline's
+ lookback); a full refresh starts at the configured start date, else the default backfill
+ window. A start past today is clamped onto today so a run always re-pulls the current day.
+ """
+ if db_incremental_field_last_value is not None:
+ start = _as_date(db_incremental_field_last_value)
+ # A run that finds no stats writes no rows, so the watermark does not move. Without this
+ # floor, every sync of an idle workspace would re-request each empty day since its last row.
+ if previous_sync_floor is not None:
+ start = max(start, previous_sync_floor)
+ else:
+ start = configured_start or (today - timedelta(days=DEFAULT_BACKFILL_DAYS - 1))
+ if resume_from is not None:
+ start = max(start, resume_from)
+ day = min(start, today)
+ days: list[date] = []
+ while day <= today:
+ days.append(day)
+ day = day + timedelta(days=1)
+ return days
+
+
+def _resume_day(resume: Optional[MoEngageResumeConfig]) -> Optional[date]:
+ saved = resume.report_day_state if resume is not None else None
+ start = saved.get("start") if isinstance(saved, dict) else None
+ return parse_iso_date(str(start)) if start else None
+
+
+def _iter_report_days(
+ build_resource: Callable[[date], Any],
+ days: list[date],
+ save_checkpoint: Callable[[date], None],
+ clear_checkpoint: Callable[[], None],
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield every day's pages in ascending day order, checkpointing once a day is fully yielded.
+
+ The checkpoint names the first day not yet yielded, so a restart replays at most the day that
+ was in progress and merge dedupes it on the synthesized `id`.
+ """
+ for index, day in enumerate(days):
+ yield from build_resource(day)
+ if index + 1 < len(days):
+ save_checkpoint(days[index + 1])
+
+ # The walk finished: leaving the last checkpoint would make a later attempt resume mid-stream.
+ clear_checkpoint()
+
+
+def _client_config(data_center: str, workspace_id: str, api_key: str) -> ClientConfig:
+ return {
+ "base_url": moengage_base_url(data_center),
+ "auth": {
+ "type": "http_basic",
+ "username": workspace_id,
+ "password": api_key,
+ },
+ # MOE-APPKEY is required by the core-services endpoints and harmless on V5, which reads the
+ # workspace id from the Basic Auth username.
+ "headers": {
+ "MOE-APPKEY": workspace_id,
+ "Accept": "application/json",
+ },
+ # Without this, a stalled MoEngage connection would hold the sync open indefinitely.
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ "max_retries": MAX_RETRY_ATTEMPTS,
+ }
+
+
+def moengage_source(
+ data_center: str,
+ workspace_id: str,
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[MoEngageResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
+ should_use_incremental_field: bool = False,
+ configured_start_date: Optional[str] = None,
+ last_synced_at: Optional[datetime] = None,
+ db_incremental_field_last_value_before_lookback: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = MOENGAGE_ENDPOINTS.get(endpoint)
+ if endpoint_config is None:
+ raise ValueError(f"Unknown MoEngage endpoint: {endpoint}")
+
+ client_config = _client_config(data_center, workspace_id, api_key)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ today = datetime.now(UTC).date()
+ # Set only where the rows come from something other than iterating `resource` once.
+ items: Optional[Callable[[], Iterator[list[dict[str, Any]]]]] = None
+ resource: Any = None
+
+ if endpoint == "campaigns":
+ campaigns_resource: EndpointResource = {
+ "name": endpoint,
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": endpoint_config.path,
+ "method": "POST",
+ # Child campaigns (periodic and flow-node executions) and archived campaigns are the
+ # rows the stats tables key to, so the list includes both.
+ "json": {"include_child_campaigns": True, "include_archive_campaigns": True},
+ "data_selector": "data.campaigns",
+ "paginator": MoEngageSearchPaginator(),
+ },
+ }
+ campaigns_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": None,
+ "resources": [campaigns_resource],
+ }
+
+ def save_search_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("page"):
+ resumable_source_manager.save_state(MoEngageResumeConfig(search_state=state))
+ else:
+ # The walk finished: leaving the last checkpoint would make a later attempt resume
+ # mid-stream.
+ resumable_source_manager.clear_state()
+
+ resource = rest_api_resource(
+ campaigns_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_search_checkpoint,
+ initial_paginator_state=resume.search_state if resume is not None else None,
+ )
+ elif endpoint == "campaign_report":
+ # A per-campaign snapshot of the trailing window the stats API allows in one call. The
+ # whole table restates each sync, so it is full-refresh only and not resumed: the window is
+ # anchored to today, and a checkpointed offset from a previous day would point into a
+ # different result set.
+ window_start = today - timedelta(days=REPORT_WINDOW_DAYS - 1)
+ report_resource: EndpointResource = {
+ "name": endpoint,
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": endpoint_config.path,
+ "method": "POST",
+ "json": _stats_body(window_start, today),
+ "data_selector": "data",
+ "paginator": MoEngageStatsPaginator(),
+ },
+ "data_map": partial(
+ _explode_stats, {"start_date": window_start.isoformat(), "end_date": today.isoformat()}
+ ),
+ }
+ report_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": None,
+ "resources": [report_resource],
+ }
+ resource = rest_api_resource(report_config, team_id, job_id, db_incremental_field_last_value)
+ else:
+ # Daily report: the stats API answers one date window per call, so the source fans out one
+ # request set per calendar day, oldest first, which keeps rows ascending for the watermark.
+ configured_start = parse_iso_date(configured_start_date) if configured_start_date else None
+ watermark = db_incremental_field_last_value if should_use_incremental_field else None
+ days = _report_days(
+ watermark,
+ today,
+ configured_start,
+ _resume_day(resume),
+ _previous_sync_floor(last_synced_at, watermark, db_incremental_field_last_value_before_lookback),
+ )
+ # One tracked session shared by every day's client, so a backfill reuses a single
+ # connection pool instead of opening one per day.
+ client_config["session"] = make_tracked_session(redact_values=(api_key,))
+
+ def build_day_resource(day: date) -> Any:
+ day_resource: EndpointResource = {
+ "name": endpoint,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": endpoint_config.path,
+ "method": "POST",
+ "json": _stats_body(day, day),
+ "data_selector": "data",
+ "paginator": MoEngageStatsPaginator(),
+ },
+ "data_map": partial(_explode_stats, {"date": day.isoformat()}),
+ }
+ day_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": None,
+ "resources": [day_resource],
+ }
+ return rest_api_resource(day_config, team_id, job_id, db_incremental_field_last_value)
+
+ def save_day_checkpoint(next_day: date) -> None:
+ resumable_source_manager.save_state(MoEngageResumeConfig(report_day_state={"start": next_day.isoformat()}))
+
+ items = partial(
+ _iter_report_days, build_day_resource, days, save_day_checkpoint, resumable_source_manager.clear_state
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=items if items is not None else (lambda: resource),
+ primary_keys=endpoint_config.primary_keys,
+ sort_mode="asc",
+ partition_count=1 if endpoint_config.partition_key else None,
+ partition_size=1 if endpoint_config.partition_key else None,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
+def validate_credentials(data_center: str, workspace_id: str, api_key: str) -> tuple[bool, str | None]:
+ """One cheap probe against the campaign search endpoint to confirm the credentials.
+
+ MoEngage issues separate API keys per feature; the campaigns and stats endpoints both take the
+ Campaign report key, so a 403 here means the wrong key kind rather than a partial scope, and it
+ is rejected at create time.
+ """
+ try:
+ session = make_tracked_session(redact_values=(api_key,))
+ response = session.post(
+ f"{moengage_base_url(data_center)}/v5/campaigns/search",
+ json={"limit": 1, "page": 1},
+ headers={
+ "MOE-APPKEY": workspace_id,
+ "Accept": "application/json",
+ "Idempotency-Key": str(uuid.uuid4()),
+ },
+ auth=(workspace_id, api_key),
+ timeout=10,
+ )
+ except Exception:
+ return False, "Couldn't reach MoEngage. Check the selected data center and try again."
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return (
+ False,
+ "MoEngage authentication failed. Check that the Workspace ID and the Campaign report API key "
+ "(Settings > Account > APIs in your MoEngage dashboard) are correct and match your data center.",
+ )
+ return False, f"MoEngage returned an unexpected response (HTTP {response.status_code}). Try again later."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/settings.py
new file mode 100644
index 000000000000..923bffafbd56
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/settings.py
@@ -0,0 +1,101 @@
+from dataclasses import field
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Hostname segment in https://api-{dc}.moengage.com. The config value is interpolated into the
+# host, so it must come from this allowlist: a crafted value like "01.evil.com" would otherwise
+# retarget the Basic Auth credential at an attacker-controlled host.
+MOENGAGE_DATA_CENTERS = ("01", "02", "03", "04", "05", "06", "101")
+
+# Documented page maximums: campaign search serves up to 15 campaigns per page, campaign-stats up
+# to 10 campaigns per page.
+SEARCH_PAGE_SIZE = 15
+STATS_PAGE_SIZE = 10
+
+# Without this, the underlying rest_source client never times out a stalled connection.
+REQUEST_TIMEOUT_SECONDS = 60
+
+# The workspace limit is 100 requests per minute. A 429 without a Retry-After header falls back to
+# exponential backoff, and the client's default 5 attempts wait about 15 seconds in total, which is
+# shorter than that window. 8 attempts wait about 2 minutes (1+2+4+8+16+32+60 seconds).
+MAX_RETRY_ATTEMPTS = 8
+
+# The campaign-stats API rejects a start_date..end_date span wider than 30 days, so the aggregate
+# campaign_report snapshot asks for exactly that trailing window.
+REPORT_WINDOW_DAYS = 30
+
+# Full-refresh floor for the daily report's day-by-day fan-out when the user sets no start date.
+# Each day costs one request set against a 100-requests-per-minute workspace limit, so an
+# unbounded backfill is not the default.
+DEFAULT_BACKFILL_DAYS = 90
+
+# Ceiling on a configured start date. The daily report fans out one request set per calendar day,
+# so an unbounded lookback (e.g. a start date of 0001-01-01) would turn one sync into hundreds of
+# thousands of requests against the 100-requests-per-minute workspace limit.
+MAX_BACKFILL_DAYS = 5 * 365
+
+# Conversion metrics for a day keep restating as attributions land, so each incremental run
+# re-pulls a trailing window; merge dedupes the overlap on the synthesized `id`.
+DAILY_REPORT_LOOKBACK_SECONDS = 60 * 60 * 24 * 3
+
+# Fixed report dimensions. The stats API requires both on every request; TOTAL_CONVERSIONS and
+# TOTAL are the widest documented options, so the synced numbers match the dashboard's defaults.
+ATTRIBUTION_TYPE = "TOTAL_CONVERSIONS"
+METRIC_TYPE = "TOTAL"
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@frozen
+class MoEngageEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str]
+ partition_key: str | None = None
+ # True only for the daily report, whose date window is a genuine server-side filter. The
+ # campaign list only filters on created_date, which would freeze status changes on old
+ # campaigns, so it stays full-refresh; the aggregate report restates wholesale every sync.
+ supports_incremental: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_lookback_seconds: int | None = None
+
+
+MOENGAGE_ENDPOINTS: dict[str, MoEngageEndpointConfig] = {
+ "campaigns": MoEngageEndpointConfig(
+ name="campaigns",
+ path="/v5/campaigns/search",
+ # With campaign versioning enabled each published revision is its own document with its own
+ # `id`; `campaign_id` stays the stable cross-version identifier and is kept as a column.
+ primary_keys=["id"],
+ partition_key="created_at",
+ ),
+ "campaign_report": MoEngageEndpointConfig(
+ name="campaign_report",
+ path="/core-services/v1/campaign-stats",
+ primary_keys=["id"],
+ ),
+ "daily_campaign_report": MoEngageEndpointConfig(
+ name="daily_campaign_report",
+ path="/core-services/v1/campaign-stats",
+ primary_keys=["id"],
+ partition_key="date",
+ supports_incremental=True,
+ incremental_fields=[_datetime_incremental_field("date")],
+ default_incremental_lookback_seconds=DAILY_REPORT_LOOKBACK_SECONDS,
+ ),
+}
+
+ENDPOINTS = tuple(MOENGAGE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in MOENGAGE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/source.py
index 5a66dedd09b7..9f9739c31791 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/source.py
@@ -1,28 +1,203 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.moengage import (
MoEngageSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.moengage import (
+ MoEngageResumeConfig,
+ moengage_source,
+ parse_iso_date,
+ start_date_error,
+ validate_credentials as validate_moengage_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.settings import (
+ INCREMENTAL_FIELDS,
+ MOENGAGE_DATA_CENTERS,
+ MOENGAGE_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_DATA_CENTER_LABELS = {
+ "01": "DC-01 (US)",
+ "02": "DC-02 (EU)",
+ "03": "DC-03 (India)",
+ "04": "DC-04 (US)",
+ "05": "DC-05 (Singapore)",
+ "06": "DC-06 (Indonesia)",
+ "101": "DC-101",
+}
+
@SourceRegistry.register
-class MoEngageSource(SimpleSource[MoEngageSourceConfig]):
+class MoEngageSource(ResumableSource[MoEngageSourceConfig, MoEngageResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # MoEngage versions per endpoint family through the URL path (the V5 campaign search, the
+ # core-services/v1 stats API) rather than one account-wide version token, so the paths pinned in
+ # settings.py are the version declaration and the framework default stays unversioned.
+ api_docs_url = "https://www.moengage.com/docs/api/introduction"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MOENGAGE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ message = (
+ "MoEngage authentication failed. Check that the Workspace ID and the Campaign report API key "
+ "(Settings > Account > APIs in your MoEngage dashboard) are correct and match your data center, "
+ "then reconnect the source."
+ )
+ return {
+ "401 Client Error: Unauthorized for url": message,
+ "403 Client Error: Forbidden for url": message,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: MoEngageSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint_config.name,
+ supports_incremental=endpoint_config.supports_incremental,
+ # Report metrics restate, so append would materialize duplicate rows; the daily
+ # report is merge-only and the other endpoints are full-refresh only.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint_config.name, []),
+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,
+ )
+ for endpoint_config in MOENGAGE_ENDPOINTS.values()
+ ]
+ 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: MoEngageSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if config.data_center not in MOENGAGE_DATA_CENTERS:
+ return False, "Select the data center your MoEngage dashboard URL shows (for example DC-01)."
+ if config.start_date:
+ try:
+ parse_iso_date(config.start_date)
+ except ValueError:
+ return False, "Enter the daily report start date as YYYY-MM-DD, or leave it empty."
+ error = start_date_error(config.start_date)
+ if error is not None:
+ return False, error
+ return validate_moengage_credentials(config.data_center, config.workspace_id, config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MoEngageResumeConfig]:
+ return ResumableSourceManager[MoEngageResumeConfig](inputs, MoEngageResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MoEngageSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MoEngageResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return moengage_source(
+ data_center=config.data_center,
+ workspace_id=config.workspace_id,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
+ configured_start_date=config.start_date,
+ last_synced_at=inputs.last_synced_at,
+ db_incremental_field_last_value_before_lookback=inputs.db_incremental_field_last_value_before_lookback,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.MOENGAGE,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="MoEngage",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Sync your MoEngage campaigns and their performance reports into the PostHog Data warehouse.
+
+Find your Workspace ID and the **Campaign report** API key in your MoEngage dashboard under **Settings** > **Account** > **APIs**. Pick the data center your dashboard URL shows (for example, `dashboard-01.moengage.com` is DC-01).
+
+The `daily_campaign_report` table backfills the last 90 days by default. Set a daily report start date to backfill further. The `campaign_report` table always covers the last 30 days.""",
+ docsUrl="https://posthog.com/docs/cdp/sources/moengage",
iconPath="/static/services/moengage.png",
keywords=["push notifications", "customer engagement", "marketing automation", "moengage"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="data_center",
+ label="Data center",
+ required=True,
+ defaultValue="01",
+ options=[
+ SourceFieldSelectConfigOption(label=_DATA_CENTER_LABELS[dc], value=dc)
+ for dc in MOENGAGE_DATA_CENTERS
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="workspace_id",
+ label="Workspace ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Campaign report API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Daily report start date (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="2025-01-01",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage.py
new file mode 100644
index 000000000000..5ed1d7206f4c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage.py
@@ -0,0 +1,570 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.moengage import (
+ START_DATE_TOO_OLD_ERROR,
+ MoEngageResumeConfig,
+ MoEngageSearchPaginator,
+ MoEngageStatsPaginator,
+ _explode_stats,
+ _report_days,
+ moengage_base_url,
+ moengage_source,
+ start_date_error,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.settings import (
+ ATTRIBUTION_TYPE,
+ DEFAULT_BACKFILL_DAYS,
+ MAX_BACKFILL_DAYS,
+ MAX_RETRY_ATTEMPTS,
+ METRIC_TYPE,
+ MOENGAGE_DATA_CENTERS,
+ REPORT_WINDOW_DAYS,
+ SEARCH_PAGE_SIZE,
+ STATS_PAGE_SIZE,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.source import MoEngageSource
+
+# RESTClient builds its session via make_tracked_session in the rest_client module; the daily
+# report shares one session built in the moengage module instead.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+MOENGAGE_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.moengage.moengage.make_tracked_session"
+)
+
+
+def _response(body: dict[str, Any], status: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ resp.url = "https://api-01.moengage.com/"
+ return resp
+
+
+def _campaigns_page(count: int) -> Response:
+ return _response({"data": {"campaigns": [{"id": f"c{i}", "created_at": "2025-01-01"} for i in range(count)]}})
+
+
+def _stats_page(campaign_ids: list[str], *, current_page: int | None = 1, total_pages: int | None = 1) -> Response:
+ body: dict[str, Any] = {
+ "data": {
+ campaign_id: [
+ {
+ "platforms": {
+ "android": {
+ "locales": {
+ "all_locales": {
+ "variations": {
+ "all_variations": {
+ "performance_stats": {"attempted": 2, "sent": 2, "click": 4},
+ "delivery_funnel": {"sent": 2},
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ ]
+ for campaign_id in campaign_ids
+ }
+ }
+ if current_page is not None:
+ body["current_page"] = current_page
+ if total_pages is not None:
+ body["total_pages"] = total_pages
+ return _response(body)
+
+
+def _make_manager(resume: MoEngageResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _drive(
+ endpoint: str,
+ responses: list[Response],
+ *,
+ manager: mock.MagicMock | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ configured_start_date: str | None = None,
+ last_synced_at: datetime | None = None,
+ db_incremental_field_last_value_before_lookback: Any = None,
+) -> tuple[list[dict[str, Any]], list[dict[str, str]], list[dict[str, Any]], mock.MagicMock]:
+ """Drive ``moengage_source`` with a mocked HTTP session.
+
+ Returns ``(sent_bodies, sent_headers, rows, manager)``. Bodies and headers are copied at
+ send time because the paginators mutate the Request in place between pages.
+ """
+ manager = manager if manager is not None else _make_manager()
+ sent_bodies: list[dict[str, Any]] = []
+ sent_headers: list[dict[str, str]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_bodies.append(dict(request.json or {}))
+ sent_headers.append(dict(request.headers or {}))
+ return next(response_iter)
+
+ with mock.patch(CLIENT_SESSION_PATCH) as MockClientSession, mock.patch(MOENGAGE_SESSION_PATCH) as MockMoeSession:
+ for factory in (MockClientSession, MockMoeSession):
+ session = factory.return_value
+ session.headers = {}
+ session.prepare_request.side_effect = lambda req: req
+ session.send.side_effect = fake_send
+
+ source_response = moengage_source(
+ data_center="01",
+ workspace_id="ws-1",
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ configured_start_date=configured_start_date,
+ last_synced_at=last_synced_at,
+ db_incremental_field_last_value_before_lookback=db_incremental_field_last_value_before_lookback,
+ )
+ rows = [row for page in cast(Iterable[Any], source_response.items()) for row in page]
+ return sent_bodies, sent_headers, rows, manager
+
+
+class TestMoEngageBaseUrl:
+ @pytest.mark.parametrize("data_center", MOENGAGE_DATA_CENTERS)
+ def test_builds_moengage_host_for_every_data_center(self, data_center: str) -> None:
+ assert moengage_base_url(data_center) == f"https://api-{data_center}.moengage.com"
+
+ @pytest.mark.parametrize("data_center", ["01.evil.com", "evil.com/", "07", ""])
+ def test_rejects_values_outside_the_allowlist(self, data_center: str) -> None:
+ # The value is interpolated into the hostname, so an unknown value must never build a URL.
+ with pytest.raises(ValueError):
+ moengage_base_url(data_center)
+
+
+class TestMoEngageSearchPaginator:
+ @pytest.mark.parametrize(
+ ("rows_on_page", "expects_next"),
+ [
+ (SEARCH_PAGE_SIZE, True),
+ (SEARCH_PAGE_SIZE - 1, False),
+ (0, False),
+ ],
+ )
+ def test_full_page_advances_and_short_page_stops(self, rows_on_page: int, expects_next: bool) -> None:
+ paginator = MoEngageSearchPaginator()
+ paginator.update_state(_campaigns_page(rows_on_page), data=[{}] * rows_on_page)
+
+ assert paginator.has_next_page is expects_next
+ assert paginator.get_resume_state() == ({"page": 2} if expects_next else None)
+
+ def test_each_request_gets_a_fresh_idempotency_key(self) -> None:
+ # MoEngage replays the response recorded for a reused Idempotency-Key, so a reused key
+ # would return page 1's body for every page.
+ paginator = MoEngageSearchPaginator()
+ request = Request(method="POST", url="https://api-01.moengage.com/v5/campaigns/search", json={})
+ paginator.init_request(request)
+ first_key = request.headers["Idempotency-Key"]
+ paginator.update_state(_campaigns_page(SEARCH_PAGE_SIZE), data=[{}] * SEARCH_PAGE_SIZE)
+ paginator.update_request(request)
+
+ assert request.headers["Idempotency-Key"] != first_key
+ assert request.json["page"] == 2
+
+ def test_set_resume_state_targets_the_saved_page(self) -> None:
+ paginator = MoEngageSearchPaginator()
+ paginator.set_resume_state({"page": 5})
+ request = Request(method="POST", url="https://api-01.moengage.com/v5/campaigns/search", json={})
+ paginator.init_request(request)
+
+ assert request.json["page"] == 5
+
+
+class TestMoEngageStatsPaginator:
+ @pytest.mark.parametrize(
+ ("campaign_count", "current_page", "total_pages", "expects_next"),
+ [
+ (STATS_PAGE_SIZE, 1, 3, True),
+ (STATS_PAGE_SIZE, 3, 3, False),
+ (0, 1, 1, False),
+ # Counters missing from the response: a full page keeps walking, a short page stops,
+ # so the walk can never loop on one offset.
+ (STATS_PAGE_SIZE, None, None, True),
+ (STATS_PAGE_SIZE - 1, None, None, False),
+ ],
+ )
+ def test_termination_follows_page_counters_then_page_size(
+ self, campaign_count: int, current_page: int | None, total_pages: int | None, expects_next: bool
+ ) -> None:
+ paginator = MoEngageStatsPaginator()
+ response = _stats_page(
+ [f"c{i}" for i in range(campaign_count)], current_page=current_page, total_pages=total_pages
+ )
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is expects_next
+
+ def test_next_page_advances_offset_in_the_body(self) -> None:
+ paginator = MoEngageStatsPaginator()
+ paginator.update_state(_stats_page([f"c{i}" for i in range(STATS_PAGE_SIZE)], current_page=1, total_pages=2))
+ request = Request(method="POST", url="https://api-01.moengage.com/core-services/v1/campaign-stats", json={})
+ paginator.update_request(request)
+
+ assert request.json["offset"] == STATS_PAGE_SIZE
+ assert request.json["limit"] == STATS_PAGE_SIZE
+
+ def test_non_json_body_stops(self) -> None:
+ paginator = MoEngageStatsPaginator()
+ resp = Response()
+ resp.status_code = 200
+ resp._content = b"<html>gateway</html>"
+ paginator.update_state(resp)
+
+ assert paginator.has_next_page is False
+
+ def test_valid_json_with_the_wrong_shape_raises_instead_of_stopping_silently(self) -> None:
+ # A 200 that parses but isn't the documented stats object (e.g. a bare list) is a broken
+ # contract, not an empty page; treating it as terminal would let a snapshot replace good
+ # data with an incomplete result without ever raising.
+ paginator = MoEngageStatsPaginator()
+ resp = Response()
+ resp.status_code = 200
+ resp._content = b"[]"
+
+ with pytest.raises(ValueError, match="Expected a MoEngage stats object response"):
+ paginator.update_state(resp)
+
+
+class TestExplodeStats:
+ DATA = {
+ "66e933029ff25f3322d8279d": [
+ {
+ "platforms": {
+ "android": {
+ "locales": {
+ "all_locales": {
+ "variations": {
+ "all_variations": {
+ "performance_stats": {"attempted": 2, "sent": 2, "click": 4, "ctr": 200},
+ "conversion_goal_stats": {"Goal 1": {"conversions": 0}},
+ "delivery_funnel": {"sent": 2, "impressions": 2},
+ "failure_breakdown": {},
+ },
+ "campaign_control_group": {
+ "delivery_funnel": {"reachable_users_in_segment": 0},
+ "failure_breakdown": {"user_removed_due_to_campaing_control_group": 1},
+ },
+ }
+ }
+ }
+ }
+ }
+ }
+ ]
+ }
+
+ def test_explodes_one_row_per_campaign_platform_locale_variation(self) -> None:
+ rows = _explode_stats({"date": "2025-01-05"}, self.DATA)
+
+ assert [(r["campaign_id"], r["platform"], r["locale"], r["variation"]) for r in rows] == [
+ ("66e933029ff25f3322d8279d", "android", "all_locales", "all_variations"),
+ ("66e933029ff25f3322d8279d", "android", "all_locales", "campaign_control_group"),
+ ]
+ main = rows[0]
+ # Flat metrics become columns; groups with dynamic keys stay nested.
+ assert main["attempted"] == 2
+ assert main["ctr"] == 200
+ assert main["date"] == "2025-01-05"
+ assert main["conversion_goal_stats"] == {"Goal 1": {"conversions": 0}}
+ assert main["delivery_funnel"] == {"sent": 2, "impressions": 2}
+ # A variation with no performance_stats block still lands as a row.
+ assert rows[1]["failure_breakdown"] == {"user_removed_due_to_campaing_control_group": 1}
+
+ def test_id_is_stable_when_metrics_restate(self) -> None:
+ # Merge updates a restated row in place only if the id hashes identity dimensions, never
+ # the metric values.
+ restated = json.loads(json.dumps(self.DATA))
+ variations = restated["66e933029ff25f3322d8279d"][0]["platforms"]["android"]["locales"]["all_locales"][
+ "variations"
+ ]
+ variations["all_variations"]["performance_stats"]["click"] = 99
+
+ original_ids = [r["id"] for r in _explode_stats({"date": "2025-01-05"}, self.DATA)]
+ restated_ids = [r["id"] for r in _explode_stats({"date": "2025-01-05"}, restated)]
+ next_day_ids = [r["id"] for r in _explode_stats({"date": "2025-01-06"}, self.DATA)]
+
+ assert original_ids == restated_ids
+ assert set(original_ids).isdisjoint(next_day_ids)
+
+ def test_empty_data_yields_no_rows(self) -> None:
+ assert _explode_stats({"date": "2025-01-05"}, {}) == []
+
+
+class TestReportDays:
+ TODAY = date(2025, 6, 15)
+
+ @pytest.mark.parametrize(
+ ("watermark", "configured_start", "resume_from", "previous_sync_floor", "expected_first", "expected_len"),
+ [
+ # Incremental run continues from the watermark.
+ (date(2025, 6, 13), None, None, None, date(2025, 6, 13), 3),
+ # Full refresh starts at the configured start date.
+ (None, date(2025, 6, 10), None, None, date(2025, 6, 10), 6),
+ # Full refresh without a start date backfills the default window.
+ (
+ None,
+ None,
+ None,
+ None,
+ date(2025, 6, 15) - timedelta(days=DEFAULT_BACKFILL_DAYS - 1),
+ DEFAULT_BACKFILL_DAYS,
+ ),
+ # A watermark at or past today still re-pulls today rather than requesting the future.
+ (date(2025, 6, 16), None, None, None, date(2025, 6, 15), 1),
+ # A resume checkpoint skips the days already yielded.
+ (date(2025, 6, 10), None, date(2025, 6, 14), None, date(2025, 6, 14), 2),
+ # A stale watermark from an idle workspace does not re-scan days the last sync covered.
+ (date(2025, 1, 1), None, None, date(2025, 6, 12), date(2025, 6, 12), 4),
+ # The previous sync never widens the scan past the watermark.
+ (date(2025, 6, 13), None, None, date(2025, 6, 1), date(2025, 6, 13), 3),
+ # A full refresh rebuilds the whole table, so the previous sync does not narrow it.
+ (None, date(2025, 6, 10), None, date(2025, 6, 14), date(2025, 6, 10), 6),
+ ],
+ )
+ def test_resolves_the_requested_days(
+ self,
+ watermark: date | None,
+ configured_start: date | None,
+ resume_from: date | None,
+ previous_sync_floor: date | None,
+ expected_first: date,
+ expected_len: int,
+ ) -> None:
+ days = _report_days(watermark, self.TODAY, configured_start, resume_from, previous_sync_floor)
+
+ assert days[0] == expected_first
+ assert days[-1] == self.TODAY
+ assert len(days) == expected_len
+
+
+class TestStartDateError:
+ TODAY = date(2025, 6, 15)
+
+ def test_within_the_cap_is_accepted(self) -> None:
+ assert start_date_error("2025-06-01", today=self.TODAY) is None
+
+ def test_past_the_cap_is_rejected(self) -> None:
+ too_old = (self.TODAY - timedelta(days=MAX_BACKFILL_DAYS + 1)).isoformat()
+
+ assert start_date_error(too_old, today=self.TODAY) == START_DATE_TOO_OLD_ERROR
+
+ def test_the_cap_floor_is_measured_from_today(self) -> None:
+ floor = self.TODAY - timedelta(days=MAX_BACKFILL_DAYS)
+
+ assert start_date_error(floor.isoformat(), today=self.TODAY) is None
+ assert start_date_error((floor - timedelta(days=1)).isoformat(), today=self.TODAY) == START_DATE_TOO_OLD_ERROR
+
+
+class TestMoEngageSourceCampaigns:
+ def test_fresh_run_pages_until_a_short_page_and_checkpoints(self) -> None:
+ responses = [_campaigns_page(SEARCH_PAGE_SIZE), _campaigns_page(SEARCH_PAGE_SIZE), _campaigns_page(1)]
+ sent_bodies, sent_headers, rows, manager = _drive("campaigns", responses)
+
+ assert [body["page"] for body in sent_bodies] == [1, 2, 3]
+ assert all(body["limit"] == SEARCH_PAGE_SIZE for body in sent_bodies)
+ assert all(body["include_child_campaigns"] is True for body in sent_bodies)
+ keys = [headers["Idempotency-Key"] for headers in sent_headers]
+ assert len(set(keys)) == len(keys)
+ assert len(rows) == SEARCH_PAGE_SIZE * 2 + 1
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ MoEngageResumeConfig(search_state={"page": 2}),
+ MoEngageResumeConfig(search_state={"page": 3}),
+ ]
+
+ def test_resume_seeds_the_saved_page(self) -> None:
+ manager = _make_manager(MoEngageResumeConfig(search_state={"page": 4}))
+ sent_bodies, _, _, _ = _drive("campaigns", [_campaigns_page(0)], manager=manager)
+
+ assert [body["page"] for body in sent_bodies] == [4]
+
+
+class TestMoEngageSourceDailyReport:
+ def test_incremental_run_requests_one_window_per_day_from_the_watermark(self) -> None:
+ today = datetime.now(UTC).date()
+ watermark = today - timedelta(days=2)
+ responses = [_stats_page(["c1"]) for _ in range(3)]
+ sent_bodies, _, rows, manager = _drive(
+ "daily_campaign_report",
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+
+ expected_days = [(watermark + timedelta(days=i)).isoformat() for i in range(3)]
+ assert [body["start_date"] for body in sent_bodies] == expected_days
+ assert [body["end_date"] for body in sent_bodies] == expected_days
+ assert all(body["attribution_type"] == ATTRIBUTION_TYPE for body in sent_bodies)
+ assert all(body["metric_type"] == METRIC_TYPE for body in sent_bodies)
+
+ # Each row is stamped with the day its request asked for, since the response carries none.
+ assert [row["date"] for row in rows] == expected_days
+ assert rows[0]["campaign_id"] == "c1"
+
+ # The checkpoint names the first day not yet yielded, once per completed day.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ MoEngageResumeConfig(report_day_state={"start": expected_days[1]}),
+ MoEngageResumeConfig(report_day_state={"start": expected_days[2]}),
+ ]
+
+ def test_resume_skips_days_already_yielded(self) -> None:
+ today = datetime.now(UTC).date()
+ manager = _make_manager(MoEngageResumeConfig(report_day_state={"start": today.isoformat()}))
+ sent_bodies, _, _, _ = _drive(
+ "daily_campaign_report",
+ [_stats_page(["c1"])],
+ manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=today - timedelta(days=5),
+ )
+
+ assert [body["start_date"] for body in sent_bodies] == [today.isoformat()]
+
+ def test_incremental_run_starts_at_the_previous_sync_minus_the_applied_lookback(self) -> None:
+ today = datetime.now(UTC).date()
+ stored_watermark = today - timedelta(days=60)
+ last_synced_at = datetime.combine(today - timedelta(days=1), datetime.min.time(), tzinfo=UTC)
+ sent_bodies, _, _, _ = _drive(
+ "daily_campaign_report",
+ [_stats_page(["c1"]) for _ in range(6)],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=stored_watermark - timedelta(days=4),
+ db_incremental_field_last_value_before_lookback=stored_watermark,
+ last_synced_at=last_synced_at,
+ )
+
+ # The 4-day lookback the pipeline applied to the watermark applies to the last sync too.
+ assert [body["start_date"] for body in sent_bodies] == [
+ (today - timedelta(days=5 - i)).isoformat() for i in range(6)
+ ]
+
+ @mock.patch("tenacity.nap.time.sleep")
+ def test_rate_limited_stats_request_outlasts_the_per_minute_window(self, mock_sleep: mock.MagicMock) -> None:
+ today = datetime.now(UTC).date()
+ sent_bodies, _, rows, _ = _drive(
+ "daily_campaign_report",
+ [*[_response({}, status=429) for _ in range(MAX_RETRY_ATTEMPTS - 1)], _stats_page(["c1"])],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=today,
+ )
+
+ assert len(sent_bodies) == MAX_RETRY_ATTEMPTS
+ assert [row["campaign_id"] for row in rows] == ["c1"]
+ # A 429 without Retry-After backs off exponentially; the waits must span the 60-second window.
+ assert sum(call.args[0] for call in mock_sleep.call_args_list) > 60
+
+ def test_full_refresh_starts_at_the_configured_date(self) -> None:
+ today = datetime.now(UTC).date()
+ start = today - timedelta(days=1)
+ sent_bodies, _, _, _ = _drive(
+ "daily_campaign_report",
+ [_stats_page(["c1"]), _stats_page(["c1"])],
+ configured_start_date=start.isoformat(),
+ )
+
+ assert [body["start_date"] for body in sent_bodies] == [start.isoformat(), today.isoformat()]
+
+
+class TestMoEngageSourceCampaignReport:
+ def test_requests_the_trailing_window_and_pages_by_offset(self) -> None:
+ today = datetime.now(UTC).date()
+ responses = [
+ _stats_page([f"c{i}" for i in range(STATS_PAGE_SIZE)], current_page=1, total_pages=2),
+ _stats_page(["c10"], current_page=2, total_pages=2),
+ ]
+ sent_bodies, _, rows, manager = _drive("campaign_report", responses)
+
+ window_start = (today - timedelta(days=REPORT_WINDOW_DAYS - 1)).isoformat()
+ assert all(body["start_date"] == window_start for body in sent_bodies)
+ assert all(body["end_date"] == today.isoformat() for body in sent_bodies)
+ assert [body["offset"] for body in sent_bodies] == [0, STATS_PAGE_SIZE]
+ assert len(rows) == STATS_PAGE_SIZE + 1
+ assert rows[0]["start_date"] == window_start
+ assert rows[0]["end_date"] == today.isoformat()
+
+ # The window is anchored to today, so a checkpointed offset from a previous attempt would
+ # point into a different result set; this endpoint restarts instead of resuming.
+ manager.save_state.assert_not_called()
+
+
+class TestMoEngageSourceErrors:
+ def test_unknown_endpoint_raises(self) -> None:
+ with pytest.raises(ValueError, match="Unknown MoEngage endpoint"):
+ moengage_source(
+ data_center="01",
+ workspace_id="ws-1",
+ api_key="k",
+ endpoint="not_a_table",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ )
+
+ @pytest.mark.parametrize(
+ "error_message",
+ [
+ "401 Client Error: Unauthorized for url: https://api-01.moengage.com/v5/campaigns/search",
+ "403 Client Error: Forbidden for url: https://api-03.moengage.com/core-services/v1/campaign-stats",
+ ],
+ )
+ def test_auth_failures_match_a_non_retryable_pattern(self, error_message: str) -> None:
+ # A sync hitting revoked credentials must fail permanently with the curated message rather
+ # than retry forever.
+ assert error_message_matches(error_message, MoEngageSource().get_non_retryable_errors())
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status", "is_valid", "message_fragment"),
+ [
+ (200, True, None),
+ (401, False, "authentication failed"),
+ (403, False, "authentication failed"),
+ (500, False, "unexpected response"),
+ ],
+ )
+ def test_maps_probe_status_to_user_message(self, status: int, is_valid: bool, message_fragment: str | None) -> None:
+ with mock.patch(MOENGAGE_SESSION_PATCH) as MockSession:
+ MockSession.return_value.post.return_value = _response({}, status=status)
+ ok, message = validate_credentials("01", "ws-1", "key")
+
+ assert ok is is_valid
+ if message_fragment is None:
+ assert message is None
+ else:
+ assert message is not None and message_fragment in message.lower()
+
+ def test_connection_failure_reports_the_data_center(self) -> None:
+ with mock.patch(MOENGAGE_SESSION_PATCH) as MockSession:
+ MockSession.return_value.post.side_effect = ConnectionError("boom")
+ ok, message = validate_credentials("01", "ws-1", "key")
+
+ assert ok is False
+ assert message is not None and "data center" in message
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage_source.py
new file mode 100644
index 000000000000..32f8334231d3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage_source.py
@@ -0,0 +1,63 @@
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.moengage import (
+ MoEngageSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.source import MoEngageSource
+
+_VALIDATE = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.moengage.source.validate_moengage_credentials"
+)
+
+
+def _config(data_center: str = "01", start_date: str | None = None) -> MoEngageSourceConfig:
+ # data_center is typed as a Literal of the known data centers; the invalid-value tests
+ # deliberately construct configs outside it, the way a crafted PATCH payload could.
+ return MoEngageSourceConfig(
+ data_center=cast(Any, data_center), workspace_id="ws-1", api_key="key", start_date=start_date
+ )
+
+
+class TestMoEngageValidateCredentials:
+ @pytest.mark.parametrize("data_center", ["01.evil.com", "evil.com/", "07", ""])
+ def test_rejects_unknown_data_center_without_calling_the_api(self, data_center: str) -> None:
+ # The data center is interpolated into the API hostname, so a value outside the fixed set
+ # must be refused before any request carries the credential.
+ with mock.patch(_VALIDATE) as mock_validate:
+ is_valid, message = MoEngageSource().validate_credentials(_config(data_center=data_center), team_id=1)
+
+ assert is_valid is False
+ assert message is not None and "data center" in message
+ mock_validate.assert_not_called()
+
+ @pytest.mark.parametrize("start_date", ["last week", "01/05/2025", "2025-13-40"])
+ def test_rejects_malformed_start_date_without_calling_the_api(self, start_date: str) -> None:
+ # An unparseable start date would otherwise pass source creation and crash every daily
+ # report sync.
+ with mock.patch(_VALIDATE) as mock_validate:
+ is_valid, message = MoEngageSource().validate_credentials(_config(start_date=start_date), team_id=1)
+
+ assert is_valid is False
+ assert message is not None and "YYYY-MM-DD" in message
+ mock_validate.assert_not_called()
+
+ def test_rejects_a_start_date_past_the_backfill_cap_without_calling_the_api(self) -> None:
+ # A start date far enough in the past (e.g. 0001-01-01) would otherwise fan out one
+ # request set per day for hundreds of thousands of days.
+ with mock.patch(_VALIDATE) as mock_validate:
+ is_valid, message = MoEngageSource().validate_credentials(_config(start_date="0001-01-01"), team_id=1)
+
+ assert is_valid is False
+ assert message is not None and "years ago" in message
+ mock_validate.assert_not_called()
+
+ @pytest.mark.parametrize("start_date", [None, "", "2025-01-01"])
+ def test_valid_config_reaches_the_credential_probe(self, start_date: str | None) -> None:
+ with mock.patch(_VALIDATE, return_value=(True, None)) as mock_validate:
+ is_valid, message = MoEngageSource().validate_credentials(_config(start_date=start_date), team_id=1)
+
+ assert (is_valid, message) == (True, None)
+ mock_validate.assert_called_once_with("01", "ws-1", "key")