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.

6.7 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.partnerize._config import PartnerizeSourceConfig
from products.warehouse_sources.sources.partnerize.partnerize import (
    PartnerizeResumeConfig,
    partnerize_source,
    validate_credentials,
)
from products.warehouse_sources.sources.partnerize.settings import ENDPOINTS, INCREMENTAL_FIELDS, PARTNERIZE_ENDPOINTS
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 PartnerizeSource(ResumableSource[PartnerizeSourceConfig, PartnerizeResumeConfig]):
    codebase_detection = detect(env=("^PARTNERIZE_",))

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    api_docs_url = "https://api-docs.partnerize.com/partner/"

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.PARTNERIZE,
            category=DataWarehouseSourceCategory.ADVERTISING,
            label="Partnerize",
            releaseStatus=ReleaseStatus.GA,
            keywords=["affiliate", "performance horizon", "ascend"],
            caption="""Enter your Partnerize API credentials to pull your partnership and affiliate marketing data into the PostHog Data warehouse.

You can find your **user application key** and **user API key** under **Account settings** in the [Partnerize platform](https://console.partnerize.com). The publisher ID identifies the partner account whose campaigns, conversions, and clicks are synced.
""",
            iconPath="/static/services/partnerize.png",
            docsUrl="https://posthog.com/docs/cdp/sources/partnerize",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="application_key",
                        label="User application key",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="",
                        # Half of the Basic auth credential pair — mark secret so it is stripped
                        # from source-configuration API responses like the user API key.
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="user_api_key",
                        label="User API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="publisher_id",
                        label="Publisher ID",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="",
                        secret=False,
                    ),
                ],
            ),
        )

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

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized for url: https://api.partnerize.com": "Your Partnerize API credentials are invalid or have been revoked. Check your user application key and user API key under Account settings, then reconnect.",
            "403 Client Error: Forbidden for url: https://api.partnerize.com": "Your Partnerize credentials do not have access to this data. Check the account's permissions and the configured publisher ID, then reconnect.",
            # Partnerize returns 404 for entities that don't exist, e.g. a publisher ID that was
            # removed or mistyped — retrying can't fix that.
            "404 Client Error: Not Found for url: https://api.partnerize.com": "Partnerize could not find the configured publisher. Check the publisher ID, then reconnect.",
        }

    def get_schemas(
        self,
        config: PartnerizeSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # The conversions, conversion items, and clicks reports accept a server-side
        # start_date/end_date window, so they sync incrementally; every other endpoint exposes no
        # timestamp filter and is full refresh only.
        return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)

    def validate_credentials(
        self,
        config: PartnerizeSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        # A single probe of the configured partner account validates the key pair and the
        # publisher ID for every endpoint at once.
        return validate_credentials(config.application_key, config.user_api_key, config.publisher_id)

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

    def source_for_pipeline(
        self,
        config: PartnerizeSourceConfig,
        resumable_source_manager: ResumableSourceManager[PartnerizeResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        if inputs.schema_name not in PARTNERIZE_ENDPOINTS:
            raise ValueError(f"Unknown Partnerize schema '{inputs.schema_name}'")

        return partnerize_source(
            application_key=config.application_key,
            user_api_key=config.user_api_key,
            publisher_id=config.publisher_id,
            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,
        )