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.

7.3 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.mailchimp._config import MailchimpSourceConfig
from products.warehouse_sources.sources.mailchimp.mailchimp import (
    EVENT_TABLE_APPEND_ERROR,
    MailchimpResumeConfig,
    mailchimp_source,
    validate_credentials as validate_mailchimp_credentials,
)
from products.warehouse_sources.sources.mailchimp.settings import ENDPOINTS, EVENT_ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    build_endpoint_schemas,
    detect,
)


@SourceRegistry.register
class MailchimpSource(ResumableSource[MailchimpSourceConfig, MailchimpResumeConfig]):
    codebase_detection = detect(
        env=("^MAILCHIMP_", "^MANDRILL_APIKEY$", "^MCAPI_TOKEN$"),
        script_hosts=("chimpstatic.com", "downloads.mailchimp.com", "list-manage.com"),
        npm=(
            "@mailchimp/mailchimp_marketing",
            "@mailchimp/mailchimp_transactional",
            "mandrill-api",
            "mailchimp-api-v3",
        ),
        pypi=("mailchimp-marketing", "mailchimp3", "mailchimp-transactional", "mandrill", "mailchimp"),
        cargo=("mailchimp_marketing",),
        cocoapods=("MailchimpSDK", "ChimpKit"),
        composer=(
            "mailchimp/marketing",
            "drewm/mailchimp-api",
            "mailchimp/marketing-sdk",
            "mailchimp/transactional",
            "mailchimp/mailchimp",
            "mandrill/mandrill",
            "mailchimp/mc-magento2",
        ),
        go=("github.com/mailchimp/mailchimp-marketing-go-sdk",),
        maven=("com.mailchimp:mailchimp-marketing", "com.github.mailchimp:Mailchimp-SDK-Android"),
        rubygems=(
            "MailchimpMarketing",
            "gibbon",
            "mailchimp-marketing",
            "MailchimpTransactional",
            "mailchimp-api",
            "mandrill-api",
            "mailchimp",
        ),
        swiftpm=("github.com/mailchimp/mailchimp-marketing-swift-sdk", "github.com/mailchimp/mailchimp-sdk-ios"),
    )

    supported_versions = ("3.0",)
    default_version = "3.0"
    api_docs_url = "https://mailchimp.com/developer/marketing/api/"

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

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

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

You can create an API key in your [Mailchimp account settings](https://us1.admin.mailchimp.com/account/api/).

The API key format is: `key-dc` (e.g., `abc123def456-us6`), where `dc` is the data center for your account.
""",
            iconPath="/static/services/mailchimp.png",
            docsUrl="https://posthog.com/docs/cdp/sources/mailchimp",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="abc123def456-us6",
                        secret=True,
                    ),
                ],
            ),
        )

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

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error": "Invalid Mailchimp API key. Please check your API key and try again.",
            "403 Client Error": "Access forbidden. Your API key may lack required permissions.",
            "Invalid Mailchimp API key format": "Invalid API key format. Expected format: key-dc (e.g., abc123-us6)",
            EVENT_TABLE_APPEND_ERROR: (
                "Append only replication isn't supported on this table. Switch it to incremental or full table "
                "replication in its sync settings, then re-enable the sync."
            ),
        }

    def get_retryable_errors(self) -> set[str]:
        # `_mailchimp_session`'s `DEFAULT_RETRY` already retries 429/5xx responses in-process
        # (Retry-After-aware backoff) before `raise_for_status()` can raise here. A response that
        # still exhausts that budget is a transient Mailchimp/edge blip, not a bug — Temporal's
        # activity retry recovers once it clears, so keep it out of error tracking as noise.
        # `requests.Response.raise_for_status` derives these prefixes from the status code alone,
        # not the vendor's reason text, so they're stable to match on.
        # A read timeout or dropped connection retries the same way, exhausting urllib3's adapter
        # retries before `_get_with_retry`'s tenacity layer ever sees it. The data-center subdomain
        # varies per account, so match urllib3's stable wrapper text instead of a fixed host.
        return {"429 Client Error", "Server Error", "Max retries exceeded with url:"}

    def get_schemas(
        self,
        config: MailchimpSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=EVENT_ENDPOINTS)

    def validate_credentials(
        self,
        config: MailchimpSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_mailchimp_credentials(config.api_key)

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

    def source_for_pipeline(
        self,
        config: MailchimpSourceConfig,
        resumable_source_manager: ResumableSourceManager[MailchimpResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return mailchimp_source(
            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,
            incremental_field=inputs.incremental_field,
            sync_type=inputs.sync_type,
        )