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 chargify import source (#67825)

Tom Owers92a00fc248b7
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 222da25da13c..504c92f5ee70 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -92,6 +92,7 @@ the row lists both.
| chameleon | HTTP | requests | ✅ |
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
| chargedesk | HTTP | requests | ✅ |
+| chargify | HTTP | requests + `rest_source.RESTClient` | ✅ |
| checkout_com | HTTP | requests | ✅ |
| churnkey | HTTP | requests | ✅ |
| coda | HTTP | requests | ✅ |
@@ -395,7 +396,6 @@ doesn't conflict with concurrent PRs.
- captain_data
- cart_com
- castor_edc
-- chargify
- chatwoot
- chift
- chorus
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/canonical_descriptions.py
new file mode 100644
index 000000000000..2e9c5f4f6c39
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/canonical_descriptions.py
@@ -0,0 +1,166 @@
+"""Canonical, documentation-sourced descriptions for Chargify (Maxio Advanced Billing) endpoints.
+
+Sourced from the official Maxio Advanced Billing API reference
+(https://developers.maxio.com/http/). Keyed by the resource names in `settings.py` `ENDPOINTS`,
+which match the `ExternalDataSchema.name` of a synced Chargify table. Columns absent here fall
+back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Fields shared by most Chargify objects; merged into each entry so we don't repeat them.
+_COMMON_COLUMNS = {
+ "id": "Unique identifier for the object within the site.",
+ "created_at": "Timestamp for when the object was created (ISO 8601).",
+ "updated_at": "Timestamp for when the object was last updated (ISO 8601).",
+}
+
+
+def _columns(**overrides: str) -> dict[str, str]:
+ return {**_COMMON_COLUMNS, **overrides}
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Customers": {
+ "description": "A customer of the site, who owns subscriptions and is billed for them.",
+ "docs_url": "https://developers.maxio.com/http/resources/customers",
+ "columns": _columns(
+ first_name="Customer's first name.",
+ last_name="Customer's last name.",
+ email="Customer's email address.",
+ organization="Company or organization name associated with the customer.",
+ reference="Unique value from your own system used to reference the customer.",
+ phone="Customer's phone number.",
+ address="Customer's street address.",
+ address_2="Second line of the customer's street address.",
+ city="Customer's city.",
+ state="Customer's state or province.",
+ zip="Customer's postal code.",
+ country="Customer's country (ISO 3166 code).",
+ verified="Whether the customer's ACH bank account has been verified.",
+ portal_customer_created_at="Timestamp for when the customer's Billing Portal account was created.",
+ vat_number="Customer's VAT number, used for tax calculations.",
+ tax_exempt="Whether the customer is exempt from tax.",
+ ),
+ },
+ "Subscriptions": {
+ "description": "A subscription binding a customer to a product, tracking its billing state and lifecycle.",
+ "docs_url": "https://developers.maxio.com/http/resources/subscriptions",
+ "columns": _columns(
+ state="Current state of the subscription (e.g. active, canceled, past_due, trialing).",
+ customer="The customer the subscription belongs to (nested object).",
+ product="The product the subscription is for (nested object).",
+ balance_in_cents="Outstanding balance owed on the subscription, in cents.",
+ current_period_started_at="Timestamp for the start of the current billing period.",
+ current_period_ends_at="Timestamp for the end of the current billing period.",
+ next_assessment_at="Timestamp for when the next billing assessment runs.",
+ trial_started_at="Timestamp for when the trial period started, if any.",
+ trial_ended_at="Timestamp for when the trial period ended, if any.",
+ activated_at="Timestamp for when the subscription became active.",
+ canceled_at="Timestamp for when the subscription was canceled, if applicable.",
+ cancellation_message="Message recorded when the subscription was canceled.",
+ expires_at="Timestamp for when the subscription is scheduled to expire.",
+ currency="Currency the subscription is billed in (ISO 4217 code).",
+ total_revenue_in_cents="Total revenue collected on the subscription, in cents.",
+ product_price_in_cents="Price of the subscription's product, in cents.",
+ ),
+ },
+ "Products": {
+ "description": "A product defining the recurring price and terms a subscription can be created against.",
+ "docs_url": "https://developers.maxio.com/http/resources/products",
+ "columns": _columns(
+ name="Name of the product.",
+ handle="Unique, URL-safe handle used to reference the product via the API.",
+ description="Description of the product.",
+ price_in_cents="Recurring price of the product, in cents.",
+ interval="Length of the billing period.",
+ interval_unit="Unit of the billing period (day or month).",
+ trial_price_in_cents="Price charged during the trial period, in cents.",
+ trial_interval="Length of the trial period.",
+ trial_interval_unit="Unit of the trial period (day or month).",
+ initial_charge_in_cents="One-time setup charge applied at signup, in cents.",
+ product_family="The product family this product belongs to (nested object).",
+ accounting_code="Accounting code used to categorize the product's revenue.",
+ request_credit_card="Whether a credit card is required at signup.",
+ archived_at="Timestamp for when the product was archived, if applicable.",
+ ),
+ },
+ "ProductFamilies": {
+ "description": "A grouping of related products, components, and coupons within the site.",
+ "docs_url": "https://developers.maxio.com/http/resources/product-families",
+ "columns": _columns(
+ name="Name of the product family.",
+ handle="Unique, URL-safe handle used to reference the product family.",
+ description="Description of the product family.",
+ accounting_code="Accounting code used to categorize the product family.",
+ ),
+ },
+ "Components": {
+ "description": "An add-on billed alongside a subscription (metered, quantity, on/off, or prepaid).",
+ "docs_url": "https://developers.maxio.com/http/resources/components",
+ "columns": _columns(
+ name="Name of the component.",
+ handle="Unique, URL-safe handle used to reference the component.",
+ kind="Type of component (e.g. metered_component, quantity_based_component, on_off_component).",
+ pricing_scheme="Pricing scheme used (e.g. per_unit, volume, tiered, stairstep).",
+ unit_name="Name of the unit the component is measured in.",
+ unit_price="Price per unit of the component.",
+ product_family_id="Identifier of the product family the component belongs to.",
+ price_per_unit_in_cents="Price per unit of the component, in cents.",
+ taxable="Whether the component is taxable.",
+ recurring="Whether the component recurs each billing period.",
+ archived_at="Timestamp for when the component was archived, if applicable.",
+ ),
+ },
+ "Transactions": {
+ "description": "A financial event on a subscription, such as a charge, payment, credit, or refund.",
+ "docs_url": "https://developers.maxio.com/http/resources/transactions",
+ "columns": _columns(
+ transaction_type="Type of transaction (e.g. charge, payment, credit, refund, adjustment).",
+ amount_in_cents="Amount of the transaction, in cents.",
+ subscription_id="Identifier of the subscription the transaction belongs to.",
+ success="Whether the transaction succeeded.",
+ memo="Description or memo recorded on the transaction.",
+ starting_balance_in_cents="Subscription balance before the transaction, in cents.",
+ ending_balance_in_cents="Subscription balance after the transaction, in cents.",
+ payment_id="Identifier of the associated payment, if any.",
+ product_id="Identifier of the product the transaction relates to.",
+ gateway_transaction_id="Identifier of the transaction in the payment gateway.",
+ kind="Finer-grained classification of the transaction.",
+ gateway_used="Payment gateway used to process the transaction.",
+ ),
+ },
+ "Events": {
+ "description": "An append-only record of an event that occurred on a subscription or the site.",
+ "docs_url": "https://developers.maxio.com/http/resources/events",
+ "columns": _columns(
+ key="Machine-readable key identifying the event type (e.g. signup_success, payment_success).",
+ message="Human-readable description of the event.",
+ subscription_id="Identifier of the subscription the event relates to, if any.",
+ customer_id="Identifier of the customer the event relates to, if any.",
+ event_specific_data="Structured payload with details specific to the event type.",
+ ),
+ },
+ "Invoices": {
+ "description": "An invoice issued for a subscription, listing line items, taxes, and payments.",
+ "docs_url": "https://developers.maxio.com/http/resources/invoices",
+ "columns": _columns(
+ uid="Globally unique identifier for the invoice.",
+ number="Sequential invoice number shown to the customer.",
+ subscription_id="Identifier of the subscription the invoice was issued for.",
+ customer_id="Identifier of the customer the invoice was issued to.",
+ status="Current status of the invoice (e.g. draft, open, paid, voided).",
+ currency="Currency of the invoice (ISO 4217 code).",
+ total_amount="Total amount of the invoice.",
+ paid_amount="Amount that has been paid on the invoice.",
+ due_amount="Amount still due on the invoice.",
+ issue_date="Date the invoice was issued.",
+ due_date="Date the invoice payment is due.",
+ paid_date="Date the invoice was paid in full, if applicable.",
+ product_name="Name of the product the invoice relates to.",
+ line_items="Line items itemizing the charges on the invoice.",
+ ),
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/chargify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/chargify.py
new file mode 100644
index 000000000000..a9c2e3820e10
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/chargify.py
@@ -0,0 +1,137 @@
+import dataclasses
+from typing import Any, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargify.settings import CHARGIFY_ENDPOINTS
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+# Chargify sites use HTTP Basic auth with the API key as the username and any value as the
+# password ('x' is the documented convention).
+CHARGIFY_BASIC_PASSWORD = "x"
+
+# Chargify pages are 1-indexed.
+BASE_PAGE = 1
+
+
+class ChargifyResumeConfig:
+ next_page: int
+
+
+def base_url(subdomain: str) -> str:
+ """Per-site hostname: each Chargify merchant site has its own subdomain."""
+ return f"https://{subdomain}.chargify.com"
+
+
+class ChargifyPaginator(PageNumberPaginator):
+ """Page-number paginator that can persist and restore its cursor.
+
+ Chargify list endpoints return a bare array with no total count, so pagination walks
+ ``page`` upward until an empty page is returned (``stop_after_empty_page``). The resume
+ state is simply the next page number to fetch.
+ """
+
+ def __init__(self, page: Optional[int] = None) -> None:
+ super().__init__(
+ base_page=BASE_PAGE,
+ page=page,
+ page_param="page",
+ # Bare-array responses carry no "total" field, so terminate on the first empty page.
+ total_path=None,
+ stop_after_empty_page=True,
+ )
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ # ``update_state`` has already advanced ``self.page`` to the next page to fetch.
+ if self._has_next_page:
+ return {"page": self.page}
+ return None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ next_page = state.get("page")
+ if next_page is not None:
+ self.page = int(next_page)
+ self._has_next_page = True
+
+
+def get_resource(name: str) -> EndpointResource:
+ endpoint = CHARGIFY_ENDPOINTS[name]
+ return {
+ "name": endpoint.name,
+ "table_name": endpoint.name.lower(),
+ # Every endpoint is full refresh today (see settings.INCREMENTAL_FIELDS), so we
+ # fully replace the table each sync.
+ "write_disposition": "replace",
+ "endpoint": {
+ "data_selector": endpoint.data_selector,
+ "path": endpoint.path,
+ "params": dict(endpoint.params),
+ },
+ "table_format": "delta",
+ }
+
+
+def chargify_source(
+ api_key: str,
+ subdomain: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ChargifyResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
+ should_use_incremental_field: bool = False,
+):
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": base_url(subdomain),
+ "auth": {
+ "type": "http_basic",
+ "username": api_key,
+ "password": CHARGIFY_BASIC_PASSWORD,
+ },
+ "paginator": ChargifyPaginator(),
+ },
+ "resource_defaults": {
+ "write_disposition": "replace",
+ },
+ "resources": [get_resource(endpoint)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"page": resume_config.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when there's a next page to resume to; Redis TTL handles cleanup
+ # once the sync completes. Saving AFTER each yielded batch means a crash re-yields
+ # the last page rather than skipping it (the merge dedupes on primary key).
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(ChargifyResumeConfig(next_page=int(state["page"])))
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def validate_credentials(api_key: str, subdomain: str) -> bool:
+ res = make_tracked_session().get(
+ f"{base_url(subdomain)}/customers.json",
+ params={"per_page": 1},
+ auth=(api_key, CHARGIFY_BASIC_PASSWORD),
+ )
+ return res.status_code == 200
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/settings.py
new file mode 100644
index 000000000000..b321e5994aed
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/settings.py
@@ -0,0 +1,109 @@
+import dataclasses
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
[email protected](frozen=True)
+class ChargifyEndpoint:
+ """Declarative metadata for a Chargify (Maxio Advanced Billing) list endpoint.
+
+ Chargify list endpoints return a bare JSON array of single-key-wrapped objects
+ (e.g. ``[{"customer": {...}}, ...]``), so ``data_selector`` unwraps the payload
+ key. Pagination is page-number based (``page`` + ``per_page``, max 200).
+ """
+
+ name: str
+ path: str
+ data_selector: str
+ primary_key: list[str]
+ # A stable creation timestamp used for datetime partitioning. Every core Chargify
+ # object exposes ``created_at`` (ISO 8601), which never changes after creation.
+ partition_key: str | None
+ # Extra query params merged onto the request (e.g. an explicit stable sort direction).
+ params: dict[str, str | int] = dataclasses.field(default_factory=dict)
+
+
+# Per-page maximum documented by the Chargify API (defaults to 20, caps at 200).
+PER_PAGE = 200
+
+CHARGIFY_ENDPOINTS: dict[str, ChargifyEndpoint] = {
+ "Customers": ChargifyEndpoint(
+ name="Customers",
+ path="/customers.json",
+ data_selector="[*].customer",
+ primary_key=["id"],
+ partition_key="created_at",
+ # Customers list supports an explicit sort direction; oldest-first keeps page
+ # boundaries stable across a full-refresh sync.
+ params={"per_page": PER_PAGE, "direction": "asc"},
+ ),
+ "Subscriptions": ChargifyEndpoint(
+ name="Subscriptions",
+ path="/subscriptions.json",
+ data_selector="[*].subscription",
+ primary_key=["id"],
+ partition_key="created_at",
+ params={"per_page": PER_PAGE, "direction": "asc"},
+ ),
+ "Products": ChargifyEndpoint(
+ name="Products",
+ path="/products.json",
+ data_selector="[*].product",
+ primary_key=["id"],
+ partition_key="created_at",
+ params={"per_page": PER_PAGE},
+ ),
+ "ProductFamilies": ChargifyEndpoint(
+ name="ProductFamilies",
+ path="/product_families.json",
+ data_selector="[*].product_family",
+ primary_key=["id"],
+ partition_key="created_at",
+ params={"per_page": PER_PAGE},
+ ),
+ "Components": ChargifyEndpoint(
+ name="Components",
+ path="/components.json",
+ data_selector="[*].component",
+ primary_key=["id"],
+ partition_key="created_at",
+ params={"per_page": PER_PAGE},
+ ),
+ "Transactions": ChargifyEndpoint(
+ name="Transactions",
+ path="/transactions.json",
+ data_selector="[*].transaction",
+ primary_key=["id"],
+ partition_key="created_at",
+ params={"per_page": PER_PAGE, "direction": "asc"},
+ ),
+ "Events": ChargifyEndpoint(
+ name="Events",
+ path="/events.json",
+ data_selector="[*].event",
+ primary_key=["id"],
+ partition_key="created_at",
+ params={"per_page": PER_PAGE, "direction": "asc"},
+ ),
+ "Invoices": ChargifyEndpoint(
+ name="Invoices",
+ path="/invoices.json",
+ # The Invoices API wraps its list under an ``invoices`` key alongside a ``meta``
+ # object (unlike the bare-array endpoints above), so the selector targets it.
+ data_selector="invoices",
+ primary_key=["id"],
+ partition_key="created_at",
+ params={"per_page": PER_PAGE, "direction": "asc"},
+ ),
+}
+
+ENDPOINTS: tuple[str, ...] = tuple(CHARGIFY_ENDPOINTS.keys())
+
+# Chargify documents server-side date filtering (``date_field`` + ``start_date``/``end_date``)
+# on some list endpoints and id-based filtering (``since_id``) on events/transactions, but the
+# filter behaviour and result ordering could not be verified against a live site, so every
+# endpoint ships as full refresh for now. Incremental sync is a deliberate follow-up once the
+# filters and sort semantics can be confirmed with a live smoke test — declaring an unverified
+# watermark risks silently skipping rows. Keeping this map empty means every schema advertises
+# no incremental fields and syncs via full refresh.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/source.py
index 67bb2b053806..11ce11406f8f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/source.py
@@ -1,30 +1,172 @@
-from typing import cast
+import re
+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.chargify.chargify import (
+ ChargifyResumeConfig,
+ chargify_source,
+ validate_credentials as validate_chargify_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargify.settings import (
+ CHARGIFY_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+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 ChargifySourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+# Chargify site subdomains are alphanumeric with optional hyphens.
+SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9-]+$")
+
@SourceRegistry.register
-class ChargifySource(SimpleSource[ChargifySourceConfig]):
+class ChargifySource(ResumableSource[ChargifySourceConfig, ChargifyResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CHARGIFY
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The stored API key is sent to `https://{subdomain}.chargify.com`, so retargeting
+ # `subdomain` must force the editor to re-enter the key (prevents credential exfiltration).
+ return ["subdomain"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # Chargify hosts are per-site subdomains, so match the stable status prefix rather
+ # than a fixed hostname. A bad or under-scoped API key can never be fixed by retrying.
+ return {
+ "401 Client Error: Unauthorized for url": "Your Chargify API key is invalid or has been revoked. Generate a new key in your Chargify site settings, then reconnect.",
+ "403 Client Error: Forbidden for url": "Your Chargify API key is missing the permissions needed to sync this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.chargify.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ChargifySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=(fields := INCREMENTAL_FIELDS.get(endpoint)) is not None,
+ supports_append=fields is not None,
+ incremental_fields=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: ChargifySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if not SUBDOMAIN_REGEX.match(config.subdomain):
+ return False, "Chargify site subdomain is invalid"
+
+ if validate_chargify_credentials(config.api_key, config.subdomain):
+ return True, None
+
+ return False, "Invalid Chargify credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ChargifyResumeConfig]:
+ return ResumableSourceManager[ChargifyResumeConfig](inputs, ChargifyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ChargifySourceConfig,
+ resumable_source_manager: ResumableSourceManager[ChargifyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ endpoint = CHARGIFY_ENDPOINTS[inputs.schema_name]
+ resource = chargify_source(
+ api_key=config.api_key,
+ subdomain=config.subdomain,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=endpoint.primary_key,
+ column_hints=resource.column_hints,
+ partition_mode="datetime" if endpoint.partition_key else None,
+ partition_format="month" if endpoint.partition_key else None,
+ partition_keys=[endpoint.partition_key] if endpoint.partition_key else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CHARGIFY,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Chargify",
- iconPath="/static/services/chargify.png",
- fields=cast(list[FieldType], []),
+ keywords=["maxio", "advanced billing"],
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Chargify (Maxio Advanced Billing) API key and site subdomain to pull your billing data into the PostHog Data warehouse.
+
+You can create an API key under **Settings → Integrations → API Access** in your Chargify site. Your subdomain is the first part of your site URL — for `acme.chargify.com` the subdomain is `acme`.""",
+ iconPath="/static/services/chargify.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/chargify",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="subdomain",
+ label="Site subdomain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="acme",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify.py
new file mode 100644
index 000000000000..91f7e8050e44
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify.py
@@ -0,0 +1,236 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargify.chargify import (
+ ChargifyPaginator,
+ ChargifyResumeConfig,
+ base_url,
+ chargify_source,
+ get_resource,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargify.settings import (
+ CHARGIFY_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class TestChargifyPaginator:
+ def test_initial_state_is_page_one(self) -> None:
+ paginator = ChargifyPaginator()
+ assert paginator.page == 1
+ # BasePaginator starts with _has_next_page=True so the first request runs.
+ assert paginator.has_next_page is True
+
+ def test_update_state_advances_page_when_data(self) -> None:
+ paginator = ChargifyPaginator()
+ response = MagicMock()
+ paginator.update_state(response, data=[{"id": 1}])
+ assert paginator.page == 2
+ assert paginator.has_next_page is True
+
+ def test_update_state_stops_on_empty_page(self) -> None:
+ paginator = ChargifyPaginator()
+ response = MagicMock()
+ paginator.update_state(response, data=[])
+ # Page is not advanced past the empty terminal page.
+ assert paginator.page == 1
+ assert paginator.has_next_page is False
+
+ def test_get_resume_state_returns_next_page(self) -> None:
+ paginator = ChargifyPaginator()
+ paginator.update_state(MagicMock(), data=[{"id": 1}])
+ assert paginator.get_resume_state() == {"page": 2}
+
+ def test_get_resume_state_returns_none_on_terminal_page(self) -> None:
+ paginator = ChargifyPaginator()
+ paginator.update_state(MagicMock(), data=[])
+ assert paginator.get_resume_state() is None
+
+ def test_set_resume_state_round_trip(self) -> None:
+ paginator = ChargifyPaginator()
+ paginator.set_resume_state({"page": 7})
+ assert paginator.page == 7
+ assert paginator.has_next_page is True
+
+ def test_set_resume_state_coerces_to_int(self) -> None:
+ # A Redis round-trip can return the page as a string; the request needs an int.
+ paginator = ChargifyPaginator()
+ paginator.set_resume_state({"page": "9"})
+ assert paginator.page == 9
+
+ def test_set_resume_state_ignores_missing_page(self) -> None:
+ paginator = ChargifyPaginator()
+ paginator.set_resume_state({})
+ assert paginator.page == 1
+
+ @pytest.mark.parametrize(("seeded_page", "expected"), [(None, 1), (4, 4)])
+ def test_init_request_targets_current_page(self, seeded_page: int | None, expected: int) -> None:
+ paginator = ChargifyPaginator()
+ if seeded_page is not None:
+ paginator.set_resume_state({"page": seeded_page})
+
+ request = Request(method="GET", url="https://acme.chargify.com/customers.json")
+ paginator.init_request(request)
+
+ assert request.params["page"] == expected
+
+
+class TestGetResource:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_resource_matches_settings(self, endpoint: str) -> None:
+ resource = get_resource(endpoint)
+ config = CHARGIFY_ENDPOINTS[endpoint]
+
+ assert resource["name"] == endpoint
+ assert resource["table_format"] == "delta"
+ # Every endpoint is full refresh today.
+ assert resource["write_disposition"] == "replace"
+ endpoint_config = cast(dict[str, Any], resource["endpoint"])
+ assert endpoint_config["path"] == config.path
+ assert endpoint_config["data_selector"] == config.data_selector
+
+ def test_bare_array_endpoints_unwrap_the_payload_key(self) -> None:
+ # Chargify wraps each row under a single object key, so the selector must unwrap it.
+ endpoint_config = cast(dict[str, Any], get_resource("Customers")["endpoint"])
+ assert endpoint_config["data_selector"] == "[*].customer"
+
+ def test_invoices_selects_the_wrapped_list(self) -> None:
+ # The Invoices API nests its list under an "invoices" key alongside "meta".
+ endpoint_config = cast(dict[str, Any], get_resource("Invoices")["endpoint"])
+ assert endpoint_config["data_selector"] == "invoices"
+
+
+def _make_http_response(body: Any, status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestChargifySourceResumeBehavior:
+ """End-to-end resume behaviour of ``chargify_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response]
+ ) -> tuple[MagicMock, list[dict[str, Any]]]:
+ """Drive ``chargify_source`` with a mocked HTTP session.
+
+ Returns ``(mock_session, sent_params)`` where ``sent_params`` captures a shallow
+ copy of ``request.params`` at send-time — the Request object is mutated in place
+ by the paginator between pages, so mock call history can't be trusted for it.
+ """
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = chargify_source(
+ api_key="test-key",
+ subdomain="acme",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=False,
+ )
+ list(cast(Iterable[Any], resource))
+ return mock_session, sent_params
+
+ @pytest.mark.parametrize("endpoint", ["Customers", "Subscriptions", "Events", "Transactions"])
+ def test_fresh_run_saves_page_after_each_non_terminal_page(self, endpoint: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ selector_key = CHARGIFY_ENDPOINTS[endpoint].data_selector.split(".")[-1]
+ responses = [
+ _make_http_response([{selector_key: {"id": 1}}]),
+ _make_http_response([{selector_key: {"id": 2}}]),
+ _make_http_response([]),
+ ]
+ _, sent_params = self._drive(endpoint, manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [1, 2, 3]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [ChargifyResumeConfig(next_page=2), ChargifyResumeConfig(next_page=3)]
+
+ def test_resume_seeds_paginator_with_saved_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ChargifyResumeConfig(next_page=5)
+
+ responses = [
+ _make_http_response([{"customer": {"id": 1}}]),
+ _make_http_response([]),
+ ]
+ _, sent_params = self._drive("Customers", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [5, 6]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ # A single empty page terminates immediately, so no resumable checkpoint is persisted.
+ responses = [_make_http_response([])]
+ self._drive("Customers", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{"customer": {"id": 1}}]), _make_http_response([])]
+ self._drive("Customers", manager, responses)
+
+ manager.load_state.assert_not_called()
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected"),
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.chargify.chargify.make_tracked_session")
+ def test_status_maps_to_validity(self, mock_session_factory: MagicMock, status_code: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ mock_session_factory.return_value.get.return_value = response
+
+ assert validate_credentials("api-key", "acme") is expected
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.chargify.chargify.make_tracked_session")
+ def test_probes_the_site_subdomain_host(self, mock_session_factory: MagicMock) -> None:
+ mock_get = mock_session_factory.return_value.get
+ mock_get.return_value = MagicMock(status_code=200)
+
+ validate_credentials("api-key", "acme")
+
+ called_url = mock_get.call_args.args[0]
+ assert called_url.startswith("https://acme.chargify.com")
+
+
+def test_base_url_is_per_site_subdomain() -> None:
+ assert base_url("acme") == "https://acme.chargify.com"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify_source.py
new file mode 100644
index 000000000000..e27bca5782b1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify_source.py
@@ -0,0 +1,184 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargify.chargify import ChargifyResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargify.settings import (
+ CHARGIFY_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargify.source import ChargifySource
+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 ChargifySourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "Customers",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestChargifySource:
+ def setup_method(self) -> None:
+ self.source = ChargifySource()
+ self.team_id = 123
+ self.config = ChargifySourceConfig(api_key="test-key", subdomain="acme")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CHARGIFY
+
+ def test_subdomain_is_a_connection_host_field(self) -> None:
+ # The stored API key is sent to https://{subdomain}.chargify.com, so changing subdomain
+ # must force the key to be re-entered — otherwise it could be exfiltrated to another host.
+ assert self.source.connection_host_fields == ["subdomain"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static catalog with no I/O, so the public docs table list can render.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Chargify"
+ assert config.label == "Chargify"
+ assert config.category == DataWarehouseSourceCategory.PAYMENTS___BILLING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/chargify"
+ assert config.iconPath == "/static/services/chargify.png"
+
+ api_key_field, subdomain_field = config.fields
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ assert isinstance(subdomain_field, SourceFieldInputConfig)
+ assert subdomain_field.name == "subdomain"
+ assert subdomain_field.type == SourceFieldInputConfigType.TEXT
+ assert subdomain_field.required is True
+ assert subdomain_field.secret is False
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas_all_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # No endpoint has a curl-verified server-side filter yet, so every schema is full refresh.
+ assert all(not s.supports_incremental for s in schemas)
+ assert all(not s.supports_append for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Subscriptions"])
+ assert [s.name for s in schemas] == ["Subscriptions"]
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ # Every advertised endpoint should have a curated description so the docs and the AI
+ # agent get authoritative metadata instead of paying for LLM enrichment.
+ assert set(self.source.get_canonical_descriptions().keys()) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ ("subdomain", "creds_valid", "expected_valid", "expected_message"),
+ [
+ ("acme", True, True, None),
+ ("acme", False, False, "Invalid Chargify credentials"),
+ ("has spaces", True, False, "Chargify site subdomain is invalid"),
+ ("bad/slash", True, False, "Chargify site subdomain is invalid"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.chargify.source.validate_chargify_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ subdomain: str,
+ creds_valid: bool,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = creds_valid
+ config = ChargifySourceConfig(api_key="test-key", subdomain=subdomain)
+
+ is_valid, error_message = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+
+ def test_validate_credentials_skips_api_call_for_bad_subdomain(self) -> None:
+ # An obviously malformed subdomain must fail before any network call is attempted.
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.chargify.source.validate_chargify_credentials"
+ ) as mock_validate:
+ config = ChargifySourceConfig(api_key="test-key", subdomain="bad domain")
+ is_valid, _ = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is False
+ mock_validate.assert_not_called()
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ChargifyResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.chargify.source.chargify_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(schema_name="Subscriptions", team_id=99, job_id="job-xyz")
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ api_key="test-key",
+ subdomain="acme",
+ endpoint="Subscriptions",
+ team_id=99,
+ job_id="job-xyz",
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ assert response.primary_keys == CHARGIFY_ENDPOINTS["Subscriptions"].primary_key
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.chargify.source.chargify_source")
+ def test_source_for_pipeline_partitions_on_created_at(self, mock_source: mock.MagicMock) -> None:
+ # A stable creation timestamp partitions the table; using created_at (never updated_at)
+ # keeps partitions from being rewritten on every sync.
+ response = self.source.source_for_pipeline(
+ self.config, mock.MagicMock(spec=ResumableSourceManager), _make_inputs(schema_name="Invoices")
+ )
+
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "month"
+ assert response.partition_keys == ["created_at"]
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 d98013e7cb45..b20b46707b3e 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
@@ -620,7 +620,8 @@ class ChargedeskSourceConfig(config.Config):
@config.config
class ChargifySourceConfig(config.Config):
- pass
+ api_key: str
+ subdomain: str
@config.config