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.

12.2 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.moengage._config import MoEngageSourceConfig
from products.warehouse_sources.sources.moengage.moengage import (
    FLOWS_UNSUPPORTED_DATA_CENTER_ERROR,
    MoEngageResumeConfig,
    moengage_source,
    parse_iso_date,
    start_date_error,
    validate_credentials as validate_moengage_credentials,
)
from products.warehouse_sources.sources.moengage.settings import (
    FLOWS_UNSUPPORTED_DATA_CENTERS,
    INCREMENTAL_FIELDS,
    MOENGAGE_DATA_CENTERS,
    MOENGAGE_ENDPOINTS,
)
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceFieldSelectConfig,
    SourceFieldSelectConfigOption,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    detect,
)

_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(ResumableSource[MoEngageSourceConfig, MoEngageResumeConfig]):
    codebase_detection = detect(
        env=("^(MO_ENGAGE|MOENGAGE)_",),
        script_hosts=("cdn.moengage.com",),
        npm=("@moengage/web-sdk", "react-native-moengage"),
        cocoapods=(
            "MoEngage-iOS-SDK",
            "MoEngageSDK",
            "MoEngage-iOS-SDK-Beta",
            "MoEngageAnalytics",
            "MoEngageCampaignsCore",
            "MoEngageCards",
            "MoEngageCore",
            "MoEngageExtensionsIntegration",
            "MoEngageGeofence",
            "MoEngageInApp",
            "MoEngageInApps",
            "MoEngageInbox",
            "MoEngageKMMConditionEvaluator",
            "MoEngageLiveActivity",
            "MoEngageMessaging",
            "MoEngageObjCUtils",
            "MoEngagePersonalization",
            "MoEngagePluginBase",
            "MoEngagePluginBase-Beta",
            "MoEngagePluginCards",
            "MoEngagePluginGeofence",
            "MoEngagePluginInbox",
            "MoEngagePluginPersonalize",
            "MoEngageRealTimeTrigger",
            "MoEngageRecommendations",
            "MoEngageRichNotification",
            "MoEngageRichNotification-Beta",
            "MoEngageSecurity",
            "MoEngageSegmentPluginBase",
            "MoEngageTelemetry",
            "MoEngageTriggerEvaluator",
            "Segment-MoEngage",
            "mParticle-MoEngage",
        ),
        maven=(
            "com.moengage:moe-android-sdk",
            "com.moengage:moengage-integration",
            "com.moengage:moengage-segment-integration",
            "com.moengage:moengage-segment-kotlin-destination",
            "com.moengage:mparticle-android-integration-moengage",
        ),
        pub=("moengage_flutter",),
        swiftpm=(
            "github.com/moengage/apple-sdk",
            "github.com/moengage/moengage-ios-cards",
            "github.com/moengage/moengage-ios-geofence",
            "github.com/moengage/moengage-ios-inapps",
            "github.com/moengage/moengage-ios-inbox",
            "github.com/moengage/moengage-ios-realtimetrigger",
            "github.com/moengage/moengage-ios-richnotification",
            "github.com/moengage/moengage-ios-sdk",
            "github.com/moengage/moengage-segment-ios",
            "github.com/moengage/moengage-segment-swift",
            "github.com/moengage/mparticle-apple-integration-moengage",
        ),
    )

    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, "
            "and that the key has access to Segmentation APIs if you sync segments. Then reconnect the source."
        )
        return {
            "401 Client Error: Unauthorized for url": message,
            "403 Client Error: Forbidden for url": message,
            FLOWS_UNSUPPORTED_DATA_CENTER_ERROR: FLOWS_UNSUPPORTED_DATA_CENTER_ERROR,
        }

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.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 not (endpoint_config.name == "flows" and config.data_center in FLOWS_UNSUPPORTED_DATA_CENTERS)
        ]
        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,
            project_code=config.project_code,
            flow_teams=config.flow_teams,
        )

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.MOENGAGE,
            category=DataWarehouseSourceCategory.MARKETING___EMAIL,
            label="MoEngage",
            releaseStatus=ReleaseStatus.BETA,
            caption="""Sync your MoEngage campaigns, flows, segments, subscription categories, and campaign 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). To sync the `segments` table, give the key access to **Segmentation APIs** too.

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],
                [
                    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",
                        sync_setting=True,
                        label="Daily report start date (optional)",
                        type=SourceFieldInputConfigType.TEXT,
                        required=False,
                        placeholder="2025-01-01",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="project_code",
                        label="Project ID (optional)",
                        type=SourceFieldInputConfigType.TEXT,
                        required=False,
                        placeholder="",
                        secret=False,
                        caption="Required for the `subscription_categories` table if your workspace uses Portfolio. Find it under **Settings** > **Account** > **Portfolio**.",
                    ),
                    SourceFieldInputConfig(
                        name="flow_teams",
                        sync_setting=True,
                        label="Flow team names (optional)",
                        type=SourceFieldInputConfigType.TEXT,
                        required=False,
                        placeholder="Marketing, Growth",
                        secret=False,
                        caption="Required for the `flows` table if your workspace has teams turned on for Flows. Enter team names separated by commas. Leave it empty otherwise.",
                    ),
                ],
            ),
        )