: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement polar.sh source (#57518)
Marcus Hofa65c9dd4da34
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 1a48bfa0db26..e2ae5432b1b8 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -69,6 +69,7 @@ the row lists both.| paddle | HTTP | requests | ✅ || pinterest_ads | HTTP | requests | ✅ || plain | HTTP | requests | ✅ |+| polar | HTTP | requests | ✅ || postgres | DB protocol | psycopg | ➖ || reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |@@ -111,7 +112,7 @@ drip, dynamodb, elasticsearch, eventbrite, facebook_pages, firebase, freshdesk,fullstory, gitlab, gong, google_analytics, google_drive, gorgias, granola, greenhouse, helpscout,instagram, intercom, iterable, jira, kafka, launchdarkly, lever, mailerlite, mailjet, marketo,microsoft_teams, mixpanel, monday, netsuite, notion, okta, omnisend, onedrive, oracle, outreach,-pagerduty, pardot, paypal, pendo, pipedrive, plaid, polar, postmark, productboard, quickbooks, recharge,+pagerduty, pardot, paypal, pendo, pipedrive, plaid, postmark, productboard, quickbooks, recharge,recurly, revenuecat, ringcentral, salesloft, sendgrid, servicenow, sftp, sharepoint, shortcut, smartsheet,square, surveymonkey, temporalio, trello, twilio, twitter_ads, webflow, woocommerce, workday, wrike, xero,youtube_analytics, zoho_crm, zoom, zuora.diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex d0cf4a9f2818..8bd5e2c2ff72 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -616,7 +616,7 @@ class PlainSourceConfig(config.Config):@config.configclass PolarSourceConfig(config.Config):- pass+ polar_api_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/polar/constants.py b/posthog/temporal/data_imports/sources/polar/constants.pynew file mode 100644index 000000000000..1ba6b0f38f1e--- /dev/null+++ b/posthog/temporal/data_imports/sources/polar/constants.py@@ -0,0 +1,8 @@+CUSTOMER_RESOURCE_NAME = "customers"+PRODUCT_RESOURCE_NAME = "products"+ORDER_RESOURCE_NAME = "orders"+SUBSCRIPTION_RESOURCE_NAME = "subscriptions"+REFUND_RESOURCE_NAME = "refunds"+CHECKOUT_RESOURCE_NAME = "checkouts"+BENEFIT_RESOURCE_NAME = "benefits"+ORGANIZATION_RESOURCE_NAME = "organizations"diff --git a/posthog/temporal/data_imports/sources/polar/polar.py b/posthog/temporal/data_imports/sources/polar/polar.pynew file mode 100644index 000000000000..22d56931dc22--- /dev/null+++ b/posthog/temporal/data_imports/sources/polar/polar.py@@ -0,0 +1,182 @@+import dataclasses+from typing import Optional+from urllib.parse import parse_qs, urlencode, urlparse++import requests+from urllib3.util.retry import Retry++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.polar.settings import ENDPOINT_SORT_FIELDS, ENDPOINTS++POLAR_BASE_URL = "https://api.polar.sh"+PAGE_SIZE = 100+++class PolarResumeConfig:+ next_url: str+++class PolarPermissionError(Exception):+ pass+++def _get_polar_session() -> requests.Session:+ # Plain session with no retry adapter: errors fail fast so the caller+ # can surface them immediately rather than silently retrying.+ return make_tracked_session(retry=Retry(total=0))+++def _build_url(endpoint: str, page: int) -> str:+ params: dict[str, str | int] = {"limit": PAGE_SIZE, "page": page}+ sort_field = ENDPOINT_SORT_FIELDS.get(endpoint)+ if sort_field is not None:+ params["sorting"] = sort_field+ return f"{POLAR_BASE_URL}/v1/{endpoint}/?{urlencode(params)}"+++def _page_from_url(url: str) -> int:+ qs = parse_qs(urlparse(url).query)+ page_values = qs.get("page", ["1"])+ try:+ return int(page_values[0])+ except (ValueError, IndexError):+ return 1+++def get_rows(+ api_key: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[PolarResumeConfig],+):+ headers = {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }++ url: Optional[str] = _build_url(endpoint, page=1)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config and resume_config.next_url:+ url = resume_config.next_url++ session = _get_polar_session()+ seen_urls: set[str] = set()++ while url:+ if url in seen_urls:+ break+ seen_urls.add(url)++ response = session.request("GET", url, headers=headers)+ response.raise_for_status()+ data = response.json()++ # Yield the whole page list; the pipeline batcher handles chunking into+ # pa.Tables at its own thresholds (5000 rows / 200 MiB) and accepts+ # lists directly without per-row overhead.+ items = data.get("items", [])+ if items:+ yield items++ pagination = data.get("pagination") or {}+ max_page = int(pagination.get("max_page") or 0)+ current_page = _page_from_url(url)++ if current_page < max_page:+ url = _build_url(endpoint, page=current_page + 1)+ else:+ url = None++ if url:+ resumable_source_manager.save_state(PolarResumeConfig(next_url=url))+ else:+ resumable_source_manager.save_state(PolarResumeConfig(next_url=""))+++def polar_source(+ api_key: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[PolarResumeConfig],+) -> SourceResponse:+ def items():+ yield from get_rows(+ api_key=api_key,+ endpoint=endpoint,+ resumable_source_manager=resumable_source_manager,+ )++ return SourceResponse(+ items=items,+ primary_keys=["id"],+ name=endpoint,+ column_hints={},+ )+++def validate_credentials(api_key: str, table_name: Optional[str] = None) -> bool:+ headers = {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+ session = _get_polar_session()++ # When called per-schema (the incremental_fields action), a 403 should surface+ # immediately so the wizard can show "missing permissions for <endpoint>".+ # When called at source-create (no table_name), the user may legitimately have+ # scopes for only a subset of endpoints, so we accept any single non-403+ # response as proof of a usable token. Per-endpoint scope checks are deferred+ # to the per-schema action / first sync. We do require ≥1 readable endpoint —+ # a token that 403s on every endpoint has no usable scope and would create a+ # source guaranteed to fail on first sync.+ if table_name and table_name in ENDPOINTS:+ is_create_probe = False+ endpoints_to_check: list[str] = [table_name]+ elif table_name:+ # A known per-schema caller (incremental_fields) but an endpoint we don't+ # support — reject explicitly rather than silently degrading to the+ # create-probe path, which would falsely pass if any other endpoint is readable.+ raise ValueError(f"Unknown Polar endpoint: {table_name}")+ else:+ is_create_probe = True+ endpoints_to_check = list(ENDPOINTS)++ forbidden: list[str] = []+ last_failure: Optional[requests.Response] = None+ for endpoint in endpoints_to_check:+ response = session.request(+ "GET",+ f"{POLAR_BASE_URL}/v1/{endpoint}/",+ headers=headers,+ params={"limit": 1},+ )+ if response.status_code == 403:+ if is_create_probe:+ forbidden.append(endpoint)+ continue+ raise PolarPermissionError(f"Missing permissions for {endpoint}")+ if is_create_probe:+ # First non-403 success is proof enough — stop probing so a transient+ # 5xx on a later endpoint can't block source creation.+ if response.ok:+ return True+ # Transient non-403 (e.g. 5xx, 401) during create-probe: don't blow+ # up the whole validation — record it and let later endpoints answer.+ last_failure = response+ continue+ response.raise_for_status()++ if is_create_probe:+ if forbidden and not last_failure:+ raise PolarPermissionError(+ f"token has no readable scope for any supported endpoint ({', '.join(forbidden)})"+ )+ if last_failure is not None:+ # Only transient errors (and possibly some 403s) — no endpoint+ # confirmed the token works. Surface the underlying HTTP error so+ # the user gets actionable feedback rather than a silent success.+ last_failure.raise_for_status()++ return Truediff --git a/posthog/temporal/data_imports/sources/polar/settings.py b/posthog/temporal/data_imports/sources/polar/settings.pynew file mode 100644index 000000000000..e0e5e9c7a34e--- /dev/null+++ b/posthog/temporal/data_imports/sources/polar/settings.py@@ -0,0 +1,35 @@+from posthog.temporal.data_imports.sources.polar.constants import (+ BENEFIT_RESOURCE_NAME,+ CHECKOUT_RESOURCE_NAME,+ CUSTOMER_RESOURCE_NAME,+ ORDER_RESOURCE_NAME,+ ORGANIZATION_RESOURCE_NAME,+ PRODUCT_RESOURCE_NAME,+ REFUND_RESOURCE_NAME,+ SUBSCRIPTION_RESOURCE_NAME,+)++ENDPOINTS = [+ CUSTOMER_RESOURCE_NAME,+ PRODUCT_RESOURCE_NAME,+ ORDER_RESOURCE_NAME,+ SUBSCRIPTION_RESOURCE_NAME,+ REFUND_RESOURCE_NAME,+ CHECKOUT_RESOURCE_NAME,+ BENEFIT_RESOURCE_NAME,+ ORGANIZATION_RESOURCE_NAME,+]++# Per-endpoint ascending sort key. Polar's API default is newest-first (`-created_at` /+# `-started_at`); we override to oldest-first so the destination table is written in row+# creation order. Subscriptions has no `created_at` sort option, so we use `started_at`.+ENDPOINT_SORT_FIELDS: dict[str, str] = {+ CUSTOMER_RESOURCE_NAME: "created_at",+ PRODUCT_RESOURCE_NAME: "created_at",+ ORDER_RESOURCE_NAME: "created_at",+ SUBSCRIPTION_RESOURCE_NAME: "started_at",+ REFUND_RESOURCE_NAME: "created_at",+ CHECKOUT_RESOURCE_NAME: "created_at",+ BENEFIT_RESOURCE_NAME: "created_at",+ ORGANIZATION_RESOURCE_NAME: "created_at",+}diff --git a/posthog/temporal/data_imports/sources/polar/source.py b/posthog/temporal/data_imports/sources/polar/source.pyindex c643659ee11b..d0657249bfbc 100644--- a/posthog/temporal/data_imports/sources/polar/source.py+++ b/posthog/temporal/data_imports/sources/polar/source.py@@ -1,19 +1,31 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import PolarSourceConfig+from posthog.temporal.data_imports.sources.polar.polar import (+ PolarPermissionError,+ PolarResumeConfig,+ polar_source,+ validate_credentials as validate_polar_credentials,+)+from posthog.temporal.data_imports.sources.polar.settings import ENDPOINTS as POLAR_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class PolarSource(SimpleSource[PolarSourceConfig]):+class PolarSource(ResumableSource[PolarSourceConfig, PolarResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.POLAR@@ -23,8 +35,88 @@ class PolarSource(SimpleSource[PolarSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.POLAR,label="Polar",+ caption=(+ "Connect your Polar.sh account using an "+ "[Organization Access Token](https://docs.polar.sh/integrate/oat) "+ "to sync customers, products, orders, subscriptions, and more.\n\n"+ "**Required scopes:** `benefits:read`, `checkouts:read`, `customers:read`, "+ "`orders:read`, `organizations:read`, `products:read`, `refunds:read`, "+ "`subscriptions:read`."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/polar",iconPath="/static/services/polar.png",iconClassName="rounded dark:bg-white p-[2px]",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ featureFlag="dwh_polar",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="polar_api_key",+ label="Organization Access Token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="polar_oat_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.polar.sh": "Your Polar Organization Access Token is invalid or expired. Please generate a new token in Polar and reconnect.",+ "403 Client Error: Forbidden for url: https://api.polar.sh": "Your Polar Organization Access Token does not have the required permissions. Please check the token's scopes in Polar and reconnect.",+ }++ def validate_credentials(+ self, config: PolarSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ validate_polar_credentials(config.polar_api_key, schema_name)+ return True, None+ except PolarPermissionError as e:+ return False, f"Polar Organization Access Token lacks permissions: {e}"+ except Exception as e:+ return False, str(e)++ def get_schemas(+ self,+ config: PolarSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Full refresh only — Polar's list endpoints accept no server-side timestamp filter,+ # so an "incremental" sync would still fetch every page. We surface that honestly by+ # not offering the incremental option in the wizard.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in POLAR_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 get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PolarResumeConfig]:+ return ResumableSourceManager[PolarResumeConfig](inputs, PolarResumeConfig)++ def source_for_pipeline(+ self,+ config: PolarSourceConfig,+ resumable_source_manager: ResumableSourceManager[PolarResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return polar_source(+ api_key=config.polar_api_key,+ endpoint=inputs.schema_name,+ resumable_source_manager=resumable_source_manager,)