: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 recharge import source (#61138)
Tom Owersfa876eb33f43
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 993159f0daa3..7acd387fdeea 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -75,6 +75,7 @@ the row lists both.| plain | HTTP | requests | ✅ || polar | HTTP | requests | ✅ || postgres | DB protocol | psycopg | ➖ |+| recharge | HTTP | requests | ✅ || reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || redshift | DB protocol | psycopg (Postgres-compatible) | ➖ || resend | HTTP | requests | ✅ |@@ -198,7 +199,6 @@ doesn't conflict with concurrent PRs.- postmark- productboard- quickbooks-- recharge- recurly- ringcentral- salesloftdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 933a1e0dc1b4..bd95cc257872 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -665,7 +665,7 @@ class QuickBooksSourceConfig(config.Config):@config.configclass RechargeSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/recharge/api_inventory.md b/posthog/temporal/data_imports/sources/recharge/api_inventory.mdnew file mode 100644index 000000000000..52ed9f41dbb1--- /dev/null+++ b/posthog/temporal/data_imports/sources/recharge/api_inventory.md@@ -0,0 +1,45 @@+# Recharge API inventory++Source: Recharge Payments — subscription management for e-commerce.++- **API version:** `2021-11` (sent via `X-Recharge-Version` header).+- **Base URL:** `https://api.rechargeapps.com`+- **Auth:** API token in the `X-Recharge-Access-Token` header (read scopes per resource).+- **Docs:** <https://developer.rechargepayments.com/2021-11>+- **Pagination:** cursor-based. List responses return `next_cursor` / `previous_cursor` in+ the body. Following a cursor accepts **only** `cursor` + `limit` — the original sort and+ filters are baked into the cursor (re-sending them returns a 422). `limit` max is 250.+- **Incremental:** server-side `updated_at_min` / `created_at_min` filters (ISO 8601, no+ offset). We sort `<field>-asc` so the pipeline watermark advances monotonically.+- **Rate limiting:** leaky bucket — 40 request burst, ~2 req/s sustained. 429s are retried+ with exponential backoff.++> ⚠️ **Unverified against a live store.** Endpoint params below come from the public 2021-11+> docs; they were not curl-verified during implementation (no test credentials). Treat the+> incremental-filter and response-shape assumptions as conservative until confirmed against a+> real account.++## Endpoints++| Schema | Path | Primary key | Partition key | Incremental | Notes |+| ----------------- | ------------------ | ----------- | ------------- | ----------- | --------------------------------------------------------------------------------- |+| `customers` | `/customers` | `id` | `created_at` | ✅ | |+| `subscriptions` | `/subscriptions` | `id` | `created_at` | ✅ | |+| `orders` | `/orders` | `id` | `created_at` | ✅ | |+| `charges` | `/charges` | `id` | `created_at` | ✅ | 90-day retention for `processed_at` filtering (we use `updated_at`/`created_at`). |+| `addresses` | `/addresses` | `id` | `created_at` | ✅ | |+| `discounts` | `/discounts` | `id` | `created_at` | ✅ | |+| `onetimes` | `/onetimes` | `id` | `created_at` | ✅ | |+| `products` | `/products` | `id` | `created_at` | ✅ | |+| `payment_methods` | `/payment_methods` | `id` | `created_at` | ✅ | Requires Recharge Pro / Custom plan. |+| `collections` | `/collections` | `id` | `created_at` | ➖ full | Server-side timestamp filter not reliably documented — full refresh. |++## Possible future work++- **Webhooks.** Recharge supports programmatically managed webhooks (`/webhooks`) with HMAC+ validation via `X-Recharge-Hmac-Sha256` (signed with the API client secret). Recharge+ webhooks are **per-topic** (one webhook per `subscription/created`, `charge/created`, …),+ which doesn't map cleanly onto the one-webhook-per-source `create_webhook` / `delete_webhook`+ contract — so realtime webhook ingestion is intentionally deferred from this initial alpha.+- **Metafields / plan-specific resources** (bundle selections, credit adjustments) require a+ fan-out or a Pro/Custom plan and are omitted from the initial endpoint set.diff --git a/posthog/temporal/data_imports/sources/recharge/recharge.py b/posthog/temporal/data_imports/sources/recharge/recharge.pynew file mode 100644index 000000000000..836ae34991d0--- /dev/null+++ b/posthog/temporal/data_imports/sources/recharge/recharge.py@@ -0,0 +1,247 @@+"""Recharge API client used by the data warehouse source.++Spec: https://developer.rechargepayments.com/2021-11 (API version 2021-11).++Recharge is a subscription-billing platform. The API is pure REST/JSON with+API-key auth (`X-Recharge-Access-Token`), cursor pagination, and server-side+timestamp filters (`updated_at_min` / `created_at_min`) for incremental syncs.++Everything here routes through ``make_tracked_session`` so outbound calls show+up in our HTTP logs, OTel metrics, and sample-capture pipeline.++NOTE: these endpoint params were taken from the public 2021-11 docs and could+not be curl-verified against a live store during implementation (no test+credentials). The pagination/filter handling is intentionally conservative —+see inline comments where behavior is assumed rather than confirmed.+"""++import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++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.recharge.settings import RECHARGE_ENDPOINTS, RechargeEndpointConfig++RECHARGE_BASE_URL = "https://api.rechargeapps.com"+RECHARGE_API_VERSION = "2021-11"+# Recharge caps page size at 250 (default 50). Larger pages = fewer round-trips+# against the leaky-bucket rate limit (40 burst, ~2 req/s sustained).+PAGE_SIZE = 250+REQUEST_TIMEOUT_SECONDS = 60+++class RechargeRetryableError(Exception):+ pass+++class RechargeResumeConfig:+ """Cursor state for resumable list iteration.++ ``cursor`` is the Recharge-issued ``next_cursor``; it encodes the original+ request filters (sort + timestamp window), so resuming only needs to replay+ the cursor. ``endpoint`` scopes the cursor to a single endpoint so we never+ replay a customers cursor against orders.+ """++ endpoint: str+ cursor: str+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "X-Recharge-Access-Token": api_key,+ "X-Recharge-Version": RECHARGE_API_VERSION,+ "Accept": "application/json",+ }+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor value for Recharge's ``*_min`` filters.++ Recharge expects ISO 8601 without a timezone offset (e.g.+ ``2021-05-04T00:00:00``), interpreted as the store's timezone. We normalize+ to UTC first to keep behavior deterministic.+ """+ if isinstance(value, datetime):+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00")+ return str(value)+++def _build_initial_params(+ config: RechargeEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ """Query params for the first page (cursor pages drop everything but limit)."""+ params: dict[str, Any] = {"limit": PAGE_SIZE}++ use_incremental = (+ config.supports_incremental+ and should_use_incremental_field+ and incremental_field is not None+ and db_incremental_field_last_value is not None+ )++ if use_incremental:+ # `incremental_field` is the user's chosen cursor column (updated_at or+ # created_at). Filter server-side on `<field>_min` and sort ascending on+ # the same field so the pipeline watermark advances monotonically.+ params[f"{incremental_field}_min"] = _format_incremental_value(db_incremental_field_last_value)+ params["sort_by"] = f"{incremental_field}-asc"+ else:+ params["sort_by"] = f"{config.default_sort_field}-asc"++ return params+++def _extract_items(payload: dict[str, Any], resource_key: str) -> list[dict[str, Any]]:+ """Pull the list of records out of a Recharge list response.++ Recharge wraps results under a key matching the resource (e.g.+ ``{"customers": [...], "next_cursor": "..."}``). Fall back to the first+ list-valued, non-cursor key if the resource key isn't present.+ """+ items = payload.get(resource_key)+ if isinstance(items, list):+ return items++ for key, value in payload.items():+ if key in ("next_cursor", "previous_cursor"):+ continue+ if isinstance(value, list):+ return value+ return []+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """Probe ``/token_information`` — the cheapest call that confirms the token.++ Returns ``(ok, error)``. A 401 means the token is invalid; anything else+ reachable-and-2xx is treated as valid.+ """+ url = f"{RECHARGE_BASE_URL}/token_information"+ try:+ # `redact_values` masks the token wherever it appears in captured HTTP+ # samples — the `X-Recharge-Access-Token` header isn't in the shared+ # auth-header denylist, so without this the token would leak in plaintext.+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=10)+ except requests.RequestException as e:+ return False, f"Could not reach Recharge: {e}"++ if response.status_code == 401:+ return False, "Invalid Recharge API token. Please check the token and try again."+ if response.ok:+ return True, None+ return False, f"Recharge rejected the request (HTTP {response.status_code})."+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RechargeResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = RECHARGE_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)++ params = _build_initial_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor: str | None = resume.cursor if resume is not None and resume.endpoint == endpoint else None++ @retry(+ retry=retry_if_exception_type((RechargeRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch_page(request_params: dict[str, Any]) -> dict[str, Any]:+ url = f"{RECHARGE_BASE_URL}{config.path}?{urlencode(request_params)}"+ # `redact_values` masks the token in captured HTTP samples (the custom+ # `X-Recharge-Access-Token` header isn't in the shared auth denylist).+ session = make_tracked_session(redact_values=(api_key,))+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise RechargeRetryableError(+ f"Recharge API error (retryable): status={response.status_code}, endpoint={endpoint}"+ )++ if not response.ok:+ logger.error(+ f"Recharge API error: status={response.status_code}, body={response.text}, endpoint={endpoint}"+ )+ response.raise_for_status()++ return response.json()++ while True:+ # When following a cursor, Recharge only accepts `cursor` + `limit` —+ # the original sort/filters are baked into the cursor itself. Sending+ # them again returns a 422.+ request_params: dict[str, Any] = {"cursor": cursor, "limit": PAGE_SIZE} if cursor else params++ data = fetch_page(request_params)+ items = _extract_items(data, endpoint)++ if items:+ yield items++ next_cursor = data.get("next_cursor")+ if not next_cursor:+ break++ # Save state AFTER yielding so a crash re-yields the last page (merge+ # dedupes on primary key) rather than skipping it.+ resumable_source_manager.save_state(RechargeResumeConfig(endpoint=endpoint, cursor=next_cursor))+ cursor = next_cursor+++def recharge_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RechargeResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = RECHARGE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ 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=["id"],+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/recharge/settings.py b/posthog/temporal/data_imports/sources/recharge/settings.pynew file mode 100644index 000000000000..caeaf877c954--- /dev/null+++ b/posthog/temporal/data_imports/sources/recharge/settings.py@@ -0,0 +1,109 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class RechargeEndpointConfig:+ """Declarative metadata for a single Recharge list endpoint.++ `path` is appended to the API base URL. `partition_key` must be a STABLE+ field (`created_at`) so partitions are never rewritten — never `updated_at`.+ `incremental_fields` is the menu of advertised cursor options; the user's+ actual choice arrives via `inputs.incremental_field`.++ `supports_incremental` is only `True` for endpoints where Recharge exposes a+ server-side `updated_at_min` / `created_at_min` filter (per the public+ 2021-11 API docs). Endpoints without a confirmed server-side timestamp filter+ ship full-refresh only.+ """++ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ partition_key: Optional[str] = "created_at"+ supports_incremental: bool = True+ # Default sort field used when not syncing incrementally. Recharge accepts+ # `<field>-asc` / `<field>-desc`; `id-asc` is a stable monotonic order that+ # avoids page-boundary skips/dupes when rows are inserted mid-sync.+ default_sort_field: str = "id"+++def _timestamp_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++# Both `updated_at` and `created_at` are offered as incremental cursors for the+# endpoints that support server-side timestamp filtering. `updated_at` is the+# better default (catches mutations); `created_at` suits append-only consumers.+_UPDATED_AND_CREATED = [_timestamp_field("updated_at"), _timestamp_field("created_at")]+++RECHARGE_ENDPOINTS: dict[str, RechargeEndpointConfig] = {+ "customers": RechargeEndpointConfig(+ name="customers",+ path="/customers",+ incremental_fields=_UPDATED_AND_CREATED,+ ),+ "subscriptions": RechargeEndpointConfig(+ name="subscriptions",+ path="/subscriptions",+ incremental_fields=_UPDATED_AND_CREATED,+ ),+ "orders": RechargeEndpointConfig(+ name="orders",+ path="/orders",+ incremental_fields=_UPDATED_AND_CREATED,+ ),+ "charges": RechargeEndpointConfig(+ name="charges",+ path="/charges",+ incremental_fields=_UPDATED_AND_CREATED,+ ),+ "addresses": RechargeEndpointConfig(+ name="addresses",+ path="/addresses",+ incremental_fields=_UPDATED_AND_CREATED,+ ),+ "discounts": RechargeEndpointConfig(+ name="discounts",+ path="/discounts",+ incremental_fields=_UPDATED_AND_CREATED,+ ),+ "onetimes": RechargeEndpointConfig(+ name="onetimes",+ path="/onetimes",+ incremental_fields=_UPDATED_AND_CREATED,+ ),+ "products": RechargeEndpointConfig(+ name="products",+ path="/products",+ incremental_fields=_UPDATED_AND_CREATED,+ ),+ "payment_methods": RechargeEndpointConfig(+ name="payment_methods",+ path="/payment_methods",+ incremental_fields=_UPDATED_AND_CREATED,+ ),+ # Collections expose `created_at`/`updated_at` on the object but the list+ # endpoint's server-side timestamp filtering is not documented as reliably+ # as the core resources, so ship full-refresh and partition by created_at.+ "collections": RechargeEndpointConfig(+ name="collections",+ path="/collections",+ incremental_fields=[],+ supports_incremental=False,+ ),+}++ENDPOINTS = tuple(RECHARGE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in RECHARGE_ENDPOINTS.items() if config.supports_incremental+}diff --git a/posthog/temporal/data_imports/sources/recharge/source.py b/posthog/temporal/data_imports/sources/recharge/source.pyindex 810caf873bed..8032c456b861 100644--- a/posthog/temporal/data_imports/sources/recharge/source.py+++ b/posthog/temporal/data_imports/sources/recharge/source.py@@ -1,19 +1,31 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,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 RechargeSourceConfig+from posthog.temporal.data_imports.sources.recharge.recharge import (+ RechargeResumeConfig,+ recharge_source,+ validate_credentials as validate_recharge_credentials,+)+from posthog.temporal.data_imports.sources.recharge.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class RechargeSource(SimpleSource[RechargeSourceConfig]):+class RechargeSource(ResumableSource[RechargeSourceConfig, RechargeResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RECHARGE@@ -23,7 +35,94 @@ class RechargeSource(SimpleSource[RechargeSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.RECHARGE,label="Recharge",+ caption="""Enter your Recharge API token to automatically pull your Recharge subscription data into the PostHog Data warehouse.++You can create an API token in your [Recharge admin](https://docs.getrecharge.com/docs/recharge-api-and-developer-tools) under **Apps & integrations > API tokens**.++Grant **read** access to the resources you want to sync, e.g.:+- Customers+- Subscriptions+- Orders+- Charges+- Addresses+- Discounts+- Products++Some resources (such as Payment methods) are only available on Recharge Pro or Custom plans.+""",iconPath="/static/services/recharge.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/recharge",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="sk_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "Recharge rejected the API token. Generate a new token and reconnect.",+ "403 Client Error: Forbidden": (+ "The Recharge API token is missing the permissions required for this resource. "+ "Grant read access to the resource and reconnect."+ ),+ }++ def get_schemas(+ self,+ config: RechargeSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=(inc_fields := INCREMENTAL_FIELDS.get(endpoint)) is not None,+ supports_append=inc_fields is not None,+ incremental_fields=inc_fields or [],+ )+ 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: RechargeSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_recharge_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RechargeResumeConfig]:+ return ResumableSourceManager[RechargeResumeConfig](inputs, RechargeResumeConfig)++ def source_for_pipeline(+ self,+ config: RechargeSourceConfig,+ resumable_source_manager: ResumableSourceManager[RechargeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return recharge_source(+ api_key=config.api_key,+ 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/posthog/temporal/data_imports/sources/recharge/tests/test_recharge.py b/posthog/temporal/data_imports/sources/recharge/tests/test_recharge.pynew file mode 100644index 000000000000..a436e73f5523--- /dev/null+++ b/posthog/temporal/data_imports/sources/recharge/tests/test_recharge.py@@ -0,0 +1,230 @@+from datetime import UTC, date, datetime+from typing import Any++from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.recharge.recharge import (+ RechargeResumeConfig,+ _build_initial_params,+ _extract_items,+ _format_incremental_value,+ get_rows,+ recharge_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.recharge.settings import RECHARGE_ENDPOINTS+++def _mock_response(status_code: int = 200, json_body: dict[str, Any] | None = None, text: str = "") -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.text = text+ response.json.return_value = json_body or {}+ return response+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00"),+ ("string_passthrough", "2026-03-04T00:00:00", "2026-03-04T00:00:00"),+ ]+ )+ def test_format_incremental_value(self, _name: str, value: object, expected: str) -> None:+ assert _format_incremental_value(value) == expected++ def test_no_offset_suffix(self) -> None:+ # Recharge rejects timezone offsets in `*_min` filters.+ assert "+00:00" not in _format_incremental_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+++class TestBuildInitialParams:+ def test_incremental_on_updated_at_sets_min_and_sort(self) -> None:+ params = _build_initial_params(+ RECHARGE_ENDPOINTS["customers"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ incremental_field="updated_at",+ )+ assert params["updated_at_min"] == "2026-03-04T02:58:14"+ assert params["sort_by"] == "updated_at-asc"+ assert params["limit"] == 250++ def test_incremental_on_created_at_uses_created_field(self) -> None:+ params = _build_initial_params(+ RECHARGE_ENDPOINTS["orders"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="created_at",+ )+ assert params["created_at_min"] == "2026-01-01T00:00:00"+ assert params["sort_by"] == "created_at-asc"+ assert "updated_at_min" not in params++ def test_full_refresh_sorts_by_stable_id(self) -> None:+ params = _build_initial_params(+ RECHARGE_ENDPOINTS["customers"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ incremental_field=None,+ )+ assert params["sort_by"] == "id-asc"+ assert not any(k.endswith("_min") for k in params)++ def test_non_incremental_endpoint_never_filters(self) -> None:+ # `collections` ships full-refresh only; even with incremental inputs set+ # it must not emit a server-side timestamp filter.+ params = _build_initial_params(+ RECHARGE_ENDPOINTS["collections"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="updated_at",+ )+ assert params["sort_by"] == "id-asc"+ assert not any(k.endswith("_min") for k in params)+++class TestExtractItems:+ @parameterized.expand(+ [+ ("resource_key_present", {"customers": [{"id": 1}], "next_cursor": "c"}, "customers", [{"id": 1}]),+ ("fallback_to_first_list", {"data": [{"id": 2}], "next_cursor": None}, "customers", [{"id": 2}]),+ ("empty_when_no_list", {"next_cursor": None}, "customers", []),+ ("ignores_cursor_keys", {"next_cursor": "x", "previous_cursor": "y"}, "orders", []),+ ]+ )+ def test_extract_items(self, _name: str, payload: dict, resource_key: str, expected: list) -> None:+ assert _extract_items(payload, resource_key) == expected+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("server_error", 500, False),+ ("forbidden", 403, False),+ ]+ )+ @patch("posthog.temporal.data_imports.sources.recharge.recharge.make_tracked_session")+ def test_status_mapping(self, _name: str, status_code: int, expected_ok: bool, mock_session: MagicMock) -> None:+ mock_session.return_value.get.return_value = _mock_response(status_code=status_code)+ ok, error = validate_credentials("token")+ assert ok is expected_ok+ if not expected_ok:+ assert error is not None++ @patch("posthog.temporal.data_imports.sources.recharge.recharge.make_tracked_session")+ def test_network_error_returns_false(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")+ ok, error = validate_credentials("token")+ assert ok is False+ assert error is not None++ @patch("posthog.temporal.data_imports.sources.recharge.recharge.make_tracked_session")+ def test_token_is_redacted_from_captured_samples(self, mock_session: MagicMock) -> None:+ # The `X-Recharge-Access-Token` header isn't in the shared auth-header+ # denylist, so the token must be passed as a `redact_values` literal to+ # keep it out of captured HTTP samples.+ mock_session.return_value.get.return_value = _mock_response(status_code=200)+ validate_credentials("secret-token")+ assert mock_session.call_args.kwargs["redact_values"] == ("secret-token",)+++class TestGetRows:+ @patch("posthog.temporal.data_imports.sources.recharge.recharge.make_tracked_session")+ def test_paginates_until_no_cursor_and_saves_state_after_yield(self, mock_session: MagicMock) -> None:+ pages = [+ _mock_response(json_body={"customers": [{"id": 1}], "next_cursor": "cursor-2"}),+ _mock_response(json_body={"customers": [{"id": 2}], "next_cursor": None}),+ ]+ mock_session.return_value.get.side_effect = pages++ manager = MagicMock()+ manager.can_resume.return_value = False++ batches = list(+ get_rows(+ api_key="token",+ endpoint="customers",+ logger=MagicMock(),+ resumable_source_manager=manager,+ )+ )++ assert batches == [[{"id": 1}], [{"id": 2}]]+ # State saved once — only when there's a next cursor to resume from.+ manager.save_state.assert_called_once()+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, RechargeResumeConfig)+ assert saved.endpoint == "customers"+ assert saved.cursor == "cursor-2"++ @patch("posthog.temporal.data_imports.sources.recharge.recharge.make_tracked_session")+ def test_token_is_redacted_from_captured_samples(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.return_value = _mock_response(+ json_body={"customers": [{"id": 1}], "next_cursor": None}+ )+ manager = MagicMock()+ manager.can_resume.return_value = False++ list(+ get_rows(api_key="secret-token", endpoint="customers", logger=MagicMock(), resumable_source_manager=manager)+ )++ assert mock_session.call_args.kwargs["redact_values"] == ("secret-token",)++ @patch("posthog.temporal.data_imports.sources.recharge.recharge.make_tracked_session")+ def test_resumes_from_saved_cursor_when_endpoint_matches(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.return_value = _mock_response(+ json_body={"customers": [{"id": 9}], "next_cursor": None}+ )++ manager = MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = RechargeResumeConfig(endpoint="customers", cursor="saved-cursor")++ list(get_rows(api_key="t", endpoint="customers", logger=MagicMock(), resumable_source_manager=manager))++ requested_url = mock_session.return_value.get.call_args.args[0]+ # When following a cursor we only send cursor + limit, no sort/filters.+ assert "cursor=saved-cursor" in requested_url+ assert "sort_by" not in requested_url++ @patch("posthog.temporal.data_imports.sources.recharge.recharge.make_tracked_session")+ def test_ignores_resume_state_from_different_endpoint(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.return_value = _mock_response(+ json_body={"orders": [{"id": 1}], "next_cursor": None}+ )++ manager = MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = RechargeResumeConfig(endpoint="customers", cursor="saved-cursor")++ list(get_rows(api_key="t", endpoint="orders", logger=MagicMock(), resumable_source_manager=manager))++ requested_url = mock_session.return_value.get.call_args.args[0]+ assert "cursor=saved-cursor" not in requested_url+ assert "sort_by=id-asc" in requested_url+++class TestRechargeSource:+ @parameterized.expand([(name,) for name in RECHARGE_ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = recharge_source(+ api_key="token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]diff --git a/posthog/temporal/data_imports/sources/recharge/tests/test_recharge_source.py b/posthog/temporal/data_imports/sources/recharge/tests/test_recharge_source.pynew file mode 100644index 000000000000..836d286ac541--- /dev/null+++ b/posthog/temporal/data_imports/sources/recharge/tests/test_recharge_source.py@@ -0,0 +1,118 @@+from unittest.mock import MagicMock, patch++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.generated_configs import RechargeSourceConfig+from posthog.temporal.data_imports.sources.recharge.recharge import RechargeResumeConfig+from posthog.temporal.data_imports.sources.recharge.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.recharge.source import RechargeSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _config(api_key: str = "sk_test") -> RechargeSourceConfig:+ return RechargeSourceConfig(api_key=api_key)+++class TestRechargeSourceType:+ def test_source_type(self) -> None:+ assert RechargeSource().source_type == ExternalDataSourceType.RECHARGE+++class TestRechargeSourceConfigFields:+ def test_exposes_required_secret_api_key(self) -> None:+ cfg = RechargeSource().get_source_config++ assert cfg.unreleasedSource is None+ names = {f.name for f in cfg.fields}+ assert names == {"api_key"}++ api_key_field = next(f for f in cfg.fields if f.name == "api_key")+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert api_key_field.secret is True+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+++class TestRechargeSourceGetSchemas:+ def test_lists_every_endpoint(self) -> None:+ schemas = RechargeSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_incremental_support_matches_settings(self) -> None:+ schemas = RechargeSource().get_schemas(_config(), team_id=1)+ for schema in schemas:+ expected = INCREMENTAL_FIELDS.get(schema.name) is not None+ assert schema.supports_incremental is expected+ assert schema.supports_append is expected++ def test_collections_is_full_refresh_only(self) -> None:+ schemas = RechargeSource().get_schemas(_config(), team_id=1)+ collections = next(s for s in schemas if s.name == "collections")+ assert collections.supports_incremental is False+ assert collections.incremental_fields == []++ def test_filters_by_names(self) -> None:+ schemas = RechargeSource().get_schemas(_config(), team_id=1, names=["customers", "orders"])+ assert {s.name for s in schemas} == {"customers", "orders"}+++class TestRechargeSourceValidateCredentials:+ @patch("posthog.temporal.data_imports.sources.recharge.source.validate_recharge_credentials")+ def test_delegates_to_client(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (True, None)+ ok, error = RechargeSource().validate_credentials(_config("tok"), team_id=1)+ assert ok is True+ assert error is None+ mock_validate.assert_called_once_with("tok")+++class TestRechargeSourceNonRetryableErrors:+ def test_includes_auth_errors(self) -> None:+ errors = RechargeSource().get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)+++class TestRechargeSourceResumableManager:+ def test_returns_manager_bound_to_resume_config(self) -> None:+ manager = RechargeSource().get_resumable_source_manager(MagicMock())+ assert manager._data_class is RechargeResumeConfig+++class TestRechargeSourcePipelinePlumbing:+ @patch("posthog.temporal.data_imports.sources.recharge.source.recharge_source")+ def test_passes_through_inputs(self, mock_recharge_source: MagicMock) -> None:+ sentinel = object()+ mock_recharge_source.return_value = sentinel++ inputs = MagicMock()+ inputs.schema_name = "customers"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00"+ inputs.incremental_field = "updated_at"++ manager = MagicMock()+ result = RechargeSource().source_for_pipeline(_config("tok"), manager, inputs)++ assert result is sentinel+ kwargs = mock_recharge_source.call_args.kwargs+ assert kwargs["api_key"] == "tok"+ assert kwargs["endpoint"] == "customers"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00"+ assert kwargs["incremental_field"] == "updated_at"++ @patch("posthog.temporal.data_imports.sources.recharge.source.recharge_source")+ def test_clears_last_value_when_not_incremental(self, mock_recharge_source: MagicMock) -> None:+ inputs = MagicMock()+ inputs.schema_name = "collections"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00"+ inputs.incremental_field = None++ RechargeSource().source_for_pipeline(_config("tok"), MagicMock(), inputs)++ kwargs = mock_recharge_source.call_args.kwargs+ assert kwargs["db_incremental_field_last_value"] is None