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 partnerize import source (#69388)

Tom Owers5c4227dd5f9c
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 f01d1ce443f8..5194eb5ee0a8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -263,6 +263,7 @@ the row lists both.
| pagerduty | HTTP | requests | ✅ |
| pandadoc | HTTP | requests | ✅ |
| papersign | HTTP | requests | ✅ |
+| partnerize | HTTP | requests | ✅ |
| partnerstack | HTTP | requests | ✅ |
| paystack | HTTP | requests + `rest_source.RESTClient` | ✅ |
| pendo | HTTP | requests | ✅ |
@@ -618,7 +619,6 @@ doesn't conflict with concurrent PRs.
- pagerduty
- paperform
- pardot
-- partnerize
- payfit
- paylocity
- paypal
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 8a211127881c..9fa38e4f0ba2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2512,7 +2512,9 @@ class PartnerStackSourceConfig(config.Config):
@config.config
class PartnerizeSourceConfig(config.Config):
- pass
+ application_key: str
+ user_api_key: str
+ publisher_id: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/canonical_descriptions.py
new file mode 100644
index 000000000000..54c33ea578ce
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/canonical_descriptions.py
@@ -0,0 +1,146 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "campaigns": {
+ "description": "Campaigns the partner is approved to promote, with tracking, commission, and invoicing settings.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20Campaigns",
+ "columns": {
+ "campaign_id": "Unique identifier for the campaign.",
+ "advertiser_id": "Identifier of the brand (advertiser) that owns the campaign.",
+ "title": "Display title of the campaign.",
+ "status": "Status of the campaign (a = active).",
+ "publisher_status": "The partner's participation status on the campaign (a = approved, p = pending, r = rejected).",
+ "conversion_type": "Type of conversion the campaign tracks (e.g. sale, lead).",
+ "default_currency": "Default currency for the campaign's commissions.",
+ "default_commission_rate": "Default commission rate applied to conversions.",
+ "cookie_period": "Cookie lifetime for attribution, in days.",
+ "destination_url": "Default landing page URL for the campaign.",
+ "tracking_method": "How conversions are tracked (e.g. s2s for server-to-server).",
+ "reporting_timezone": "Timezone the campaign reports in.",
+ "vertical_name": "Industry vertical the campaign belongs to.",
+ },
+ },
+ "conversions": {
+ "description": "Conversions (sales, leads) attributed to the partner, with commission values, statuses, per-item breakdowns, and the originating click.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/partner-conversions",
+ "columns": {
+ "conversion_id": "Unique identifier for the conversion.",
+ "campaign_id": "Identifier of the campaign the conversion belongs to.",
+ "publisher_id": "Identifier of the partner credited with the conversion.",
+ "conversion_time": "Datetime the conversion occurred.",
+ "last_modified": "Datetime the conversion was last updated (e.g. a status change).",
+ "currency": "Currency of the conversion value.",
+ "conversion_value": "Total value of the conversion, with commission and status breakdowns.",
+ "conversion_items": "Per-item breakdown of the conversion, including SKU, value, commission, and item status.",
+ "conversion_reference": "The brand's reference for the conversion (e.g. order ID).",
+ "publisher_reference": "The partner's own reference attached to the originating click.",
+ "advertiser_reference": "Reference the brand attached to the conversion.",
+ "customer_reference": "The brand's reference for the customer.",
+ "customer_type": "Whether the customer was new or existing.",
+ "click": "The originating click, including its set time and click reference.",
+ "country": "ISO country code where the conversion happened.",
+ "conversion_type": "Type of conversion (maps to the conversion_types reference table).",
+ "ref_device_id": "Device the conversion happened on (maps to the devices reference table).",
+ "ref_traffic_source_id": "Traffic source of the conversion (maps to the traffic_sources reference table).",
+ "ref_partnership_model_id": "Partnership model of the conversion (maps to the partnership_models reference table).",
+ "ref_conversion_metric_id": "Conversion metric (maps to the conversion_metrics reference table).",
+ "ref_user_context_id": "User context of the conversion (maps to the user_contexts reference table).",
+ "campaign_title": "Display title of the campaign at report time.",
+ "publisher_name": "Display name of the partner at report time.",
+ "referer_ip": "IP address the conversion request came from.",
+ "source_referer": "Referring URL for the conversion.",
+ },
+ },
+ "clicks": {
+ "description": "Clicks recorded on the partner's tracking links, with device, traffic source, and referer detail.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/partner-clicks",
+ "columns": {
+ "clickref": "Partnerize's reference for the click; conversions link back to it.",
+ "campaign_id": "Identifier of the campaign the click belongs to.",
+ "publisher_id": "Identifier of the partner whose link was clicked.",
+ "set_time": "Datetime the click was first recorded.",
+ "set_ip": "IP address the click came from.",
+ "last_used": "When the click was last used for attribution.",
+ "last_ip": "IP address of the most recent use of the click.",
+ "type": "Type of click (e.g. standard).",
+ "status": "Processing status of the click.",
+ "publisher_reference": "The partner's own reference attached to the click.",
+ "referer": "Referring URL for the click.",
+ "creative_id": "Identifier of the creative the click came from, if any.",
+ "ref_device_id": "Device the click happened on (maps to the devices reference table).",
+ "ref_traffic_source_id": "Traffic source of the click (maps to the traffic_sources reference table).",
+ "ref_partnership_model_id": "Partnership model of the click (maps to the partnership_models reference table).",
+ "ref_user_context_id": "User context of the click (maps to the user_contexts reference table).",
+ },
+ },
+ "countries": {
+ "description": "Reference list of countries with ISO codes, currency, and geographic metadata.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20all%20Countries",
+ "columns": {
+ "ref_country_id": "Unique identifier for the country.",
+ "iso": "Two-letter ISO 3166-1 country code.",
+ "iso3": "Three-letter ISO 3166-1 country code.",
+ "printable_name": "Human-readable country name.",
+ "currency_iso": "ISO code of the country's currency.",
+ "continent_name": "Name of the country's continent.",
+ },
+ },
+ "currencies": {
+ "description": "Reference list of currencies supported by Partnerize.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20all%20Currencies",
+ "columns": {
+ "currency_id": "Unique identifier for the currency (its ISO code).",
+ },
+ },
+ "devices": {
+ "description": "Reference list of device types clicks and conversions are attributed to.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20all%20Devices",
+ "columns": {
+ "ref_device_id": "Unique identifier for the device type.",
+ },
+ },
+ "timezones": {
+ "description": "Reference list of timezones available for campaign reporting.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20all%20Timezones",
+ "columns": {
+ "ref_timezone_id": "Unique identifier for the timezone.",
+ },
+ },
+ "traffic_sources": {
+ "description": "Reference list of traffic sources clicks and conversions are attributed to.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20Traffic%20Sources",
+ "columns": {
+ "ref_traffic_source_id": "Unique identifier for the traffic source.",
+ },
+ },
+ "user_contexts": {
+ "description": "Reference list of user contexts (environments such as web or in-app) for attribution.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20all%20User%20Contexts",
+ "columns": {
+ "ref_user_context_id": "Unique identifier for the user context.",
+ },
+ },
+ "conversion_types": {
+ "description": "Reference list of conversion types (e.g. sale, lead) used by campaigns.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20Conversion%20Type",
+ "columns": {
+ "conversion_type_id": "Unique identifier for the conversion type.",
+ },
+ },
+ "conversion_metrics": {
+ "description": "Reference list of conversion metrics used to classify conversions.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20Conversion%20Metrics",
+ "columns": {
+ "ref_conversion_metric_id": "Unique identifier for the conversion metric.",
+ },
+ },
+ "partnership_models": {
+ "description": "Reference list of partnership models (e.g. affiliate, influencer) for attribution.",
+ "docs_url": "https://api-docs.partnerize.com/partner/#operation/List%20Partnership%20Models",
+ "columns": {
+ "ref_partnership_model_id": "Unique identifier for the partnership model.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/partnerize.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/partnerize.py
new file mode 100644
index 000000000000..d45145eecac8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/partnerize.py
@@ -0,0 +1,307 @@
+import base64
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import requests
+from dateutil import parser as dateutil_parser
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.settings import (
+ PARTNERIZE_ENDPOINTS,
+ PartnerizeEndpointConfig,
+)
+
+PARTNERIZE_BASE_URL = "https://api.partnerize.com"
+# The report endpoints page at a fixed server-side size of 300 rows (echoed in the response's
+# `limit` field) with no documented way to override it; we read the echoed value defensively.
+REPORT_PAGE_LIMIT = 300
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+# start_date is a required parameter on the report endpoints, so full-refresh syncs use a fixed
+# floor that predates the platform (Performance Horizon, now Partnerize, launched in 2010).
+DEFAULT_START_DATE = "2010-01-01T00:00:00Z"
+
+
+class PartnerizeRetryableError(Exception):
+ pass
+
+
+class PartnerizeResumeConfig:
+ # Report endpoints resume from the row offset within the current date window; the window
+ # itself is recomputed deterministically from the job's incremental inputs.
+ offset: int | None = None
+ # List endpoints resume from the hypermedia next-page URL.
+ next_url: str | None = None
+
+
+def _headers(application_key: str, user_api_key: str) -> dict[str, str]:
+ # Partnerize uses HTTP Basic auth with the user application key as the username and the user
+ # API key as the password.
+ token = base64.b64encode(f"{application_key}:{user_api_key}".encode("ascii")).decode("ascii")
+ return {"Authorization": f"Basic {token}", "Accept": "application/json"}
+
+
+def _format_start_date(value: Any) -> str:
+ """Coerce an incremental watermark to the ISO-8601 format the report endpoints document."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return f"{value.isoformat()}T00:00:00Z"
+ if isinstance(value, str) and value:
+ # Watermarks read back from the warehouse arrive as "YYYY-MM-DD HH:MM:SS" strings.
+ try:
+ return _format_start_date(dateutil_parser.parse(value))
+ except (ValueError, OverflowError):
+ return DEFAULT_START_DATE
+ return DEFAULT_START_DATE
+
+
+@retry(
+ retry=retry_if_exception_type((PartnerizeRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _get_json(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any] | None,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Partnerize rate-limits with 429s and publishes no numeric limit or reset header, so
+ # exponential backoff is the only strategy available.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PartnerizeRetryableError(f"Partnerize API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Partnerize API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, dict):
+ raise PartnerizeRetryableError(f"Partnerize returned an unexpected payload for {url}: {type(data).__name__}")
+
+ return data
+
+
+def _unwrap_rows(data: dict[str, Any], config: PartnerizeEndpointConfig) -> list[dict[str, Any]]:
+ """Extract the row list and strip Partnerize's single-key item wrapper (e.g. {"campaign": {...}})."""
+ items = data.get(config.data_key)
+ if not isinstance(items, list):
+ raise PartnerizeRetryableError(
+ f"Partnerize returned an unexpected '{config.data_key}' field: {type(items).__name__}"
+ )
+
+ rows: list[dict[str, Any]] = []
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ inner = item.get(config.item_key) if config.item_key else None
+ rows.append(inner if isinstance(inner, dict) else item)
+ return rows
+
+
+def _endpoint_url(config: PartnerizeEndpointConfig, publisher_id: str) -> str:
+ return f"{PARTNERIZE_BASE_URL}{config.path.format(publisher_id=publisher_id)}"
+
+
+def _get_report_rows(
+ session: requests.Session,
+ config: PartnerizeEndpointConfig,
+ publisher_id: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PartnerizeResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ params: dict[str, Any] = {}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ params["start_date"] = _format_start_date(db_incremental_field_last_value)
+ # Rows at exactly the boundary timestamp are re-fetched; merge dedupes them on the
+ # primary key.
+ if incremental_field is not None:
+ params.update(config.incremental_field_params.get(incremental_field, {}))
+ else:
+ params["start_date"] = DEFAULT_START_DATE
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if (resume and resume.offset is not None) else 0
+ if offset:
+ logger.debug(f"Partnerize: resuming {config.name} from offset {offset}")
+
+ url = _endpoint_url(config, publisher_id)
+
+ while True:
+ data = _get_json(session, url, {**params, "offset": offset}, logger)
+ rows = _unwrap_rows(data, config)
+ if rows:
+ yield rows
+
+ page_limit = data.get("limit")
+ if not isinstance(page_limit, int) or page_limit <= 0:
+ page_limit = REPORT_PAGE_LIMIT
+
+ # A short (or empty) page marks the end of the window.
+ if len(rows) < page_limit:
+ break
+
+ offset += len(rows)
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(PartnerizeResumeConfig(offset=offset))
+
+
+def _get_list_rows(
+ session: requests.Session,
+ config: PartnerizeEndpointConfig,
+ publisher_id: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PartnerizeResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume and resume.next_url:
+ url = resume.next_url
+ logger.debug(f"Partnerize: resuming {config.name} from {url}")
+ else:
+ url = _endpoint_url(config, publisher_id)
+
+ while True:
+ data = _get_json(session, url, None, logger)
+ rows = _unwrap_rows(data, config)
+ if rows:
+ yield rows
+
+ next_page = ((data.get("hypermedia") or {}).get("pagination") or {}).get("next_page")
+ # A missing next_page marks the end of the list. An empty page also terminates
+ # defensively so a lingering cursor can never produce an infinite loop.
+ if not isinstance(next_page, str) or not next_page or not rows:
+ break
+
+ # The session carries the Partnerize Basic auth header, so only follow the cursor when it
+ # stays on Partnerize: a relative path, or an absolute URL under the API host. Anything
+ # else (an attacker-tampered response pointing at an internal host) terminates the list.
+ if next_page.startswith("/"):
+ url = f"{PARTNERIZE_BASE_URL}{next_page}"
+ elif next_page.startswith(f"{PARTNERIZE_BASE_URL}/"):
+ url = next_page
+ else:
+ break
+ resumable_source_manager.save_state(PartnerizeResumeConfig(next_url=url))
+
+
+def get_rows(
+ application_key: str,
+ user_api_key: str,
+ publisher_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PartnerizeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = PARTNERIZE_ENDPOINTS[endpoint]
+ session = make_tracked_session(
+ headers=_headers(application_key, user_api_key), redact_values=(application_key, user_api_key)
+ )
+
+ if config.kind == "report":
+ yield from _get_report_rows(
+ session,
+ config,
+ publisher_id,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ incremental_field,
+ )
+ else:
+ yield from _get_list_rows(session, config, publisher_id, logger, resumable_source_manager)
+
+
+def partnerize_source(
+ application_key: str,
+ user_api_key: str,
+ publisher_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PartnerizeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = PARTNERIZE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ application_key=application_key,
+ user_api_key=user_api_key,
+ publisher_id=publisher_id,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ # The report endpoints document no ordering guarantee and accept no sort parameter, so the
+ # incremental watermark only commits once a sync completes ("desc" semantics) instead of
+ # checkpointing after every batch, which would risk skipping rows on an interrupted sync.
+ sort_mode="desc" if config.kind == "report" else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def check_access(application_key: str, user_api_key: str, publisher_id: str) -> tuple[int, Optional[str]]:
+ """Probe the partner account to validate the credential pair and publisher ID in one call.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403``/``404`` auth or access
+ failure, ``0`` for a connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(
+ headers=_headers(application_key, user_api_key), redact_values=(application_key, user_api_key)
+ )
+ try:
+ response = session.get(
+ f"{PARTNERIZE_BASE_URL}/user/publisher/{publisher_id}",
+ timeout=15,
+ )
+ except Exception as e:
+ return 0, f"Could not connect to Partnerize: {e}"
+
+ if response.status_code in (401, 403, 404):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Partnerize returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(application_key: str, user_api_key: str, publisher_id: str) -> tuple[bool, str | None]:
+ status, message = check_access(application_key, user_api_key, publisher_id)
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Invalid Partnerize API credentials. Check your user application key and user API key."
+ if status in (403, 404):
+ return False, f"Your Partnerize credentials do not have access to publisher '{publisher_id}'."
+ return False, message or "Could not validate Partnerize credentials"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/settings.py
new file mode 100644
index 000000000000..148a99f5012d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/settings.py
@@ -0,0 +1,146 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class PartnerizeEndpointConfig:
+ name: str
+ # Path relative to the API base. `{publisher_id}` is substituted with the configured partner ID.
+ path: str
+ # Key the row list is nested under in the response body (e.g. {"conversions": [...]}).
+ data_key: str
+ # Partnerize wraps every list item in a single-key object (e.g. {"campaign": {...}},
+ # {"conversion_data": {...}}); this is that inner key. None when rows are flat.
+ item_key: Optional[str]
+ primary_keys: list[str]
+ # "report" endpoints take a required start_date/end_date window and paginate by offset;
+ # "list" endpoints return everything, following hypermedia.pagination.next_page when present.
+ kind: Literal["report", "list"] = "list"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style
+ # field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ # Extra query params keyed by the user's chosen incremental field. Partnerize's report
+ # endpoints filter on the conversion time by default; passing date_type=last_updated makes
+ # the start_date/end_date window apply to last_modified instead.
+ incremental_field_params: dict[str, dict[str, str]] = field(default_factory=dict)
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+# Partnerize Partner API endpoints (https://api-docs.partnerize.com/partner/). The conversions and
+# clicks reports accept a server-side start_date/end_date window, so they support incremental sync;
+# campaigns and the reference catalogs expose no timestamp filter and are full refresh only.
+PARTNERIZE_ENDPOINTS: dict[str, PartnerizeEndpointConfig] = {
+ "campaigns": PartnerizeEndpointConfig(
+ name="campaigns",
+ # `/a` restricts the list to campaigns the partner is approved on.
+ path="/user/publisher/{publisher_id}/campaign/a",
+ data_key="campaigns",
+ item_key="campaign",
+ primary_keys=["campaign_id"],
+ ),
+ "conversions": PartnerizeEndpointConfig(
+ name="conversions",
+ path="/reporting/report_publisher/publisher/{publisher_id}/conversion.json",
+ data_key="conversions",
+ item_key="conversion_data",
+ primary_keys=["conversion_id"],
+ kind="report",
+ partition_key="conversion_time",
+ incremental_fields=[_datetime_field("conversion_time"), _datetime_field("last_modified")],
+ # date_type=last_updated re-windows the report on last_modified, so status changes
+ # (pending -> approved/rejected) on old conversions are picked up.
+ incremental_field_params={"last_modified": {"date_type": "last_updated"}},
+ ),
+ "clicks": PartnerizeEndpointConfig(
+ name="clicks",
+ path="/reporting/report_publisher/publisher/{publisher_id}/click.json",
+ data_key="clicks",
+ item_key="click",
+ # clickref is Partnerize's click reference; the docs don't state global uniqueness, so the
+ # campaign is included to keep the key unique table-wide.
+ primary_keys=["campaign_id", "clickref"],
+ kind="report",
+ partition_key="set_time",
+ incremental_fields=[_datetime_field("set_time")],
+ ),
+ "countries": PartnerizeEndpointConfig(
+ name="countries",
+ path="/reference/country",
+ data_key="countries",
+ item_key="country",
+ primary_keys=["ref_country_id"],
+ ),
+ "currencies": PartnerizeEndpointConfig(
+ name="currencies",
+ path="/reference/currency",
+ data_key="currencies",
+ item_key="currency",
+ primary_keys=["currency_id"],
+ ),
+ "devices": PartnerizeEndpointConfig(
+ name="devices",
+ path="/reference/device",
+ data_key="devices",
+ item_key="device",
+ primary_keys=["ref_device_id"],
+ ),
+ "timezones": PartnerizeEndpointConfig(
+ name="timezones",
+ path="/reference/timezone",
+ data_key="timezones",
+ item_key="timezone",
+ primary_keys=["ref_timezone_id"],
+ ),
+ "traffic_sources": PartnerizeEndpointConfig(
+ name="traffic_sources",
+ path="/reference/traffic_source",
+ data_key="traffic_sources",
+ item_key="traffic_source",
+ primary_keys=["ref_traffic_source_id"],
+ ),
+ "user_contexts": PartnerizeEndpointConfig(
+ name="user_contexts",
+ path="/reference/user_context",
+ data_key="user_contexts",
+ item_key="user_context",
+ primary_keys=["ref_user_context_id"],
+ ),
+ "conversion_types": PartnerizeEndpointConfig(
+ name="conversion_types",
+ path="/reference/conversion_type",
+ data_key="conversion_types",
+ item_key="conversion_type",
+ primary_keys=["conversion_type_id"],
+ ),
+ "conversion_metrics": PartnerizeEndpointConfig(
+ name="conversion_metrics",
+ path="/reference/conversion_metric",
+ data_key="conversion_metrics",
+ item_key="conversion_metric",
+ primary_keys=["ref_conversion_metric_id"],
+ ),
+ "partnership_models": PartnerizeEndpointConfig(
+ name="partnership_models",
+ path="/reference/partnership_model",
+ data_key="partnership_models",
+ item_key="partnership_model",
+ primary_keys=["ref_partnership_model_id"],
+ ),
+}
+
+ENDPOINTS = tuple(PARTNERIZE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in PARTNERIZE_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/source.py
index 38f4dbd4f306..32fb804f5a42 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+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.generated_configs import PartnerizeSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.partnerize import (
+ PartnerizeResumeConfig,
+ partnerize_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PARTNERIZE_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PartnerizeSource(SimpleSource[PartnerizeSourceConfig]):
+class PartnerizeSource(ResumableSource[PartnerizeSourceConfig, PartnerizeResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PARTNERIZE
@@ -24,7 +48,118 @@ class PartnerizeSource(SimpleSource[PartnerizeSourceConfig]):
name=SchemaExternalDataSourceType.PARTNERIZE,
category=DataWarehouseSourceCategory.ADVERTISING,
label="Partnerize",
+ releaseStatus=ReleaseStatus.ALPHA,
+ 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",
- fields=cast(list[FieldType], []),
+ 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,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.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,
+ ) -> list[SourceSchema]:
+ # Conversions and clicks reports accept a server-side start_date/end_date window, so they
+ # sync incrementally; campaigns and the reference catalogs expose no timestamp filter and
+ # are full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint in INCREMENTAL_FIELDS,
+ supports_append=endpoint in INCREMENTAL_FIELDS,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ 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: PartnerizeSourceConfig, team_id: int, schema_name: Optional[str] = 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,
+ logger=inputs.logger,
+ 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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/tests/test_partnerize.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/tests/test_partnerize.py
new file mode 100644
index 000000000000..01b9c185de30
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/tests/test_partnerize.py
@@ -0,0 +1,372 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerize import partnerize
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.partnerize import (
+ DEFAULT_START_DATE,
+ PARTNERIZE_BASE_URL,
+ PartnerizeResumeConfig,
+ PartnerizeRetryableError,
+ _format_start_date,
+ _unwrap_rows,
+ check_access,
+ get_rows,
+ partnerize_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.settings import (
+ ENDPOINTS,
+ PARTNERIZE_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_get_json_unwrapped = partnerize._get_json.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: PartnerizeResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[PartnerizeResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> PartnerizeResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: PartnerizeResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestFormatStartDate:
+ @parameterized.expand(
+ [
+ ("aware_datetime", datetime(2020, 3, 8, 17, 18, 33, tzinfo=UTC), "2020-03-08T17:18:33Z"),
+ ("naive_datetime", datetime(2020, 3, 8, 17, 18, 33), "2020-03-08T17:18:33Z"),
+ ("date", date(2020, 3, 8), "2020-03-08T00:00:00Z"),
+ # Watermarks read back from the warehouse arrive as strings in Partnerize's own format.
+ ("api_format_string", "2020-03-08 17:18:33", "2020-03-08T17:18:33Z"),
+ ("iso_string", "2020-03-08T17:18:33+00:00", "2020-03-08T17:18:33Z"),
+ ("unparseable_string", "not a date at all 12345 67890", DEFAULT_START_DATE),
+ ("none", None, DEFAULT_START_DATE),
+ ]
+ )
+ def test_coerces_watermark_to_iso_z(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_start_date(value) == expected
+
+
+class TestUnwrapRows:
+ def test_strips_single_key_item_wrapper(self) -> None:
+ data = {"campaigns": [{"campaign": {"campaign_id": "10l176", "title": "Demo"}}]}
+ rows = _unwrap_rows(data, PARTNERIZE_ENDPOINTS["campaigns"])
+ assert rows == [{"campaign_id": "10l176", "title": "Demo"}]
+
+ def test_missing_wrapper_key_yields_item_as_is(self) -> None:
+ # Defensive: if the API returns flat rows, they pass through unmodified.
+ data = {"conversions": [{"conversion_id": "111111l314"}]}
+ rows = _unwrap_rows(data, PARTNERIZE_ENDPOINTS["conversions"])
+ assert rows == [{"conversion_id": "111111l314"}]
+
+ def test_missing_data_key_is_retryable(self) -> None:
+ with pytest.raises(PartnerizeRetryableError):
+ _unwrap_rows({"count": 0}, PARTNERIZE_ENDPOINTS["clicks"])
+
+
+class TestGetJson:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(PartnerizeRetryableError):
+ _get_json_unwrapped(session, "https://api.partnerize.com/reference/country", None, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _get_json_unwrapped(session, "https://api.partnerize.com/reference/country", None, MagicMock())
+
+ def test_non_dict_body_is_retryable(self) -> None:
+ session = self._session_returning(200, [{"id": 1}])
+ with pytest.raises(PartnerizeRetryableError):
+ _get_json_unwrapped(session, "https://api.partnerize.com/reference/country", None, MagicMock())
+
+
+def _collect_rows(
+ monkeypatch: Any,
+ manager: _FakeResumableManager,
+ responses: list[dict[str, Any]],
+ endpoint: str,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> tuple[list[dict], list[tuple[str, dict | None]]]:
+ """Run get_rows against queued fake responses, returning (rows, requests made)."""
+ calls: list[tuple[str, dict | None]] = []
+ queue = list(responses)
+
+ def fake_get_json(session: Any, url: str, params: dict | None, logger: Any) -> dict[str, Any]:
+ calls.append((url, params))
+ return queue.pop(0)
+
+ monkeypatch.setattr(partnerize, "_get_json", fake_get_json)
+ monkeypatch.setattr(partnerize, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ application_key="app-key",
+ user_api_key="api-key",
+ publisher_id="111111l92",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ):
+ rows.extend(batch)
+ return rows, calls
+
+
+def _conversion_page(ids: list[str], limit: int) -> dict[str, Any]:
+ return {
+ "conversions": [{"conversion_data": {"conversion_id": i}} for i in ids],
+ "limit": limit,
+ "count": len(ids),
+ }
+
+
+class TestReportRows:
+ def test_paginates_by_offset_and_saves_state_after_yield(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = [_conversion_page(["a", "b"], limit=2), _conversion_page(["c"], limit=2)]
+ rows, calls = _collect_rows(monkeypatch, manager, pages, "conversions")
+
+ assert [r["conversion_id"] for r in rows] == ["a", "b", "c"]
+ assert [params["offset"] for _, params in calls if params] == [0, 2]
+ # State is saved after the full first page is yielded, then the short page terminates.
+ assert [s.offset for s in manager.saved] == [2]
+
+ def test_short_first_page_stops_without_saving(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, calls = _collect_rows(monkeypatch, manager, [_conversion_page(["a"], limit=300)], "conversions")
+ assert len(rows) == 1
+ assert len(calls) == 1
+ assert manager.saved == []
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(PartnerizeResumeConfig(offset=600))
+ _, calls = _collect_rows(monkeypatch, manager, [_conversion_page([], limit=300)], "conversions")
+ assert calls[0][1] is not None and calls[0][1]["offset"] == 600
+
+ def test_full_refresh_uses_default_start_date(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ _, calls = _collect_rows(monkeypatch, manager, [_conversion_page([], limit=300)], "conversions")
+ assert calls[0][1] is not None and calls[0][1]["start_date"] == DEFAULT_START_DATE
+
+ def test_incremental_windows_from_watermark(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ _, calls = _collect_rows(
+ monkeypatch,
+ manager,
+ [_conversion_page([], limit=300)],
+ "conversions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-05-01 12:00:00",
+ incremental_field="conversion_time",
+ )
+ params = calls[0][1]
+ assert params is not None
+ assert params["start_date"] == "2024-05-01T12:00:00Z"
+ # The default window filters on the conversion time, no date_type override needed.
+ assert "date_type" not in params
+
+ def test_last_modified_cursor_sets_date_type(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ _, calls = _collect_rows(
+ monkeypatch,
+ manager,
+ [_conversion_page([], limit=300)],
+ "conversions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-05-01 12:00:00",
+ incremental_field="last_modified",
+ )
+ params = calls[0][1]
+ assert params is not None and params["date_type"] == "last_updated"
+
+ def test_report_url_contains_publisher_id(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ _, calls = _collect_rows(monkeypatch, manager, [_conversion_page([], limit=300)], "conversions")
+ assert calls[0][0] == f"{PARTNERIZE_BASE_URL}/reporting/report_publisher/publisher/111111l92/conversion.json"
+
+
+class TestListRows:
+ def test_follows_hypermedia_next_page_and_saves_state(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ next_url = f"{PARTNERIZE_BASE_URL}/reference/country?page=2"
+ pages: list[dict[str, Any]] = [
+ {
+ "countries": [{"country": {"ref_country_id": 1}}],
+ "hypermedia": {"pagination": {"next_page": next_url}},
+ },
+ {"countries": [{"country": {"ref_country_id": 2}}]},
+ ]
+ rows, calls = _collect_rows(monkeypatch, manager, pages, "countries")
+
+ assert [r["ref_country_id"] for r in rows] == [1, 2]
+ assert calls[1][0] == next_url
+ assert [s.next_url for s in manager.saved] == [next_url]
+
+ def test_relative_next_page_is_resolved_against_base(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages: list[dict[str, Any]] = [
+ {
+ "campaigns": [{"campaign": {"campaign_id": "10l1"}}],
+ "hypermedia": {"pagination": {"next_page": "/user/publisher/111111l92/campaign/a?page=2"}},
+ },
+ {"campaigns": []},
+ ]
+ _, calls = _collect_rows(monkeypatch, manager, pages, "campaigns")
+ assert calls[1][0] == f"{PARTNERIZE_BASE_URL}/user/publisher/111111l92/campaign/a?page=2"
+
+ def test_off_host_next_page_terminates_without_following(self, monkeypatch: Any) -> None:
+ # The session carries the Basic auth header, so a tampered next_page pointing off-host (a
+ # different host, or a lookalike that only prefixes the base) must not be followed (SSRF
+ # guard). The first page's rows still surface; the cursor is not followed and not saved.
+ for next_page in ("https://evil.example.com/steal", "https://api.partnerize.com.evil.example.com/steal"):
+ manager = _FakeResumableManager()
+ pages: list[dict[str, Any]] = [
+ {
+ "countries": [{"country": {"ref_country_id": 1}}],
+ "hypermedia": {"pagination": {"next_page": next_page}},
+ },
+ ]
+ rows, calls = _collect_rows(monkeypatch, manager, pages, "countries")
+ assert [r["ref_country_id"] for r in rows] == [1], next_page
+ assert len(calls) == 1, next_page
+ assert manager.saved == [], next_page
+
+ def test_single_page_stops_without_saving(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, calls = _collect_rows(
+ monkeypatch, manager, [{"countries": [{"country": {"ref_country_id": 1}}]}], "countries"
+ )
+ assert len(rows) == 1
+ assert len(calls) == 1
+ assert manager.saved == []
+
+ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:
+ resume_url = f"{PARTNERIZE_BASE_URL}/reference/country?page=5"
+ manager = _FakeResumableManager(PartnerizeResumeConfig(next_url=resume_url))
+ _, calls = _collect_rows(monkeypatch, manager, [{"countries": []}], "countries")
+ assert calls[0][0] == resume_url
+
+
+class TestPartnerizeSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = partnerize_source(
+ application_key="app-key",
+ user_api_key="api-key",
+ publisher_id="111111l92",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ config = PARTNERIZE_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.kind == "report":
+ # The reports document no ordering guarantee, so the watermark only commits on completion.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("not_found", 404, False, 404, None),
+ ("server_error", 500, False, 500, "Partnerize returned HTTP 500"),
+ ]
+ )
+ @patch(f"{partnerize.__name__}.make_tracked_session")
+ def test_status_mapping(
+ self,
+ _name: str,
+ status: int,
+ ok: bool,
+ expected_status: int,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ mock_session.return_value = self._session(response)
+ assert check_access("app-key", "api-key", "111111l92") == (expected_status, expected_message)
+
+ @patch(f"{partnerize.__name__}.make_tracked_session")
+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:
+ mock_session.return_value = self._session(requests.ConnectionError("boom"))
+ status, message = check_access("app-key", "api-key", "111111l92")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("not_found", 404, False),
+ ("server_error", 500, False),
+ ]
+ )
+ @patch(f"{partnerize.__name__}.make_tracked_session")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ mock_session.return_value = self._session(response)
+ valid, message = validate_credentials("app-key", "api-key", "111111l92")
+ assert valid is expected_valid
+ assert (message is None) is expected_valid
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/tests/test_partnerize_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/tests/test_partnerize_source.py
new file mode 100644
index 000000000000..b963cf646353
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerize/tests/test_partnerize_source.py
@@ -0,0 +1,166 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PartnerizeSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.partnerize import (
+ PartnerizeResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.source import PartnerizeSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"conversions", "clicks"}
+
+
+class TestPartnerizeSource:
+ def setup_method(self) -> None:
+ self.source = PartnerizeSource()
+ self.team_id = 123
+ self.config = PartnerizeSourceConfig(
+ application_key="app-key", user_api_key="api-key", publisher_id="111111l92"
+ )
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.PARTNERIZE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Partnerize"
+ assert config.label == "Partnerize"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/partnerize"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["application_key", "user_api_key", "publisher_id"]
+
+ def test_user_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "user_api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_incremental_flags(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ by_name = {s.name: s for s in schemas}
+ for name, schema in by_name.items():
+ expected = name in INCREMENTAL_ENDPOINTS
+ assert schema.supports_incremental is expected
+ assert schema.supports_append is expected
+ assert bool(schema.incremental_fields) is expected
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["conversions"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "conversions"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+ by_name = {t["name"]: t for t in tables}
+ assert "Incremental" in by_name["conversions"]["sync_methods"]
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.partnerize.com/reporting/report_publisher/publisher/111111l92/conversion.json?start_date=2010-01-01T00%3A00%3A00Z&offset=0",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://api.partnerize.com/reference/country",
+ ),
+ (
+ "unknown_publisher",
+ "404 Client Error: Not Found for url: https://api.partnerize.com/user/publisher/111111l92/campaign/a",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://api.partnerize.com/reference/country",
+ ),
+ (
+ "rate_limited",
+ "429 Client Error: Too Many Requests for url: https://api.partnerize.com/reference/currency",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.source.validate_credentials"
+ )
+ def test_validate_credentials_delegates_with_config_values(self, mock_validate: mock.MagicMock) -> None:
+ # The status-to-message mapping lives in partnerize.validate_credentials; here we only assert
+ # the source probes with the configured credentials and returns the delegate's verdict.
+ mock_validate.return_value = (False, "Invalid Partnerize API credentials")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ mock_validate.assert_called_once_with("app-key", "api-key", "111111l92")
+ assert result == (False, "Invalid Partnerize API credentials")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is PartnerizeResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.source.partnerize_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "conversions"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-05-01 12:00:00"
+ inputs.incremental_field = "conversion_time"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["application_key"] == "app-key"
+ assert kwargs["user_api_key"] == "api-key"
+ assert kwargs["publisher_id"] == "111111l92"
+ assert kwargs["endpoint"] == "conversions"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-05-01 12:00:00"
+ assert kwargs["incremental_field"] == "conversion_time"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.partnerize.source.partnerize_source")
+ def test_source_for_pipeline_drops_watermark_for_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "conversions"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-05-01 12:00:00"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Partnerize schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)