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.

9.2 KB
Raw Blame
from typing import TYPE_CHECKING, Optional, cast

from products.warehouse_sources.sources.mailjet import mailjet as api_client
from products.warehouse_sources.sources.mailjet._config import MailjetSourceConfig
from products.warehouse_sources.sources.mailjet.mailjet import (
    MailjetResumeConfig,
    mailjet_source,
    validate_credentials as validate_mailjet_credentials,
)
from products.warehouse_sources.sources.mailjet.settings import (
    ENDPOINTS,
    INCREMENTAL_FIELDS,
    MAILJET_WEBHOOK_EVENTS,
    SCHEMA_TO_WEBHOOK_RESOURCE,
    WEBHOOK_SCHEMA_NAMES,
)
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    ExternalWebhookInfo,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    WebhookCreationResult,
    WebhookDeletionResult,
    WebhookSource,
    WebhookSourceManager,
    WebhookSyncResult,
    build_endpoint_schemas,
    detect,
)

if TYPE_CHECKING:
    from products.warehouse_sources.sources.sdk import HogFunctionTemplateDC


@SourceRegistry.register
class MailJetSource(
    ResumableSource[MailjetSourceConfig, MailjetResumeConfig],
    WebhookSource[MailjetSourceConfig],
):
    # Mailjet's documented env convention is MJ_APIKEY_PUBLIC / *_PRIVATE.
    codebase_detection = detect(
        env=("^MAILJET_", "^MJ_APIKEY_", "^MJ_API_TOKEN$"),
        npm=("node-mailjet",),
        pypi=("mailjet-rest",),
        composer=(
            "mailjet/mailjet-apiv3-php",
            "mailjet/laravel-mailjet",
            "mailjet/mailjet-apiv3-php-simple",
            "mailjet/mailjet-bundle",
            "mailjet/mailjet-magento2",
            "mailjet/mailjet-swiftmailer",
        ),
        go=("github.com/mailjet/mailjet-apiv3-go",),
        maven=("com.mailjet:mailjet-client",),
        rubygems=("mailjet",),
    )

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs

    supported_versions = ("v3",)
    default_version = "v3"
    api_docs_url = "https://dev.mailjet.com/"

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.MAILJET

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.MAILJET,
            category=DataWarehouseSourceCategory.MARKETING___EMAIL,
            label="Mailjet",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Mailjet API key and secret key to pull your Mailjet data into the PostHog Data warehouse.

You can find your API key and secret key in your [Mailjet API key management page](https://app.mailjet.com/account/apikeys).
""",
            iconPath="/static/services/mailjet.png",
            docsUrl="https://posthog.com/docs/cdp/sources/mailjet",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="Mailjet API key",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="secret_key",
                        label="Secret key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="Mailjet secret key",
                        secret=True,
                    ),
                ],
            ),
            webhookSetupCaption=(
                "PostHog registers one Mailjet event callback URL per event type using the API key above, "
                "covering sent, open, click, bounce, blocked, spam and unsub.\n\n"
                "Mailjet does not sign its deliveries, so PostHog embeds generated basic-auth credentials in "
                "the callback URL it registers. Mailjet sends those back as an Authorization header on every "
                "delivery, and PostHog rejects anything that doesn't match.\n\n"
                "The sent event fires once for every message you send, so this table can grow quickly on high "
                "volume accounts."
            ),
        )

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.mailjet.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: MailjetSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # List resources have no reliable server-side time filter (full refresh only).
        # The statistics endpoints support Mailjet's FromTS window, so they sync incrementally
        # (they're exactly the endpoints carrying incremental fields). Within-sync resumption is
        # handled by ResumableSource for all endpoints.
        schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, supports_webhooks=WEBHOOK_SCHEMA_NAMES)
        for schema in schemas:
            # `messageevent` has no list endpoint behind it, so the UI must offer webhook sync only.
            schema.webhook_only = schema.name in WEBHOOK_SCHEMA_NAMES
        return schemas

    def validate_credentials(
        self,
        config: MailjetSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        if validate_mailjet_credentials(config.api_key, config.secret_key):
            return True, None

        return False, "Invalid Mailjet API key or secret key"

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized for url: https://api.mailjet.com": (
                "Your Mailjet API key or secret key is invalid. Please check your credentials in the Mailjet "
                "API key management page and reconnect."
            ),
        }

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MailjetResumeConfig]:
        return ResumableSourceManager[MailjetResumeConfig](inputs, MailjetResumeConfig)

    def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
        return WebhookSourceManager(inputs, inputs.logger)

    @property
    def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
        from products.warehouse_sources.sources.mailjet.webhook_template import template  # noqa: PLC0415

        return template

    @property
    def webhook_resource_map(self) -> dict[str, str]:
        return SCHEMA_TO_WEBHOOK_RESOURCE

    def get_desired_webhook_events(
        self, config: MailjetSourceConfig, eligible_schema_names: list[str]
    ) -> list[str] | None:
        if not any(name in WEBHOOK_SCHEMA_NAMES for name in eligible_schema_names):
            return []
        return list(MAILJET_WEBHOOK_EVENTS)

    def create_webhook(
        self, config: MailjetSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
    ) -> WebhookCreationResult:
        return api_client.create_webhook(config.api_key, config.secret_key, webhook_url)

    def sync_webhook_events(
        self,
        config: MailjetSourceConfig,
        webhook_url: str,
        team_id: int,
        eligible_schema_names: list[str],
        api_version: str | None = None,
    ) -> WebhookSyncResult:
        desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []
        return api_client.sync_webhook_events(config.api_key, config.secret_key, webhook_url, desired_events)

    def get_external_webhook_info(
        self, config: MailjetSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
    ) -> ExternalWebhookInfo | None:
        return api_client.get_external_webhook_info(config.api_key, config.secret_key, webhook_url)

    def delete_webhook(
        self, config: MailjetSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
    ) -> WebhookDeletionResult:
        return api_client.delete_webhook(config.api_key, config.secret_key, webhook_url)

    def source_for_pipeline(
        self,
        config: MailjetSourceConfig,
        resumable_source_manager: ResumableSourceManager[MailjetResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return mailjet_source(
            api_key=config.api_key,
            secret_key=config.secret_key,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            resumable_source_manager=resumable_source_manager,
            webhook_source_manager=self.get_webhook_source_manager(inputs),
            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,
        )